diff --git a/.github/ROADMAP_EXECUTION.md b/.github/ROADMAP_EXECUTION.md index 9eec4144..cc392364 100644 --- a/.github/ROADMAP_EXECUTION.md +++ b/.github/ROADMAP_EXECUTION.md @@ -40,9 +40,14 @@ Key corrections from the audit: - Earthquake has the main model adapters (`PhaseNet`, `EQTransformer`, `GPD`, `EQNet`), but the SeisBench / pick-benchmark / pyCSEP / AEFA benchmark-data stack is still missing. -- Flood has the main model adapters (`NeuralHydrology`, `FloodCast`, - `UrbanFloodCast`), but the Caravan / WaterBench / FloodCastBench / - HydroBench benchmark-data stack is still missing. +- Flood: the NeuralHydrology LSTM / EA-LSTM and Google's released FloodHub + model are faithful ports, with real CAMELS-US and Caravan readers and per-basin + NSE / KGE evaluation. `HydroGraphNet` (PhysicsNeMo MeshGraphKAN, with a real + White River mesh reader and rollout evaluation) and `UrbanFloodCast` (the DNO, + written from the paper and checked against the unlicensed official code) are + faithful too. `FloodCast` stays an experimental stand-in (flood-model code never + released, widths not in the paper), and WaterBench / FloodCastBench / HydroBench + have no readers (their former adapters generated random numbers and were removed). - Storm has the main model adapters, but `TCBench`, `IBTrACS`, and `TropiCycloneNet-Dataset` are still missing. `GraphCast`, `Pangu`, and `FourCastNet` remain experimental wrappers and must not be counted as @@ -251,17 +256,12 @@ Own: - `pyhazards/models/tropicyclonenet.py` - `pyhazards/models/saf_net.py` - `pyhazards/models/tcif_fusion.py` -- `pyhazards/models/graphcast_tc.py` -- `pyhazards/models/pangu_tc.py` -- `pyhazards/models/fourcastnet_tc.py` +- `pyhazards/forecasts/**` (FourCastNet / GraphCast / Pangu-Weather cyclone pipelines; the former graphcast_tc, pangu_tc and fourcastnet_tc placeholders were removed) - `pyhazards/model_cards/hurricast.yaml` - `pyhazards/model_cards/tropicalcyclone_mlp.yaml` - `pyhazards/model_cards/tropicyclonenet.yaml` - `pyhazards/model_cards/saf_net.yaml` - `pyhazards/model_cards/tcif_fusion.yaml` -- `pyhazards/model_cards/graphcast_tc.yaml` -- `pyhazards/model_cards/pangu_tc.yaml` -- `pyhazards/model_cards/fourcastnet_tc.yaml` - `tests/test_tc_*.py` Do not edit: @@ -537,17 +537,12 @@ You own: - pyhazards/models/tropicyclonenet.py - pyhazards/models/saf_net.py - pyhazards/models/tcif_fusion.py -- pyhazards/models/graphcast_tc.py -- pyhazards/models/pangu_tc.py -- pyhazards/models/fourcastnet_tc.py +- pyhazards/forecasts/** (FourCastNet / GraphCast / Pangu-Weather cyclone pipelines; the former graphcast_tc, pangu_tc and fourcastnet_tc placeholders were removed) - pyhazards/model_cards/hurricast.yaml - pyhazards/model_cards/tropicalcyclone_mlp.yaml - pyhazards/model_cards/tropicyclonenet.yaml - pyhazards/model_cards/saf_net.yaml - pyhazards/model_cards/tcif_fusion.yaml -- pyhazards/model_cards/graphcast_tc.yaml -- pyhazards/model_cards/pangu_tc.yaml -- pyhazards/model_cards/fourcastnet_tc.yaml - tests/test_tc_*.py Do not edit: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 09a073ee..08e02b92 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,5 +46,8 @@ jobs: - name: Generated coverage audit docs check run: python scripts/render_appendix_a_docs.py --check + - name: Generated prompted-baseline docs check + run: python scripts/render_prompted_docs.py --check + - name: Catalog smoke test run: python scripts/verify_table_entries.py diff --git a/.github/workflows/model-docs-sync.yml b/.github/workflows/model-docs-sync.yml index cc8f207f..0a175c80 100644 --- a/.github/workflows/model-docs-sync.yml +++ b/.github/workflows/model-docs-sync.yml @@ -12,10 +12,13 @@ on: - "pyhazards/dataset_catalog.py" - "pyhazards/benchmark_catalog.py" - "pyhazards/appendix_a_catalog.py" + - "pyhazards/prompted/cards/**" + - "pyhazards/prompted/catalog.py" - "scripts/render_model_docs.py" - "scripts/render_dataset_docs.py" - "scripts/render_benchmark_docs.py" - "scripts/render_appendix_a_docs.py" + - "scripts/render_prompted_docs.py" permissions: contents: write @@ -44,6 +47,7 @@ jobs: python scripts/render_model_docs.py python scripts/render_benchmark_docs.py python scripts/render_appendix_a_docs.py + python scripts/render_prompted_docs.py cd docs sphinx-build -b html source build/html cp -r build/html/* . diff --git a/.github/workflows/oracle.yml b/.github/workflows/oracle.yml new file mode 100644 index 00000000..e80235ee --- /dev/null +++ b/.github/workflows/oracle.yml @@ -0,0 +1,274 @@ +name: Oracle + +# Compares PyHazards models with their pinned reference implementations (tests/oracle). +# Reference stacks that cannot share one environment run as separate matrix entries; every +# tests/oracle/test_*.py file must be listed in exactly one entry (checked by the CI test suite). + +on: + push: + branches: [main, master] + paths: + - "pyhazards/models/**" + - "pyhazards/simulators/**" + - "pyhazards/prompted/**" + - "pyhazards/datasets/figlib_smokebench/**" + - "pyhazards/datasets/tc/**" + - "pyhazards/benchmarks/tc.py" + - "pyhazards/forecasts/**" + - "pyhazards/datasets/flood/**" + - "pyhazards/metrics/**" + - "pyhazards/benchmarks/flood.py" + - "tests/oracle/**" + - "scripts/fetch_oracles.py" + - ".github/workflows/oracle.yml" + pull_request: + branches: [main, master] + paths: + - "pyhazards/models/**" + - "pyhazards/simulators/**" + - "pyhazards/prompted/**" + - "pyhazards/datasets/figlib_smokebench/**" + - "pyhazards/datasets/tc/**" + - "pyhazards/benchmarks/tc.py" + - "pyhazards/forecasts/**" + - "pyhazards/datasets/flood/**" + - "pyhazards/metrics/**" + - "pyhazards/benchmarks/flood.py" + - "tests/oracle/**" + - "scripts/fetch_oracles.py" + - ".github/workflows/oracle.yml" + workflow_dispatch: + +jobs: + oracle: + name: oracle (${{ matrix.suite }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - suite: default + python: "3.10" + torch: torch torchvision + requirements: tests/oracle/requirements.txt + references: >- + utae-paps WildfireSpreadTS utae_pastis_weights wildfire_forecasting + segformer_mit_b0 segformer_b0_ade TS-SatFire TCN uncertainty-wildfires firecastnet + tests: >- + tests/oracle/test_wildfirespreadts_oracle.py + tests/oracle/test_wildfire_forecasting_oracle.py + tests/oracle/test_classical_oracle.py + tests/oracle/test_deep_ensemble_oracle.py + tests/oracle/test_segformer_oracle.py + tests/oracle/test_attention_unet_oracle.py + tests/oracle/test_tcn_oracle.py + tests/oracle/test_deeplabv3_oracle.py + tests/oracle/test_convgru_oracle.py + # The original U-Net release is Caffe; OpenCV 4.x's Caffe importer runs it (OpenCV 5 dropped it). + - suite: unet + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-unet.txt + references: unet_release + tests: tests/oracle/test_unet_oracle.py + # timm 0.4.12 (fire-asufm) conflicts with the timm 0.6.12 pin of smp 0.3.2. + - suite: swin + python: "3.10" + torch: torch torchvision + requirements: tests/oracle/requirements-swin.txt + references: Swin-Unet fire-asufm swin_tiny_imagenet SwinLSTM + tests: tests/oracle/test_swin_oracle.py tests/oracle/test_swinlstm_oracle.py + # EarthFarseer pins timm 0.9.16 (smp 0.3.2 needs 0.6.12, fire-asufm 0.4.12); Rainformer needs + # einops. Default-size models and the 751 MB Rainformer KNMI checkpoint are compared locally + # (PYHAZARDS_ORACLE_LARGE=1); CI compares reduced models. + - suite: farseer-rainformer + python: "3.10" + torch: torch torchvision + requirements: tests/oracle/requirements-farseer-rainformer.txt + references: EarthFarseer Rainformer + tests: >- + tests/oracle/test_earthfarseer_oracle.py + tests/oracle/test_rainformer_oracle.py + # MONAI's UNETR / SwinUNETR need einops, and TS-SatFire's SwinUNETR copy imports torchinfo. + - suite: tssatfire + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-tssatfire.txt + references: TS-SatFire + tests: >- + tests/oracle/test_unet3d_oracle.py + tests/oracle/test_unetr_oracle.py + tests/oracle/test_swin_unetr_oracle.py + tests/oracle/test_ts_satfire_oracle.py + # The official FireCastNet code runs on DGL, whose CPU wheels need torch 2.4 (pinned in the + # requirements file). The comparison on the full global grid peaks at about 8 GB of RAM. + - suite: firecastnet + python: "3.10" + torch: "" + requirements: tests/oracle/requirements-firecastnet.txt + references: >- + firecastnet firecastnet_global_cls_ts24_h1 firecastnet_global_regr_ts24_h1 + firecastnet_lam_aust_cls_ts24_h1 + tests: tests/oracle/test_firecastnet_oracle.py + # The official Earthformer model file needs einops, which no other suite installs. The SEVIR + # and ICAR-ENSO checkpoints (35 MB and 6 MB) are fetched and compared in CI. + - suite: earthformer + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-earthformer.txt + references: earth-forecasting-transformer earthformer_sevir earthformer_icarenso2021 + tests: tests/oracle/test_earthformer_oracle.py + # The official TrajGRU code (HKO-7) is MXNet; MXNet 1.9.1 runs it and needs numpy < 1.24. + - suite: trajgru + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-trajgru.txt + references: HKO-7 hko7_movingmnist_weights hko7_hko_weights + tests: tests/oracle/test_trajgru_oracle.py + # ForeFire (GPL-3.0) is installed from its official 2.5.0 wheel in this job only; the pinned + # repository and its Git LFS test files provide the official inputs and reference output. + - suite: forefire + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-forefire.txt + references: forefire forefire_runff_data forefire_runff_reference + tests: tests/oracle/test_forefire_oracle.py + # SmokeBench authors' evaluation scripts (prompted VLM baselines): OpenCV + torchvision. + # The check over all 5,046 SmokeBench images needs the 11.4 GB download and runs locally. + - suite: smokebench + python: "3.10" + torch: torch torchvision + requirements: tests/oracle/requirements-smokebench.txt + references: SoraLink-MLLM smokeynet_metadata + tests: tests/oracle/test_smokebench_oracle.py + # Tropical cyclone models: the official tropicalcyclone_MLP Keras model and the TCIF-fusion notebook graph + # (about 300 M parameters, ~3 GB RAM) run on Keras 3 with the PyTorch backend; SAF-Net's notebook network, + # TropiCycloneNet's generator and Hurricast's encoder-decoders are plain PyTorch, Hurricast's second stage + # is XGBoost. The TropiCycloneNet checkpoint (56 MB, Zenodo, CC BY 4.0) is fetched and compared in CI. + - suite: tc + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-tc.txt + references: tropicalcyclone_MLP TI_Prediction TropiCycloneNet tropicyclonenet_checkpoint hurricast TCIF-fusion + tests: >- + tests/oracle/test_tropicalcyclone_mlp_oracle.py + tests/oracle/test_saf_net_oracle.py + tests/oracle/test_tropicyclonenet_oracle.py + tests/oracle/test_hurricast_oracle.py + tests/oracle/test_tcif_fusion_oracle.py + # Cyclone trackers and TCBench scoring: TempestExtremes v2.4.2 is built from its pinned source + # (needs cmake and the netCDF C library) and compared with pyhazards.forecasts.tempest on synthetic + # fields; TCBench's own metric functions score its released 2023 tracks. The check on TCBench's + # raw Pangu-Weather fields reads ~200 MB over HTTP and runs locally (PYHAZARDS_ORACLE_LARGE=1). + - suite: tc-tracking + python: "3.10" + torch: torch + apt: cmake libnetcdf-dev + requirements: tests/oracle/requirements-tc-tracking.txt + references: >- + tempestextremes TCBench_Alpha tcbench_matched_pangu tcbench_matched_fcnet tcbench_ibtracs_2023 + tcbench_pangu_unmatched_20230716_12 + tests: tests/oracle/test_tempest_oracle.py tests/oracle/test_tcbench_evaluation_oracle.py + # Weather-model sources: earth2studio 0.19.0 (Python >= 3.11) drives its Persistence model through + # the PyHazards runner; zarr + gcsfs read small slices of the public WeatherBench 2 stores. + - suite: weather + python: "3.12" + torch: torch + requirements: tests/oracle/requirements-weather.txt + references: "" + tests: tests/oracle/test_forecasts_weather_oracle.py + # NeuralHydrology and googlehydrology (Google's flood-forecasting fork) are imported from their pinned + # checkouts; googlehydrology targets Python 3.12. Both repositories provide real test data (4 CAMELS-US + # basins, Caravan netCDF files) and the released FloodHub weights; the 939 MB HydroShare archive of the + # Kratzert et al. (2019) runs is not fetched in CI (those tests run locally with PYHAZARDS_ORACLE_LARGE=1). + # The official UrbanFloodCast DNO (no licence; test oracle only) needs torch, numpy, scipy and matplotlib, + # which this suite has. + - suite: flood + python: "3.12" + torch: torch + requirements: tests/oracle/requirements-flood.txt + references: neuralhydrology ealstm_regional_modeling flood-forecasting floodhub_weights UrbanFloodCast + tests: >- + tests/oracle/test_neuralhydrology_oracle.py + tests/oracle/test_google_flood_forecasting_oracle.py + tests/oracle/test_urbanfloodcast_oracle.py + # HydroGraphNet: NVIDIA PhysicsNeMo's MeshGraphKAN, physics loss, rollout and HydroGraphDataset, imported + # from the pinned checkout. PyTorch Geometric + torch_scatter (CPU wheels up to torch 2.12) and the + # packages `import physicsnemo` needs; see requirements-physicsnemo.txt. + - suite: physicsnemo + python: "3.12" + torch: torch==2.12.0 torchvision==0.27.0 + requirements: tests/oracle/requirements-physicsnemo.txt + references: physicsnemo + tests: tests/oracle/test_hydrographnet_oracle.py + # TerraTorch 0.99.8 (the Prithvi-EO-2.0 BurnScars training stack) needs Python >= 3.12 and + # torch 2.6. The 1.3 GB checkpoints are not fetched in CI; those tests run locally. + - suite: prithvi + python: "3.12" + torch: torch==2.6.0 torchvision==0.21.0 + requirements: tests/oracle/requirements-prithvi.txt + references: prithvi_eo2_tl_model_code prithvi_burnscars_config prithvi_burnscars_example + tests: tests/oracle/test_prithvi_oracle.py + # Earthquake phase pickers: the official PhaseNet (TF1 graph), EQTransformer and GPD (Keras) run on + # TensorFlow 2.11 with their released weights; SeisBench 0.12.6 (GPL-3.0) is a second oracle. + # WaveCastNet's official PyTorch code and both released checkpoints (40 MB, 66 MB, Google Drive), + # and EQNet's backbone / heads (AI4EPS/EQNet, non-commercial: oracle only) need only torch and numpy. + - suite: earthquake + python: "3.10" + torch: torch + requirements: tests/oracle/requirements-earthquake.txt + references: >- + PhaseNet EQTransformer generalized-phase-detection seisbench_phasenet_original + seisbench_eqtransformer_original seisbench_eqtransformer_original_nonconservative + seisbench_gpd_original WaveCastNet wavecastnet_dense_checkpoint wavecastnet_sparse_checkpoint + EQNet EQNet-2022 + tests: >- + tests/oracle/test_picking_metrics_oracle.py + tests/oracle/test_phasenet_oracle.py + tests/oracle/test_eqtransformer_oracle.py + tests/oracle/test_gpd_oracle.py + tests/oracle/test_seisbench_reader_oracle.py + tests/oracle/test_wavecastnet_oracle.py + tests/oracle/test_eqnet_oracle.py + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: Cache reference implementations and weights + uses: actions/cache@v4 + with: + path: | + ~/.cache/pyhazards-oracles + ~/.cache/torch/hub + key: oracles-${{ matrix.suite }}-${{ hashFiles('tests/oracle/repos.yaml') }} + + - name: Install system packages + if: matrix.apt != '' + run: sudo apt-get update && sudo apt-get install -y ${{ matrix.apt }} + + - name: Install dependencies (CPU Torch + reference packages) + run: | + python -m pip install --upgrade pip + if [ -n "${{ matrix.torch }}" ]; then + python -m pip install ${{ matrix.torch }} --index-url https://download.pytorch.org/whl/cpu + fi + python -m pip install pytest + python -m pip install -r ${{ matrix.requirements }} + python -m pip install -e . + + - name: Fetch pinned reference implementations + if: matrix.references != '' + run: python scripts/fetch_oracles.py --dest ~/.cache/pyhazards-oracles ${{ matrix.references }} + + - name: Oracle tests + run: | + export PYHAZARDS_ORACLE_DIR="$HOME/.cache/pyhazards-oracles" + mkdir -p "$PYHAZARDS_ORACLE_DIR" + export PYHAZARDS_ORACLE_REQUIRED=1 + export DGLBACKEND=pytorch + export KERAS_BACKEND=torch + python -m pytest ${{ matrix.tests }} -v -rs diff --git a/README.md b/README.md index 92927611..c688ed00 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Intended users: - **Wildfire**: danger forecasting, weekly forecasting, spread baselines, fuels, burn products, and active-fire sources. - **Earthquake**: waveform picking, dense-grid forecasting adapters, and linked benchmark ecosystems for picking and forecasting. - **Flood**: streamflow and inundation baselines with benchmark-backed evaluation paths. -- **Tropical Cyclone**: track-and-intensity forecasting baselines plus shared benchmark ecosystems and adapters. +- **Tropical Cyclone**: track-and-intensity forecasting baselines, IBTrACS / TCND / SHIPS readers, and cyclone tracks from global weather models (FourCastNet, GraphCast, Pangu-Weather) via trackers and published forecasts (`pyhazards.forecasts`). ## Installation @@ -90,14 +90,8 @@ python -c "import pyhazards; print(pyhazards.__version__)" ```python from pyhazards.models import build_model -model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, -) -print(type(model).__name__) +model = build_model(name="hydrographnet", task="regression") # PhysicsNeMo's MeshGraphKAN +print(type(model).__name__, sum(p.numel() for p in model.parameters())) # HydroGraphNet 2318722 ``` 3. Run a benchmark-aligned smoke configuration: diff --git a/docs/source/api/pyhazards.datasets.rst b/docs/source/api/pyhazards.datasets.rst index 1a7c06fc..1c8378fa 100644 --- a/docs/source/api/pyhazards.datasets.rst +++ b/docs/source/api/pyhazards.datasets.rst @@ -14,27 +14,27 @@ For the curated browsing experience, use :doc:`/pyhazards_datasets`. Shared Forcing ~~~~~~~~~~~~~~ -:doc:`ERA5 `, :doc:`GOES-R `, :doc:`MERRA-2 `. +:doc:`ERA5 `, :doc:`GOES-R `, :doc:`HRRR `, :doc:`LandScan Global `, :doc:`MERRA-2 `, :doc:`NDFD `, :doc:`SNODAS `. Wildfire ~~~~~~~~ -:doc:`FIRMS `, :doc:`FPA-FOD Tabular `, :doc:`FPA-FOD Weekly `, :doc:`LANDFIRE `, :doc:`MTBS `, :doc:`WFIGS `. +:doc:`CAL FIRE FRAP Fire Perimeters `, :doc:`FIgLib SmokeBench `, :doc:`FIRMS `, :doc:`FPA-FOD Tabular `, :doc:`FPA-FOD Weekly `, :doc:`GeoMAC Historical Perimeters `, :doc:`GOES-R ABI Fire/Hot Spot Characterization (FDCF) `, :doc:`LANDFIRE `, :doc:`MTBS `, :doc:`NOAA HMS Smoke Polygons `, :doc:`Track-O Wildfire Occurrence `, :doc:`WFIGS `, :doc:`Wildfire Risk to Communities: Housing Density `, :doc:`WRF-SFIRE Outputs `. Flood ~~~~~ -:doc:`Caravan `, :doc:`FloodCastBench `, :doc:`HydroBench `, :doc:`NOAA Flood Events `, :doc:`WaterBench `. +:doc:`CAMELS-US `, :doc:`Caravan `, :doc:`HydroGraphNet White River `, :doc:`NOAA Flood Events `, :doc:`Synthetic Mesh Hydrographs `, :doc:`Synthetic Urban Flood Events `. Earthquake ~~~~~~~~~~ -:doc:`AEFA Forecast `, :doc:`pick-benchmark `, :doc:`SeisBench `. +:doc:`SeisBench-format Waveforms `, :doc:`Synthetic Phase-Picking Waveforms `, :doc:`Synthetic Wavefield Sequences `. Tropical Cyclone ~~~~~~~~~~~~~~~~ -:doc:`IBTrACS `, :doc:`TCBench Alpha `, :doc:`TropiCycloneNet-Dataset `. +:doc:`Hurricast IBTrACS + ERA5 Inputs `, :doc:`IBTrACS `, :doc:`SHIPS Predictors (Xu et al. 2021) `, :doc:`Synthetic Hurricast Inputs `, :doc:`Synthetic SAF-Net Inputs `, :doc:`Synthetic SHIPS Predictors `, :doc:`Synthetic Storm Histories `, :doc:`Synthetic TCIF-fusion Inputs `, :doc:`Synthetic TCND Samples `, :doc:`TCBench Alpha `, :doc:`TropiCycloneNet Dataset `. Developer Dataset Workflow -------------------------- @@ -58,7 +58,7 @@ Load a Registered Dataset print(available_datasets()) data = load_dataset( - "seisbench_waveforms", + "earthquake_waveforms_synthetic", micro=True, ).load() print(sorted(data.splits.keys())) diff --git a/docs/source/api/pyhazards.forecasts.rst b/docs/source/api/pyhazards.forecasts.rst new file mode 100644 index 00000000..3586abc3 --- /dev/null +++ b/docs/source/api/pyhazards.forecasts.rst @@ -0,0 +1,79 @@ +pyhazards.forecasts package +=========================== + +Cyclone tracks from global ML weather models (FourCastNet, GraphCast, Pangu-Weather): readers for +published forecasts and tracks (TCBench, WeatherBench 2), an optional earth2studio runner, the +TempestExtremes-compatible and ECMWF-style trackers, IBTrACS matching and scoring. See +:doc:`/pyhazards_forecasts`. + +Submodules +---------- + +pyhazards.forecasts.tempest module +---------------------------------- + +.. automodule:: pyhazards.forecasts.tempest + :members: + :show-inheritance: + +pyhazards.forecasts.following module +------------------------------------ + +.. automodule:: pyhazards.forecasts.following + :members: + :show-inheritance: + +pyhazards.forecasts.matching module +----------------------------------- + +.. automodule:: pyhazards.forecasts.matching + :members: + +pyhazards.forecasts.scoring module +---------------------------------- + +.. automodule:: pyhazards.forecasts.scoring + :members: + +pyhazards.forecasts.pipeline module +----------------------------------- + +.. automodule:: pyhazards.forecasts.pipeline + :members: + +pyhazards.forecasts.tcbench module +---------------------------------- + +.. automodule:: pyhazards.forecasts.tcbench + :members: + :show-inheritance: + +pyhazards.forecasts.weatherbench2 module +---------------------------------------- + +.. automodule:: pyhazards.forecasts.weatherbench2 + :members: + +pyhazards.forecasts.earth2studio\_runner module +----------------------------------------------- + +.. automodule:: pyhazards.forecasts.earth2studio_runner + :members: + +pyhazards.forecasts.fields module +--------------------------------- + +.. automodule:: pyhazards.forecasts.fields + :members: + +pyhazards.forecasts.catalog module +---------------------------------- + +.. automodule:: pyhazards.forecasts.catalog + :members: + +pyhazards.forecasts.synthetic module +------------------------------------ + +.. automodule:: pyhazards.forecasts.synthetic + :members: diff --git a/docs/source/api/pyhazards.metrics.rst b/docs/source/api/pyhazards.metrics.rst index a79a09ac..a8c136d3 100644 --- a/docs/source/api/pyhazards.metrics.rst +++ b/docs/source/api/pyhazards.metrics.rst @@ -5,3 +5,19 @@ pyhazards.metrics package :members: :undoc-members: :show-inheritance: + +pyhazards.metrics.hydrology module +---------------------------------- + +.. automodule:: pyhazards.metrics.hydrology + :members: + :undoc-members: + :show-inheritance: + +pyhazards.metrics.inundation module +----------------------------------- + +.. automodule:: pyhazards.metrics.inundation + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/api/pyhazards.models.rst b/docs/source/api/pyhazards.models.rst index f2ee6f21..be922a62 100644 --- a/docs/source/api/pyhazards.models.rst +++ b/docs/source/api/pyhazards.models.rst @@ -17,7 +17,7 @@ Wildfire Implemented Models ++++++++++++++++++ -:doc:`ASUFM `, :doc:`DNN-LSTM-AutoEncoder `, :doc:`FireCastNet `, :doc:`ForeFire Adapter `, :doc:`Wildfire Forecasting `, :doc:`WildfireSpreadTS `, :doc:`WRF-SFIRE Adapter `, :doc:`CNN-ASPP `. +:doc:`ASUFM `, :doc:`Attention U-Net `, :doc:`ConvGRU `, :doc:`ConvLSTM `, :doc:`Deep Ensemble `, :doc:`DeepLabV3 `, :doc:`DNN-LSTM-AutoEncoder `, :doc:`Earthfarseer `, :doc:`Earthformer `, :doc:`FireCastNet `, :doc:`Logistic Regression (pixel) `, :doc:`Prithvi-EO-2.0 BurnScars `, :doc:`Prithvi-EO-2.0-TL `, :doc:`Rainformer `, :doc:`Random Forest `, :doc:`ResNet-18 U-Net `, :doc:`SegFormer `, :doc:`Swin-Unet `, :doc:`SwinLSTM `, :doc:`SwinUNETR `, :doc:`TCN `, :doc:`TrajGRU `, :doc:`TS-SatFire Baselines `, :doc:`U-Net-3D (MONAI) `, :doc:`U-TAE `, :doc:`UNETR `, :doc:`Wildfire Forecasting `, :doc:`WildfireSpreadTS Baselines `, :doc:`CNN-ASPP `, :doc:`U-Net `, :doc:`XGBoost `. Earthquake ~~~~~~~~~~ @@ -25,7 +25,7 @@ Earthquake Implemented Models ++++++++++++++++++ -:doc:`EQNet `, :doc:`EQTransformer `, :doc:`GPD `, :doc:`PhaseNet `, :doc:`WaveCastNet `. +:doc:`EQTransformer `, :doc:`GPD `, :doc:`PhaseNet `, :doc:`WaveCastNet `, :doc:`EQNet `. Flood ~~~~~ @@ -33,7 +33,12 @@ Flood Implemented Models ++++++++++++++++++ -:doc:`EA-LSTM `, :doc:`FloodCast `, :doc:`Google Flood Forecasting `, :doc:`NeuralHydrology LSTM `, :doc:`UrbanFloodCast `, :doc:`HydroGraphNet `. +:doc:`EA-LSTM `, :doc:`Google Flood Forecasting `, :doc:`HydroGraphNet `, :doc:`NeuralHydrology LSTM `, :doc:`UrbanFloodCast `. + +Experimental Adapters ++++++++++++++++++++++ + +:doc:`FloodCast `. Tropical Cyclone ~~~~~~~~~~~~~~~~ @@ -43,11 +48,6 @@ Implemented Models :doc:`Hurricast `, :doc:`SAF-Net `, :doc:`TCIF-fusion `, :doc:`Tropical Cyclone MLP `, :doc:`TropiCycloneNet `. -Experimental Adapters -+++++++++++++++++++++ - -:doc:`FourCastNet TC Adapter `, :doc:`GraphCast TC Adapter `, :doc:`Pangu TC Adapter `. - Developer Registry Workflow --------------------------- @@ -63,7 +63,7 @@ Build a Registered Model model = build_model( name="phasenet", - task="regression", + task="picking", in_channels=3, ) diff --git a/docs/source/api/pyhazards.prompted.rst b/docs/source/api/pyhazards.prompted.rst new file mode 100644 index 00000000..534b6833 --- /dev/null +++ b/docs/source/api/pyhazards.prompted.rst @@ -0,0 +1,51 @@ +pyhazards.prompted package +========================== + +Prompted multimodal-LLM baselines following SmokeBench; see :doc:`/pyhazards_prompted`. + +.. automodule:: pyhazards.prompted + :members: + :undoc-members: + :show-inheritance: + +pyhazards.prompted.prompts module +--------------------------------- + +.. automodule:: pyhazards.prompted.prompts + :members: + +pyhazards.prompted.geometry module +---------------------------------- + +.. automodule:: pyhazards.prompted.geometry + :members: + +pyhazards.prompted.parsers module +--------------------------------- + +.. automodule:: pyhazards.prompted.parsers + :members: + +pyhazards.prompted.metrics module +--------------------------------- + +.. automodule:: pyhazards.prompted.metrics + :members: + +pyhazards.prompted.runner module +-------------------------------- + +.. automodule:: pyhazards.prompted.runner + :members: + +pyhazards.prompted.backends package +----------------------------------- + +.. automodule:: pyhazards.prompted.backends.base + :members: + +.. automodule:: pyhazards.prompted.backends.hf + :members: + +.. automodule:: pyhazards.prompted.backends.api + :members: diff --git a/docs/source/api/pyhazards.rst b/docs/source/api/pyhazards.rst index 385a8563..358093eb 100644 --- a/docs/source/api/pyhazards.rst +++ b/docs/source/api/pyhazards.rst @@ -9,6 +9,9 @@ Subpackages pyhazards.datasets pyhazards.models + pyhazards.prompted + pyhazards.simulators + pyhazards.forecasts pyhazards.benchmarks pyhazards.configs pyhazards.reports diff --git a/docs/source/api/pyhazards.simulators.rst b/docs/source/api/pyhazards.simulators.rst new file mode 100644 index 00000000..c5c8a635 --- /dev/null +++ b/docs/source/api/pyhazards.simulators.rst @@ -0,0 +1,38 @@ +pyhazards.simulators package +============================ + +Adapters to external, physics-based fire simulators. ForeFire runs through +:class:`~pyhazards.simulators.ForeFireSimulator` (the official ``pyforefire``, installed +separately); WRF-SFIRE outputs are read by :mod:`pyhazards.datasets.wrf_sfire`. See +:doc:`/pyhazards_simulators`. + +Submodules +---------- + +pyhazards.simulators.forefire module +------------------------------------ + +.. automodule:: pyhazards.simulators.forefire + :members: + :show-inheritance: + +pyhazards.datasets.wrf_sfire.reader module +------------------------------------------ + +.. automodule:: pyhazards.datasets.wrf_sfire.reader + :members: + :show-inheritance: + +pyhazards.datasets.wrf_sfire.dataset module +------------------------------------------- + +.. automodule:: pyhazards.datasets.wrf_sfire.dataset + :members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: pyhazards.simulators + :members: + :show-inheritance: diff --git a/docs/source/appendix_a_coverage.rst b/docs/source/appendix_a_coverage.rst index 10610e49..e09d7f93 100644 --- a/docs/source/appendix_a_coverage.rst +++ b/docs/source/appendix_a_coverage.rst @@ -9,40 +9,61 @@ Overview This page audits the current PyHazards implementation against the planned methods, benchmarks, and datasets listed in ``pyhazard_plan.pdf``. It separates implemented public entries from variant-only entries, -experimental wrappers, and items that are still missing. +experimental wrappers, external simulators, foundation-model pipelines, and items that are still missing. Status meanings: - ``Implemented``: a public PyHazards adapter exists for the named method or resource. - ``Experimental``: a lightweight wrapper exists, but it should not be counted as stable core coverage. +- ``External simulator``: PyHazards drives the official simulator, installed separately, or reads + its outputs. Nothing of the simulator is reimplemented, and it is not counted as a model. +- ``Foundation model pipeline``: a global weather model whose hazard results come from tracking its + forecast fields. PyHazards reads published forecasts or tracks, can run the official model through a + separately installed runner, and provides the tracker and the scoring; the model itself is not + reimplemented and is not counted as a model. - ``Missing``: no aligned adapter or benchmark integration is present yet. Hazard Summary -------------- .. list-table:: - :widths: 26 18 18 18 + :widths: 22 13 13 13 13 13 13 :header-rows: 1 :class: dataset-list * - Hazard Family - Implemented + - Variant only - Experimental + - External + - Pipeline - Missing * - Earthquake - - 8 + - 4 + - 1 + - 0 - 0 - 0 + - 3 * - Wildfire - - 6 + - 4 + - 0 + - 0 + - 2 - 0 - 0 * - Flood - - 8 + - 4 - 0 + - 1 - 0 + - 0 + - 3 * - Hurricane / Tropical Cyclone - 8 + - 0 + - 0 + - 0 - 3 - 0 @@ -65,199 +86,199 @@ Method and Resource Matrix - Baseline - ``Implemented`` - :doc:`PhaseNet ` - - Model adapter is implemented, but the SeisBench / pick-benchmark data path is still missing. + - Port of the official TensorFlow U-Net (268,443 parameters); the released checkpoint 190703-214543 loads without TensorFlow and matches the official graph and SeisBench's port. Scored with the PhaseNet and EQTransformer pick metrics on real SeisBench-format / STEAD data. * - Earthquake - `EQTransformer `_ - Baseline - ``Implemented`` - :doc:`EQTransformer ` - - Model adapter is implemented, but the benchmark stack remains lighter than the PDF target. + - Port of the released Keras models (paper model 371,639 parameters, conservative 376,423) with detection, P and S outputs; both official .h5 files load and match Keras and SeisBench. * - Earthquake - `GPD `_ - Baseline - ``Implemented`` - :doc:`GPD ` - - Model adapter is implemented behind the shared picking interface. + - Port of the released Keras P/S/noise window classifier (1,741,003 parameters) and its sliding-window picker; the official weights match Keras and SeisBench and reproduce the shipped Anza picks. * - Earthquake - `EQNet `_ - Baseline - - ``Implemented`` + - ``Variant only`` - :doc:`EQNet ` - - Model adapter is implemented behind the shared picking interface. + - Rebuilt from the paper (Zhu et al. 2022, doi:10.1029/2021JB023283; 1,043,619 parameters): 1-D ResNet-18 feature extractor, P and S picking heads, shift-and-stack over candidate hypocentres and event detection, with a multi-station input (station gathers plus travel times). The official repository (non-commercial licence, no shift-and-stack, no weights) is only a test oracle: the feature extractor and both heads match the author's code; the shift-and-stack module and the end-to-end model are unverified. Its picking heads are scored on the earthquake.picking task. * - Earthquake - `SeisBench `_ - Benchmark / Data Ecosystem - ``Implemented`` - None - - A synthetic-backed SeisBench-compatible waveform adapter is registered for smoke benchmarking. + - seisbench_waveforms reads SeisBench-format datasets (and STEAD's own files) with PyHazards' own reader, checked against SeisBench's writer and reader; SeisBench itself (GPL-3.0) is only a test oracle. Datasets are downloaded by the user. * - Earthquake - `pick-benchmark `_ - Benchmark - - ``Implemented`` + - ``Missing`` - None - - A synthetic-backed pick-benchmark-compatible waveform adapter is registered for smoke benchmarking. + - Its SeisBench-format datasets can be read with seisbench_waveforms, but its three evaluation tasks (event detection AUC, phase identification MCC, onset regression on sampled windows) are not implemented; PyHazards scores pickers with the PhaseNet / EQTransformer pick metrics instead. The former synthetic pick_benchmark_waveforms adapter was removed. * - Earthquake - `pyCSEP `_ - Benchmark / Reports - - ``Implemented`` + - ``Missing`` - None - - The forecasting smoke benchmark exports a pyCSEP-style JSON artifact. + - pyCSEP tests earthquake-rate forecasts (Savran et al. 2022, doi:10.1785/0220220033); PyHazards has no rate-forecasting task. The former 'pyCSEP-style' JSON export of the wavefield-forecasting benchmark was only a metrics dump and was removed. * - Earthquake - `AEFA `_ - Dataset / Forecast Benchmark - - ``Implemented`` + - ``Missing`` - None - - A synthetic-backed AEFA-style forecasting dataset adapter is registered. + - AEFA is a weekly earthquake-occurrence forecasting dataset with electromagnetic / geoacoustic features (Chen et al. 2025, doi:10.1016/j.geoai.2025.100022; README states GPL-3.0). No loader exists; the former aefa_forecast adapter generated synthetic wavefields (now earthquake_wavefield_synthetic, used by WaveCastNet's wavefield-forecasting task) and was removed. * - Wildfire - `wildfire_forecasting `_ - Baseline - ``Implemented`` - :doc:`Wildfire Forecasting ` - - + - The paper's LSTM (default) and ConvLSTM are ported and checked against the official code; the Greek datacube is not loaded yet (synthetic smoke data). The paper's random forest (random_forest, checked against the official notebook) and XGBoost (xgboost, hyperparameters pending the paper's Supporting Information) are separate entries. * - Wildfire - `WildfireSpreadTS `_ - Baseline / Benchmark - ``Implemented`` - - :doc:`WildfireSpreadTS ` + - :doc:`WildfireSpreadTS Baselines ` - * - Wildfire - `ASUFM `_ - Baseline - ``Implemented`` - :doc:`ASUFM ` - - + - Next-day fire-mask segmentation on 64x64 NDWS tiles, verified against the official code; the smoke benchmark runs it on synthetic 64x64 spread rasters because no NDWS loader exists yet. * - Wildfire - `WRF-SFIRE `_ - - Simulator Adapter - - ``Implemented`` - - :doc:`WRF-SFIRE Adapter ` - - The current adapter is lightweight and synthetic-backed rather than a full external simulator binding. + - Simulator Output Reader + - ``External simulator`` + - :doc:`WRF-SFIRE Outputs `, :doc:`Simulators ` + - PyHazards does not run WRF-SFIRE (an MPI Fortran model). The ``wrf_sfire_spread`` dataset reads the fire grid (TIGN_G, LFN, FIRE_AREA, FGRNHFX, ROS, ...) of wrfout files written by the official model into spread rasters. Variable names and layout follow the official Registry and were checked on a real output of the official hill ideal case. * - Wildfire - `ForeFire `_ - Simulator Adapter - - ``Implemented`` - - :doc:`ForeFire Adapter ` - - The current adapter is lightweight and synthetic-backed rather than a full external simulator binding. + - ``External simulator`` + - :doc:`Simulators ` + - ForeFireSimulator runs the official ForeFire engine (GPL-3.0; installed separately with ``pip install forefire``, never vendored) on PyHazards rasters and returns arrival-time and burned-mask rasters. It reproduces ForeFire's own regression reference (tests/runff) and the official idealized-wind example. It is a physics simulator, not a trainable model. * - Wildfire - `FireCastNet `_ - Optional Baseline - ``Implemented`` - :doc:`FireCastNet ` - - + - Pure PyTorch port of the official model; the released SeasFire checkpoints load and match the official DGL implementation. SeasFire datacube backing is still missing. * - Flood - `NeuralHydrology `_ - Baseline Family - ``Implemented`` - :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM ` - - The LSTM and EA-LSTM adapters are implemented, but Caravan / WaterBench benchmark backing is still missing. + - Ports of NeuralHydrology's CudaLSTM and EA-LSTM at the Kratzert et al. (2019) configuration, checked against NeuralHydrology and the official 2019 checkpoints; CAMELS-US and Caravan readers and the per-basin NSE / KGE evaluation are checked against NeuralHydrology's datasets and Tester. * - Flood - `Caravan `_ - Dataset - ``Implemented`` - - None - - A synthetic-backed Caravan adapter is registered for streamflow smoke benchmarking. + - :doc:`Caravan ` + - ``caravan_streamflow`` reads a local copy of the official release (netCDF or CSV) into NeuralHydrology-style samples; checked against NeuralHydrology's reader on real Caravan files. * - Flood - `WaterBench `_ - Dataset - - ``Implemented`` + - ``Missing`` - None - - A synthetic-backed WaterBench adapter is registered for streamflow smoke benchmarking. + - No reader. The former ``waterbench_streamflow`` adapter generated random numbers and was removed. * - Flood - `FloodCast `_ - Baseline - - ``Implemented`` + - ``Experimental`` - :doc:`FloodCast ` - - The model adapter is implemented, but FloodCastBench-backed evaluation is not wired yet. + - The model under this name is a small CNN, not FloodCast (Xu et al. 2024, doi:10.1016/j.watres.2024.122162). The flood model (sequence-to-sequence GeoPINS, a physics-informed space-time Fourier operator) was never released, and the paper does not report its channel widths, so it cannot be rebuilt faithfully; the repository has no licence. * - Flood - `FloodCastBench `_ - Benchmark - - ``Implemented`` + - ``Missing`` - None - - A synthetic-backed FloodCastBench-style inundation adapter is registered. + - No reader for the 21.6 GB release (Zenodo 10.5281/zenodo.14017092); the former ``floodcastbench_inundation`` adapter generated random numbers and was removed. Its FNO / FNO+ baselines (4 layers, 12 modes, width 20) are not provided: only the data-generation code was released (no licence), so there is no model code to check a port against. The ``flood.inundation`` metrics (RMSE, NSE, Pearson r, CSI) cover its scores. * - Flood - `UrbanFloodCast `_ - Baseline - ``Implemented`` - :doc:`UrbanFloodCast ` - - The model adapter is implemented on synthetic inundation fixtures today. + - The deep neural operator (DNO-3, 4,470,437 parameters, 24 steps at once) written from the paper with U-NO (BSD-2) and FNO (MIT) blocks, since the official code has no licence; parameters, seeded initialisation, outputs, the one-shot input pipeline and the evaluation metrics match the official code. The Berlin GeoTIFFs (Zenodo 10.5281/zenodo.15700880) have no reader yet (urbanfloodcast_synthetic in their layout). * - Flood - `HydroBench `_ - Benchmark / Diagnostics - - ``Implemented`` + - ``Missing`` - None - - A synthetic-backed HydroBench adapter is registered for streamflow smoke benchmarking. + - No integration. The former ``hydrobench_streamflow`` adapter generated random numbers and was removed; the flood benchmark computes NeuralHydrology's hydrograph metrics instead. * - Flood - `google-research/flood-forecasting `_ - Reference Baseline - ``Implemented`` - :doc:`Google Flood Forecasting ` - - + - Port of the released FloodHub model (MeanEmbeddingForecastLSTM, Gauch et al. 2025); the released weights load and match googlehydrology. Caravan MultiMet forecast inputs are not read yet. * - Hurricane / Tropical Cyclone - `Hurricast `_ - Baseline - ``Implemented`` - :doc:`Hurricast ` - - The model adapter is implemented, but the real TCBench / IBTrACS data path is still missing. + - Written from the paper (the official code has no licence): the CNN + Transformer encoder-decoder matches the official network for every released preset (seeded weights, outputs, gradients) and XGBoost runs on its embeddings with the official defaults; hurricast_ibtracs_era5 reads IBTrACS and ERA5. The paper's GRU decoder is not in the released code; no weights were released. * - Hurricane / Tropical Cyclone - `tropicalcyclone_MLP `_ - Baseline - ``Implemented`` - :doc:`Tropical Cyclone MLP ` - - The model adapter is implemented as a basin-filtered storm baseline. + - The official 24-hour intensity-change MLP (121 SHIPS predictors, BSD-2) is ported and matches the official Keras model; ships_xu2021 reads the authors' predictor table (Zenodo 4784610) with the official leave-one-year-out folds. No trained weights were released. * - Hurricane / Tropical Cyclone - `TCIF-fusion `_ - Baseline - ``Implemented`` - :doc:`TCIF-fusion ` - - The model adapter is implemented behind the shared storm evaluator. + - Written from the paper and the notebook (no licence); the notebook graph rebuilt in Keras 3 gives the same outputs with copied weights and the authors' printed layer counts (299.6 M parameters). The ALL input has the paper's 65 channels (notebook: 85). The CMA / ERA5 / GridSat-B1 inputs have no reader yet (synthetic layout only). * - Hurricane / Tropical Cyclone - `SAF-Net `_ - Baseline - ``Implemented`` - :doc:`SAF-Net ` - - The model adapter is implemented behind the shared storm evaluator. + - Written from the paper (the official code has no licence); the released checkpoint loads strictly and matches the official notebook network. The CMA / ERA-Interim inputs have no PyHazards reader yet (synthetic layout only). * - Hurricane / Tropical Cyclone - `TropiCycloneNet `_ - Baseline - ``Implemented`` - :doc:`TropiCycloneNet ` - - The model adapter is implemented, but the public benchmark/data track remains synthetic-first. + - The six-generator GAN (CC BY 4.0 release) is ported; the released checkpoint loads strictly and matches the official code. The benchmark reports the paper's best-of-6 errors next to sample-mean errors. * - Hurricane / Tropical Cyclone - `TropiCycloneNet-Dataset `_ - Dataset - ``Implemented`` - - None - - A synthetic-backed TropiCycloneNet-Dataset adapter is registered. + - :doc:`TropiCycloneNet Dataset ` + - tropicyclonenet_dataset reads TCND Data1d, Env-Data and 500 hPa GPH files (Zenodo, CC BY 4.0) exactly like the official TropiCycloneNet loader; tropicyclonenet_dataset_synthetic is a random stand-in for smoke tests. * - Hurricane / Tropical Cyclone - `TCBench Alpha `_ - Benchmark - ``Implemented`` - - None - - A synthetic-backed TCBench Alpha adapter is registered. + - :doc:`TCBench Alpha `, :doc:`Foundation Weather Models ` + - pyhazards.forecasts reads TCBench's released tracks and raw forecast fields (Hugging Face, pinned revision), re-implements its TempestExtremes tracking (identical tracks) and HuracanPy matching, and scores direct position error and intensity errors exactly as its evaluation does (the DPE values printed in its notebook are reproduced; one only with the IBTrACS position TCBench used, since revised by NCEI). CRPS, along/cross-track errors, rapid-intensification scores and its post-processing models are not implemented. * - Hurricane / Tropical Cyclone - `IBTrACS `_ - Dataset - ``Implemented`` - - None - - A synthetic-backed IBTrACS adapter is registered. + - :doc:`IBTrACS ` + - ibtracs_tracks reads NOAA NCEI IBTrACS v04 CSV or netCDF files (best-track positions, intensities, agency columns) into forecast windows; the cyclone benchmark scores great-circle track error in km and intensity errors per lead time. * - Hurricane / Tropical Cyclone - - `GraphCast / GenCast `_ - - Foundation Adapter - - ``Experimental`` - - :doc:`GraphCast TC Adapter ` - - The current wrapper is intentionally lightweight and should not be counted as stable core coverage. + - `GraphCast `_ + - Foundation Model Pipeline + - ``Foundation model pipeline`` + - :doc:`Foundation Weather Models ` + - Not reimplemented: GraphCast (36.3M parameters, JAX) is a global weather model whose cyclone tracks come from a tracker run on its forecasts. PyHazards reads WeatherBench 2's GraphCast forecasts (2018 from the 1979-2017 model, 2020), can run it through earth2studio (user-installed; weights CC BY 4.0 per the README since 2026-08-06), tracks with a re-implementation of the paper's modified ECMWF tracker (the tracker was never released) and scores against IBTrACS. The paper's Fig. 3 numbers are not reproduced. GenCast is a different model and is not covered. * - Hurricane / Tropical Cyclone - `Pangu-Weather `_ - - Foundation Adapter - - ``Experimental`` - - :doc:`Pangu TC Adapter ` - - The current wrapper is intentionally lightweight and should not be counted as stable core coverage. + - Foundation Model Pipeline + - ``Foundation model pipeline`` + - :doc:`Foundation Weather Models ` + - Not reimplemented: PyHazards reads TCBench's released 2023 Pangu-Weather tracks and fields and WeatherBench 2's 2018-2022 forecasts, can run the official ONNX graphs through earth2studio, and tracks with the paper's ECMWF-style rules or TCBench's TempestExtremes rules. TCBench's released tracks are reproduced byte for byte from the raw fields, and its published DPE values exactly. The TC2018 numbers (120.29 / 195.65 km) are not reproduced. Weights CC BY-NC-SA 4.0 (non-commercial); the official repository has no code licence. * - Hurricane / Tropical Cyclone - `FourCastNet `_ - - Foundation Adapter - - ``Experimental`` - - :doc:`FourCastNet TC Adapter ` - - The current wrapper is intentionally lightweight and should not be counted as stable core coverage. + - Foundation Model Pipeline + - ``Foundation model pipeline`` + - :doc:`Foundation Weather Models ` + - Not reimplemented: FourCastNet (74.7M-parameter AFNO) can be run through earth2studio (FCN, a 26-variable retrain) and its fields tracked and scored. The paper has only a qualitative cyclone case. TCBench's 'FourCastNet v2' tracks and fields (SFNO small, a different model) can be read and scored. Current Public Non-Core Implementations --------------------------------------- @@ -278,25 +299,21 @@ part of the current core method set. - ``variant`` - :doc:`CNN-ASPP ` - Implemented outside the current core method set and kept public as an additional model. - * - Earthquake + * - Wildfire - ``variant`` - - :doc:`WaveCastNet ` + - :doc:`U-Net ` - Implemented outside the current core method set and kept public as an additional model. - * - Flood + * - Wildfire - ``variant`` - - :doc:`HydroGraphNet ` + - :doc:`XGBoost ` - Implemented outside the current core method set and kept public as an additional model. - * - Tropical Cyclone - - ``experimental`` - - :doc:`FourCastNet TC Adapter ` - - Wrapper-style experimental adapter pending stronger benchmark and dataset support. - * - Tropical Cyclone - - ``experimental`` - - :doc:`GraphCast TC Adapter ` - - Wrapper-style experimental adapter pending stronger benchmark and dataset support. - * - Tropical Cyclone + * - Earthquake + - ``variant`` + - :doc:`EQNet ` + - Planned method rebuilt from its paper; only the parts covered by a reference implementation are verified against code (see its Reproduction section). + * - Flood - ``experimental`` - - :doc:`Pangu TC Adapter ` + - :doc:`FloodCast ` - Wrapper-style experimental adapter pending stronger benchmark and dataset support. Execution Note diff --git a/docs/source/benchmarks/aefa.rst b/docs/source/benchmarks/aefa.rst deleted file mode 100644 index 725ed707..00000000 --- a/docs/source/benchmarks/aefa.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. - -AEFA -==== - -Overview --------- - -The AEFA alignment is implemented as a synthetic-backed dense-grid forecasting adapter used by the WaveCastNet benchmark config. - -It keeps the forecasting task and metric shape aligned without claiming a full AEFA data pipeline. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Kind - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Ecosystem - - .. container:: catalog-stat-note - - Family benchmark or external ecosystem view. - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Earthquake - - .. container:: catalog-stat-note - - Public hazard grouping used on the benchmark index page. - - .. grid-item-card:: Support Status - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :bdg-info:`Synthetic-backed` - - .. container:: catalog-stat-note - - Current maturity of the adapter or evaluator path. - - .. grid-item-card:: Linked Models - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - 1 model - - -Benchmark Mapping ------------------ - -**Shared benchmark key:** ``earthquake`` - -**Registered class:** ``EarthquakeBenchmark`` - -Mapped benchmark family -~~~~~~~~~~~~~~~~~~~~~~~ - -:doc:`Earthquake Benchmark ` - -Primary Source -~~~~~~~~~~~~~~ - -`AEFA `_. - -.. dropdown:: Supported Tasks - :class-container: catalog-dropdown - - - Wavefield Forecasting - -.. dropdown:: Key Metrics - :class-container: catalog-dropdown - - - ``mae`` - - ``mse`` - -.. dropdown:: Smoke Configs - :class-container: catalog-dropdown - - - ``wavecastnet_benchmark_smoke.yaml`` - -.. dropdown:: Linked Models - :class-container: catalog-dropdown - - :doc:`WaveCastNet `. diff --git a/docs/source/benchmarks/waterbench.rst b/docs/source/benchmarks/camels_us.rst similarity index 52% rename from docs/source/benchmarks/waterbench.rst rename to docs/source/benchmarks/camels_us.rst index 73c5ca68..87854871 100644 --- a/docs/source/benchmarks/waterbench.rst +++ b/docs/source/benchmarks/camels_us.rst @@ -1,14 +1,14 @@ .. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. -WaterBench -========== +CAMELS-US +========= Overview -------- -The current WaterBench alignment uses a metadata-only adapter over the shared synthetic streamflow bundle and preserves the streamflow task contract. +``camels_us_streamflow`` reads a local CAMELS-US copy with the paper's defaults (forcings, the 27 attributes, 270-day windows, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30). The ``flood.streamflow`` evaluator reports the median and mean NSE over basins and the number of basins with NSE <= 0, as in Table 2 of the paper, plus KGE, alpha-NSE, beta-NSE, FHV, FMS and FLV. -It is currently exercised by the EA-LSTM smoke benchmark path. +Applied to the official stored simulations of the 2019 runs, the PyHazards metrics give the paper's Table 2 values (e.g. EA-LSTM NSE* median 0.71 single / 0.74 ensemble; LSTM with static inputs 0.73 / 0.76). The smoke configs exercise the contract on synthetic basins. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 1 + 2 .. container:: catalog-stat-note - 1 model + 2 models Benchmark Mapping @@ -77,7 +77,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting `_ (`repo `__). +`Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,17 +87,27 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``mae`` - - ``rmse`` - ``nse`` - - ``kge`` + - ``nse_mean`` + - ``n_basins_nse_le_0`` + - ``alpha_nse`` + - ``beta_nse`` + - ``fhv`` + - ``fms`` + - ``flv`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown + - ``neuralhydrology_lstm_smoke.yaml`` - ``neuralhydrology_ealstm_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`EA-LSTM `. + :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - Dataset: Addor et al. (HESS 2017), CC BY 4.0; extended Maurer forcings on HydroShare (doi 10.4211/hs.17c896843cf940339c3c3496d0c1c077). PyHazards downloads nothing. diff --git a/docs/source/benchmarks/caravan.rst b/docs/source/benchmarks/caravan.rst index 291aecb3..010fa1f2 100644 --- a/docs/source/benchmarks/caravan.rst +++ b/docs/source/benchmarks/caravan.rst @@ -6,9 +6,9 @@ Caravan Overview -------- -The current Caravan alignment is a metadata-backed streamflow adapter layered on top of the shared synthetic graph-temporal flood dataset. +``caravan_streamflow`` reads the official Caravan layout (per-basin netCDF or CSV time series and attribute CSVs) into NeuralHydrology-style samples; the ``flood.streamflow`` evaluator then reports per-basin NSE, KGE and the other NeuralHydrology metrics, summarised by the median and mean over basins. -It currently drives the public smoke runs for NeuralHydrology LSTM and Google Flood Forecasting. +Caravan has no fixed benchmark split: choose inputs, basins and periods for the experiment. Google's FloodHub model was trained on Caravan with the MultiMet forecast products (not read by PyHazards). The smoke configs exercise the same contract on synthetic basins. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 2 + 3 .. container:: catalog-stat-note - 2 models + 3 models Benchmark Mapping @@ -77,7 +77,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`Caravan - A global community dataset for large-sample hydrology `_ (`repo `__). +`Caravan - A global community dataset for large-sample hydrology `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,10 +87,9 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``mae`` - - ``rmse`` - ``nse`` - ``kge`` + - ``nse_mean`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown @@ -101,4 +100,9 @@ Primary Source .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`NeuralHydrology LSTM `, :doc:`Google Flood Forecasting `. + :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM `, :doc:`Google Flood Forecasting `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - The reader is checked against NeuralHydrology's Caravan dataset on real Caravan basin files. diff --git a/docs/source/benchmarks/earthquake_benchmark.rst b/docs/source/benchmarks/earthquake_benchmark.rst index c1beb12f..58b60226 100644 --- a/docs/source/benchmarks/earthquake_benchmark.rst +++ b/docs/source/benchmarks/earthquake_benchmark.rst @@ -6,9 +6,11 @@ Earthquake Benchmark Overview -------- -The earthquake benchmark family groups the picking and forecasting paths under one registered evaluator and benchmark runner entrypoint. +``earthquake.picking`` takes three-component windows ``(n, 3, samples)`` and arrival targets ``(n, 2)`` (P, S samples; NaN = none). Each model's own pipeline turns waveforms into picks (``annotate`` = official normalisation + forward; ``extract_picks`` = official post-processing: PhaseNet peaks above 0.5, EQTransformer's detection-and-picking rule, GPD's sliding-window triggers). Picks are matched to the manual arrivals per phase: precision, recall and F1 within a tolerance window and residual mean, standard deviation and MAE in seconds, with ``protocol=phasenet`` (Zhu & Beroza 2019: TP if |dt| < 0.1 s, residual statistics over |dt| < 0.5 s) or ``protocol=eqtransformer`` (Mousavi et al. 2020: TP if |dt| < 0.5 s). Models with a detection output also get trace-level detection precision, recall and F1. -Current public coverage is synthetic-backed but already exposes the same task and report shape used across the earthquake smoke configs. +Real data comes from ``seisbench_waveforms`` (SeisBench-format datasets and STEAD's own files); the smoke configs run on ``earthquake_waveforms_synthetic``. EQNet is scored here through its single-station picking heads (the paper's STEAD evaluation); its multi-station event detection has no benchmark task yet. + +``earthquake.forecasting`` takes velocity wavefields ``(n, 3, T_in, H, W)`` and future frames ``(n, 3, T_out, H, W)``. Models with ``rollout`` (WaveCastNet) forecast ``T_out`` frames by repeated calls on their own output, as the official validation does, in evaluation mode with a seeded generator for the decoder noise (param ``seed``). Metrics follow WaveCastNet's ``Validation_pixel.py`` (equations 17-18 of Lyu et al. 2025): ACC, RFNE and RMSE per (sequence, channel) over time and space, averaged over all pairs (``acc``, ``rfne``, ``rmse``) and per channel (``acc_x`` ... ``rfne_z``), plus MAE and MSE. It runs on ``earthquake_wavefield_synthetic`` only (synthetic point sources): the paper's SW4 simulations (tens of GB) have no reader yet. This task is not earthquake-occurrence forecasting (AEFA, pyCSEP are not implemented). At a Glance ----------- @@ -44,7 +46,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -72,7 +74,7 @@ Benchmark Mapping Mapped benchmark ecosystems ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:doc:`AEFA `, :doc:`pick-benchmark `, :doc:`pyCSEP `, :doc:`SeisBench `. +:doc:`pick-benchmark `, :doc:`SeisBench `. .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -83,11 +85,30 @@ Mapped benchmark ecosystems .. dropdown:: Key Metrics :class-container: catalog-dropdown + - ``p_precision`` + - ``p_recall`` + - ``p_f1`` + - ``p_residual_mean`` + - ``p_residual_std`` - ``p_pick_mae`` + - ``s_precision`` + - ``s_recall`` + - ``s_f1`` + - ``s_residual_mean`` + - ``s_residual_std`` - ``s_pick_mae`` - - ``precision`` - - ``recall`` - - ``f1`` + - ``detection_precision`` + - ``detection_recall`` + - ``detection_f1`` + - ``acc`` + - ``rfne`` + - ``rmse`` + - ``acc_x`` + - ``acc_y`` + - ``acc_z`` + - ``rfne_x`` + - ``rfne_y`` + - ``rfne_z`` - ``mae`` - ``mse`` @@ -108,4 +129,7 @@ Mapped benchmark ecosystems .. dropdown:: Notes :class-container: catalog-dropdown - - Forecasting runs export a pyCSEP-style report artifact through the shared earthquake benchmark. + - Before this release the picking evaluator reported one hit rate (both regressed picks within 8 samples) as precision, recall and F1 alike; those numbers are not comparable with the new ones. + - EQTransformer's MAPE is not computed: the paper does not define its denominator. + - Smoke configs use randomly initialised models on synthetic data; pass ``pretrained`` in the model params and a real dataset for meaningful numbers. + - Before this release ``earthquake.forecasting`` reported only MAE / MSE of a single forward pass on moving Gaussian blobs (``earthquake_forecast_synthetic``); the ACC / RFNE numbers are new. diff --git a/docs/source/benchmarks/flood_benchmark.rst b/docs/source/benchmarks/flood_benchmark.rst index f21f03a3..3ca051df 100644 --- a/docs/source/benchmarks/flood_benchmark.rst +++ b/docs/source/benchmarks/flood_benchmark.rst @@ -6,9 +6,11 @@ Flood Benchmark Overview -------- -The flood benchmark family keeps streamflow and inundation scoring under one shared evaluator contract while preserving hazard-task-specific metrics. +``flood.streamflow`` follows Kratzert et al. (HESS 2019) and NeuralHydrology: each model predicts the discharge of every day of the evaluation period from the preceding window of daily forcings and the basin's static attributes; predictions go back to mm/day with the training scaler, negative values are set to zero, and NeuralHydrology's metrics (NSE, MSE, RMSE, KGE, alpha-NSE, beta-KGE, beta-NSE, Pearson r, FHV, FMS, FLV, peak timing, missed peaks, peak MAPE) are computed per basin over the period. Reported values are the median over basins (``nse``, ``kge``, ...), the mean over basins (``nse_mean``, ...), ``n_basins`` and ``n_basins_nse_le_0``; per-basin values are in the report metadata. Probabilistic models are scored by their mixture mean. -Current public coverage is synthetic-backed, but the same family already drives the streamflow and inundation smoke configs used across the flood models. +Real streamflow data come from ``camels_us_streamflow`` and ``caravan_streamflow`` (local copies of the official releases); the smoke configs run the same contract on ``flood_streamflow_synthetic``. + +``flood.inundation`` scores water depth. Rasters: the model maps the split inputs to depth ``(batch, 1, H, W)`` or to several variables channels-last (UrbanFloodCast: depth and x / y unit discharge for 24 steps, with a NaN mask). Meshes: each test hydrograph of ``hydrographnet_white_river`` is rolled out with the model's ``rollout`` method as in the HydroGraphNet example, and depths are scored in metres (``rollout_rmse``: depth RMSE per step averaged over steps and hydrographs). Reported: ``pixel_mae`` / ``rmse`` (depth errors over all cells), ``iou`` / ``f1`` (prediction >= 0.5 m against depth > 0), and, averaged over events / hydrographs as the UrbanFloodCast test loop does, depth CSI at 1 / 10 / 50 cm (``csi_1cm``, ``csi_10cm``, ``csi_50cm``) and the relative L2 error, NSE and Pearson r over all predicted variables. Real mesh data: ``hydrographnet_white_river``; the UrbanFloodCast and FloodCastBench rasters have no reader yet. At a Glance ----------- @@ -44,7 +46,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -72,7 +74,7 @@ Benchmark Mapping Mapped benchmark ecosystems ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:doc:`Caravan `, :doc:`FloodCastBench `, :doc:`HydroBench `, :doc:`WaterBench `. +:doc:`CAMELS-US `, :doc:`Caravan `, :doc:`HydroGraphNet White River `. .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -83,25 +85,41 @@ Mapped benchmark ecosystems .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``mae`` - - ``rmse`` - ``nse`` - ``kge`` + - ``alpha_nse`` + - ``beta_nse`` + - ``fhv`` + - ``fms`` + - ``flv`` + - ``nse_mean`` + - ``n_basins_nse_le_0`` - ``pixel_mae`` + - ``rmse`` - ``iou`` - ``f1`` + - ``csi_10cm`` + - ``relative_l2`` + - ``rollout_rmse`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - - ``hydrographnet_smoke.yaml`` - ``neuralhydrology_lstm_smoke.yaml`` - ``neuralhydrology_ealstm_smoke.yaml`` - ``google_flood_forecasting_smoke.yaml`` + - ``hydrographnet_smoke.yaml`` - ``floodcast_smoke.yaml`` - ``urbanfloodcast_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`HydroGraphNet `, :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM `, :doc:`Google Flood Forecasting `, :doc:`FloodCast `, :doc:`UrbanFloodCast `. + :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM `, :doc:`Google Flood Forecasting `, :doc:`HydroGraphNet `, :doc:`FloodCast `, :doc:`UrbanFloodCast `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - The streamflow evaluation (reader, normalisation, rescaling, clipping and per-basin metrics) is checked against NeuralHydrology's Tester on real CAMELS-US basins, and the metric code reproduces Table 2 of Kratzert et al. (2019) from the official stored simulations. + - hydrographnet (PhysicsNeMo's MeshGraphKAN) and urbanfloodcast (the UrbanFloodCast DNO) match their official code; the inundation metrics, the HydroGraphNet rollout and both input pipelines are checked against the official evaluation code (oracle tests). floodcast is still an experimental stand-in: the published flood model was never released and the paper does not give its widths. + - WaterBench, HydroBench and FloodCastBench have no PyHazards reader; the former adapters with these names generated random numbers and were removed. diff --git a/docs/source/benchmarks/floodcastbench.rst b/docs/source/benchmarks/floodcastbench.rst deleted file mode 100644 index 70297a31..00000000 --- a/docs/source/benchmarks/floodcastbench.rst +++ /dev/null @@ -1,103 +0,0 @@ -.. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. - -FloodCastBench -============== - -Overview --------- - -The current FloodCastBench alignment is implemented as a synthetic raster inundation adapter used by the public inundation smoke configs. - -It documents the benchmark/data protocol behind the FloodCast and UrbanFloodCast smoke paths. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Kind - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Ecosystem - - .. container:: catalog-stat-note - - Family benchmark or external ecosystem view. - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Flood - - .. container:: catalog-stat-note - - Public hazard grouping used on the benchmark index page. - - .. grid-item-card:: Support Status - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :bdg-info:`Synthetic-backed` - - .. container:: catalog-stat-note - - Current maturity of the adapter or evaluator path. - - .. grid-item-card:: Linked Models - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 2 - - .. container:: catalog-stat-note - - 2 models - - -Benchmark Mapping ------------------ - -**Shared benchmark key:** ``flood`` - -**Registered class:** ``FloodBenchmark`` - -Mapped benchmark family -~~~~~~~~~~~~~~~~~~~~~~~ - -:doc:`Flood Benchmark ` - -Primary Source -~~~~~~~~~~~~~~ - -`FloodCastBench `_. - -.. dropdown:: Supported Tasks - :class-container: catalog-dropdown - - - Inundation - -.. dropdown:: Key Metrics - :class-container: catalog-dropdown - - - ``pixel_mae`` - - ``iou`` - - ``f1`` - -.. dropdown:: Smoke Configs - :class-container: catalog-dropdown - - - ``floodcast_smoke.yaml`` - - ``urbanfloodcast_smoke.yaml`` - -.. dropdown:: Linked Models - :class-container: catalog-dropdown - - :doc:`FloodCast `, :doc:`UrbanFloodCast `. diff --git a/docs/source/benchmarks/hydrobench.rst b/docs/source/benchmarks/hydrographnet_white_river.rst similarity index 58% rename from docs/source/benchmarks/hydrobench.rst rename to docs/source/benchmarks/hydrographnet_white_river.rst index 7e4213b7..1fb15e89 100644 --- a/docs/source/benchmarks/hydrobench.rst +++ b/docs/source/benchmarks/hydrographnet_white_river.rst @@ -1,14 +1,14 @@ .. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. -HydroBench -========== +HydroGraphNet White River +========================= Overview -------- -The current HydroBench alignment uses a metadata-backed streamflow adapter over the shared synthetic flood streamflow dataset. +``hydrographnet_white_river`` reads a local copy of the release exactly like PhysicsNeMo's ``HydroGraphDataset``. The ``flood.inundation`` evaluator rolls every test hydrograph out for 30 steps (10 hours) with the model's ``rollout`` method, as the HydroGraphNet example's inference script does, and reports ``rollout_rmse`` (depth RMSE per step, averaged over steps and hydrographs, in metres; the per-step curve is in the report metadata), depth MAE / RMSE, CSI and NSE. -It is currently exercised through the HydroGraphNet smoke benchmark path. +The release has no official test split, and the paper's numbers could not be accessed, so no paper result is reproduced. The smoke config runs the contract on ``flood_mesh_synthetic``. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -77,20 +77,21 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`HydroBench `_. +`Interpretable physics-informed graph neural networks for flood forecasting `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown - - Streamflow + - Inundation .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``mae`` + - ``rollout_rmse`` + - ``pixel_mae`` - ``rmse`` + - ``csi_10cm`` - ``nse`` - - ``kge`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown @@ -101,3 +102,8 @@ Primary Source :class-container: catalog-dropdown :doc:`HydroGraphNet `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - Dataset: Zenodo 14969507 (HydroGraphNet.zip, 8.3 GB, CC BY 4.0). PyHazards downloads nothing. diff --git a/docs/source/benchmarks/ibtracs.rst b/docs/source/benchmarks/ibtracs.rst index 0279ab5d..18a04191 100644 --- a/docs/source/benchmarks/ibtracs.rst +++ b/docs/source/benchmarks/ibtracs.rst @@ -6,9 +6,9 @@ IBTrACS Overview -------- -The current IBTrACS alignment uses a metadata-backed storm-history adapter over the shared synthetic tropical-cyclone dataset. +``ibtracs_tracks`` reads IBTrACS v04 CSV or netCDF files with PyHazards' reader and builds forecasting windows (history of six-hourly observations, targets at the requested lead times) for any agency's winds and pressures. -It is the benchmark ecosystem currently used by Hurricast and the experimental weather-model adapter smoke configs. +``hurricast_ibtracs_era5`` builds Hurricast's inputs from IBTrACS (30 statistical features per 3-hour step) and ERA5 maps, with the IBTrACS wind 24 h ahead or position 24 h ahead as targets. The weather-model cyclone pipelines (forecast fields, tracker, scoring against IBTrACS) are pending. IBTrACS is also the reference of the weather-model cyclone pipelines in ``pyhazards.forecasts``: forecast tracks of FourCastNet, GraphCast and Pangu-Weather (tracked in their forecast fields) are matched to IBTrACS storms and scored by great-circle track error and intensity errors per lead time. No ported neural network consumes IBTrACS directly yet (Hurricast, which uses IBTrACS with ERA5, is pending). At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 4 + 1 .. container:: catalog-stat-note - 4 models + 1 model Benchmark Mapping @@ -83,22 +83,20 @@ Primary Source :class-container: catalog-dropdown - Track + Intensity + - Intensity .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``track_error`` + - ``track_error_km`` - ``intensity_mae`` + - ``pressure_mae`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - - ``hurricast_smoke.yaml`` - - ``graphcast_tc_smoke.yaml`` - - ``pangu_tc_smoke.yaml`` - - ``fourcastnet_tc_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`Hurricast `, :doc:`GraphCast TC Adapter `, :doc:`Pangu TC Adapter `, :doc:`FourCastNet TC Adapter `. + :doc:`Hurricast `. diff --git a/docs/source/benchmarks/pick_benchmark.rst b/docs/source/benchmarks/pick_benchmark.rst index bf9da111..00cd5562 100644 --- a/docs/source/benchmarks/pick_benchmark.rst +++ b/docs/source/benchmarks/pick_benchmark.rst @@ -6,9 +6,9 @@ pick-benchmark Overview -------- -The current pick-benchmark path reuses the synthetic waveform picking bundle and tags it as a pick-benchmark-style benchmark adapter. +pick-benchmark compares deep-learning pickers on eight SeisBench datasets with three tasks: event detection (ROC-AUC), phase identification (Matthews correlation) and onset-time regression (residual distributions), on windows cut around the picks. PyHazards scores pickers with the pick metrics of the PhaseNet and EQTransformer papers instead; pick-benchmark's tasks, window sampling and MCC / AUC metrics are not reproduced. -It supports the earthquake picking smoke path for the transformer and CNN picking baselines. +Its numbers for PhaseNet were obtained with SeisBench's pre-0.3 PhaseNet (23,305 parameters), not the original architecture that PyHazards ports. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-warning:`Experimental` .. container:: catalog-stat-note @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 2 + 3 .. container:: catalog-stat-note - 2 models + 3 models Benchmark Mapping @@ -77,7 +77,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`pick-benchmark `_. +`Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers (Münchmeyer et al., J. Geophys. Res. Solid Earth 127, e2021JB023499, 2022) `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,11 +87,8 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``p_pick_mae`` - - ``s_pick_mae`` - - ``precision`` - - ``recall`` - - ``f1`` + - ``p_f1`` + - ``s_f1`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown @@ -102,4 +99,9 @@ Primary Source .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`EQTransformer `, :doc:`GPD `. + :doc:`PhaseNet `, :doc:`EQTransformer `, :doc:`GPD `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - pick-benchmark is GPL-3.0; it is not vendored or imported. diff --git a/docs/source/benchmarks/seisbench.rst b/docs/source/benchmarks/seisbench.rst index 9fc1ba8e..53b65bba 100644 --- a/docs/source/benchmarks/seisbench.rst +++ b/docs/source/benchmarks/seisbench.rst @@ -6,9 +6,9 @@ SeisBench Overview -------- -The current SeisBench path uses a synthetic waveform adapter that preserves the same picking task shape expected by the shared earthquake benchmark. +SeisBench (Woollam et al. 2022) distributes seismic machine-learning benchmark datasets in a common format (metadata CSV + waveform HDF5). PyHazards reads that format without importing SeisBench, whose GPL-3.0 code is used only as a test oracle (the reader, and the PhaseNet, EQTransformer and GPD ports, are compared with SeisBench in ``tests/oracle``). -It exists today as a benchmark-compatible smoke path rather than a full external SeisBench ingestion pipeline. +The datasets are not redistributed; download them with SeisBench or from their providers. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 2 + 3 .. container:: catalog-stat-note - 2 models + 3 models Benchmark Mapping @@ -77,7 +77,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`SeisBench - A Toolbox for Machine Learning in Seismology `_ (`repo `__). +`SeisBench - A Toolbox for Machine Learning in Seismology (Woollam et al., Seismological Research Letters 93(3):1695-1709, 2022) `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,19 +87,27 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown + - ``p_precision`` + - ``p_recall`` + - ``p_f1`` - ``p_pick_mae`` + - ``s_precision`` + - ``s_recall`` + - ``s_f1`` - ``s_pick_mae`` - - ``precision`` - - ``recall`` - - ``f1`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - ``phasenet_smoke.yaml`` - - ``eqnet_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`PhaseNet `, :doc:`EQNet `. + :doc:`PhaseNet `, :doc:`EQTransformer `, :doc:`GPD `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - SeisBench is GPL-3.0; PyHazards (MIT) neither vendors nor imports it. + - The smoke config runs on synthetic windows; point ``seisbench_waveforms`` at a downloaded dataset for real numbers. diff --git a/docs/source/benchmarks/pycsep.rst b/docs/source/benchmarks/ships_xu2021.rst similarity index 59% rename from docs/source/benchmarks/pycsep.rst rename to docs/source/benchmarks/ships_xu2021.rst index 5150e19e..b3c9df8f 100644 --- a/docs/source/benchmarks/pycsep.rst +++ b/docs/source/benchmarks/ships_xu2021.rst @@ -1,14 +1,12 @@ .. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. -pyCSEP -====== +SHIPS Predictors (Xu et al. 2021) +================================= Overview -------- -The current pyCSEP alignment is implemented as a report export contract inside the shared earthquake benchmark rather than as a standalone benchmark family. - -It documents the forecasting artifact shape used by the WaveCastNet smoke config. +``ships_xu2021`` reads the authors' table (Zenodo 4784610, CC BY 4.0): 121 SHIPS predictors per storm and forecast time and the 24-hour change of the maximum wind in knots. Test rows are a year's Atlantic operational cases; the paper averages the folds 2010-2018. At a Glance ----------- @@ -33,7 +31,7 @@ At a Glance .. container:: catalog-stat-value - Earthquake + Tropical Cyclone .. container:: catalog-stat-note @@ -44,7 +42,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -65,42 +63,43 @@ At a Glance Benchmark Mapping ----------------- -**Shared benchmark key:** ``earthquake`` +**Shared benchmark key:** ``tc`` -**Registered class:** ``EarthquakeBenchmark`` +**Registered class:** ``TropicalCycloneBenchmark`` Mapped benchmark family ~~~~~~~~~~~~~~~~~~~~~~~ -:doc:`Earthquake Benchmark ` +:doc:`Tropical Cyclone Benchmark ` Primary Source ~~~~~~~~~~~~~~ -`pyCSEP `_. +`Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown - - Wavefield Forecasting + - Intensity .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``mae`` - - ``mse`` + - ``intensity_mae`` + - ``intensity_rmse`` + - ``intensity_mae_group_mean`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - - ``wavecastnet_benchmark_smoke.yaml`` + - ``tropicalcyclone_mlp_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`WaveCastNet `. + :doc:`Tropical Cyclone MLP `. .. dropdown:: Notes :class-container: catalog-dropdown - - Current repo support is report-export alignment, not a separate pyCSEP benchmark runner. + - The smoke config uses ships_xu2021_synthetic (random data in the same layout). diff --git a/docs/source/benchmarks/tcbench_alpha.rst b/docs/source/benchmarks/tcbench_alpha.rst index 4943e4f7..99529fba 100644 --- a/docs/source/benchmarks/tcbench_alpha.rst +++ b/docs/source/benchmarks/tcbench_alpha.rst @@ -6,9 +6,11 @@ TCBench Alpha Overview -------- -The current TCBench Alpha alignment uses a metadata-backed storm-history adapter over the shared synthetic tropical-cyclone dataset. +``pyhazards.forecasts`` reads TCBench's released tracks and raw forecast fields from the Hugging Face dataset (pinned revision), re-implements its TempestExtremes tracking and HuracanPy matching, and scores tracks with ``score_forecast_tracks(..., protocol="tcbench")``, which reproduces TCBench's ``evaluate_tracks.py`` exactly (including its float16 reading of IBTrACS positions). -It currently drives the tropicalcyclone_MLP, SAF-Net, and TCIF-fusion smoke configs. +Verified: on TCBench's raw Pangu-Weather fields the tracker writes TCBench's released track files byte for byte (and the official TempestExtremes binaries agree), every row of the released Pangu-Weather and FourCastNet v2 matched tracks scores exactly as TCBench's own metric code, and the DPE / AE values printed in TCBench's notebook are reproduced. + +Not implemented: CRPS, along/cross-track errors, rapid-intensification scores and TCBench's post-processing models. TCBench's "FourCastNet v2" is SFNO-small, not the FourCastNet of Pathak et al. At a Glance ----------- @@ -44,7 +46,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +57,11 @@ At a Glance .. container:: catalog-stat-value - 3 + 0 .. container:: catalog-stat-note - 3 models + 0 models Benchmark Mapping @@ -77,7 +79,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`TCBench Alpha `_. +`TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,17 +89,21 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``track_error`` + - ``track_error_km`` - ``intensity_mae`` + - ``pressure_mae`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - - ``tropicalcyclone_mlp_smoke.yaml`` - - ``saf_net_smoke.yaml`` - - ``tcif_fusion_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`Tropical Cyclone MLP `, :doc:`SAF-Net `, :doc:`TCIF-fusion `. + None. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - TCBench code and data are MIT-licensed; the Pangu-Weather forecasts derive from CC BY-NC-SA 4.0 weights (non-commercial). + - Weather models are pipelines, not PyHazards models, so no model is linked here; see the Foundation Weather Models page. diff --git a/docs/source/benchmarks/tropical_cyclone_benchmark.rst b/docs/source/benchmarks/tropical_cyclone_benchmark.rst index a9aa8309..3a55fc9e 100644 --- a/docs/source/benchmarks/tropical_cyclone_benchmark.rst +++ b/docs/source/benchmarks/tropical_cyclone_benchmark.rst @@ -6,9 +6,13 @@ Tropical Cyclone Benchmark Overview -------- -The tropical cyclone benchmark family is the single storm evaluator used by the hurricane-specific and all-basin tropical-cyclone smoke configs. +``tc.track_intensity`` scores forecasts of position, maximum wind and central pressure at the dataset's lead times: great-circle track error (km; ``track_distance: tcn_equirectangular`` gives TropiCycloneNet's 111 km-per-degree formula), wind MAE in the dataset's unit (knots for IBTrACS, m/s for TCND) and pressure MAE (hPa), each per lead time and averaged. Models with several samples per storm are scored on the sample mean and with the best-of-k errors of the TropiCycloneNet paper (per lead time and per variable, the smallest error among the samples). -Current coverage is synthetic-backed, but the same evaluator contract already scores core storm baselines and experimental weather-model adapters. +``tc.intensity`` scores one intensity (or 24-hour intensity change) per storm and time: MAE and RMSE in the dataset's unit, per test year when the split names years, and their unweighted mean, the way Xu et al. (2021) and SAF-Net report results. + +Real data: ``ibtracs_tracks`` (IBTrACS best tracks), ``tropicyclonenet_dataset`` (TCND), ``ships_xu2021`` (SHIPS predictors) and ``hurricast_ibtracs_era5`` (IBTrACS statistics and ERA5 maps; Hurricast's 24-hour intensity with ``tc.intensity`` and track with ``tc.track_intensity`` at lead 24 h). The smoke configs run on synthetic data with the same layouts. Real data: ``ibtracs_tracks`` (IBTrACS best tracks), ``tropicyclonenet_dataset`` (TCND) and ``ships_xu2021`` (SHIPS predictors). The smoke configs run on synthetic data with the same layouts. + +Global weather models (FourCastNet, GraphCast, Pangu-Weather) are not models of this benchmark: their cyclone tracks come from a tracker run on their forecast fields. ``pyhazards.forecasts`` builds those tracks (TCBench's TempestExtremes rules or the papers' ECMWF-style tracker) and ``pyhazards.forecasts.score_forecast_tracks`` scores them against IBTrACS with this evaluator's ``track_intensity_metrics`` (same metric names, ``tc`` / ``tc.track_intensity`` results). At a Glance ----------- @@ -44,7 +48,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -55,11 +59,11 @@ At a Glance .. container:: catalog-stat-value - 8 + 5 .. container:: catalog-stat-note - 8 models + 5 models Benchmark Mapping @@ -72,37 +76,45 @@ Benchmark Mapping Mapped benchmark ecosystems ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:doc:`IBTrACS `, :doc:`TCBench Alpha `, :doc:`TropiCycloneNet-Dataset `. +:doc:`IBTrACS `, :doc:`SHIPS Predictors (Xu et al. 2021) `, :doc:`TCBench Alpha `, :doc:`TropiCycloneNet Dataset `. .. dropdown:: Supported Tasks :class-container: catalog-dropdown - Track + Intensity + - Intensity .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``track_error`` + - ``track_error_km`` - ``intensity_mae`` + - ``pressure_mae`` + - ``best_of_k_track_error_km`` + - ``best_of_k_intensity_mae`` + - ``best_of_k_pressure_mae`` + - ``intensity_rmse`` + - ``intensity_mae_group_mean`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown - - ``hurricast_smoke.yaml`` - ``tropicalcyclone_mlp_smoke.yaml`` - - ``tropicyclonenet_smoke.yaml`` - ``saf_net_smoke.yaml`` + - ``tropicyclonenet_smoke.yaml`` + - ``hurricast_smoke.yaml`` - ``tcif_fusion_smoke.yaml`` - - ``graphcast_tc_smoke.yaml`` - - ``pangu_tc_smoke.yaml`` - - ``fourcastnet_tc_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`Hurricast `, :doc:`Tropical Cyclone MLP `, :doc:`TropiCycloneNet `, :doc:`SAF-Net `, :doc:`TCIF-fusion `, :doc:`GraphCast TC Adapter `, :doc:`Pangu TC Adapter `, :doc:`FourCastNet TC Adapter `. + :doc:`Tropical Cyclone MLP `, :doc:`SAF-Net `, :doc:`TropiCycloneNet `, :doc:`Hurricast `, :doc:`TCIF-fusion `. .. dropdown:: Notes :class-container: catalog-dropdown - - IBTrACS, TCBench Alpha, and TropiCycloneNet-Dataset are surfaced as the public storm benchmark ecosystems. + - Smoke configs use synthetic datasets (tc_tracks_synthetic, ships_xu2021_synthetic, safnet_cma_era_interim_synthetic, tropicyclonenet_dataset_synthetic, hurricast_synthetic, tcif_fusion_synthetic); their scores mean nothing. Benchmark results carry synthetic=True for them. The hurricast smoke config runs the network head (the XGBoost stage needs fitting) and the tcif_fusion one a reduced copy of the network. + - The GraphCast / Pangu-Weather / FourCastNet adapters are experimental generic stand-ins, not the published models. + - Smoke configs use synthetic datasets (tc_tracks_synthetic, ships_xu2021_synthetic, safnet_cma_era_interim_synthetic, tropicyclonenet_dataset_synthetic); their scores mean nothing. Benchmark results carry synthetic=True for them. + - hurricast and tcif_fusion are experimental generic stand-ins, not the published models. + - The former graphcast_tc, pangu_tc and fourcastnet_tc entries (small networks without forecast fields, weights or tracker) were removed; see the Foundation Weather Models page (pyhazards.forecasts). diff --git a/docs/source/benchmarks/tropicyclonenet_dataset.rst b/docs/source/benchmarks/tropicyclonenet_dataset.rst index 50b9f92b..a0da7f6c 100644 --- a/docs/source/benchmarks/tropicyclonenet_dataset.rst +++ b/docs/source/benchmarks/tropicyclonenet_dataset.rst @@ -1,14 +1,14 @@ .. This file is generated by scripts/render_benchmark_docs.py. Do not edit by hand. -TropiCycloneNet-Dataset +TropiCycloneNet Dataset ======================= Overview -------- -The current TropiCycloneNet-Dataset alignment uses a metadata-backed storm-history adapter over the shared synthetic tropical-cyclone dataset. +``tropicyclonenet_dataset`` reads the TCND files (Zenodo, CC BY 4.0) into TropiCycloneNet's input layout; targets are position, central pressure (hPa) and maximum wind (m/s) at 6, 12, 18 and 24 h. -It exists today to support the public TropiCycloneNet smoke benchmark path. +The paper reports best-of-6 errors (per lead time and variable, the smallest error among six sampled forecasts); the evaluator reports those and the errors of the sample mean. At a Glance ----------- @@ -44,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - :bdg-info:`Synthetic-backed` + :bdg-success:`Real-backed` .. container:: catalog-stat-note @@ -77,7 +77,7 @@ Mapped benchmark family Primary Source ~~~~~~~~~~~~~~ -`TropiCycloneNet-Dataset `_. +`Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ (`repo `__). .. dropdown:: Supported Tasks :class-container: catalog-dropdown @@ -87,8 +87,12 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown - - ``track_error`` + - ``track_error_km`` - ``intensity_mae`` + - ``pressure_mae`` + - ``best_of_k_track_error_km`` + - ``best_of_k_intensity_mae`` + - ``best_of_k_pressure_mae`` .. dropdown:: Smoke Configs :class-container: catalog-dropdown @@ -99,3 +103,8 @@ Primary Source :class-container: catalog-dropdown :doc:`TropiCycloneNet `. + +.. dropdown:: Notes + :class-container: catalog-dropdown + + - The smoke config uses tropicyclonenet_dataset_synthetic (random data in the TCND layout). diff --git a/docs/source/benchmarks/wildfire_benchmark.rst b/docs/source/benchmarks/wildfire_benchmark.rst index 24016f64..9e7c68c7 100644 --- a/docs/source/benchmarks/wildfire_benchmark.rst +++ b/docs/source/benchmarks/wildfire_benchmark.rst @@ -6,7 +6,7 @@ Wildfire Benchmark Overview -------- -The wildfire benchmark family is the single scoring layer for tabular danger tasks, weekly forecasting tasks, and raster spread tasks. +The wildfire benchmark family is the single scoring layer for tabular, daily-sequence and gridded (per-cell) danger tasks, weekly forecasting tasks, and raster spread tasks. Current coverage is synthetic-backed, but it already exposes a single hazard-level evaluator contract across wildfire danger and wildfire spread smoke configs. @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 8 + 29 .. container:: catalog-stat-note - 8 models + 29 models Benchmark Mapping @@ -89,6 +89,7 @@ Mapped benchmark ecosystems - ``pr_auc`` - ``mae`` - ``rmse`` + - ``average_precision`` - ``iou`` - ``f1`` - ``burned_area_mae`` @@ -101,16 +102,21 @@ Mapped benchmark ecosystems - ``asufm_smoke.yaml`` - ``wildfire_spread_smoke.yaml`` - ``wildfirespreadts_smoke.yaml`` - - ``forefire_smoke.yaml`` - - ``wrf_sfire_smoke.yaml`` - ``firecastnet_smoke.yaml`` + - ``track_o_convlstm_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`DNN-LSTM-AutoEncoder `, :doc:`Wildfire Forecasting `, :doc:`ASUFM `, :doc:`CNN-ASPP `, :doc:`WildfireSpreadTS `, :doc:`ForeFire Adapter `, :doc:`WRF-SFIRE Adapter `, :doc:`FireCastNet `. + :doc:`DNN-LSTM-AutoEncoder `, :doc:`Wildfire Forecasting `, :doc:`Random Forest `, :doc:`XGBoost `, :doc:`Deep Ensemble `, :doc:`ASUFM `, :doc:`CNN-ASPP `, :doc:`WildfireSpreadTS Baselines `, :doc:`Logistic Regression (pixel) `, :doc:`ResNet-18 U-Net `, :doc:`ConvLSTM `, :doc:`ConvGRU `, :doc:`U-TAE `, :doc:`SegFormer `, :doc:`Swin-Unet `, :doc:`SwinLSTM `, :doc:`TrajGRU `, :doc:`Attention U-Net `, :doc:`TS-SatFire Baselines `, :doc:`U-Net-3D (MONAI) `, :doc:`UNETR `, :doc:`SwinUNETR `, :doc:`TCN `, :doc:`Earthformer `, :doc:`U-Net `, :doc:`DeepLabV3 `, :doc:`Earthfarseer `, :doc:`Rainformer `, :doc:`FireCastNet `. .. dropdown:: Notes :class-container: catalog-dropdown - WildfireSpreadTS is the public Appendix-A benchmark ecosystem surfaced on this page. + - Track-O (from PR #33 by runyangxu) scores ``wildfire.danger`` as daily fire occurrence on a latitude-longitude grid: whether a cell has a NASA FIRMS detection on a day, from that day's weather (MERRA-2 surface variables or any NetCDF files on a regular grid) and LANDFIRE fuels. Build the cache with ``scripts/build_wildfire_track_o_cache.py``, load it with the ``wildfire_track_o_raster`` / ``_temporal`` / ``_tabular`` datasets, and train and score registry models with ``scripts/run_wildfire_track_o_baselines.py``. Raster and temporal layouts are scored per cell (one logit per cell; accuracy and macro F1 at probability 0.5, ROC AUC, PR AUC). The smoke config ``track_o_convlstm_smoke.yaml`` runs on the synthetic ``micro`` cache; no real-data Track-O results are published with PyHazards. + - The Kondylatos et al. (2022) tree baselines ``random_forest`` and ``xgboost`` read the same daily danger tensors as ``wildfire_forecasting`` but must be fitted (``model.fit``) before they are scored, so they have no smoke config; pass the fitted model to ``BenchmarkRunner.run(model=...)``. ``deep_ensemble`` wraps any of the linked models (the ten-LSTM danger ensemble of Kondylatos et al. 2025, or U-TAE members for spread). + - FireCastNet forecasts seasonal burned-area presence on the SeasFire datacube (AUPRC in its paper); without a SeasFire adapter its smoke config runs on synthetic rasters and is scored with the spread-mask metrics. + - Earthfarseer and Rainformer are frame-sequence forecasters (Sim2Real-Fire baselines); their task="segmentation" adaptation maps the first predicted frame to fire-mask logits, which is a PyHazards convention, not a published Sim2Real-Fire configuration. + - Prithvi-EO-2.0 BurnScars and Prithvi-EO-2.0-TL segment burn scars after a fire (post-fire burned-area mapping). They are wildfire models but are not linked here, because this family scores danger and spread prediction, not post-fire mapping. + - ForeFire and WRF-SFIRE are physics simulators, not trainable models, so they are not linked models. ``pyhazards.simulators.ForeFireSimulator`` runs the official ForeFire (installed separately) on spread rasters, and the ``wrf_sfire_spread`` dataset turns WRF-SFIRE ``wrfout`` files into spread samples for this family's ``wildfire.spread`` task. diff --git a/docs/source/benchmarks/wildfirespreadts_ecosystem.rst b/docs/source/benchmarks/wildfirespreadts_ecosystem.rst index 73f88b7c..e586aa84 100644 --- a/docs/source/benchmarks/wildfirespreadts_ecosystem.rst +++ b/docs/source/benchmarks/wildfirespreadts_ecosystem.rst @@ -55,11 +55,11 @@ At a Glance .. container:: catalog-stat-value - 5 + 8 .. container:: catalog-stat-note - 5 models + 8 models Benchmark Mapping @@ -87,6 +87,7 @@ Primary Source .. dropdown:: Key Metrics :class-container: catalog-dropdown + - ``average_precision`` - ``iou`` - ``f1`` - ``burned_area_mae`` @@ -96,11 +97,8 @@ Primary Source - ``wildfire_spread_smoke.yaml`` - ``wildfirespreadts_smoke.yaml`` - - ``forefire_smoke.yaml`` - - ``wrf_sfire_smoke.yaml`` - - ``firecastnet_smoke.yaml`` .. dropdown:: Linked Models :class-container: catalog-dropdown - :doc:`CNN-ASPP `, :doc:`WildfireSpreadTS `, :doc:`ForeFire Adapter `, :doc:`WRF-SFIRE Adapter `, :doc:`FireCastNet `. + :doc:`CNN-ASPP `, :doc:`WildfireSpreadTS Baselines `, :doc:`Logistic Regression (pixel) `, :doc:`ResNet-18 U-Net `, :doc:`ConvLSTM `, :doc:`U-TAE `, :doc:`SegFormer `, :doc:`Swin-Unet `. diff --git a/docs/source/datasets/aefa_forecast.rst b/docs/source/datasets/aefa_forecast.rst deleted file mode 100644 index e116a389..00000000 --- a/docs/source/datasets/aefa_forecast.rst +++ /dev/null @@ -1,113 +0,0 @@ -.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. - -AEFA Forecast -============= - -Synthetic-backed dense-grid forecasting adapter aligned to the AEFA earthquake forecasting workflow. - -Overview --------- - -AEFA Forecast is the public forecasting adapter used by the earthquake benchmark when exercising dense-grid wavefield forecasting models. - -The current implementation is synthetic-backed, but it preserves the task shape, tensor layout, and reporting surface used by the shared earthquake evaluator. - -At a Glance ------------ - -.. list-table:: - :widths: 28 72 - :stub-columns: 1 - - * - Provider - - AEFA forecasting ecosystem surfaced through a PyHazards adapter - * - Hazard Family - - Earthquake - * - Source Role - - Forecast Benchmark - * - Coverage - - Benchmark-aligned earthquake forecasting samples - * - Geometry - - Dense-grid wavefield tensors - * - Spatial Resolution - - Benchmark-defined dense sensor grid - * - Temporal Resolution - - Short history and forecast windows - * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs - * - Period of Record - - Synthetic-backed benchmark adapter - * - Formats - - PyTorch tensors via the dataset registry - * - Registry Entry - - ``aefa_forecast`` - -Data Characteristics --------------------- - -- Multichannel dense-grid history tensors paired with future dense-grid targets. -- Registry-backed benchmark adapter rather than a raw external archive loader. -- Intended for forecasting-path validation and report generation. - -Typical Use Cases -~~~~~~~~~~~~~~~~~ - -- Smoke tests for WaveCastNet-style earthquake forecasting. -- Shared forecasting benchmark runs under the earthquake evaluator. -- Validation of report exports aligned to the forecasting path. - -Access ------- - -Use the links below to access the upstream source or its public documentation. - -- `AEFA repository `_ - -PyHazards Usage ---------------- - -Use this adapter when you want the public earthquake forecasting benchmark surface rather than the private synthetic dataset name. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``aefa_forecast`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "aefa_forecast", - micro=True, - temporal_in=5, - temporal_out=4, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) - -- micro=True keeps the synthetic-backed forecasting path lightweight for validation. - -Related Coverage -~~~~~~~~~~~~~~~~ - -**Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`AEFA ` - -**Representative Models:** :doc:`WaveCastNet ` - -Inspection Workflow -------------------- - -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. - -Notes ------ - -- This is a benchmark adapter, not a full external AEFA ingestion pipeline. - -Reference ---------- - -- `AEFA `_. diff --git a/docs/source/datasets/camels_us_streamflow.rst b/docs/source/datasets/camels_us_streamflow.rst new file mode 100644 index 00000000..8f964070 --- /dev/null +++ b/docs/source/datasets/camels_us_streamflow.rst @@ -0,0 +1,111 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +CAMELS-US +========= + +Reader for a local copy of CAMELS-US (671 US catchments, daily forcings, USGS streamflow and catchment attributes) in the setup of Kratzert et al. (2019), as NeuralHydrology reads it. + +Overview +-------- + +CAMELS-US provides basin-averaged daily meteorological forcings (Daymet, Maurer, NLDAS), USGS streamflow and catchment attributes (Newman et al., HESS 2015; Addor et al., HESS 2017; CC BY 4.0, Zenodo 15529996). Kratzert et al. (HESS 2019) used 531 of its basins with the extended Maurer forcings (daily minimum and maximum temperature added; HydroShare, doi 10.4211/hs.17c896843cf940339c3c3496d0c1c077) and 27 attributes, the standard benchmark for the NeuralHydrology models. + +``camels_us_streamflow`` reads that layout like NeuralHydrology's ``CamelsUS`` dataset (discharge from cubic feet per second to mm/day with the area of the forcing-file header, negative values to NaN) and builds streamflow samples. Defaults are the paper's: forcings ``maurer_extended``, inputs prcp, srad, tmax, tmin, vp, the 27 attributes, 270-day windows, train 1999-10-01 to 2008-09-30 and test 1989-10-01 to 1999-09-30 (validation 1980-10-01 to 1989-09-30, from NeuralHydrology's example configuration). PyHazards downloads nothing. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NCAR / USGS CAMELS data set (Newman et al. 2015; Addor et al. 2017), read by PyHazards from a local copy + * - Hazard Family + - Flood + * - Source Role + - Streamflow Benchmark + * - Coverage + - 671 catchments in the contiguous United States (531 in the Kratzert et al. 2019 benchmark) + * - Geometry + - Daily basin time series with static attributes + * - Spatial Resolution + - Catchment averages (one series per gauge) + * - Temporal Resolution + - Daily + * - Update Cadence + - Static research dataset (extended Maurer forcings released separately in 2019) + * - Period of Record + - 1980-2014 + * - Formats + - Whitespace-separated forcing and streamflow text files; ';'-separated attribute tables + * - Registry Entry + - ``camels_us_streamflow`` + +Data Characteristics +-------------------- + +- Layout: ``basin_mean_forcing//[/]_*_forcing_leap.txt``, ``usgs_streamflow/[/]_streamflow_qc.txt``, ``camels_attributes_v2.0/camels_*.txt``. +- Target ``QObs(mm/d)``; with several forcing products the input columns get a ``_`` suffix. +- Normalisation and sample selection as for Caravan (training statistics; training samples with missing inputs or targets dropped; every evaluation day kept). + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Reproducing the Kratzert et al. (2019) LSTM and EA-LSTM benchmark. +- Per-basin NSE / KGE / FHV / FMS / FLV evaluation with the flood benchmark (``flood.streamflow``). + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `CAMELS (NCAR RAL) `_ +- `CAMELS time series and attributes (Zenodo) `_ +- `Extended Maurer forcings (HydroShare) `_ +- `NeuralHydrology data prerequisites `_ + +PyHazards Usage +--------------- + +Point ``data_dir`` at the CAMELS-US root (with ``basin_mean_forcing/maurer_extended`` added) and pass the basin list. + +Score models with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.streamflow``). + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``camels_us_streamflow`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + # The 531 basins of Kratzert et al. (2019), e.g. NeuralHydrology's 531_basin_list.txt. + data = load_dataset("camels_us_streamflow", data_dir="/data/CAMELS_US", basins="531_basin_list.txt").load() + inputs, y = data.get_split("test").inputs[0] + print(inputs["x_d"].shape, inputs["x_s"].shape, y.shape) # (270, 5) (27,) (270, 1) + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Flood Benchmark `, :doc:`CAMELS-US ` + +**Representative Models:** :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- The reader, scaler and samples are checked against NeuralHydrology's CamelsUS dataset on the real CAMELS-US test basins shipped with NeuralHydrology (oracle test), and the whole evaluation against NeuralHydrology's Tester. + +Reference +--------- + +- `Addor, Newman, Mizukami and Clark (2017). The CAMELS data set: catchment attributes and meteorology for large-sample studies. HESS 21:5293-5313. `_. +- `Kratzert et al. (2019). Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets. HESS 23:5089-5110. `_ (`repo `__). diff --git a/docs/source/datasets/caravan_streamflow.rst b/docs/source/datasets/caravan_streamflow.rst index 414bef72..792b1d7a 100644 --- a/docs/source/datasets/caravan_streamflow.rst +++ b/docs/source/datasets/caravan_streamflow.rst @@ -3,14 +3,14 @@ Caravan ======= -Synthetic-backed streamflow benchmark adapter aligned to the Caravan large-sample hydrology ecosystem. +Reader for a local copy of Caravan, the global large-sample hydrology dataset (daily ERA5-Land forcings, catchment attributes and observed streamflow), in NeuralHydrology's sample layout. Overview -------- -Caravan is the public flood streamflow adapter used to align PyHazards with a large-sample hydrology benchmark surface. +Caravan (Kratzert et al., Scientific Data 10:61, 2023) harmonises the CAMELS-style datasets of several countries: every basin has daily ERA5-Land forcings and states (precipitation, temperature, radiation, pressure, wind, soil water, evaporation, ...) aggregated over the catchment in local time, observed streamflow in mm/day, and HydroATLAS / ERA5-Land climate attributes. The Zenodo records are licensed CC BY 4.0, with per-source licence notes in the dataset's ``licenses/`` folder. -The current implementation is synthetic-backed, but it preserves the streamflow forecasting contract used by the shared flood benchmark. +``caravan_streamflow`` reads that layout (as NeuralHydrology's ``Caravan`` dataset does) and builds streamflow samples: ``seq_length``-day windows of the chosen dynamic inputs ``x_d``, the basin's static attributes ``x_s`` and the discharge series ``y``, normalised with training-period statistics, split into the train / val / test periods you pass. PyHazards downloads nothing. At a Glance ----------- @@ -20,54 +20,57 @@ At a Glance :stub-columns: 1 * - Provider - - Caravan community dataset surfaced through a PyHazards adapter + - Caravan community dataset (Kratzert et al. 2023), read by PyHazards from a local copy * - Hazard Family - Flood * - Source Role - Streamflow Benchmark * - Coverage - - Benchmark-aligned streamflow forecasting samples + - 6,830 catchments in the original release (Australia, Brazil, Canada, Chile, Great Britain, Central Europe, United States) plus extensions * - Geometry - - Graph-temporal basin or node sequences + - Daily basin time series with static attributes * - Spatial Resolution - - Basin or gauge nodes represented as graph elements + - Catchment averages (one series per gauge) * - Temporal Resolution - - Rolling history windows for streamflow prediction + - Daily * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs + - Versioned Zenodo releases (netCDF and CSV editions) plus community extensions * - Period of Record - - Synthetic-backed benchmark adapter + - 1981-2020 in the original release (later versions extend it) * - Formats - - PyTorch graph-temporal dataset objects via the dataset registry + - Per-basin netCDF or CSV time series; per-source attribute CSV files * - Registry Entry - ``caravan_streamflow`` Data Characteristics -------------------- -- Graph-temporal sequences with node-level targets for next-step streamflow prediction. -- Registry-backed benchmark adapter instead of a raw Caravan ingestion pipeline. -- Supports the public streamflow smoke path for NeuralHydrology LSTM and Google Flood Forecasting. +- Layout: ``attributes//attributes_{caravan,hydroatlas,other}_.csv`` (column ``gauge_id``) and ``timeseries/{netcdf,csv}//_.{nc,csv}``; basin ids are ``_``. +- Inputs and target are standardised with the mean and population standard deviation over all training basins and days; static attributes with their mean and standard deviation over the training basins, sorted alphabetically (NeuralHydrology's order). +- Training samples with a missing input in the window or a missing target on the last day are dropped; validation and test keep one sample per basin and day so that metrics cover the whole period. +- Caravan publishes no single input set or split, so ``dynamic_inputs`` and ``periods`` are required. Typical Use Cases ~~~~~~~~~~~~~~~~~ -- Streamflow smoke tests for benchmark-linked flood models. -- Shared flood benchmark runs with streamflow metrics such as NSE and KGE. -- Regression checks for graph-temporal basin workflows. +- Regional or global LSTM streamflow models (``neuralhydrology_lstm``, ``neuralhydrology_ealstm``, ``google_flood_forecasting``). +- Per-basin NSE / KGE evaluation with the flood benchmark (``flood.streamflow``). Access ------ Use the links below to access the upstream source or its public documentation. -- `Caravan paper `_ +- `Caravan paper (Scientific Data 2023) `_ - `Caravan repository `_ +- `Caravan netCDF release (Zenodo) `_ PyHazards Usage --------------- -Use this adapter when you want the public Caravan-aligned streamflow surface exposed by the flood benchmark. +Point ``data_dir`` at an extracted Caravan release and pass basin ids (or a basin file), dynamic inputs and periods. + +Score models with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.streamflow``). Registry Workflow ~~~~~~~~~~~~~~~~~ @@ -80,20 +83,22 @@ Primary dataset name: ``caravan_streamflow`` data = load_dataset( "caravan_streamflow", - micro=True, - history=4, - nodes=6, + data_dir="/data/Caravan", + basins=["camelsgb_28015", "lamah_215"], + dynamic_inputs=["total_precipitation_sum", "temperature_2m_mean", "potential_evaporation_sum"], + static_attributes=["p_mean", "aridity", "area"], + periods={"train": ("1981-10-01", "1990-09-30"), "test": ("2000-10-01", "2010-09-30")}, # your split + seq_length=365, ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) + inputs, y = data.get_split("test").inputs[0] + print(inputs["x_d"].shape, inputs["x_s"].shape, y.shape) Related Coverage ~~~~~~~~~~~~~~~~ **Benchmarks:** :doc:`Flood Benchmark `, :doc:`Caravan ` -**Representative Models:** :doc:`NeuralHydrology LSTM `, :doc:`Google Flood Forecasting ` +**Representative Models:** :doc:`NeuralHydrology LSTM `, :doc:`EA-LSTM `, :doc:`Google Flood Forecasting ` Inspection Workflow ------------------- @@ -104,9 +109,10 @@ so there is no standalone inspection CLI documented for it. Notes ----- -- This is a synthetic-backed benchmark adapter rather than a full Caravan downloader. +- The reader is checked against NeuralHydrology's Caravan dataset on real Caravan basin files (oracle test). +- Until 2026-10 this registry name generated random numbers; it now reads only real Caravan files (synthetic data is ``flood_streamflow_synthetic``). Reference --------- -- `Caravan - A global community dataset for large-sample hydrology `_ (`repo `__). +- `Kratzert et al. (2023). Caravan - A global community dataset for large-sample hydrology. Scientific Data 10:61. `_ (`repo `__). diff --git a/docs/source/datasets/earthquake_wavefield_synthetic.rst b/docs/source/datasets/earthquake_wavefield_synthetic.rst new file mode 100644 index 00000000..dd564b15 --- /dev/null +++ b/docs/source/datasets/earthquake_wavefield_synthetic.rst @@ -0,0 +1,99 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Wavefield Sequences +============================= + +Synthetic X / Y / Z ground-velocity wavefields of point sources for wavefield-forecasting smoke runs. Not real data. + +Overview +-------- + +This dataset is synthetic. Each sequence is a point source at a random grid position and onset radiating a P and an S wavefront (Ricker pulses at two speeds, amplitudes decaying with distance): P moves particles radially and vertically, S transversally, giving X, Y and Z velocity channels. It mimics only the layout of WaveCastNet's data (three velocity components on a regular grid); it is not an elastic simulation and says nothing about forecasting skill on real or SW4-simulated wavefields. + +It exercises the ``earthquake.forecasting`` task (ACC / RFNE / RMSE of WaveCastNet) in CI. Formerly ``earthquake_forecast_synthetic`` (moving Gaussian blobs; that name is kept as a deprecated alias) and, before that, ``aefa_forecast``: AEFA is an unrelated earthquake-occurrence forecasting dataset. + +WaveCastNet's own data (SW4 simulations of the San Francisco Bay Area, arrays ``(events, 3, 376, 256, 461)``, 16-24 GB per file) are on the authors' Google Drive; PyHazards has no reader for them yet. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - Generated locally by PyHazards (pyhazards/datasets/earthquake/synthetic.py) + * - Hazard Family + - Earthquake + * - Source Role + - Synthetic Smoke Data + * - Coverage + - Not applicable (synthetic) + * - Geometry + - Regular grid of three-component velocity frames + * - Spatial Resolution + - Not applicable (synthetic grid, default 32 x 24 cells) + * - Temporal Resolution + - Frames (default 6 input and 6 target frames) + * - Update Cadence + - Generated on load + * - Period of Record + - Not applicable (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``earthquake_wavefield_synthetic`` + +Data Characteristics +-------------------- + +- Inputs ``(n, 3, temporal_in, height, width)``, targets ``(n, 3, temporal_out, height, width)``; channels X, Y, Z (``channel_names`` metadata). +- Seeded generator (``seed``); ``vp`` and ``vs`` are wave speeds in grid cells per frame; height and width default to multiples of 8, as WaveCastNet needs. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- WaveCastNet smoke tests of the wavefield-forecasting benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `Generator source `_ + +PyHazards Usage +--------------- + +Used by ``wavecastnet_benchmark_smoke.yaml``. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``earthquake_wavefield_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("earthquake_wavefield_synthetic", micro=True, temporal_in=6, temporal_out=6).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (4, 3, 6, 32, 24) (4, 3, 6, 32, 24) + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Earthquake Benchmark ` + +**Representative Models:** :doc:`WaveCastNet ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Reference +--------- + +- `PyHazards synthetic wavefield generator (no external source). `_. diff --git a/docs/source/datasets/earthquake_waveforms_synthetic.rst b/docs/source/datasets/earthquake_waveforms_synthetic.rst new file mode 100644 index 00000000..cc3dc0e0 --- /dev/null +++ b/docs/source/datasets/earthquake_waveforms_synthetic.rst @@ -0,0 +1,101 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Phase-Picking Waveforms +================================= + +Synthetic three-component windows with P and S wavelets for picking smoke runs. Not real data. + +Overview +-------- + +This dataset is synthetic. Each event window is Gaussian background noise plus two damped sinusoids that start at the P arrival (about 8 Hz, strongest on Z) and at the S arrival (about 4 Hz, strongest on N and E); about a quarter of the windows are noise only. It exists to exercise the picking models and the ``earthquake.picking`` benchmark in CI; numbers obtained on it say nothing about real seismic data. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - Generated locally by PyHazards (pyhazards/datasets/earthquake/synthetic.py) + * - Hazard Family + - Earthquake + * - Source Role + - Synthetic Smoke Data + * - Coverage + - Not applicable (synthetic) + * - Geometry + - Three-component waveform windows + * - Spatial Resolution + - Not applicable (synthetic) + * - Temporal Resolution + - 100 Hz by default + * - Update Cadence + - Generated on load from a fixed seed + * - Period of Record + - Not applicable (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``earthquake_waveforms_synthetic`` + +Data Characteristics +-------------------- + +- Inputs ``(n, 3, length)`` in Z, N, E order, 100 Hz, ``length`` 6000 by default (60 s, EQTransformer's window). +- Targets ``(n, 2)``: P and S arrival samples, NaN for noise windows. +- Deterministic: the same ``seed`` and sizes give the same data; ``micro=True`` makes 24 windows. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests of PhaseNet, EQTransformer, GPD and the picking evaluator. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `Generator source `_ + +PyHazards Usage +--------------- + +Used by the earthquake picking smoke configs; use ``seisbench_waveforms`` for real data. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``earthquake_waveforms_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("earthquake_waveforms_synthetic", micro=True).load() + test = data.get_split("test") + print(test.inputs.shape, test.targets.shape) # (4, 3, 6000), (4, 2) + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Earthquake Benchmark ` + +**Representative Models:** :doc:`PhaseNet `, :doc:`EQTransformer `, :doc:`GPD `, :doc:`EQNet ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Renamed from ``earthquake_waveforms``; it also replaces the synthetic data that used to be served as ``seisbench_waveforms`` and ``pick_benchmark_waveforms``. + +Reference +--------- + +- `PyHazards synthetic phase-picking generator (no external source). `_. diff --git a/docs/source/datasets/era5.rst b/docs/source/datasets/era5.rst index e816179a..4f921650 100644 --- a/docs/source/datasets/era5.rst +++ b/docs/source/datasets/era5.rst @@ -10,7 +10,7 @@ Overview ERA5 is ECMWF's fifth-generation global reanalysis, combining historical observations with a modern data assimilation system to produce temporally consistent atmospheric fields. -PyHazards uses ERA5 as a shared meteorological baseline for flood, wildfire, and weather-aware graph workflows, including the HydroGraphNet example path. +PyHazards uses ERA5 as a shared meteorological baseline for flood, wildfire, and weather-aware graph workflows. At a Glance ----------- @@ -68,16 +68,11 @@ Use the links below to access the upstream source or its public documentation. PyHazards Usage --------------- -Use the inspection command for direct file validation, then feed local ERA5 files into HydroGraphNet-style helper loaders when you need graph-temporal training inputs. +Use the inspection command for direct file validation, then feed local ERA5 files into the graph helper ``pyhazards.data.load_hydrograph_data`` (grid cells as nodes) when you need generic graph-temporal inputs. This dataset is currently documented as an external or inspection-first source rather than a public ``load_dataset(...)`` entrypoint. -Related Coverage -~~~~~~~~~~~~~~~~ - -**Representative Models:** :doc:`HydroGraphNet ` - Inspection Workflow ------------------- @@ -90,7 +85,7 @@ Use the documented inspection path below to validate local files before training Notes ----- -- ERA5 is inspection-first in the public catalog; the downstream HydroGraphNet helper is documented here for convenience but is not a ``load_dataset(...)`` registry entry. +- ERA5 is inspection-first in the public catalog; the graph helper is documented here for convenience but is not a ``load_dataset(...)`` registry entry. It is not HydroGraphNet's data (HydroGraphNet runs on HEC-RAS mesh hydrographs, see ``hydrographnet_white_river``). Reference --------- diff --git a/docs/source/datasets/figlib_smokebench.rst b/docs/source/datasets/figlib_smokebench.rst new file mode 100644 index 00000000..18759103 --- /dev/null +++ b/docs/source/datasets/figlib_smokebench.rst @@ -0,0 +1,101 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +FIgLib SmokeBench +================= + +The SmokeBench evaluation images -- HPWREN FIgLib camera frames with the SmokeyNet smoke boxes -- for prompting multimodal LLMs to classify and localize early wildfire smoke. + +Overview +-------- + +SmokeBench (Qi, Li & Barnes, WACV 2026) evaluates multimodal LLMs on 5,046 smoke images with ground-truth boxes and 1,000 smoke-free images from FIgLib, the HPWREN Fire Ignition images Library of fixed-view camera sequences around wildfire ignitions. + +SmokeBench released no data or image lists. The 5,046 boxes are the bbox_labels of SmokeyNet's metadata.pkl (Apache-2.0 repository, pinned and checksummed): one box per frame on 145 sequences, whose area quintiles are exactly the SmokeBench area bins (42, 4356, 11232, 28565, 83157, 2232020 pixels). + +The frames are downloaded from the official HPWREN CDN on demand; PyHazards redistributes no images. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - HPWREN (UC San Diego) FIgLib images; SmokeyNet (Dewangan et al. 2022) boxes; SmokeBench (Qi, Li & Barnes, WACV 2026) protocol + * - Hazard Family + - Wildfire + * - Source Role + - Smoke Detection Benchmark + * - Coverage + - Southern California (HPWREN camera network) + * - Geometry + - Fixed-camera RGB photographs with smoke bounding boxes + * - Spatial Resolution + - 1600 x 1200 to 3072 x 2048 pixel frames from mountain-top cameras + * - Temporal Resolution + - Sequences of up to 81 frames, usually one minute apart, from 40 minutes before to 40 minutes after the first visible plume + * - Update Cadence + - Static evaluation set (FIgLib itself keeps adding sequences) + * - Period of Record + - Fires of 2016-2020 (the 145 annotated sequences) + * - Formats + - JPEG frames in per-sequence tgz archives; boxes in a Python pickle (SmokeyNet metadata.pkl) + * - Inspection CLI + - ``python -m pyhazards.datasets.figlib_smokebench.inspection --root /path/to/figlib --download`` + +Data Characteristics +-------------------- + +- Smoke images are frames at or after the first visible plume (file names _+.jpg) that SmokeyNet's annotators boxed; smoke-free images are frames before it (_-.jpg). +- Frame sizes: 2,846 at 2048 x 1536, 1,994 at 3072 x 2048, 172 at 1600 x 1200 and 34 at 2560 x 1920 among the smoke images. +- Boxes are [x1, y1, x2, y2] integer pixel coordinates of the original frame (extremes of the annotated polygon); smoke areas range from 42 to 2,232,020 pixels. +- SmokeBench's 1,000 smoke-free frames were an unseeded random draw over all FIgLib sequences and were not released; the adapter draws a seeded sample from the pre-ignition frames of the 145 annotated sequences (5,666 candidates). + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Zero-shot evaluation of multimodal LLMs on smoke classification, tile and grid localization and box detection (SmokeBench). +- Studying how smoke size and contrast limit early wildfire smoke detection. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `HPWREN FIgLib `_ +- `FIgLib sequence archives (HPWREN CDN) `_ +- `SmokeyNet repository (boxes in data/metadata.pkl) `_ + +PyHazards Usage +--------------- + +pyhazards.datasets.figlib_smokebench.FIgLibSmokeBench(root) yields SmokeSample(image_id, path, label, boxes) and decodes frames to RGB arrays; download_smokebench(root) fetches the boxes and frames. + +pyhazards.prompted.evaluate_smokebench runs the SmokeBench tasks on it with a prompted multimodal-LLM backend (see the Prompted VLM Baselines page). + +This dataset is currently documented as an external or inspection-first +source rather than a public ``load_dataset(...)`` entrypoint. + +Inspection Workflow +------------------- + +Use the documented inspection path below to validate local files before training or analysis. + +.. code-block:: bash + + python -m pyhazards.datasets.figlib_smokebench.inspection --root /path/to/figlib --download + +- --download fetches the pinned SmokeyNet metadata.pkl (sha256-checked) and streams the 145 FIgLib archives (about 11.4 GB), keeping only the JPEG frames. + +Notes +----- + +- Licence: HPWREN publishes FIgLib as public data and asks that derivative work credit https://www.hpwren.ucsd.edu/; no licence file accompanies the images. The SmokeyNet repository (boxes) is Apache-2.0. +- Smoke-free accuracy on the seeded sample is not the same sample as SmokeBench Table 3. + +Reference +--------- + +- `Qi, T., Li, W., Barnes, N. (2026). SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection. WACV 2026. `_. +- `Dewangan, A. et al. (2022). FIgLib & SmokeyNet: Dataset and Deep Learning Model for Real-Time Wildland Fire Smoke Detection. Remote Sensing 14(4):1007. `_ (`repo `__). diff --git a/docs/source/datasets/firms.rst b/docs/source/datasets/firms.rst index 8199627c..c43622f5 100644 --- a/docs/source/datasets/firms.rst +++ b/docs/source/datasets/firms.rst @@ -92,4 +92,4 @@ Use the documented inspection path below to validate local files before training Reference --------- -- `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product. `_. +- `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product. `_. diff --git a/docs/source/datasets/flood_mesh_synthetic.rst b/docs/source/datasets/flood_mesh_synthetic.rst new file mode 100644 index 00000000..109728b6 --- /dev/null +++ b/docs/source/datasets/flood_mesh_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Mesh Hydrographs +========================== + +Random mesh fields and toy hydrographs in the HydroGraphNet (White River) layout, for smoke tests of hydrographnet and of mesh inundation rollouts. + +Overview +-------- + +Synthetic data. Static fields are random and the depth series is a toy function of a random inflow curve and the terrain; scores on it mean nothing. It runs the same pipeline as ``hydrographnet_white_river`` (normalisation, 4-nearest-neighbour graph, 16 node features, training windows with physics data, rollout test split), so models and the flood benchmark can be exercised without the 8.3 GB release. ``write_hydrograph_files`` writes such data in the release's file layout. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real flood) + * - Hazard Family + - Flood + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Graph-temporal basin or node sequences + * - Spatial Resolution + - Not applicable (random points) + * - Temporal Resolution + - Not applicable (synthetic steps) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``flood_mesh_synthetic`` + +Data Characteristics +-------------------- + +- Default: 64 nodes, 4 training and 2 test hydrographs of 48 steps, rollouts of 30 steps; ``micro=True``: 24 nodes, 2 + 1 hydrographs of 16 steps, rollouts of 6 steps. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of hydrographnet and of the ``flood.inundation`` mesh rollouts. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; the real data are ``hydrographnet_white_river``. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``flood_mesh_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("flood_mesh_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Flood Benchmark ` + +**Representative Models:** :doc:`HydroGraphNet ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True. Until this release the name held random node series on a line graph. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/flood/hydrograph.py) `_. diff --git a/docs/source/datasets/floodcastbench_inundation.rst b/docs/source/datasets/floodcastbench_inundation.rst deleted file mode 100644 index 77a95f66..00000000 --- a/docs/source/datasets/floodcastbench_inundation.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. - -FloodCastBench -============== - -Synthetic-backed inundation benchmark adapter aligned to the FloodCastBench evaluation ecosystem. - -Overview --------- - -FloodCastBench is the public inundation adapter used by PyHazards for raster flood prediction benchmarks. - -The current implementation is synthetic-backed, but it preserves the raster task and metric surface used by the shared flood evaluator. - -At a Glance ------------ - -.. list-table:: - :widths: 28 72 - :stub-columns: 1 - - * - Provider - - FloodCastBench ecosystem surfaced through a PyHazards adapter - * - Hazard Family - - Flood - * - Source Role - - Inundation Benchmark - * - Coverage - - Benchmark-aligned flood inundation samples - * - Geometry - - Raster inundation sequences - * - Spatial Resolution - - Benchmark-defined raster tiles - * - Temporal Resolution - - Short history windows with next-horizon inundation targets - * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs - * - Period of Record - - Synthetic-backed benchmark adapter - * - Formats - - PyTorch tensors via the dataset registry - * - Registry Entry - - ``floodcastbench_inundation`` - -Data Characteristics --------------------- - -- Multi-step raster inputs paired with next-horizon inundation targets. -- Registry-backed benchmark adapter rather than a raw external dataset ingestion path. -- Intended for pixel-level evaluation such as IoU and pixel MAE. - -Typical Use Cases -~~~~~~~~~~~~~~~~~ - -- Smoke tests for FloodCast and UrbanFloodCast. -- Shared flood benchmark runs on inundation tasks. -- Regression checks for raster flood prediction outputs. - -Access ------- - -Use the links below to access the upstream source or its public documentation. - -- `FloodCastBench repository `_ - -PyHazards Usage ---------------- - -Use this adapter when you want the public FloodCastBench-aligned inundation surface exposed by the flood benchmark. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``floodcastbench_inundation`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "floodcastbench_inundation", - micro=True, - history=4, - channels=3, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) - -Related Coverage -~~~~~~~~~~~~~~~~ - -**Benchmarks:** :doc:`Flood Benchmark `, :doc:`FloodCastBench ` - -**Representative Models:** :doc:`FloodCast `, :doc:`UrbanFloodCast ` - -Inspection Workflow -------------------- - -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. - -Notes ------ - -- This is a synthetic-backed benchmark adapter rather than a full FloodCastBench ingestion pipeline. - -Reference ---------- - -- `FloodCastBench `_. diff --git a/docs/source/datasets/fpa_fod_weekly.rst b/docs/source/datasets/fpa_fod_weekly.rst index 6dfa3f7f..04f85959 100644 --- a/docs/source/datasets/fpa_fod_weekly.rst +++ b/docs/source/datasets/fpa_fod_weekly.rst @@ -98,7 +98,7 @@ Related Coverage **Benchmarks:** :doc:`Wildfire Benchmark ` -**Representative Models:** :doc:`DNN-LSTM-AutoEncoder `, :doc:`Wildfire Forecasting `, :doc:`ASUFM ` +**Representative Models:** :doc:`DNN-LSTM-AutoEncoder ` Inspection Workflow ------------------- diff --git a/docs/source/datasets/frap_fire_perimeters.rst b/docs/source/datasets/frap_fire_perimeters.rst new file mode 100644 index 00000000..29e70186 --- /dev/null +++ b/docs/source/datasets/frap_fire_perimeters.rst @@ -0,0 +1,83 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +CAL FIRE FRAP Fire Perimeters +============================= + +California's historical wildfire perimeter archive, maintained by CAL FIRE's Fire and Resource Assessment Program, with fires back to 1878. + +Overview +-------- + +The FRAP fire perimeter layer is CAL FIRE's statewide archive of mapped wildfire perimeters on public and private land in California, compiled with federal and local agencies and updated each spring with the previous fire season. Prescribed burns are kept in a separate layer. + +It is a long, regional perimeter record that complements the national incident feeds (WFIGS) and satellite detections (FIRMS) for California. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - CAL FIRE Fire and Resource Assessment Program (FRAP), with USFS Region 5, BLM, NPS, USFWS, California State Parks and contract counties + * - Hazard Family + - Wildfire + * - Source Role + - Historical Perimeters + * - Coverage + - California + * - Geometry + - Fire perimeter polygons + * - Spatial Resolution + - Vector polygons (native coordinate system California Teale Albers, EPSG:3310) + * - Temporal Resolution + - One record per fire, with alarm and containment dates + * - Update Cadence + - Annual, each spring, adding the previous fire season (release firep25_1, April 2026) + * - Period of Record + - 1878 to 2025 in release firep25_1 + * - Formats + - File geodatabase; shapefile, GeoJSON, CSV, KML and GeoPackage exports from the California open-data hub + +Data Characteristics +-------------------- + +- Minimum mapped size for CAL FIRE and contract counties: at least 10 acres of timber, 50 acres of brush or 300 acres of grass, or at least 3 damaged or destroyed structures, or a fatality; other agencies submit perimeters of at least 10 acres. The criteria changed around 1991 and 2010. +- The archive is incomplete: some historical records were lost or too small for the cutoffs, some fires are duplicated or over-generalised, and unburned islands inside perimeters are mapped as burned. Perimeters may differ from those published by NIFC. +- Attributes include YEAR_, AGENCY, UNIT_ID, FIRE_NAME, INC_NUM, IRWINID, ALARM_DATE, CONT_DATE, CAUSE, C_METHOD, OBJECTIVE, GIS_ACRES and COMPLEX_NAME. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Historical burned-area footprints for California wildfire studies. +- Validating perimeters from national feeds or satellite products in California. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `California Fire Perimeters (all) on data.ca.gov `_ +- `California Natural Resources Agency open-data hub (downloads and services) `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for California perimeter data. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: data.ca.gov lists the dataset under CC BY; the metadata asks users to cite the California Department of Forestry and Fire Protection as the source, states "There are no restrictions on distribution of the data by users", and gives no warranty. + +Reference +--------- + +- `CAL FIRE FRAP (2026). Fire Perimeters, release firep25_1 (metadata). `_. diff --git a/docs/source/datasets/geomac_historical.rst b/docs/source/datasets/geomac_historical.rst new file mode 100644 index 00000000..fad61ac0 --- /dev/null +++ b/docs/source/datasets/geomac_historical.rst @@ -0,0 +1,84 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +GeoMAC Historical Perimeters +============================ + +Wildfire perimeters processed by the USGS GeoMAC service from 2000 to 2019, now distributed by the National Interagency Fire Center. + +Overview +-------- + +GeoMAC was the USGS-operated wildfire mapping website (2000-2020) that published fire perimeters for incident support. After it was shut down on 30 April 2020, its historical perimeters moved to the National Interagency Fire Center (NIFC) open-data site. + +It is the main national perimeter archive for 2000-2019. For 2021 onwards the interagency WFIGS perimeters are the successor; the NIFC Interagency Fire Perimeter History layer also covers perimeters through 2019. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - USGS Geospatial Multi-Agency Coordination (GeoMAC; shut down on 30 April 2020), archive distributed by NIFC Open Data + * - Hazard Family + - Wildfire + * - Source Role + - Historical Perimeters + * - Coverage + - United States (the 2019 layer covers the conterminous 48 states and Alaska) + * - Geometry + - Fire perimeter polygons + * - Spatial Resolution + - Vector polygons (geographic coordinates, NAD83) + * - Temporal Resolution + - The latest perimeter processed for each fire, with its perimeter date and time + * - Update Cadence + - Static archive (GeoMAC was retired on 30 April 2020) + * - Period of Record + - 2000 to 2019 (a combined 2000-2018 layer and a separate 2019 layer) + * - Formats + - File geodatabase downloads and ArcGIS feature services + +Data Characteristics +-------------------- + +- The combined 2000-2018 layer holds 23,776 perimeters; 2019 is a separate layer. +- Attributes include incidentname, fireyear, perimeterdatetime, gisacres, agency, mapmethod, uniquefireidentifier, irwinid, state and complexname. +- The perimeters are the last ones processed by the GeoMAC team for each fire; NIFC notes that they are not necessarily the final or official perimeter. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- National wildfire burned-area footprints for 2000-2019. +- Extending perimeter records before the WFIGS era. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NIFC Open Data, Historic Perimeters Combined 2000-2018 GeoMAC `_ +- `NIFC Open Data, Historic GeoMAC Perimeters 2019 `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for historical U.S. wildfire perimeters. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: the NIFC items state no licence and carry no-warranty disclaimers. USGS-produced data are in the U.S. public domain under USGS policy, but the items do not say so explicitly. + +Reference +--------- + +- `National Interagency Fire Center. Historic Perimeters Combined 2000-2018 GeoMAC (NIFC Open Data). `_. +- `Walters, Schneider and Guthrie (2011). Geospatial Multi-Agency Coordination (GeoMAC) wildland fire perimeters, 2008. USGS Data Series 612 (documents the 2008 season only). `_. diff --git a/docs/source/datasets/goesr_fdcf.rst b/docs/source/datasets/goesr_fdcf.rst new file mode 100644 index 00000000..a310a9dc --- /dev/null +++ b/docs/source/datasets/goesr_fdcf.rst @@ -0,0 +1,87 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +GOES-R ABI Fire/Hot Spot Characterization (FDCF) +================================================ + +NOAA's GOES-R ABI Level-2 fire detection and characterization product on the full-disk scan, every 10 minutes since April 2019, openly distributed on AWS. + +Overview +-------- + +ABI-L2-FDCF is the full-disk version of the GOES-R Fire/Hot Spot Characterization product. The FDCA algorithm (the operational version of WFABBA) flags fire pixels in Advanced Baseline Imager data and estimates their fire radiative power, temperature and area. + +It gives geostationary fire activity every 10 minutes, much more often than the polar-orbiting MODIS and VIIRS detections distributed by FIRMS, at a coarser 2 km pixel. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA NESDIS GOES-R Series; Fire Detection and Characterization Algorithm (FDCA) from UW-Madison CIMSS + * - Hazard Family + - Wildfire + * - Source Role + - Active Fire Detections + * - Coverage + - The full disk of each GOES satellite (GOES-East and GOES-West positions over the Americas) + * - Geometry + - Raster imagery time series on the ABI fixed grid + * - Spatial Resolution + - 2 km at nadir (5424 x 5424 full-disk fixed grid) + * - Temporal Resolution + - A full-disk product every 10 minutes since 2 April 2019 (scan mode 6); every 15 minutes before (mode 3) + * - Update Cadence + - Continuous operational production + * - Period of Record + - From 24 May 2017 (GOES-16); see the notes for the per-satellite archives + * - Formats + - NetCDF-4 (CF-1.7) in the geostationary projection + +Data Characteristics +-------------------- + +- Variables: Mask (fire category codes, e.g. 10 good-quality fire, 11 saturated, 12 cloud contaminated, 13-15 high / medium / low probability, 30-35 their temporally filtered versions), Power (MW), Temp (K), Area (m2) and DQF, plus viewing angles and summaries. +- Pixels are on the ABI fixed grid (geostationary projection) and need reprojection for latitude-longitude work. +- AWS buckets per satellite: noaa-goes16 (2017-05-24 to 2025-04-07), noaa-goes17 (2018-08-27 to January 2023), noaa-goes18 (from 2022-05-11) and noaa-goes19 (from 2024-10-17); GOES-East data after April 2025 are in noaa-goes19. Keys look like ABI-L2-FDCF/YYYY/DDD/HH/OR_ABI-L2-FDCF-M6_G16_s....nc. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- High-frequency fire activity time series over the Americas. +- Fire radiative power for growth and intensity analyses. +- Timing ignitions more precisely than polar-orbiting detections allow. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NOAA NESDIS GOES-R series data products `_ +- `NOAA GOES on the AWS Registry of Open Data `_ +- `NOAA STAR GOES-R fire product page `_ + +PyHazards Usage +--------------- + +PyHazards does not load this product; it is listed as an external reference. The ``goesr`` entry covers ABI imagery in general. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: NOAA Open Data Dissemination states that the data "are open to the public and can be used as desired", requests attribution and forbids implying NOAA endorsement. The "license" attribute inside the NetCDF files ("Access is restricted to approved users only") is boilerplate that does not apply to the open distribution. + +Reference +--------- + +- `Schmidt (2020). Monitoring Fires with the GOES-R Series. In The GOES-R Series, Elsevier, 145-163. `_. +- `GOES-R Algorithm Working Group (2018). NOAA GOES-R Series ABI Level 2 Fire/Hot Spot Characterization (FDC). NOAA NCEI. `_. +- `Schmidt, Hoffman, Prins and Lindstrom (2020). GOES-R ABI Algorithm Theoretical Basis Document for Fire / Hot Spot Characterization, version 2.7. NOAA NESDIS STAR. `_. diff --git a/docs/source/datasets/hms_smoke.rst b/docs/source/datasets/hms_smoke.rst new file mode 100644 index 00000000..d49683d0 --- /dev/null +++ b/docs/source/datasets/hms_smoke.rst @@ -0,0 +1,84 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +NOAA HMS Smoke Polygons +======================= + +Analyst-drawn smoke plume outlines from NOAA's Hazard Mapping System, produced daily since August 2005. + +Overview +-------- + +The Hazard Mapping System (HMS), first implemented in 2002, is NOAA's analyst-driven fire and smoke product: satellite analysts outline the smoke plumes visible in satellite imagery and record the satellite and the time window of each outline. + +The smoke polygons describe where smoke was visible, which fire detections and perimeters do not; they are commonly used to flag smoke-affected days and to link plumes to fires. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA NESDIS Office of Satellite and Product Operations (OSPO), Satellite Analysis Branch + * - Hazard Family + - Wildfire + * - Source Role + - Smoke Plumes + * - Coverage + - North America, Hawaii and the Caribbean + * - Geometry + - Analyst-drawn smoke polygons + * - Spatial Resolution + - Vector polygons (WGS84); annual smoke-day rasters at 0.05 deg + * - Temporal Resolution + - Daily analyses, the first around 11:00-12:00 US Eastern time and usually a second around 19:00-20:00; each polygon has start and end times + * - Update Cadence + - Daily + * - Period of Record + - 5 August 2005 to the present + * - Formats + - Zipped shapefiles (daily files and annual bundles), KML, annual GeoTIFF smoke-day rasters + +Data Characteristics +-------------------- + +- Attributes are Satellite, Start, End and Density (Light, Medium, Heavy or NA). +- The density attribute is consistently filled only from 1 June 2010; most earlier files have "NA" (apart from April-December 2008), so density-based analyses should start in mid-2010. +- File names and columns changed on 19 July 2022, when NOAA regenerated the historical archive; daily shapefiles are named hms_smokeYYYYMMDD.zip. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Flagging smoke-affected days and regions in air-quality or wildfire impact studies. +- Linking smoke plumes to fire detections and perimeters. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NOAA OSPO Hazard Mapping System `_ +- `HMS smoke polygon archive (shapefile, KML, GeoTIFF) `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for wildfire smoke extent. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: the OSPO pages state no licence; the data.gov catalogue record lists CC0. + +Reference +--------- + +- `Ruminski and Kondragunta (2006). Monitoring fire and smoke emissions with the hazard mapping system. Proc. SPIE 6412. `_. +- `Brey et al. (2018). Connecting smoke plumes to sources using Hazard Mapping System (HMS) smoke and fire location data over North America. Atmospheric Chemistry and Physics 18, 1745-1761. `_. diff --git a/docs/source/datasets/hrrr.rst b/docs/source/datasets/hrrr.rst new file mode 100644 index 00000000..ff766b5b --- /dev/null +++ b/docs/source/datasets/hrrr.rst @@ -0,0 +1,83 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +HRRR +==== + +NOAA's 3 km, hourly updated, convection-allowing forecast model for the United States, archived on AWS since July 2014. + +Overview +-------- + +The High-Resolution Rapid Refresh is NOAA's operational convection-allowing model. It is run every hour and produces short-range forecasts of near-surface and upper-air weather at 3 km. + +Its near-surface temperature, humidity, wind and precipitation forecasts are a common source of short-range fire-weather inputs; since HRRRv4 it also predicts wildfire smoke inline. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA (run operationally by NCEP; developed by the NOAA Global Systems Laboratory) + * - Hazard Family + - Shared Forcing + * - Source Role + - Weather Forecast + * - Coverage + - Conterminous United States; an Alaska domain from July 2018 + * - Geometry + - Gridded forecast fields + * - Spatial Resolution + - 3 km + * - Temporal Resolution + - Hourly forecast output; with HRRRv4 (since 2 December 2020) 18-hour forecasts every hour and 48-hour forecasts at 00, 06, 12 and 18 UTC + * - Update Cadence + - Every hour for CONUS; every 3 hours for Alaska + * - Period of Record + - AWS archive from 30 July 2014; operational since 30 September 2014 + * - Formats + - GRIB2 with .idx index files + +Data Characteristics +-------------------- + +- Forecast length changed with the model version: 15 hours until 2016, 18 hours from about September 2016, 36 hours at the synoptic cycles from mid-2018 and 48 hours from December 2020. +- Files are grouped into surface (wrfsfc), pressure-level (wrfprs), native-level (wrfnat) and sub-hourly (wrfsubh) products; AWS keys look like hrrr.YYYYMMDD/conus/hrrr.tHHz.wrfsfcfFF.grib2. +- The first two months on AWS predate operations and some early surface files are missing. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Short-range fire-weather covariates (wind, humidity, temperature) for wildfire models. +- Smoke forecast fields from HRRRv4 onwards. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NOAA HRRR on the AWS Registry of Open Data `_ +- `NOAA Rapid Refresh / HRRR information page `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for short-range weather forecasts. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: NOAA Open Data Dissemination states that the data "are open to the public and can be used as desired", requests attribution and forbids implying NOAA endorsement. + +Reference +--------- + +- `Dowell et al. (2022). The High-Resolution Rapid Refresh (HRRR): An Hourly Updating Convection-Allowing Forecast Model. Part I: Motivation and System Description. Weather and Forecasting 37(8), 1371-1395. `_. diff --git a/docs/source/datasets/hurricast_ibtracs_era5.rst b/docs/source/datasets/hurricast_ibtracs_era5.rst new file mode 100644 index 00000000..ae00d95b --- /dev/null +++ b/docs/source/datasets/hurricast_ibtracs_era5.rst @@ -0,0 +1,120 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Hurricast IBTrACS + ERA5 Inputs +=============================== + +The inputs of Hurricast (Boussioux et al. 2022): 30 IBTrACS statistical features and nine storm-centred ERA5 maps per 3-hour step, 8 steps per sample, with the 24-hour intensity or position as target. + +Overview +-------- + +``hurricast_ibtracs_era5`` builds Hurricast's samples. From IBTrACS (``read_ibtracs``) it keeps the rows on the 3-hour grid, interpolates the WMO wind and pressure linearly within each storm, and computes per step the 30 features of the official feature tables: latitude, longitude, WMO wind and pressure, distance to land, translation speed, cosine / sine of the day of year, direction, latitude and longitude, the Saffir-Simpson category value, one-hot basin and storm nature, and the latitude / longitude change since the previous step. + +Storms are selected like the official ``sort_storm``: kept when more than ``min_steps`` (20, i.e. 60 h) of their steps reach ``min_wind`` (34 kt), cut to start at the first such step and to at most ``max_steps`` (120) steps. Each window of 8 steps followed by 8 more gives a sample (windows whose target period has a step without any movement are dropped, as the official ``remove_zeros``). Winds of samples outside the North Atlantic and Eastern Pacific are converted from 10-minute to 1-minute values (/ 0.93). + +With ``era5=`` (a netCDF / zarr path or an ``xarray.Dataset`` with u, v and z, e.g. a Copernicus Climate Data Store download or the NCAR RDA copy) each step gets the nine maps u, v, z at 225, 500 and 700 hPa on the 25 x 25 one-degree grid centred on the grid point nearest to the storm (a 0.25-degree source is sampled at whole degrees). Maps are read only for samples of a split. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA NCEI (IBTrACS v04) and ECMWF / Copernicus Climate Change Service (ERA5), read from files the user provides + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Model Inputs (best track + reanalysis) + * - Coverage + - All IBTrACS basins (the paper reports test scores for the North Atlantic and Eastern Pacific) + * - Geometry + - Storm-centred sequences of feature vectors and 25 x 25 one-degree maps + * - Spatial Resolution + - Storm-centre positions; maps 25 x 25 at 1 degree around the storm + * - Temporal Resolution + - Three-hourly steps (t-21 h ... t), 24-hour lead time + * - Update Cadence + - Follows the user's IBTrACS and ERA5 files + * - Period of Record + - Paper: 1980-2019 (train 1980-2011, validation 2012-2015, test 2016-2019) + * - Formats + - IBTrACS v04 CSV or netCDF; ERA5 pressure-level netCDF / zarr (or an xarray Dataset) with u, v, z at 225, 500, 700 hPa + * - Registry Entry + - ``hurricast_ibtracs_era5`` + +Data Characteristics +-------------------- + +- Inputs per split: ``x_stat`` ``(N, 8, 30)``, ``x_viz`` ``(N, 8, 9, 25, 25)`` (channels u225, u500, u700, v..., z...; rows north to south) and ``position`` ``(N, 2)`` (latitude, longitude at the forecast time). Targets: ``target="intensity"`` the WMO wind 24 h ahead (1-minute kt, ``tc.intensity``); ``target="displacement"`` the position 24 h ahead ``(N, 1, 2)`` (``tc.track_intensity``). +- ``standardize=True`` standardises latitude, longitude, wind, pressure, distance to land, speed and the displacements (paper Table 2) and every map channel with the training split's statistics (recorded in the metadata); cyclic encodings and categories are left as they are. +- Splits by season (paper defaults: 1980-2011 / 2012-2015 / 2016-2019); the test split keeps only ``test_basins`` (NA, EP). The paper further restricts its test cases to those with ATCF operational forecasts (837 EP / 899 NA track cases), which needs the ATCF data and is not done here. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Training and evaluating Hurricast (encoder-decoder embeddings and XGBoost) on real storms. +- Multimodal (tabular + reanalysis map) 24-hour track and intensity forecasting experiments. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `IBTrACS v04r01 files (NOAA NCEI) `_ +- `ERA5 hourly data on pressure levels (Copernicus Climate Data Store) `_ +- `ERA5 on NCAR RDA (ds633.0) `_ + +PyHazards Usage +--------------- + +Fit ``hurricast`` with ``model.fit(train.inputs, train.targets, val.inputs, val.targets)`` and score it with the ``tc`` benchmark: ``tc.intensity`` (MAE in kt) or ``tc.track_intensity`` with lead 24 h (great-circle error in km, the paper's haversine metric). + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``hurricast_ibtracs_era5`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset( + "hurricast_ibtracs_era5", + path="ibtracs.since1980.list.v04r01.csv", + era5="era5_u_v_z_225_500_700.nc", # covering the storms' 25 x 25 degree neighbourhoods + target="intensity", + ).load() + train = data.get_split("train") + print(train.inputs["x_stat"].shape, train.inputs["x_viz"].shape, train.targets.shape) + +- path= is an IBTrACS v04 CSV or netCDF file; era5= is optional (without it only the statistical inputs are built, enough for HUML-(stat, xgb)). +- min_wind, min_steps, max_steps, window_size, predict_at, the split seasons, test_basins and basins can be changed; the defaults are the paper's. +- The official per-step CDS requests (area latitude +-12.008, longitude +-12, 1-degree grid) are not reproduced; the maps are cut from the data the user provides. + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`IBTrACS ` + +**Representative Models:** :doc:`Hurricast ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- The official repository (no licence) did not release the code that built the paper's 30-feature tables, only their column names; the features are computed from the paper (Table 2, footnote 2) and those names, and the storm selection, interpolation, category and displacement columns are checked against the released src/utils/data_processing.py. Differences from that code: rows off the 3-hour grid (e.g. landfall records at 10:15) are dropped, WMO values are interpolated within each storm (the official numeric_data interpolates across the whole table, so a storm's first gaps take values from the previous storm), and spur tracks are skipped. +- Neither file is redistributed: IBTrACS follows the WDC-Meteorology open-access policy, ERA5 is CC BY 4.0 (Copernicus). The tests use the 4-storm IBTrACS cut of tests/fixtures/ibtracs and a 9-time ERA5 cut around Hurricane Ophelia (tests/fixtures/era5). + +Reference +--------- + +- `Boussioux, L., C. Zeng, T. Guenais and D. Bertsimas (2022). Hurricane Forecasting: A Novel Multimodal Machine Learning Framework. Weather and Forecasting 37(6), 817-831. `_. +- `Knapp, K. R. et al. (2010). The International Best Track Archive for Climate Stewardship (IBTrACS). BAMS 91, 363-376; Gahtan, J. et al. (2024), IBTrACS v04r01, NOAA NCEI. `_. +- `Hersbach, H. et al. (2023). ERA5 hourly data on pressure levels from 1940 to present. Copernicus Climate Change Service (C3S) Climate Data Store. `_. diff --git a/docs/source/datasets/hurricast_synthetic.rst b/docs/source/datasets/hurricast_synthetic.rst new file mode 100644 index 00000000..d408fe7e --- /dev/null +++ b/docs/source/datasets/hurricast_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Hurricast Inputs +========================== + +Random inputs in the hurricast_ibtracs_era5 layout (8 steps of 30 statistical features and 9 maps of 25 x 25) for smoke tests of hurricast. + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run hurricast and the cyclone benchmark without IBTrACS or ERA5 files. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Feature sequences and image sequences + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``hurricast_synthetic`` + +Data Characteristics +-------------------- + +- x_stat (N, 8, 30) with standard-normal numerical features, cyclic encodings in [-1, 1] and valid one-hot basin / nature columns; x_viz (N, 8, 9, 25, 25) standard normal; position (N, 2); targets random winds (kt) or positions (target='displacement'). + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of hurricast and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; real data come from hurricast_ibtracs_era5. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``hurricast_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("hurricast_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`Hurricast ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/hydrobench_streamflow.rst b/docs/source/datasets/hydrobench_streamflow.rst deleted file mode 100644 index 7bcc3e1b..00000000 --- a/docs/source/datasets/hydrobench_streamflow.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. - -HydroBench -========== - -Synthetic-backed streamflow diagnostics adapter aligned to the HydroBench ecosystem. - -Overview --------- - -HydroBench is the public flood adapter used for streamflow diagnostics and HydroGraphNet-aligned benchmark runs. - -The current implementation is synthetic-backed, but it preserves the streamflow task and metric contract exposed by the shared flood benchmark. - -At a Glance ------------ - -.. list-table:: - :widths: 28 72 - :stub-columns: 1 - - * - Provider - - HydroBench ecosystem surfaced through a PyHazards adapter - * - Hazard Family - - Flood - * - Source Role - - Streamflow Benchmark - * - Coverage - - Benchmark-aligned streamflow forecasting samples - * - Geometry - - Graph-temporal basin or node sequences - * - Spatial Resolution - - Basin or gauge nodes represented as graph elements - * - Temporal Resolution - - Rolling history windows for streamflow prediction - * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs - * - Period of Record - - Synthetic-backed benchmark adapter - * - Formats - - PyTorch graph-temporal dataset objects via the dataset registry - * - Registry Entry - - ``hydrobench_streamflow`` - -Data Characteristics --------------------- - -- Graph-temporal sequences with node-level targets for next-step streamflow prediction. -- Registry-backed benchmark adapter rather than a raw HydroBench dataset ingestion path. -- Intended for HydroGraphNet smoke runs and flood benchmark diagnostics. - -Typical Use Cases -~~~~~~~~~~~~~~~~~ - -- HydroGraphNet smoke tests. -- Shared flood benchmark runs with HydroBench-aligned metrics. -- Diagnostics for graph-based flood forecasting experiments. - -Access ------- - -Use the links below to access the upstream source or its public documentation. - -- `HydroBench repository `_ - -PyHazards Usage ---------------- - -Use this adapter when you want the public HydroBench-aligned streamflow surface exposed by the flood benchmark. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``hydrobench_streamflow`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "hydrobench_streamflow", - micro=True, - history=4, - nodes=6, - ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) - -Related Coverage -~~~~~~~~~~~~~~~~ - -**Benchmarks:** :doc:`Flood Benchmark `, :doc:`HydroBench ` - -**Representative Models:** :doc:`HydroGraphNet ` - -Inspection Workflow -------------------- - -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. - -Notes ------ - -- This is a synthetic-backed benchmark adapter rather than a full HydroBench downloader. - -Reference ---------- - -- `HydroBench `_. diff --git a/docs/source/datasets/hydrographnet_white_river.rst b/docs/source/datasets/hydrographnet_white_river.rst new file mode 100644 index 00000000..3af157bd --- /dev/null +++ b/docs/source/datasets/hydrographnet_white_river.rst @@ -0,0 +1,115 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +HydroGraphNet White River +========================= + +Reader for a local copy of the HydroGraphNet dataset (HEC-RAS flood simulations on a 4,787-cell mesh of the White River near Muncie, Indiana), read as PhysicsNeMo's HydroGraphDataset reads it. + +Overview +-------- + +The dataset of HydroGraphNet (Taghizadeh et al., Computer-Aided Civil and Infrastructure Engineering 2025): HEC-RAS 2-D simulations of 500 boundary-inflow hydrographs with rainfall on the White River mesh, with per-cell terrain attributes (area, elevation, slope, aspect, curvature, Manning's n, flow accumulation, infiltration) and per-step water depth and volume. CC BY 4.0, Zenodo 14969507. + +``hydrographnet_white_river`` reproduces PhysicsNeMo's ``HydroGraphDataset``: it drops the first 72 steps of every hydrograph and cuts it 25 steps after the inflow peak, converts precipitation, builds the 4-nearest-neighbour graph with standardised (dx, dy, distance) edge features, standardises static features per column and the dynamic series with statistics of the training hydrographs, and yields the 16 node features, the next depth / volume change and the physics data of the continuity loss for every two-step window; test hydrographs are whole rollouts. PyHazards downloads nothing. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - Taghizadeh et al. (University of Virginia), Zenodo record 14969507; read by PyHazards from a local copy + * - Hazard Family + - Flood + * - Source Role + - Inundation Benchmark + * - Coverage + - White River near Muncie, Indiana, USA + * - Geometry + - Unstructured 2-D mesh cells with a k-nearest-neighbour graph + * - Spatial Resolution + - Mesh cells of about 80 m (4,787 cells) + * - Temporal Resolution + - 20-minute steps + * - Update Cadence + - Static research dataset (released 2025-03-05) + * - Period of Record + - 500 simulated inflow / rainfall events (hydrographs) + * - Formats + - Tab-separated text files (HydroGraphNet.zip, 8.3 GB) + * - Registry Entry + - ``hydrographnet_white_river`` + +Data Characteristics +-------------------- + +- Layout: ``M80_XY.txt``, ``M80_{CA,CE,CS,A,CU,N,FA,IP}.txt`` (static), ``M80_{WD,V,US_InF,Pr}_.txt`` per hydrograph ``H1`` ... ``H500``, ``train.txt``, ``static_norm_stats.json``, ``dynamic_norm_stats.json``. +- Training split: sliding windows (``n_time_steps=2``) with ``(node_features (N, 16), edge_features (E, 3), edge_index (2, E), physics)`` and the target (N, 2); batch them with ``hydrograph_collate``. +- Test split: one item per hydrograph with the first window, the normalised inflow / precipitation and the true depth / volume of the next ``rollout_length`` (30) steps. +- The release ships no test list: ``train.txt`` names all 500 hydrographs and the example's ``Test/test.txt`` is not published, so ``test_ids`` must be given (they are removed from the training list). + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Training and evaluating HydroGraphNet as in the PhysicsNeMo example. +- Mesh inundation rollouts scored in metres with the flood benchmark (``flood.inundation``). + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `HydroGraphNet dataset (Zenodo 14969507) `_ +- `PhysicsNeMo HydroGraphNet example `_ + +PyHazards Usage +--------------- + +Point ``data_dir`` at the unzipped release and pass the test hydrographs as ``test_ids``. + +Score models that provide ``rollout(...)`` (HydroGraphNet) with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.inundation``). + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``hydrographnet_white_river`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + # Unzipped HydroGraphNet.zip; hold out e.g. the last 50 hydrographs for rollouts. + data = load_dataset( + "hydrographnet_white_river", + data_dir="/data/HydroGraphNet", + test_ids=[f"H{i}" for i in range(451, 501)], + ).load() + inputs, target = data.get_split("train").inputs[0] + print(inputs["node_features"].shape, target.shape) # (4787, 16) (4787, 2) + +- ``norm_stats='files'`` uses the released normalisation statistics instead of recomputing them. + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Flood Benchmark `, :doc:`HydroGraphNet White River ` + +**Representative Models:** :doc:`HydroGraphNet ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Every training window, physics value and rollout target equals PhysicsNeMo's HydroGraphDataset on fixtures in the release layout (oracle test); a local check on real hydrographs of the release (H1, H2) matched as well. + +Reference +--------- + +- `Taghizadeh, Zandsalimi, Nabian, Shafiee-Jood and Alemazkoor (2025). Interpretable physics-informed graph neural networks for flood forecasting. Computer-Aided Civil and Infrastructure Engineering 40(18):2629-2649. `_ (`repo `__). diff --git a/docs/source/datasets/ibtracs_tracks.rst b/docs/source/datasets/ibtracs_tracks.rst index a3dbf0e3..e8c9a3e1 100644 --- a/docs/source/datasets/ibtracs_tracks.rst +++ b/docs/source/datasets/ibtracs_tracks.rst @@ -3,14 +3,14 @@ IBTrACS ======= -Synthetic-backed storm-track adapter aligned to the IBTrACS tropical cyclone archive. +NOAA NCEI's International Best Track Archive for Climate Stewardship (v04r01), read from its CSV or netCDF files into best-track forecasting windows. Overview -------- -IBTrACS is the public storm-track adapter used by PyHazards for shared tropical cyclone benchmark runs. +IBTrACS merges the best tracks of the WMO Regional Specialized Meteorological Centres and other agencies into one archive with a merged position (``LAT`` / ``LON``) and each agency's own positions, maximum sustained winds and central pressures (``USA_WIND``, ``TOKYO_WIND``, ``CMA_PRES``, ...). -The current implementation is synthetic-backed, but it preserves the track-intensity forecasting surface used by the shared tropical cyclone evaluator. +``ibtracs_tracks`` reads an IBTrACS v04 CSV or netCDF file with PyHazards' own reader (``pyhazards.datasets.tc.read_ibtracs``) and turns each storm into forecasting windows: ``history`` six-hourly observations of the chosen variables before a forecast time and the same variables at ``lead_hours`` after it. At a Glance ----------- @@ -20,53 +20,55 @@ At a Glance :stub-columns: 1 * - Provider - - NOAA NCEI International Best Track Archive for Climate Stewardship surfaced through a PyHazards adapter + - NOAA National Centers for Environmental Information (NCEI), merging the WMO Regional Specialized Meteorological Centres and other agencies * - Hazard Family - Tropical Cyclone * - Source Role - Track Archive * - Coverage - - Benchmark-aligned tropical cyclone track and intensity samples + - All tropical cyclone basins (NA, SA, EP, WP, NI, SI, SP) * - Geometry - Storm-track history sequences * - Spatial Resolution - - Storm-centered best-track sequences + - Storm-centre positions (0.1 degree precision) * - Temporal Resolution - - Historical track windows with forecast horizons + - Three-hourly track points (six-hourly synoptic times are used for samples) * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs + - Updated by NCEI several times a week; PyHazards reads the file the user downloads * - Period of Record - - Synthetic-backed benchmark adapter + - 1842 to present (agency coverage varies by basin and era) * - Formats - - PyTorch tensors via the dataset registry + - CSV (ibtracs..list.v04r01.csv) or netCDF (IBTrACS..v04r01.nc) * - Registry Entry - ``ibtracs_tracks`` Data Characteristics -------------------- -- Storm-history sequences with future latitude, longitude, and intensity targets. -- Registry-backed benchmark adapter rather than a raw IBTrACS archive loader. -- Supports both basin-specific hurricane models and broader tropical cyclone adapters. +- Inputs ``(samples, history, V)`` and targets ``(samples, len(lead_hours), V)`` hold the ``variables`` in physical units (default latitude, longitude, maximum sustained wind in knots, central pressure in hPa) from one ``agency`` (default ``usa``; ``wmo`` gives the WMO_WIND / WMO_PRES columns of the responsible RSMC). Windows need every value present; spur tracks are skipped unless ``include_spur``. +- Winds are as reported by each agency, which use different averaging periods (1-minute for the US agencies, 2-minute for CMA, 10-minute for most RSMCs); IBTrACS does not convert them. +- The merged ``LON`` stays continuous across the dateline (values above 180 occur); agency longitudes are wrapped to [-180, 180) and are unwrapped inside each window. The track error of the benchmark is a great-circle distance, which does not depend on the convention. +- CSV details handled by the reader: the second line holds units, missing values are a single space, and ``NA`` (North Atlantic) is a basin code, not a missing value. The netCDF file (storm x date_time arrays) gives the same table. Typical Use Cases ~~~~~~~~~~~~~~~~~ -- Hurricast smoke tests. -- Shared tropical cyclone benchmark runs for track and intensity prediction. -- Benchmark-aligned validation for weather-model storm adapters. +- Ground truth for track and intensity forecasts scored by the PyHazards cyclone benchmark. +- Training and evaluating best-track (persistence, CLIPER-style or learned) track and intensity models. Access ------ Use the links below to access the upstream source or its public documentation. -- `IBTrACS product page `_ +- `IBTrACS product page (NOAA NCEI) `_ +- `v04r01 CSV files `_ +- `v04r01 netCDF files `_ PyHazards Usage --------------- -Use this adapter when you want the public IBTrACS-aligned storm-track surface exposed by the tropical cyclone benchmark. +Score forecasts of any model that returns latitude, longitude and intensity at the dataset's lead times with the ``tc`` benchmark (``tc.track_intensity``): great-circle track error in km and wind / pressure MAE in knots / hPa, per lead time. Registry Workflow ~~~~~~~~~~~~~~~~~ @@ -76,24 +78,29 @@ Primary dataset name: ``ibtracs_tracks`` .. code-block:: python from pyhazards.datasets import load_dataset + from pyhazards.datasets.tc import download_ibtracs + path = download_ibtracs("data/ibtracs", subset="NA") # 58 MB; ALL is 333 MB data = load_dataset( "ibtracs_tracks", - micro=True, - history=6, - horizon=5, + path=str(path), + variables=["lat", "lon", "wind", "pres"], + history=4, + lead_hours=[24, 48, 72], + test_seasons=[2023, 2024], ).load() + test = data.get_split("test") + print(test.inputs.shape, test.targets.shape, data.metadata["units"]) - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) +- path= is an IBTrACS v04 CSV or netCDF file; alternatively cache_dir= with download=True fetches ibtracs..list.v04r01.csv from NCEI. +- Splits are by season: test_seasons / val_seasons (other seasons train); by default the last season is the test split and the one before validation. +- Split metadata lists each sample's SID, name, basin, season and forecast time (iso_time). Related Coverage ~~~~~~~~~~~~~~~~ **Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`IBTrACS ` -**Representative Models:** :doc:`Hurricast `, :doc:`GraphCast TC Adapter `, :doc:`Pangu TC Adapter `, :doc:`FourCastNet TC Adapter ` - Inspection Workflow ------------------- @@ -103,9 +110,11 @@ so there is no standalone inspection CLI documented for it. Notes ----- -- This is a synthetic-backed benchmark adapter rather than a full IBTrACS ingestion pipeline. +- Terms of use (NCEI): IBTrACS follows the World Data Center for Meteorology policy of full and open access, with WMO Resolution 40 as the guide for commercial use; it is not stated to be public domain. PyHazards downloads it from NCEI on request and never redistributes it; tests use a 4-storm cut of the official files (tests/fixtures/ibtracs). +- The files change several times a week, so they cannot be pinned by checksum; the dataset records the sha256 of the file it read (metadata source_sha256). Reference --------- -- `IBTrACS `_. +- `Knapp, K. R., M. C. Kruk, D. H. Levinson, H. J. Diamond and C. J. Neumann (2010). The International Best Track Archive for Climate Stewardship (IBTrACS): Unifying tropical cyclone best track data. Bulletin of the American Meteorological Society 91, 363-376. `_. +- `Gahtan, J., K. R. Knapp, C. J. Schreck, H. J. Diamond, J. P. Kossin and M. C. Kruk (2024). International Best Track Archive for Climate Stewardship (IBTrACS) Project, Version 4r01. NOAA National Centers for Environmental Information. `_. diff --git a/docs/source/datasets/landscan_population.rst b/docs/source/datasets/landscan_population.rst new file mode 100644 index 00000000..40438141 --- /dev/null +++ b/docs/source/datasets/landscan_population.rst @@ -0,0 +1,84 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +LandScan Global +=============== + +ORNL's annual 30 arc-second global grid of ambient (24-hour average) population, an exposure layer for hazard impact studies. + +Overview +-------- + +LandScan Global estimates the ambient (24-hour average) population of every 30 arc-second cell of the world, as one grid per year from 2000. + +For hazards it is a population-exposure layer: how many people live or spend time where a fire, flood or storm occurs. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - Oak Ridge National Laboratory (ORNL) + * - Hazard Family + - Shared Forcing + * - Source Role + - Population Exposure + * - Coverage + - Global + * - Geometry + - Gridded population rasters (WGS84 geographic) + * - Spatial Resolution + - 30 arc-seconds (about 1 km at the equator); 21,600 x 43,200 cells + * - Temporal Resolution + - Annual + * - Update Cadence + - Annual releases (LandScan Global 2024 was published in August 2025) + * - Period of Record + - 2000 to 2024 + * - Formats + - GeoTIFF + +Data Characteristics +-------------------- + +- One band of population counts per cell, one file per year. +- Ambient (24-hour average) population rather than night-time residence counts. +- Downloads from the ORNL portal require a short registration form; the 2000-2022 releases are also mirrored on figshare. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Population exposure to wildfire, flood or tropical-cyclone footprints. +- Weighting hazard maps by the people affected. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `LandScan portal (ORNL) `_ +- `LandScan Global 2024 record (OSTI) `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for population exposure. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: since May 2022 LandScan Global is released under the Creative Commons Attribution 4.0 International licence ("free to use, copy, distribute, transmit, and adapt the data for commercial and non-commercial purposes ... as long as clear attribution of the source is provided"). The figshare mirror is labelled CC0; the ORNL licence is the authoritative one. + +Reference +--------- + +- `Lebakula et al. (2025). LandScan Global 2024. Oak Ridge National Laboratory. `_. +- `Lebakula et al. (2025). LandScan Global 30 Arcsecond Annual Global Gridded Population Datasets from 2000 to 2022. Scientific Data 12, 495. `_. diff --git a/docs/source/datasets/ndfd.rst b/docs/source/datasets/ndfd.rst new file mode 100644 index 00000000..21ce0661 --- /dev/null +++ b/docs/source/datasets/ndfd.rst @@ -0,0 +1,85 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +NDFD +==== + +The National Weather Service's gridded official forecasts, including relative humidity, wind, Red Flag Warnings and SPC fire-weather outlook grids, archived since 2004. + +Overview +-------- + +The National Digital Forecast Database holds the official National Weather Service forecasts as grids: temperature, humidity, wind, precipitation, sky cover, weather type and hazard (watch / warning / advisory) elements, written by the forecast offices and national centres. + +For wildfire work it carries the fire-weather ingredients forecasters use (minimum relative humidity, wind and gusts) and the SPC fire-weather outlook grids. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA National Weather Service (forecast offices and NCEP; the Storm Prediction Center supplies the fire-weather outlooks) + * - Hazard Family + - Shared Forcing + * - Source Role + - Weather Forecast + * - Coverage + - United States and territories + * - Geometry + - Gridded forecast fields + * - Spatial Resolution + - 2.5 km for CONUS (2145 x 1377 Lambert conformal grid); separate Alaska, Hawaii, Puerto Rico, Guam and oceanic grids + * - Temporal Resolution + - Element-dependent forecast steps over days 1-7 + * - Update Cadence + - As often as every 30 minutes, depending on the element + * - Period of Record + - 6 June 2004 to the present at NCEI; AWS archive from 16 April 2020 + * - Formats + - GRIB2 + +Data Characteristics +-------------------- + +- Fire-relevant elements: SPC fire-weather outlooks (critfireo, critical and extremely critical areas, days 1-7; dryfireo, dry thunderstorm areas), minrh / maxrh / rhm, wspd / wdir / wgust, and the wwa hazard grid, whose codes include Red Flag Warning (FW.W) and Fire Weather Watch (FW.A). The SPC outlook grids became operational on 14 July 2011 and cover CONUS only. +- Archive access depends on the period: NCEI holds data from 6 June 2004 (older years in bulk archives, recent years online) and AWS from 16 April 2020. +- Some GRIB2 decoders misread the grid scanning order; NOAA recommends degrib, wgrib2 or grib2io. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Operational fire-weather forecast covariates and Red Flag Warning history. +- Comparing machine-learning forecasts with the official forecast. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NDFD at NOAA NCEI (archive) `_ +- `NOAA NDFD on the AWS Registry of Open Data `_ +- `Current NDFD GRIB2 files (NWS) `_ +- `NDFD documentation (NOAA MDL) `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for official fire-weather forecasts. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: NWS information is in the public domain unless noted otherwise and may be used for any lawful purpose as long as users do not claim it as their own, imply NWS endorsement, or present modified content as official (https://www.weather.gov/disclaimer). + +Reference +--------- + +- `Glahn and Ruth (2003). The New Digital Forecast Database of the National Weather Service. Bulletin of the American Meteorological Society 84(2), 195-202. `_. diff --git a/docs/source/datasets/nohrsc_snodas.rst b/docs/source/datasets/nohrsc_snodas.rst new file mode 100644 index 00000000..fd9977c9 --- /dev/null +++ b/docs/source/datasets/nohrsc_snodas.rst @@ -0,0 +1,84 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +SNODAS +====== + +NOAA NOHRSC's daily 1 km snow analysis (snow water equivalent, depth, melt, sublimation) for the conterminous United States, distributed by NSIDC since 2003. + +Overview +-------- + +SNODAS is a modelling and data-assimilation system developed by NOHRSC to provide the best possible daily estimates of snow cover and related variables on a 1 km grid, in support of hydrologic modelling and analysis. + +For hazard work it describes snowpack and melt timing, which shape spring flood risk and the length of the fire season in snow-dominated mountains. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - NOAA NWS National Operational Hydrologic Remote Sensing Center (NOHRSC); distributed by NOAA@NSIDC as data set G02158 + * - Hazard Family + - Shared Forcing + * - Source Role + - Snow Analysis + * - Coverage + - Masked version, conterminous United States and some Canadian basins (24.95-52.875 N, 124.733-66.942 W); unmasked version extends into Canada and Mexico + * - Geometry + - Regular latitude-longitude grid + * - Spatial Resolution + - 30 arc-seconds (nominally 1 km) + * - Temporal Resolution + - Daily; states are snapshots at 06 UTC, fluxes are 24-hour totals from 06 to 06 UTC + * - Update Cadence + - Daily + * - Period of Record + - Masked files from 30 September 2003, unmasked files from 9 December 2009; NSIDC discourages use before October 2004 + * - Formats + - Daily .tar files of gzipped flat binary 16-bit big-endian grids with text headers (NoData -9999) + +Data Characteristics +-------------------- + +- Eight variables: snow water equivalent, snow depth, snowmelt runoff, snowpack sublimation, blowing-snow sublimation, solid and liquid precipitation, and snowpack average temperature. +- Known defects documented by NSIDC: snow water equivalent and depth wrongly zero in 126,950 cells from 9 October 2014 to 10 October 2019 (a repair mask is provided), values saturating at 32.767 m, snowpack temperature missing before 21 February 2004 and a 5% cell shift on 1 October 2013. +- The unmasked version's coverage is not consistent until 2013. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Snowmelt inputs for spring flood and streamflow models. +- Snow-cover duration and melt timing as covariates of mountain fire seasons. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NSIDC data set G02158 `_ +- `NSIDC SNODAS file archive `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for snow state. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: NSIDC states "As a condition of using these data, you must cite the use of this data set" with the citation above. + +Reference +--------- + +- `National Operational Hydrologic Remote Sensing Center (2004). Snow Data Assimilation System (SNODAS) Data Products at NSIDC, Version 1. NSIDC. `_. +- `Barrett (2003). National Operational Hydrologic Remote Sensing Center Snow Data Assimilation System (SNODAS) Products at NSIDC. NSIDC Special Report 11. `_. diff --git a/docs/source/datasets/pick_benchmark_waveforms.rst b/docs/source/datasets/pick_benchmark_waveforms.rst deleted file mode 100644 index 008adadf..00000000 --- a/docs/source/datasets/pick_benchmark_waveforms.rst +++ /dev/null @@ -1,111 +0,0 @@ -.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. - -pick-benchmark -============== - -Synthetic-backed waveform picking adapter aligned to the pick-benchmark evaluation ecosystem. - -Overview --------- - -pick-benchmark is the public waveform adapter used by the earthquake benchmark for transformer and CNN picking baselines. - -The current implementation is synthetic-backed, but it preserves the phase-picking task shape, labels, and metrics expected by the shared earthquake evaluator. - -At a Glance ------------ - -.. list-table:: - :widths: 28 72 - :stub-columns: 1 - - * - Provider - - pick-benchmark ecosystem surfaced through a PyHazards adapter - * - Hazard Family - - Earthquake - * - Source Role - - Waveform Benchmark - * - Coverage - - Benchmark-aligned earthquake phase-picking samples - * - Geometry - - Multichannel waveform windows - * - Spatial Resolution - - Benchmark-defined waveform channels and sample windows - * - Temporal Resolution - - Short waveform windows with phase-pick targets - * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs - * - Period of Record - - Synthetic-backed benchmark adapter - * - Formats - - PyTorch tensors via the dataset registry - * - Registry Entry - - ``pick_benchmark_waveforms`` - -Data Characteristics --------------------- - -- Multichannel waveform windows paired with P- and S-arrival sample targets. -- Registry-backed benchmark adapter rather than a raw external waveform ingestion path. -- Intended for phase-picking validation and smoke tests. - -Typical Use Cases -~~~~~~~~~~~~~~~~~ - -- EQTransformer and GPD smoke tests. -- Shared earthquake picking benchmark runs. -- Regression checks for waveform-based picking models. - -Access ------- - -Use the links below to access the upstream source or its public documentation. - -- `pick-benchmark repository `_ - -PyHazards Usage ---------------- - -Use this adapter when you want the public pick-benchmark-aligned waveform surface exposed by the earthquake benchmark. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``pick_benchmark_waveforms`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "pick_benchmark_waveforms", - micro=True, - channels=3, - length=256, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) - -Related Coverage -~~~~~~~~~~~~~~~~ - -**Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`pick-benchmark ` - -**Representative Models:** :doc:`EQTransformer `, :doc:`GPD ` - -Inspection Workflow -------------------- - -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. - -Notes ------ - -- This is a synthetic-backed benchmark adapter rather than a full pick-benchmark downloader. - -Reference ---------- - -- `pick-benchmark `_. diff --git a/docs/source/datasets/safnet_cma_era_interim_synthetic.rst b/docs/source/datasets/safnet_cma_era_interim_synthetic.rst new file mode 100644 index 00000000..c55275c8 --- /dev/null +++ b/docs/source/datasets/safnet_cma_era_interim_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic SAF-Net Inputs +======================== + +Random inputs in the SAF-Net layout (96 wide predictors and (2, 4, 31, 31, 4) u/v wind cubes) for smoke tests of saf_net. + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone benchmark without downloading data. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Tabular feature vectors + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``safnet_cma_era_interim_synthetic`` + +Data Characteristics +-------------------- + +- Inputs uniform in [0, 1] like the MinMax-scaled official inputs; targets uniform in 10-70 m/s with a prediction_transform that maps the model's scaled output to m/s. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of the linked models and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``safnet_cma_era_interim_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("safnet_cma_era_interim_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`SAF-Net ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/seisbench_waveforms.rst b/docs/source/datasets/seisbench_waveforms.rst index 5fb54c8f..3921d28e 100644 --- a/docs/source/datasets/seisbench_waveforms.rst +++ b/docs/source/datasets/seisbench_waveforms.rst @@ -1,16 +1,16 @@ .. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. -SeisBench -========= +SeisBench-format Waveforms +========================== -Synthetic-backed waveform picking adapter aligned to the SeisBench ecosystem. +Reader for labelled three-component waveform datasets in the SeisBench format (STEAD, INSTANCE, ETHZ, ... as distributed for SeisBench) and in STEAD's own CSV + HDF5 layout. Overview -------- -SeisBench is the public waveform adapter used by PyHazards for the earthquake picking path. +``seisbench_waveforms`` reads real phase-picking datasets from disk: the SeisBench format (``metadata.csv`` + ``waveforms.hdf5``, optionally in chunks, with trace blocks ``$``) and the layout in which the STEAD authors distribute STEAD (``.csv`` + ``.hdf5``, one ``(6000, 3)`` E/N/Z array per trace). PyHazards implements the reader itself with ``h5py`` and ``csv``; SeisBench (GPL-3.0) is not imported. Its output equals SeisBench's ``WaveformDataset`` on a dataset written by SeisBench's ``WaveformDataWriter`` (``tests/oracle/test_seisbench_reader_oracle.py``). -The current implementation is synthetic-backed, but it preserves the picking task shape, labels, and metrics expected by the shared earthquake evaluator. +Nothing is downloaded or redistributed: STEAD is about 85 GB and INSTANCE's event waveforms about 160 GB. Download them from their providers (or with SeisBench, which converts them to its format) and pass the directory as ``path``. At a Glance ----------- @@ -20,54 +20,56 @@ At a Glance :stub-columns: 1 * - Provider - - SeisBench ecosystem surfaced through a PyHazards adapter + - Dataset authors (STEAD - Stanford; INSTANCE - INGV; others via SeisBench); read by PyHazards * - Hazard Family - Earthquake * - Source Role - Waveform Benchmark * - Coverage - - Benchmark-aligned earthquake phase-picking samples + - Dataset dependent (STEAD global; INSTANCE Italy) * - Geometry - - Multichannel waveform windows + - Three-component station waveform windows * - Spatial Resolution - - Benchmark-defined waveform channels and sample windows + - Single seismic stations * - Temporal Resolution - - Short waveform windows with phase-pick targets + - Dataset sampling rate (100 Hz for STEAD and INSTANCE) * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs + - Static benchmark releases downloaded by the user * - Period of Record - - Synthetic-backed benchmark adapter + - Dataset dependent (see the dataset papers) * - Formats - - PyTorch tensors via the dataset registry + - metadata CSV + waveform HDF5 * - Registry Entry - ``seisbench_waveforms`` Data Characteristics -------------------- -- Multichannel waveform windows paired with P- and S-arrival sample targets. -- Registry-backed benchmark adapter rather than a raw external waveform ingestion path. -- Intended for phase-picking validation and smoke tests. +- Inputs ``(n, 3, window)`` float32 in the dataset's component order (``metadata["component_order"]``, e.g. ``ZNE`` for SeisBench files, ``ENZ`` for STEAD's own files); the earthquake benchmark reorders channels to each model's order. Targets ``(n, 2)``: P and S arrival samples relative to the window start, NaN when a trace has no such arrival (noise traces) or it falls outside the window. +- Splits follow the dataset's ``split`` column (``train`` / ``dev`` -> ``val`` / ``test``). STEAD's own files have no split: ``test_trace_names`` (e.g. EQTransformer's ``ModelsAndSampleData/test.npy``) selects the test traces and the rest are ``train``; without it all traces are ``test``. +- Arrival columns are read in order of preference (``trace_p_arrival_sample``, ``trace_P_arrival_sample``, ``trace_P1_arrival_sample``, ``trace_Pg_arrival_sample``, ... and the S equivalents; ``p_arrival_sample`` / ``s_arrival_sample`` for STEAD files); ``phase_columns`` overrides the list. +- Licences: STEAD and INSTANCE are CC BY 4.0 (STEAD repository LICENSE; INGV INSTANCE page and repository). Cite the dataset papers below when publishing results. Typical Use Cases ~~~~~~~~~~~~~~~~~ -- PhaseNet and EQNet smoke tests. -- Shared earthquake benchmark runs on picking tasks. -- Regression checks for waveform-based seismic models. +- Scoring PhaseNet, EQTransformer and GPD (official weights) with the ``earthquake.picking`` benchmark. +- Training phase pickers on real labelled waveforms. Access ------ Use the links below to access the upstream source or its public documentation. -- `SeisBench paper `_ -- `SeisBench repository `_ +- `STEAD (download links and licence) `_ +- `INSTANCE (INGV) `_ +- `SeisBench data format `_ +- `SeisBench repository (GPL-3.0) `_ PyHazards Usage --------------- -Use this adapter when you want the public SeisBench-aligned waveform surface exposed by the earthquake benchmark. +Pair it with ``phasenet``, ``eqtransformer`` (60-s windows, ``window_samples=6000``) or ``gpd`` and the ``earthquake`` benchmark (``hazard_task=earthquake.picking``). Registry Workflow ~~~~~~~~~~~~~~~~~ @@ -78,22 +80,29 @@ Primary dataset name: ``seisbench_waveforms`` from pyhazards.datasets import load_dataset - data = load_dataset( + # A SeisBench-format directory (metadata.csv + waveforms.hdf5), e.g. SeisBench's copy of STEAD. + data = load_dataset("seisbench_waveforms", path="~/.seisbench/datasets/stead", max_traces=1000).load() + + # STEAD as distributed by its authors (merged.csv + merged.hdf5) with EQTransformer's test split. + stead = load_dataset( "seisbench_waveforms", - micro=True, - channels=3, - length=256, + path="/data/STEAD", + preset="stead", + test_trace_names="/data/STEAD/test.npy", ).load() + test = stead.get_split("test") + print(test.inputs.shape, test.targets.shape) # (n, 3, 6000), (n, 2) - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) +- ``window_samples`` / ``window_start`` cut a fixed window (zero-padded when a trace is shorter); traces of different lengths need it. +- ``max_traces`` keeps the first rows of each split (``micro=True`` keeps 8); ``trace_category`` filters STEAD's ``earthquake_local`` / ``noise`` rows. +- ``preset='instance'`` supplies INSTANCE's component order (E, N, Z) and 100 Hz when the files lack a ``data_format`` group. Related Coverage ~~~~~~~~~~~~~~~~ -**Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`SeisBench ` +**Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`SeisBench `, :doc:`pick-benchmark ` -**Representative Models:** :doc:`PhaseNet `, :doc:`EQNet ` +**Representative Models:** :doc:`PhaseNet `, :doc:`EQTransformer `, :doc:`GPD ` Inspection Workflow ------------------- @@ -104,9 +113,11 @@ so there is no standalone inspection CLI documented for it. Notes ----- -- This is a synthetic-backed benchmark adapter rather than a full SeisBench ingestion pipeline. +- Until this release ``seisbench_waveforms`` and ``pick_benchmark_waveforms`` generated synthetic Gaussian pulses; the synthetic data is now ``earthquake_waveforms_synthetic``. Reference --------- -- `SeisBench - A Toolbox for Machine Learning in Seismology `_ (`repo `__). +- `Woollam, J., Münchmeyer, J., Tilmann, F., et al. (2022). SeisBench - A Toolbox for Machine Learning in Seismology. Seismological Research Letters 93(3):1695-1709. `_ (`repo `__). +- `Mousavi, S. M., Sheng, Y., Zhu, W., Beroza, G. C. (2019). STanford EArthquake Dataset (STEAD): A Global Data Set of Seismic Signals for AI. IEEE Access 7:179464-179476. `_ (`repo `__). +- `Michelini, A., Cianetti, S., Gaviano, S., Giunchi, C., Jozinović, D., Lauciani, V. (2021). INSTANCE - the Italian seismic dataset for machine learning. Earth System Science Data 13:5509-5544. `_ (`repo `__). diff --git a/docs/source/datasets/ships_xu2021.rst b/docs/source/datasets/ships_xu2021.rst new file mode 100644 index 00000000..7a4102c9 --- /dev/null +++ b/docs/source/datasets/ships_xu2021.rst @@ -0,0 +1,108 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +SHIPS Predictors (Xu et al. 2021) +================================= + +The standardised SHIPS predictor table of Xu et al. (2021) with 24-hour intensity-change targets, read into the official leave-one-year-out folds. + +Overview +-------- + +Each row holds the SHIPS predictors of one storm at one forecast time, standardised by the reanalysis standard deviation, with ``name``, ``year``, ``basin``, ``type`` (``rea`` reanalysis predictors or ``opr`` operational predictors) and the target ``dvs24``, the 24-hour change of the maximum sustained wind in knots. + +``ships_xu2021`` selects the 121 predictors of the paper's 24-hour model (``SHIPS_PREDICTORS``) and builds the fold of ``leave_out_year`` as the official ``load_loyo_data`` does for the MLP: training rows are reanalysis rows except Atlantic rows of that year, test rows are that year's operational rows, and a random 10 % of the training rows (seeded) is the validation split. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - Xu et al. (PNNL), "Supporting data for Xu et al. 2021 - Weather and Forecasting" (Zenodo 4784610, CC BY 4.0), built from the SHIPS developmental data (NHC / CIRA) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Intensity Benchmark + * - Coverage + - Atlantic test basin; global training basins (AL, EP, WP, SH, ...) + * - Geometry + - Tabular feature vectors + * - Spatial Resolution + - One row per storm and forecast time + * - Temporal Resolution + - Six-hourly forecast times + * - Update Cadence + - Static release (2021) + * - Period of Record + - Reanalysis predictors 1982-2017 (global basins); operational predictors 2010-2018 (Atlantic) + * - Formats + - CSV (train_global_fill_REA_na_wo_img_scaled.csv, 392 MB) + * - Registry Entry + - ``ships_xu2021`` + +Data Characteristics +-------------------- + +- Inputs (samples, 121) float32 standardised predictors in the official order; targets (samples,) dvs24 in knots. +- Split metadata gives each row's year (``groups``), storm name and basin; the benchmark reports MAE per test year. +- Rows with a missing predictor or target are dropped (``drop_missing``). + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Training and evaluating the ``tropicalcyclone_mlp`` 24-hour intensity-change model (``tc.intensity`` task). + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `Zenodo record 4784610 (CC BY 4.0) `_ +- `tropicalcyclone_MLP repository `_ + +PyHazards Usage +--------------- + +Score with the ``tc`` benchmark and ``hazard_task: tc.intensity`` (MAE / RMSE in knots, per test year). + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``ships_xu2021`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + fold = load_dataset("ships_xu2021", path="train_global_fill_REA_na_wo_img_scaled.csv", leave_out_year=2018).load() + test = fold.get_split("test") + print(test.inputs.shape, test.targets.shape) # (cases, 121), (cases,) + +- The paper's leave-one-year-out test averages the folds 2010-2018 (2,464 Atlantic cases). + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`Tropical Cyclone MLP ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- The official loyo_testing.py reads a ``..._w2020.csv`` variant that is not in the Zenodo record. The independent 2019 / 2020 operational files of the record are not standardised and are not read. +- PyHazards never redistributes the table; tests use ten real rows cut from it (tests/fixtures/ships_xu2021). + +Reference +--------- + +- `Xu, W., K. Balaguru, A. August, N. Lalo, N. Hodas, M. DeMaria and D. Judi (2021). Deep Learning Experiments for Tropical Cyclone Intensity Forecasts. Weather and Forecasting 36(4), 1453-1470. `_. +- `Xu, W., et al. (2021). Supporting data for Xu et al. 2021 - Weather and Forecasting (Version 1). Zenodo. `_. diff --git a/docs/source/datasets/ships_xu2021_synthetic.rst b/docs/source/datasets/ships_xu2021_synthetic.rst new file mode 100644 index 00000000..dee904d7 --- /dev/null +++ b/docs/source/datasets/ships_xu2021_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic SHIPS Predictors +========================== + +Random inputs in the layout of ships_xu2021 (121 predictors, 24-hour intensity change in knots) for smoke tests of tropicalcyclone_mlp. + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone benchmark without downloading data. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Tabular feature vectors + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``ships_xu2021_synthetic`` + +Data Characteristics +-------------------- + +- (samples, 121) standard-normal inputs; targets are a fixed random linear function of two inputs plus noise, rounded, labelled knots; test years 2017 / 2018 alternate. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of the linked models and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``ships_xu2021_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("ships_xu2021_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`Tropical Cyclone MLP ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/tc_tracks_synthetic.rst b/docs/source/datasets/tc_tracks_synthetic.rst new file mode 100644 index 00000000..b2f018b7 --- /dev/null +++ b/docs/source/datasets/tc_tracks_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Storm Histories +========================= + +Random storm-history features and lat / lon / intensity targets for smoke tests of the generic experimental storm adapters (hurricast, tcif_fusion). + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone benchmark without downloading data. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Storm-track history sequences + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``tc_tracks_synthetic`` + +Data Characteristics +-------------------- + +- (samples, history=6, features=8) standard-normal inputs; targets (samples, horizon=5, 3) are the last step's first three features plus a fixed drift, labelled lat, lon and wind with lead times 6-30 h. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of the linked models and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``tc_tracks_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("tc_tracks_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`Hurricast `, :doc:`TCIF-fusion ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/tcbench_alpha.rst b/docs/source/datasets/tcbench_alpha.rst index a0989b29..cb54ec8b 100644 --- a/docs/source/datasets/tcbench_alpha.rst +++ b/docs/source/datasets/tcbench_alpha.rst @@ -3,14 +3,14 @@ TCBench Alpha ============= -Synthetic-backed storm-track benchmark adapter aligned to the TCBench Alpha ecosystem. +Weather-model cyclone tracks (Pangu-Weather, FourCastNet v2, AIFS; 2023) matched to IBTrACS, with the raw forecast fields they were tracked in; read by pyhazards.forecasts at a pinned revision. Overview -------- -TCBench Alpha is the public storm adapter used by several tropical cyclone baselines on the shared track-intensity evaluator. +TCBench provides data-processing tools, evaluation protocols and baselines to compare tropical cyclone forecasts: tracks extracted from numerical and data-driven weather models with TempestExtremes are matched with IBTrACS best tracks and scored by lead time. -The current implementation is synthetic-backed, but it preserves the task, metric, and reporting surface used by the shared tropical cyclone benchmark. +``pyhazards.forecasts.tcbench`` reads the released ``matched_tracks`` and ``unmatched_tracks`` files and, with HTTP range requests, only the variables a tracker needs from the raw forecast files. ``pyhazards.forecasts.tempest`` reproduces TCBench's TempestExtremes tracks from those fields byte for byte, and ``score_forecast_tracks(..., protocol="tcbench")`` its evaluation. At a Glance ----------- @@ -20,41 +20,39 @@ At a Glance :stub-columns: 1 * - Provider - - TCBench Alpha ecosystem surfaced through a PyHazards adapter + - TCBench project (Gomez et al.), MIT-licensed code and data on the Hugging Face Hub (TCBench/TCBench) * - Hazard Family - Tropical Cyclone * - Source Role - Track Benchmark * - Coverage - - Benchmark-aligned tropical cyclone track and intensity samples + - Global tropical cyclones present in IBTrACS * - Geometry - - Storm-track history sequences + - Storm-track tables and global gridded forecast fields * - Spatial Resolution - - Storm-centered best-track sequences + - 0.25-degree global fields; track points on that grid * - Temporal Resolution - - Historical track windows with forecast horizons + - Six-hourly forecast steps to 120 h, initialised at 00 and 12 UTC * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs + - Static release (PyHazards pins revision 0124d14d) * - Period of Record - - Synthetic-backed benchmark adapter + - 2023 forecasts (TCBench's test year) * - Formats - - PyTorch tensors via the dataset registry - * - Registry Entry - - ``tcbench_alpha`` + - CSV track tables (matched_tracks, unmatched_tracks) and netCDF4 forecast fields (about 3 GB per forecast) Data Characteristics -------------------- -- Storm-history sequences with future latitude, longitude, and intensity targets. -- Registry-backed benchmark adapter rather than a raw external benchmark ingestion path. -- Intended for benchmark-linked track-intensity forecasting runs. +- matched_tracks/2023_.csv: SID, Initial Time, Valid Time, wind max (m/s in the released files), pressure min (Pa), lat, lon. +- unmatched_tracks: TempestExtremes StitchNodes CSV per forecast (track_id, time, grid indices, lon, lat, slp, wind10). +- neural_weather_models: int16-packed netCDF4 fields (msl, u10, v10, t2m and u, v, z, t, q on 13 levels for Pangu-Weather) for lead times 6-120 h. +- TCBench's evaluation reads IBTrACS LAT / LON as float16, which shifts its position errors by up to several km; the tcbench protocol reproduces this. Typical Use Cases ~~~~~~~~~~~~~~~~~ -- Tropical Cyclone MLP, SAF-Net, and TCIF-fusion smoke tests. -- Shared tropical cyclone benchmark runs. -- Regression checks for storm-track baselines. +- Scoring weather-model cyclone tracks against IBTrACS with TCBench's protocol. +- Re-tracking published weather-model forecasts with other trackers (e.g. the ECMWF-style tracker of the Pangu-Weather and GraphCast papers). Access ------ @@ -62,50 +60,33 @@ Access Use the links below to access the upstream source or its public documentation. - `TCBench Alpha repository `_ +- `TCBench data on the Hugging Face Hub `_ PyHazards Usage --------------- -Use this adapter when you want the public TCBench Alpha-aligned storm surface exposed by the tropical cyclone benchmark. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``tcbench_alpha`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "tcbench_alpha", - micro=True, - history=6, - horizon=5, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) +Not a registered dataset: the tracks are forecasts, not training data. Use ``pyhazards.forecasts.read_tcbench_matched_tracks`` / ``read_tcbench_fields`` and score with ``pyhazards.forecasts.score_forecast_tracks`` against IBTrACS (see the Foundation Weather Models page). Related Coverage ~~~~~~~~~~~~~~~~ **Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`TCBench Alpha ` -**Representative Models:** :doc:`Tropical Cyclone MLP `, :doc:`SAF-Net `, :doc:`TCIF-fusion ` - Inspection Workflow ------------------- -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. Notes ----- -- This is a synthetic-backed benchmark adapter rather than a full TCBench Alpha ingestion pipeline. +- The repository and the Hugging Face dataset are MIT-licensed (Copyright (c) 2023 Milton Gomez). +- The Pangu-Weather forecasts derive from weights licensed CC BY-NC-SA 4.0 (non-commercial use only). +- TCBench's "FourCastNet v2" is NVIDIA's SFNO-small, not the FourCastNet (AFNO) of Pathak et al. 2022. Reference --------- -- `TCBench Alpha `_. +- `Gomez, M. et al. (2026). TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale. arXiv:2601.23268. `_. +- `TCBench Alpha (repository and documentation) `_. diff --git a/docs/source/datasets/tcif_fusion_synthetic.rst b/docs/source/datasets/tcif_fusion_synthetic.rst new file mode 100644 index 00000000..b6dec7a0 --- /dev/null +++ b/docs/source/datasets/tcif_fusion_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic TCIF-fusion Inputs +============================ + +Random inputs in the TCIF-fusion layout (ERA5 U, V, W, SST, ALL, 30 history features, infrared images; channels last) for smoke tests of tcif_fusion. + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run tcif_fusion and the cyclone benchmark; the paper's inputs (CMA best track, ERA5, GridSat-B1) have no PyHazards reader yet. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Gridded fields, images and feature vectors + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``tcif_fusion_synthetic`` + +Data Characteristics +-------------------- + +- u, v, w (N, grid, grid, 5, 4), sst (N, grid, grid, 5, 1), all (their concatenation, 65 channels), his (N, 30), ir (N, ir_size, ir_size, 5); targets uniform 10-70 m/s. The defaults are the paper's sizes (grid 25, IR 224); the smoke config uses grid 9 and IR 32 with a small model. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of tcif_fusion and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``tcif_fusion_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("tcif_fusion_synthetic", micro=True, grid_size=9, ir_size=32).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`TCIF-fusion ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/tropicyclonenet_dataset.rst b/docs/source/datasets/tropicyclonenet_dataset.rst index 41508b57..2ec92192 100644 --- a/docs/source/datasets/tropicyclonenet_dataset.rst +++ b/docs/source/datasets/tropicyclonenet_dataset.rst @@ -1,16 +1,16 @@ .. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. -TropiCycloneNet-Dataset +TropiCycloneNet Dataset ======================= -Synthetic-backed storm-track benchmark adapter aligned to the TropiCycloneNet-Dataset ecosystem. +The TropiCycloneNet Dataset (TCND) of Huang et al. (2025) - best tracks, environmental features and ERA5 500 hPa geopotential for 3,630 storms in six basins - read in the layout of the official TropiCycloneNet loader. Overview -------- -TropiCycloneNet-Dataset is the public storm adapter used by the TropiCycloneNet model path on the shared track-intensity evaluator. +TCND combines Data1d (best-track position, central pressure and 2-minute maximum wind, normalised), Data3d (ERA5 geopotential, wind and SST around the storm) and Env-Data (intensity class, motion, month, location bins, 12/24-hour motion direction, 24-hour intensity change). It is the training and test data of the TropiCycloneNet model. -The current implementation is synthetic-backed, but it preserves the task, metric, and reporting surface used by the shared tropical cyclone benchmark. +``tropicyclonenet_dataset`` builds samples exactly like the official ``TrajectoryDataset`` and ``seq_collate`` (checked by an oracle test): windows of 8 observed and 4 future six-hourly steps, the observed track and its steps, Env-Data per observed step and 64 x 64 scaled 500 hPa geopotential frames; targets are the future latitude, longitude, pressure (hPa) and wind (m/s). At a Glance ----------- @@ -20,53 +20,55 @@ At a Glance :stub-columns: 1 * - Provider - - TropiCycloneNet-Dataset ecosystem surfaced through a PyHazards adapter + - Huang et al. (authors of the TropiCycloneNet paper), Zenodo releases under CC BY 4.0 * - Hazard Family - Tropical Cyclone * - Source Role - Track Benchmark * - Coverage - - Benchmark-aligned tropical cyclone track and intensity samples + - Six basins (EP, NA, NI, SI, SP, WP) * - Geometry - Storm-track history sequences * - Spatial Resolution - - Storm-centered best-track sequences + - Storm-centre positions (0.1 degree); 20 x 20 degree ERA5 crops at 0.25 degree * - Temporal Resolution - - Historical track windows with forecast horizons + - Six-hourly * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs + - Static releases (Zenodo 15009527 dataset, 17104690 training data) * - Period of Record - - Synthetic-backed benchmark adapter + - 1950-2023 (paper experiments 1950-2016 train / validation, 2017-2021 test) * - Formats - - PyTorch tensors via the dataset registry + - Tab-separated Data1d text files, pickled Env-Data .npy dicts, GPH .npy crops (and Data3d netCDF) * - Registry Entry - ``tropicyclonenet_dataset`` Data Characteristics -------------------- -- Storm-history sequences with future latitude, longitude, and intensity targets. -- Registry-backed benchmark adapter rather than a raw external dataset ingestion path. -- Intended for benchmark-linked storm forecasting smoke runs. +- Expected layout (the official loader's names under ``root``): ``BST_data///BST.txt``, ``Env_data////.npy`` and ``ERA5_gph500////.npy``; the Zenodo training-data archives extract to ``bst_divi10_train_val_test_inlcude15_2023``, ``all_area_correct_location_includeunder15_2023`` and ``all_ocean_gph500_2023`` (pass them as ``data1d_dir``, ``env_dir`` and ``gph_dir``). +- Normalisation of Data1d: longitude = 5 x + 180 degrees east, latitude = 5 y, pressure = 50 p + 960 hPa, wind = 25 w + 40 m/s. GPH crops (100 x 100) are resized to 64 x 64 bilinearly and scaled with the range (44490.578125, 58768.4486860389), clipped to [0, 1]. +- Env-Data features that are not yet defined (value -1, e.g. the 24-hour history at a track's start) are replaced by the first defined value in the window, as the official loader does. The Env-Data files also contain future-looking keys (future_direction24, future_inte_change24), which are not read. +- The whole requested split is loaded into memory (about 0.13 MB per sample); restrict ``areas``, ``splits`` or ``max_samples`` for large runs. Env-Data files are pickled numpy objects (loaded with allow_pickle); only read files from the official release. Typical Use Cases ~~~~~~~~~~~~~~~~~ -- TropiCycloneNet smoke tests. -- Shared tropical cyclone benchmark runs. -- Regression checks for track-intensity prediction models. +- Training and evaluating TropiCycloneNet (``tropicyclonenet``) with its official inputs. +- Multi-basin track and intensity forecasting at 6-24 h scored with the cyclone benchmark. Access ------ Use the links below to access the upstream source or its public documentation. +- `TCND on Zenodo (10.5281/zenodo.15009527) `_ +- `TCN_M training data on Zenodo (record 17104690) `_ - `TropiCycloneNet-Dataset repository `_ PyHazards Usage --------------- -Use this adapter when you want the public TropiCycloneNet-Dataset-aligned storm surface exposed by the tropical cyclone benchmark. +Score ``tropicyclonenet`` (or any model with a ``forecast`` method returning lat / lon / pres / wind) with the ``tc`` benchmark; sampled forecasts get the paper's best-of-k errors and sample-mean errors. Registry Workflow ~~~~~~~~~~~~~~~~~ @@ -79,18 +81,22 @@ Primary dataset name: ``tropicyclonenet_dataset`` data = load_dataset( "tropicyclonenet_dataset", - micro=True, - history=6, - horizon=5, + data1d_dir="TCND/bst_divi10_train_val_test_inlcude15_2023", + env_dir="TCND/all_area_correct_location_includeunder15_2023", + gph_dir="TCND/all_ocean_gph500_2023", + areas=["WP"], + splits=["test"], ).load() + test = data.get_split("test") + print(test.inputs["obs_traj"].shape, test.inputs["image_obs"].shape, test.targets.shape) - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) +- Inputs are a dict: obs_traj / obs_traj_rel (8, N, 4), image_obs (N, 1, 8, 64, 64), env_data (nine arrays (N, 8, width)); targets (N, 4, 4) = lat, lon, pres, wind at 6-24 h. +- root= is accepted when the three folders are named BST_data, Env_data and ERA5_gph500. Related Coverage ~~~~~~~~~~~~~~~~ -**Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`TropiCycloneNet-Dataset ` +**Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`TropiCycloneNet Dataset ` **Representative Models:** :doc:`TropiCycloneNet ` @@ -103,9 +109,9 @@ so there is no standalone inspection CLI documented for it. Notes ----- -- This is a synthetic-backed benchmark adapter rather than a full TropiCycloneNet-Dataset downloader. +- Licence: the Zenodo releases are CC BY 4.0 (the GitHub dataset repository has no LICENSE file although its README mentions MIT). PyHazards never redistributes the data; tests use one storm's real Data1d and Env-Data files (EP 2018 Carlotta, tests/fixtures/tcnd) and generated geopotential crops of the real shape. Reference --------- -- `TropiCycloneNet-Dataset `_. +- `Huang, C., P. Mu, J. Zhang, S. Chan, S. Zhang, H. Yan, S. Chen and C. Bai (2025). Benchmark dataset and deep learning method for global tropical cyclone forecasting. Nature Communications 16, 5923. `_. diff --git a/docs/source/datasets/tropicyclonenet_dataset_synthetic.rst b/docs/source/datasets/tropicyclonenet_dataset_synthetic.rst new file mode 100644 index 00000000..9661b8b8 --- /dev/null +++ b/docs/source/datasets/tropicyclonenet_dataset_synthetic.rst @@ -0,0 +1,97 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic TCND Samples +====================== + +Random inputs in the TropiCycloneNet (TCND) layout with random-walk targets for smoke tests of tropicyclonenet. + +Overview +-------- + +Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone benchmark without downloading data. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real storms) + * - Hazard Family + - Tropical Cyclone + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Storm-track history sequences + * - Spatial Resolution + - Not applicable (random numbers) + * - Temporal Resolution + - Not applicable (random numbers) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``tropicyclonenet_dataset_synthetic`` + +Data Characteristics +-------------------- + +- obs_traj / obs_traj_rel (8, N, 4) normalised random walks, image_obs (N, 1, 8, 64, 64) uniform, env_data random one-hot features; targets (N, 4, 4) lat, lon, pressure (hPa) and wind (m/s) continuing the walk. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of the linked models and of the cyclone benchmark. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + + +PyHazards Usage +--------------- + +Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``tropicyclonenet_dataset_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("tropicyclonenet_dataset_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + +**Representative Models:** :doc:`TropiCycloneNet ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True, and benchmark results report it. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_. diff --git a/docs/source/datasets/urbanfloodcast_synthetic.rst b/docs/source/datasets/urbanfloodcast_synthetic.rst new file mode 100644 index 00000000..092e744c --- /dev/null +++ b/docs/source/datasets/urbanfloodcast_synthetic.rst @@ -0,0 +1,98 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Synthetic Urban Flood Events +============================ + +Random urban flood events in the UrbanFloodCast one-shot layout (current state, rainfall and terrain in; depth and discharges of 24 steps out), for smoke tests of urbanfloodcast. + +Overview +-------- + +Synthetic data. Each event is a random rain pulse on a tilted random terrain with NaN "buildings"; scores on it mean nothing. The events go through ``prepare_urbanfloodcast_event``, the official UrbanFloodCast one-shot preparation (checked against the official ``flood_data``), so the inputs ``(n, Sy, Sx, 24, 1, 5)``, targets ``(n, Sy, Sx, 24, 3)`` and NaN mask have the layout of the real benchmark. PyHazards has no reader for the Berlin GeoTIFFs yet (Zenodo 10.5281/zenodo.15700880). + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards (generated in memory; no real flood) + * - Hazard Family + - Flood + * - Source Role + - Synthetic Smoke Data + * - Coverage + - None (synthetic) + * - Geometry + - Raster inundation sequences + * - Spatial Resolution + - Not applicable (32 x 32 synthetic cells) + * - Temporal Resolution + - Not applicable (24 synthetic output steps) + * - Update Cadence + - Generated on every load + * - Period of Record + - None (synthetic) + * - Formats + - PyTorch tensors via the dataset registry + * - Registry Entry + - ``urbanfloodcast_synthetic`` + +Data Characteristics +-------------------- + +- Inputs per cell and step: depth, x / y unit discharge at the start (repeated), log(1 + rain / 0.01) / 10, terrain L2-normalised along x; targets: depth, x / y unit discharge; the mask is in ``split.metadata['mask']``. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Smoke tests and CI runs of urbanfloodcast and of the ``flood.inundation`` raster evaluation. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `UrbanFloodCast benchmark dataset (Zenodo, real data, not read by PyHazards) `_ + +PyHazards Usage +--------------- + +Use only for smoke tests. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``urbanfloodcast_synthetic`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + data = load_dataset("urbanfloodcast_synthetic", micro=True).load() + print(data.get_split("train").inputs.shape) # (2, 32, 32, 24, 1, 5) + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Flood Benchmark ` + +**Representative Models:** :doc:`UrbanFloodCast ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- Bundle metadata carries synthetic=True. + +Reference +--------- + +- `PyHazards synthetic smoke data (pyhazards/datasets/flood/urbanfloodcast.py) `_. diff --git a/docs/source/datasets/waterbench_streamflow.rst b/docs/source/datasets/waterbench_streamflow.rst deleted file mode 100644 index e9530966..00000000 --- a/docs/source/datasets/waterbench_streamflow.rst +++ /dev/null @@ -1,112 +0,0 @@ -.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. - -WaterBench -========== - -Synthetic-backed streamflow benchmark adapter aligned to the WaterBench ecosystem. - -Overview --------- - -WaterBench is the public flood streamflow adapter used by the EA-LSTM path on the shared flood benchmark. - -The current implementation is synthetic-backed, but it preserves the streamflow forecasting contract expected by the shared evaluator. - -At a Glance ------------ - -.. list-table:: - :widths: 28 72 - :stub-columns: 1 - - * - Provider - - WaterBench ecosystem surfaced through a PyHazards adapter - * - Hazard Family - - Flood - * - Source Role - - Streamflow Benchmark - * - Coverage - - Benchmark-aligned streamflow forecasting samples - * - Geometry - - Graph-temporal basin or node sequences - * - Spatial Resolution - - Basin or gauge nodes represented as graph elements - * - Temporal Resolution - - Rolling history windows for streamflow prediction - * - Update Cadence - - Generated locally for smoke and benchmark-alignment runs - * - Period of Record - - Synthetic-backed benchmark adapter - * - Formats - - PyTorch graph-temporal dataset objects via the dataset registry - * - Registry Entry - - ``waterbench_streamflow`` - -Data Characteristics --------------------- - -- Graph-temporal sequences with node-level targets for next-step streamflow prediction. -- Registry-backed benchmark adapter rather than a raw WaterBench ingestion pipeline. -- Intended for benchmark-linked streamflow smoke runs. - -Typical Use Cases -~~~~~~~~~~~~~~~~~ - -- EA-LSTM smoke tests. -- Shared flood benchmark runs with streamflow metrics. -- Regression checks for basin-scale forecasting experiments. - -Access ------- - -Use the links below to access the upstream source or its public documentation. - -- `WaterBench abstract `_ -- `WaterBench repository `_ - -PyHazards Usage ---------------- - -Use this adapter when you want the public WaterBench-aligned streamflow surface exposed by the flood benchmark. - -Registry Workflow -~~~~~~~~~~~~~~~~~ - -Primary dataset name: ``waterbench_streamflow`` - -.. code-block:: python - - from pyhazards.datasets import load_dataset - - data = load_dataset( - "waterbench_streamflow", - micro=True, - history=4, - nodes=6, - ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) - -Related Coverage -~~~~~~~~~~~~~~~~ - -**Benchmarks:** :doc:`Flood Benchmark `, :doc:`WaterBench ` - -**Representative Models:** :doc:`EA-LSTM ` - -Inspection Workflow -------------------- - -This dataset is currently surfaced as a registry-backed benchmark adapter, -so there is no standalone inspection CLI documented for it. - -Notes ------ - -- This is a synthetic-backed benchmark adapter rather than a full WaterBench downloader. - -Reference ---------- - -- `WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting `_ (`repo `__). diff --git a/docs/source/datasets/wildfire_track_o.rst b/docs/source/datasets/wildfire_track_o.rst new file mode 100644 index 00000000..fa06f8c2 --- /dev/null +++ b/docs/source/datasets/wildfire_track_o.rst @@ -0,0 +1,120 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Track-O Wildfire Occurrence +=========================== + +Daily fire / no-fire grids from NASA FIRMS detections with gridded weather and LANDFIRE fuel covariates, built locally for gridded wildfire-danger experiments. + +Overview +-------- + +Track-O ("occurrence") is the real-data wildfire setting contributed in PyHazards PR #33: on a daily latitude-longitude grid, predict whether a cell has at least one satellite fire detection on a day from that day's weather (and, in the temporal layout, the preceding days) and a static fuel layer. + +``scripts/build_wildfire_track_o_cache.py`` turns NASA FIRMS active-fire CSVs, daily weather NetCDF files and an optional LANDFIRE fuel-model GeoTIFF into a cache of per-day NumPy arrays; the three registered datasets read that cache as raster, temporal or tabular samples. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - PyHazards cache builder (PR #33, runyangxu) over NASA FIRMS, MERRA-2 or other gridded weather, and LANDFIRE + * - Hazard Family + - Wildfire + * - Source Role + - Occurrence Benchmark + * - Coverage + - The weather grid's extent (global for MERRA-2); the LANDFIRE fuel layer covers the conterminous United States only + * - Geometry + - Daily latitude-longitude grids + * - Spatial Resolution + - That of the weather grid (0.5 deg x 0.625 deg for MERRA-2), optionally subsampled + * - Temporal Resolution + - Daily (UTC days) + * - Update Cadence + - Built by the user from downloaded source files; PyHazards downloads nothing for it + * - Period of Record + - Any period covered by the user's weather and FIRMS files; the default split is calendar year 2024 + * - Formats + - NetCDF weather, FIRMS CSV and LANDFIRE GeoTIFF inputs; NumPy .npy cache + * - Registry Entry + - ``wildfire_track_o_raster`` + +Data Characteristics +-------------------- + +- Label: 1 where at least one FIRMS detection falls nearest to the cell centre on that UTC day (``acq_date``). By default only FIRMS ``type`` 0 (presumed vegetation fire) is kept, which drops volcanoes, other static land sources and offshore detections. ``type`` exists only in the standard-quality (archive) files, so near-real-time files are used unfiltered; detections outside the grid are ignored. +- Weather: daily means of the requested variables, by default the 14 MERRA-2 surface variables T2M, QV2M, TQV, U10M, V10M, GWETROOT, TS, LAI, EFLUX, HFLUX, SWGNT, SWTNT, LWGAB and LWGEM, standardised with training-split statistics; missing values (MERRA-2 land variables over the ocean) become 0 after standardisation. +- Fuel: the most frequent LANDFIRE fuel-model code (FBFM13 or FBFM40) within each cell divided by 100, plus a validity mask; both are 0 outside the raster. LANDFIRE's -9999 fill is excluded and the non-burnable codes (91, 92, 93, 98 and 99) are kept as codes. The code is categorical, so the scaled value is only a crude numeric encoding (kept from PR #33). +- Same-day setting: the label of day t is paired with the weather of day t. With reanalysis weather such as MERRA-2 this is not a forecast, because that weather is only known afterwards. +- Default split (PR #33): train 2024-01-01 to 2024-09-30, validation October 2024, test November-December 2024. The test months have a different fire regime from the training months. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Gridded wildfire danger baselines scored by the PyHazards wildfire benchmark (``wildfire.danger``). +- Comparing tabular (tree), raster and temporal models on the same daily fire labels. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `NASA FIRMS archive download `_ +- `MERRA-2 at NASA GES DISC `_ +- `LANDFIRE `_ +- `PyHazards PR #33 (original Track-O pipeline) `_ + +PyHazards Usage +--------------- + +Build a cache with ``python scripts/build_wildfire_track_o_cache.py --cache-dir DIR --weather-dir WEATHER --firms-dir FIRMS [--fuel-raster LANDFIRE.tif]``. The default variables are in the MERRA-2 hourly collections M2T1NXSLV (T2M, QV2M, TQV, U10M, V10M, TS), M2T1NXLND (GWETROOT, LAI), M2T1NXFLX (EFLUX, HFLUX) and M2T1NXRAD (SWGNT, SWTNT, LWGAB, LWGEM), which can be passed as they are (an Earthdata login is needed to download them); the ``MERRA2_sfc_YYYYMMDD.nc`` files written by ``python -m pyhazards.datasets.merra2.inspection YYYYMMDD`` also hold them. Any NetCDF files with the variables on a regular latitude-longitude grid and the date in the file name work. Aligning the fuel raster needs ``pip install 'pyhazards[geo]'``. + +Train and score registry models with ``python scripts/run_wildfire_track_o_baselines.py --cache-dir DIR --output-dir RUNS``; it writes per-seed histories, metrics and settings. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``wildfire_track_o_raster`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + + # micro=True is a small synthetic cache for smoke tests; pass cache_dir="..." for real data. + data = load_dataset("wildfire_track_o_raster", micro=True).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (days, channels, height, width), (days, 1, height, width) + +- ``wildfire_track_o_temporal`` gives windows of ``history`` consecutive days (default 6) ``(samples, history, channels, height, width)``; windows that would cross a missing day are skipped. ``wildfire_track_o_tabular`` gives one row per cell and day with the weather, normalised latitude / longitude, day-of-year sine and cosine and the fuel columns, and int64 labels. +- ``downsample_factor`` keeps every f-th grid row and column (defaults: 4 raster, 8 temporal and tabular) and ``spatial_multiple`` crops the grid to a multiple of it (4 by default; 16 for the U-Net). +- ``micro=True`` replaces the cache with random fields on a 64 x 96 grid; its numbers mean nothing. + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Wildfire Benchmark ` + +**Representative Models:** :doc:`Logistic Regression (pixel) `, :doc:`U-Net `, :doc:`ConvLSTM `, :doc:`Random Forest `, :doc:`XGBoost ` + +Inspection Workflow +------------------- + +This dataset is currently surfaced as a registry-backed benchmark adapter, +so there is no standalone inspection CLI documented for it. + +Notes +----- + +- PR #33 took its weather from its own Prithvi-WxC forecast files, which were not published; the builder reads MERRA-2 (or any gridded NetCDF) instead. PR #33's fuel alignment wrote the LANDFIRE layer north-up onto a grid whose latitude runs south to north (as MERRA-2's and Prithvi-WxC's files do), which puts CONUS fuels at 22-52 degrees south, and shifted it by half a cell; the builder here aligns it to the cell edges and the cache's row order. +- PyHazards publishes no real-data Track-O results. ``scripts/run_wildfire_track_o_baselines.py`` has only been run on the synthetic micro cache and on small synthetic fixtures. + +Reference +--------- + +- `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product: Algorithm description and initial assessment. `_. +- `Giglio, Schroeder and Justice (2016). The collection 6 MODIS active fire detection algorithm and fire products. `_. +- `Gelaro et al. (2017). The Modern-Era Retrospective Analysis for Research and Applications, Version 2 (MERRA-2). `_. +- `Rollins (2009). LANDFIRE: A nationally consistent vegetation, wildland fire, and fuel assessment. `_. diff --git a/docs/source/datasets/wrc_housing_density.rst b/docs/source/datasets/wrc_housing_density.rst new file mode 100644 index 00000000..45629de6 --- /dev/null +++ b/docs/source/datasets/wrc_housing_density.rst @@ -0,0 +1,82 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +Wildfire Risk to Communities: Housing Density +============================================= + +USDA Forest Service 30 m rasters of housing-unit density, exposure and wildfire risk for populated areas of the United States (2nd edition, 2024). + +Overview +-------- + +The Wildfire Risk to Communities populated-areas data set (RDS-2020-0060-2) maps where people and homes are and how exposed they are to wildfire, combining census housing and population estimates with building footprints and the Forest Service wildfire hazard layers. + +Its housing-unit density layer (HUDen) gives housing units per square kilometre at 30 m, an exposure covariate for wildfire-risk and wildland-urban-interface studies. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - USDA Forest Service, Rocky Mountain Research Station (Forest Service Research Data Archive) + * - Hazard Family + - Wildfire + * - Source Role + - Exposure and Risk + * - Coverage + - Conterminous United States, Alaska and Hawaii (per-state files and CONUS mosaics) + * - Geometry + - Gridded raster layers + * - Spatial Resolution + - 30 m + * - Temporal Resolution + - Static snapshot + * - Update Cadence + - Edition-based (2nd edition published June 2024, metadata corrected September 2024) + * - Period of Record + - Housing from 2020 Census estimates, building footprints reflecting 2022, wildfire hazard from LANDFIRE 2020 (v2.2.0) + * - Formats + - LZW-compressed GeoTIFF + +Data Characteristics +-------------------- + +- Ten layers: BuildingCount, BuildingDensity, BuildingCover, PopCount, PopDen, HUCount, HUDen (housing units per square kilometre), HUExposure, HUImpact and HURisk. +- HUExposure, HUImpact and HURisk are NoData outside populated areas. +- The 1st edition (RDS-2020-0060) used 2018 Census estimates; the 2nd edition uses 2020 housing estimates. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Housing exposure and wildland-urban-interface covariates for wildfire models. +- Weighting wildfire hazard maps by the homes at risk. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `Forest Service Research Data Archive, RDS-2020-0060-2 `_ + +PyHazards Usage +--------------- + +PyHazards does not load this source; it is listed as an external reference for wildfire exposure. + +Inspection Workflow +------------------- + +PyHazards has no inspection command or loader for this source; it is listed +as an external reference. Use the provider's access links above. + +Notes +----- + +- Terms: the data "can be used without additional permissions or fees"; the archive asks that publications cite the data set as above, and gives no warranty. + +Reference +--------- + +- `Jaffe, Scott, Callahan, Dillon, Karau and Lazarz (2024). Wildfire Risk to Communities: Spatial datasets of wildfire risk for populated areas in the United States. 2nd Edition. Forest Service Research Data Archive. `_. diff --git a/docs/source/datasets/wrf_sfire.rst b/docs/source/datasets/wrf_sfire.rst new file mode 100644 index 00000000..412703c5 --- /dev/null +++ b/docs/source/datasets/wrf_sfire.rst @@ -0,0 +1,127 @@ +.. This file is generated by scripts/render_dataset_docs.py. Do not edit by hand. + +WRF-SFIRE Outputs +================= + +Fire-grid outputs of the coupled WRF-SFIRE atmosphere-fire model, read from wrfout files into spread rasters. + +Overview +-------- + +WRF-SFIRE couples the WRF atmosphere model with SFIRE, a level-set fire-spread model with Rothermel rate of spread and two-way heat and moisture flux coupling (Mandel, Beezley and Kochanski, GMD 2011). + +PyHazards does not run WRF-SFIRE, which is an MPI Fortran model built per machine, and reimplements none of it. It reads the fire-grid fields that a WRF-SFIRE run writes to its wrfout history files and turns them into wildfire.spread rasters and samples. + +At a Glance +----------- + +.. list-table:: + :widths: 28 72 + :stub-columns: 1 + + * - Provider + - OpenWFM WRF-SFIRE (University of Colorado Denver and collaborators); runs made by the user + * - Hazard Family + - Wildfire + * - Source Role + - Simulator Outputs + * - Coverage + - Any WRF domain the user configures + * - Geometry + - Fire-grid raster time series + * - Spatial Resolution + - Fire mesh of DX/sr_x by DY/sr_y (typically a few to tens of metres) + * - Temporal Resolution + - WRF history interval of the run + * - Update Cadence + - Generated by the user's own WRF-SFIRE runs + * - Period of Record + - Whatever the user simulates + * - Formats + - NetCDF WRF history files (wrfout) + * - Inspection CLI + - ``python -m pyhazards.datasets.wrf_sfire.inspection --path /path/to/wrfout_d01_*`` + * - Registry Entry + - ``wrf_sfire_spread`` + +Data Characteristics +-------------------- + +- Fire-grid variables have dimensions (Time, south_north_subgrid, west_east_subgrid); the fire mesh is sr_x by sr_y times finer than the atmospheric grid, and the last sr_y rows and sr_x columns are padding, which the reader removes. +- TIGN_G is the fire arrival time in seconds since the simulation start where a cell has burned; unburned cells hold a time one fire step in the future. +- LFN is the level-set function; the fire region is LFN < 0, which the reader uses as the burned mask. +- FIRE_AREA (fraction of the cell on fire), FUEL_FRAC, FGRNHFX (ground heat flux, W/m^2), ROS and F_ROS (rate of spread, m/s), FLINEINT, NFUEL_CAT, ZSF, UF/VF and FXLONG/FXLAT can be read as extra fields. Names, units and descriptions follow Registry/registry.fire of release W4.4-S0.1. +- XTIME gives the output times in minutes since the simulation start; arrays are returned north-up by default (origin='upper') or in WRF's south-up order. + +Typical Use Cases +~~~~~~~~~~~~~~~~~ + +- Training or evaluating spread models on physics-based simulations of chosen scenarios. +- Comparing learned spread models with a coupled atmosphere-fire model on the same domain. +- Extracting arrival-time maps and burned-area time series from WRF-SFIRE runs. + +Access +------ + +Use the links below to access the upstream source or its public documentation. + +- `WRF-SFIRE repository (official code) `_ +- `Running WRF-SFIRE with real data in the WRFx system `_ +- `wrfxpy (official Python workflow for real-data runs) `_ + +PyHazards Usage +--------------- + +Use load_dataset('wrf_sfire_spread', paths=...) for wildfire.spread samples, or read_wrf_sfire_fire_grid for the raw fire grid. + +PyHazards only reads WRF-SFIRE outputs; producing them needs the official WRF-SFIRE build and its inputs (meteorology, fuels, topography), for example through wrfxpy. + +Registry Workflow +~~~~~~~~~~~~~~~~~ + +Primary dataset name: ``wrf_sfire_spread`` + +.. code-block:: python + + from pyhazards.datasets import load_dataset + from pyhazards.datasets.wrf_sfire import read_wrf_sfire_fire_grid + + # Next-frame spread samples: burned mask (LFN < 0) plus chosen fields -> next burned mask. + data = load_dataset("wrf_sfire_spread", paths="run/wrfout_d01_*", horizon=1, features=("NFUEL_CAT", "ZSF")).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (N, 3, rows, cols), (N, 1, rows, cols) + + # Or the raw fire grid: arrival time (s since simulation start) and burned masks. + grid = read_wrf_sfire_fire_grid("run/wrfout_d01_*", variables=("TIGN_G", "LFN", "FIRE_AREA")) + print(grid.arrival_time().shape, grid.burned_masks().shape, grid.fire_dx) + +- There is no synthetic fallback; paths must point at wrfout files from a real WRF-SFIRE run. +- Splits are chronological over the output frames of the run. + +Related Coverage +~~~~~~~~~~~~~~~~ + +**Benchmarks:** :doc:`Wildfire Benchmark ` + +Inspection Workflow +------------------- + +Use the documented inspection path below to validate local files before training or analysis. + +.. code-block:: bash + + python -m pyhazards.datasets.wrf_sfire.inspection --path /path/to/wrfout_d01_* + +- Prints the fire-grid size and spacing, the burned area of each output frame and the range of fire arrival times. + +Notes +----- + +- The reader was checked on a real history file of the official ideal case test/em_fire/hill (WRF-SFIRE W4.4-S0.1 built locally); the header of that file is kept in tests/fixtures/wrf_sfire_hill_wrfout_header.json and the unit tests write synthetic files with the same layout. +- The former wrf_sfire model entry was a fixed diffusion kernel unrelated to WRF-SFIRE and was removed; this reader replaces it. + +Reference +--------- + +- `Mandel, Beezley and Kochanski (2011). Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011. Geoscientific Model Development 4:591-610. `_ (`repo `__). +- `Mandel et al. (2014). Recent advances and applications of WRF-SFIRE. Natural Hazards and Earth System Sciences 14:2829-2845. `_. diff --git a/docs/source/index.rst b/docs/source/index.rst index 7804de80..e08d4255 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -287,6 +287,9 @@ for project discussion and coordination. pyhazards_datasets pyhazards_models + pyhazards_prompted + pyhazards_simulators + pyhazards_forecasts pyhazards_benchmarks pyhazards_configs pyhazards_reports diff --git a/docs/source/modules/models_asufm.rst b/docs/source/modules/models_asufm.rst index 388e3e7f..f5639a3f 100644 --- a/docs/source/modules/models_asufm.rst +++ b/docs/source/modules/models_asufm.rst @@ -6,7 +6,7 @@ ASUFM Overview -------- -``asufm`` is a compact temporal convolution baseline for next-window wildfire activity prediction. +``asufm`` is a Swin U-Net (patch 4, embedding 96, depths (2, 2, 2, 2), heads (3, 6, 12, 24), window 8) whose encoder blocks apply focal modulation before window attention, with patch-expanding decoder stages and skip connections. It maps one day of Next Day Wildfire Spread (NDWS) features, 64x64 at 1 km, to logits for the next day's fire mask (Li & Rad, IEEE CAI 2024). At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Forecasting + Segmentation .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,9 +63,9 @@ At a Glance Description ----------- -``asufm`` is a compact temporal convolution baseline for next-window wildfire activity prediction. +``asufm`` is a Swin U-Net (patch 4, embedding 96, depths (2, 2, 2, 2), heads (3, 6, 12, 24), window 8) whose encoder blocks apply focal modulation before window attention, with patch-expanding decoder stages and skip connections. It maps one day of Next Day Wildfire Spread (NDWS) features, 64x64 at 1 km, to logits for the next day's fire mask (Li & Rad, IEEE CAI 2024). -PyHazards exposes it through the shared wildfire benchmark and config workflow. +The implementation reproduces the official fire-asufm code (``get_asfum_6_configs`` with six features by default, ``get_asufm_12_configs`` with all twelve) with the same parameter names and initialisation, so official checkpoints load with ``strict=True``. It is assembled from MIT-licensed Swin Transformer and FocalNet blocks rather than copied, because the official model package derives from the unlicensed Attention Swin U-Net code. Benchmark Compatibility ----------------------- @@ -75,7 +75,25 @@ Benchmark Compatibility External References ------------------- -**Paper:** `Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer `_ | **Repo:** `Repository `__ +**Paper:** `Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data `_ (`repo `__): Dataset used by ASUFM (64x64 tiles, 12 input features). The official training script uses six features (elevation, th, sph, pr, NDVI, PrevFireMask), BCE with pos_weight 3, AdamW (amsgrad) lr 1e-4 with cosine annealing and linear warm-up, batch 16 and mixed precision; the authors also release a 2012-2023 North America extension on Kaggle. The paper reports, on NDWS (Table I), PR-AUC 0.3728, precision 0.4301, recall 0.4050 and Dice 0.4109, and on the extended dataset (Table IV, 35M parameters) PR-AUC 0.3974 and Dice 0.4066, trained with weighted BCE (positive weight 3.0), Adam with weight decay 0.05, cosine annealing with warm-up and batch 16. +- `Focal Modulation Networks `_ (`repo `__): Focal modulation in the encoder blocks (focal level 1, window 3). +- `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_ (`repo `__): Window-attention blocks, patch merging and patch embedding. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/bronteee/fire-asufm `__ at ``688dda9`` (Apache-2.0) +- **Checked configuration:** ASUFM(get_asfum_6_configs(), num_classes=1) and ASUFM(get_asufm_12_configs(), num_classes=1) from configs/asufm.py (35,047,840 and 35,057,056 parameters), plus the focal=False variant get_swin_unet_attention_configs, on (batch, 6 or 12, 64, 64) inputs. +- **Parameter count:** 35,047,840 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_swin_oracle.py`` +- **Deviation:** The official blocks return their window-attention maps and the decoder adds the encoder's maps to them ("spatial attention"), but the sums are discarded and never reach the output. They are not computed here; outputs are identical. +- **Deviation:** The configuration's cross-contextual-attention mode (CrossViT skips) is not part of ASUFM and is not implemented. Registry Name ------------- @@ -85,7 +103,7 @@ Primary entrypoint: ``asufm`` Supported Tasks --------------- -- Forecasting +- Segmentation Programmatic Use ---------------- @@ -95,17 +113,17 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="asufm", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) - preds = model(torch.randn(2, 12, 7)) - print(preds.shape) + # Six NDWS features: elevation, th, sph, pr, NDVI, PrevFireMask. + model = build_model(name="asufm", task="segmentation", in_channels=6) + logits = model(torch.randn(2, 6, 64, 64)) + print(logits.shape) # (2, 1, 64, 64) Notes ----- -- The smoke path uses weekly wildfire count windows with seasonal time features. +- Inputs must be 64x64 (img_size); the architecture is tied to the token grid it was built for. +- Decoder stages fuse each skip connection twice through the same concat_back_dim layer, because the configured spatial-attention branch concatenates and projects again. This is the official behaviour and is kept. +- Decoder blocks contain focal-modulation weights that the official code never applies; the top-level patch_embed (4 input channels) and decoder.norm are also unused. All are kept so official state dicts load. +- The official model ignores the config's drop_path_rate, attn_drop_rate, ape and patch_size (fixed at 0.1, 0, False and 4). +- The paper (Section III-A) describes spatial attention carried along the skip connections; in the official code those maps never reach the output (see the first deviation), so the released network is a Swin U-Net with focal modulation. The paper's 35M parameter count (Table IV) matches. +- The authors' Kaggle checkpoint link (bronteli/attention-swin-u-net-with-focal-modulation-asufm) returned HTTP 404 on 2026-10-07, so no trained weights are checked. diff --git a/docs/source/modules/models_attention_unet.rst b/docs/source/modules/models_attention_unet.rst new file mode 100644 index 00000000..bdf36dd8 --- /dev/null +++ b/docs/source/modules/models_attention_unet.rst @@ -0,0 +1,135 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Attention U-Net +=============== + +Overview +-------- + +``attention_unet`` is an encoder-decoder with strided-convolution down-sampling and transposed-convolution up-sampling in which every skip connection is multiplied by an attention map before it is merged with the decoder feature, following the additive attention gate of Oktay et al. (2018). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``attention_unet`` is an encoder-decoder with strided-convolution down-sampling and transposed-convolution up-sampling in which every skip connection is multiplied by an attention map before it is merged with the decoder feature, following the additive attention gate of Oktay et al. (2018). + +The implementation reproduced is MONAI's ``AttentionUnet`` (MONAI 1.3.2, Apache-2.0), because that is what the wildfire paper used, ported to plain PyTorch with MONAI's module names so MONAI state dicts load with ``strict=True``. It is not Oktay et al.'s official network: MONAI computes the gate at the skip resolution from the already up-sampled decoder feature, with no grid sub-sampling of the gating signal, a single gate per level and no deep supervision. + +With the defaults (``spatial_dims=3``) the model is TS-SatFire's Attention-U-Net-3D: input ``(batch, time, channels, H, W)``, 3D convolutions over (time, H, W) with stride (1, 2, 2) at every level so time is never down-sampled, widths 64-1024, and two-class logits averaged over time to ``(batch, 2, H, W)``. ``spatial_dims=2`` gives TS-SatFire's single-image 2D baseline (stride 2 at every level, input ``(batch, channels, H, W)``). + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Attention U-Net: Learning Where to Look for the Pancreas `_ | **Repo:** `Repository `__ + +Used In +------- + +- `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ (`repo `__): Attention-U-Net-3D from the repository's modified MONAI copy (channels 64-1024, stride (1, 2, 2) at every level) on 256x256 tiles of daily VIIRS and auxiliary data, 43 channels after the land-cover one-hot for next-day progression prediction, T in {2, 4, 6}, logits averaged over time; Dice loss, Adam lr 0.0012, batch 8, 100 epochs. Paper Table 3 (6 input days; arXiv 2412.11555): 94.5M parameters, F1 0.770 / 0.712 / 0.354 and IoU 0.654 / 0.607 / 0.312 on active fire / burned area / prediction. The 2D Attention-U-Net (stock MONAI, stride 2) has 31.7M parameters and F1 0.763 / 0.793 on active fire / burned area. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Project-MONAI/MONAI `__ at ``1.3.2`` (Apache-2.0) +- **Checked configuration:** TS-SatFire's AttentionUnet(spatial_dims=3, in_channels=43, out_channels=2, channels=(64, 128, 256, 512, 1024), strides=(1, 2, 2)) from spatial_models/attentionunet.py at da75732 (MONAI 1.2/1.3.0 code with shared strides; the repository has no license and is used only as a test oracle) on monai 1.3.2, with its outputs averaged over time; MONAI 1.3.2 AttentionUnet(spatial_dims=2, in_channels=8, out_channels=2, same channels, strides=(2, 2, 2, 2)) for the 2D baseline (31,743,282 parameters); and 1D/2D/3D MONAI configurations with non-uniform per-level strides, kernel size 5 and dropout. Forward passes use 32x32 (3D, T=2) and 64x64 (2D) inputs instead of 256x256 to keep the CPU test fast. +- **Parameter count:** 94,555,506 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_attention_unet_oracle.py`` +- **Deviation:** Architecture is MONAI's, not the official Attention-Gated-Networks code (eee4881, MIT), which is not ported. Its 3D segmentation networks (unet_grid_attention_3D, unet_CT_single/multi_att_dsv_3D) down-sample with max pooling at widths [64, 128, 256, 512, 1024] / feature_scale (4 by default), take the gating signal from a coarser level, sub-sample the skip feature with a strided theta convolution (attention_dsample (2, 2, 2)) before the additive gate, up-sample the attention map trilinearly and pass the gated feature through a 1x1 convolution and BatchNorm; the CT models add deep supervision (and two gates per level in the multi-attention model), and all use Kaiming initialisation. MONAI gates at the skip resolution with the up-convolved decoder feature, has one gate per level, no deep supervision and PyTorch's default initialisation. +- **Deviation:** TS-SatFire's copy was taken from MONAI 1.2/1.3.0 and ignores ``kernel_size`` (its blocks are always 3x3x3); this port honours ``kernel_size`` as MONAI 1.3.2 does. The two are identical at the kernel size 3 that TS-SatFire uses. +- **Deviation:** TS-SatFire averages the 3D logits over time in its training script (``outputs.mean(2)``); here that read-out is part of the model (``time_reduction="mean"``), which also takes PyHazards' ``(batch, time, channels, H, W)`` layout instead of ``(batch, channels, time, H, W)``. +- **Deviation:** Configurations the reference rejects with IndexError or NotImplementedError (too few strides, even kernel sizes) or a size-mismatch RuntimeError (spatial sizes not divisible by the stride product) raise ValueError instead. +- **Deviation:** The paper reports 94.5M parameters for Attention-U-Net-3D across all three tasks; the prediction configuration with 43 input channels has 94,555,506 (94,495,026 with the 8-channel active-fire / burned-area input). + +Registry Name +------------- + +Primary entrypoint: ``attention_unet`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # TS-SatFire prediction model: 43 channels, logits averaged over the input days. + model = build_model(name="attention_unet", task="segmentation", in_channels=43) + logits = model(torch.randn(1, 4, 43, 64, 64)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 64, 64) + + # TS-SatFire's single-image 2D baseline. + model_2d = build_model(name="attention_unet", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 64, 64)).shape) # (1, 2, 64, 64) + +Notes +----- + +- Every spatial size must be divisible by the product of the strides along that dimension: 16 for height and width with the default four levels; time is never down-sampled. +- The default two output channels follow TS-SatFire, which applied a sigmoid Dice loss to both; use out_channels=1 for a single-logit binary head. +- time_reduction='none' returns per-date maps (batch, classes, time, H, W), as TS-SatFire uses for its active-fire and burned-area tasks. +- strides follow MONAI (one entry per level, each an int or one value per dimension); stride_mode='shared' takes TS-SatFire's single strides=(1, 2, 2) literally and builds the same network as strides=[(1, 2, 2)] * 4. +- MONAI quirks are kept: the merge convolution after each gate uses instance norm and PReLU, and dropout is applied in the convolution blocks and merges but never in the gates or up-convolutions. diff --git a/docs/source/modules/models_convgru.rst b/docs/source/modules/models_convgru.rst new file mode 100644 index 00000000..c1713ee1 --- /dev/null +++ b/docs/source/modules/models_convgru.rst @@ -0,0 +1,131 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +ConvGRU +======= + +Overview +-------- + +``convgru`` runs a stack of convolutional GRU cells over a ``(batch, time, channels, height, width)`` sequence and maps the hidden state of the last time step to per-pixel logits with a ``Conv2d`` head. Each cell follows Ballas et al.: one convolution over ``[x_t, h_{t-1}]`` gives the update and reset gates, a second convolution over ``[x_t, r * h_{t-1}]`` gives the candidate, and ``h_t = (1 - z) * h_{t-1} + z * tanh(candidate)``. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``convgru`` runs a stack of convolutional GRU cells over a ``(batch, time, channels, height, width)`` sequence and maps the hidden state of the last time step to per-pixel logits with a ``Conv2d`` head. Each cell follows Ballas et al.: one convolution over ``[x_t, h_{t-1}]`` gives the update and reset gates, a second convolution over ``[x_t, r * h_{t-1}]`` gives the candidate, and ``h_t = (1 - z) * h_{t-1} + z * tanh(candidate)``. + +The default is the Conv-GRU baseline of FireCastNet (Michail et al., Scientific Reports 2025), as in its ``configs/conv-gru-config.yaml``: 11 SeasFire variables, one layer of 128 hidden channels, 5x5 kernels, a dense 64x64 logit map trained with BCE on every pixel. FireCastNet's code has no license, so the module is written from the equations; it is checked against FireCastNet's ``ConvGRUSeg``, whose state dicts load with ``strict=True``, and gives identical outputs and seeded initial weights. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Delving Deeper into Convolutional Networks for Learning Video Representations `_ + +Used In +------- + +- `FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction `_ (`repo `__): Conv-GRU baseline (arXiv:2502.01550). SeasFire datacube (0.25 degree, 8-day steps), 11 inputs (mslp, tp, vpd, sst, t2m_mean, ssrd, swvl1, lst_day, ndvi, pop_dens and the land-sea mask), binary burned area (gwis_ba) h periods ahead, years 2002-2017 / 2018 / 2019 for training / validation / testing, BCE, AdamW lr 1e-3. Global test AUPRC with 24 input steps (Table 2): 0.593 / 0.579 / 0.556 / 0.551 / 0.545 / 0.569 for h = 1 / 2 / 4 / 8 / 16 / 24; with 12 steps (Figure 3) 0.624 / 0.614 / 0.604 / 0.593 / 0.582 / 0.579, the best Conv-GRU setting, and with 6 steps 0.604 / 0.597 / 0.586 / 0.571 / 0.560 / 0.557. FireCastNet scores 0.641 at h = 1 with 24 steps. +- `A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA) `_ (`repo `__): Same cell, different model. WildfireIA's ConvGRU baseline (train.py ConvGRUClassifier at aba9be9, MIT) is one cell with 64 channels and 3x3 kernels on 29x29 event patches, read out by global pooling and an MLP to one score. Initial-attack failure prediction: AUPRC 41.2 +/- 1.6, AUROC 84.1 +/- 0.6 (Table 3); containment duration: MAE 36.4 h (Table 6). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/SeasFire/firecastnet `__ at ``dc0d131`` (none (no LICENSE file; seasfire/backbones/conv_gru.py is used only as the test oracle, not copied)) +- **Checked configuration:** configs/conv-gru-config.yaml: ConvGRULit(input_dim_grid_nodes 11, hidden_layers 1, hidden_dim 128, kernel_size [5, 5]) -> ConvGRUSeg(..., num_classes=1), 64x64 patches, checked on (batch, 12, 11, 64, 64) inputs, also with all-zero (padding) steps; the paper's 64 hidden channels (361,793 parameters); a three-layer model with two classes (outputs and input gradients). +- **Parameter count:** 1,337,985 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_convgru_oracle.py`` +- **Deviation:** The reference looks for all-zero (padding) time steps and, if there are any, re-indexes the per-step outputs passed to the next layer with a batch-sized index (giving a ``(batch, batch, ...)`` tensor). This never changes the output of the one-layer model and breaks deeper ones. The port does not look for padding: padded steps update the state, as they do in the one-layer reference. +- **Deviation:** The head's padding is ``(kernel - 1) // 2`` per dimension; the reference uses the first kernel dimension for both, which only differs for non-square kernels. +- **Deviation:** Only ``task="segmentation"`` exists: the reference maps a sequence to one map of logits and has no frames-to-frames form. The ConvGRU baseline of Shi et al. (2017), a frame forecaster with a different cell (reset gate after the state convolution, leaky ReLU), is ``build_model("trajgru", task="forecasting", layer_type="ConvGRU")``. + +Registry Name +------------- + +Primary entrypoint: ``convgru`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # FireCastNet's Conv-GRU: 12 eight-day steps of 11 standardised SeasFire variables on 64x64 patches. + model = build_model(name="convgru", task="segmentation") # 1,337,985 parameters + x = torch.randn(2, 12, 11, 64, 64) # (batch, time, variables, lat, lon) + logits = model(x) # (2, 1, 64, 64); train with BCEWithLogitsLoss on every pixel + print(logits.shape) + + # The paper's size: one hidden layer of 64 channels. + small = build_model(name="convgru", task="segmentation", hidden_dim=64) # 361,793 parameters + +Notes +----- + +- Paper and code differ, and the code is followed. Hidden size: the paper (Sec. 5.1) gives the Conv-GRU "a single hidden layer with 64 hidden units" (also ConvGRULit's default), the configuration file 128 (the default here; ``hidden_dim=64`` gives the paper's size). Equations: the paper writes the candidate as ``tanh(W_xh * x + r . (W_hh * h) + b)``, reset gate after the state convolution, while the code, like Ballas et al. (Eq. 7), applies it before: ``tanh(W * [x, r . h])``. Read-out: the paper describes a (2r+1)x(2r+1) grid around each location and MLP layers that reduce it to one prediction; the code predicts a dense 64x64 map with a 5x5 convolution and BCE over all pixels. Training: the paper uses AdamW, lr 1e-3, SGDR (cycles of 10 and 40 epochs) and weight decay 1e-7; the configuration file lr 1e-3, weight decay 1e-8, gradient clipping 0.5, 50 epochs, 12 input steps and a target shift of 16. + +- Input layout and preprocessing: ConvGRULit permutes SeasFire batches from ``(B, C, T, H, W)`` to ``(B, T, C, H, W)``, the layout used here. Variables are prepared by FireCastNet's data module (log1p for tp and pop_dens, standardisation; see the ``firecastnet`` card). + diff --git a/docs/source/modules/models_convlstm.rst b/docs/source/modules/models_convlstm.rst new file mode 100644 index 00000000..68d25cab --- /dev/null +++ b/docs/source/modules/models_convlstm.rst @@ -0,0 +1,124 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +ConvLSTM +======== + +Overview +-------- + +``convlstm`` runs a stack of ConvLSTM cells (Shi et al., 2015) over a ``(batch, time, channels, height, width)`` sequence and maps the cell state of the last time step to per-pixel logits with a ``Conv2d`` head. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``convlstm`` runs a stack of ConvLSTM cells (Shi et al., 2015) over a ``(batch, time, channels, height, width)`` sequence and maps the cell state of the last time step to per-pixel logits with a ``Conv2d`` head. + +The implementation is a port of the ConvLSTM that WildfireSpreadTS vendors from utae-paps (originally TUM-LMF/MTLCC-pytorch): gates come from one convolution over the concatenated input and hidden state, there are no peephole connections, and the head reads the cell state rather than the hidden state. Parameter names match the reference, so its state dicts load with ``strict=True``. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting `_ | **Repo:** `Repository `__ + +Used In +------- + +- `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ (`repo `__): One layer, 64 hidden channels, 3x3 kernels, 5 days x 40 channels, 128x128 crops with tiled inference, Jaccard loss, AdamW lr 0.01; test AP 0.292-0.310 (paper Table 5). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/VSainteuf/utae-paps `__ at ``987874e`` (MIT) +- **Checked configuration:** ConvLSTM_Seg(num_classes=1, input_dim=40, hidden_dim=64, kernel_size=(3, 3)), the WildfireSpreadTS configuration; WildfireSpreadTS vendors this file unchanged. +- **Parameter count:** 240,449 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_wildfirespreadts_oracle.py`` +- **Deviation:** The reference fixes the spatial size at construction; this port reads it from the input. Outputs are identical at the reference size. +- **Deviation:** The reference head uses ``padding=1`` for every kernel size; this port uses ``kernel_size // 2``, which only differs for kernels other than 3x3. + +Registry Name +------------- + +Primary entrypoint: ``convlstm`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + model = build_model(name="convlstm", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 5, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) + +Notes +----- + +- Multi-layer stacks are supported; WildfireSpreadTS uses one layer. +- Set readout='hidden' to read the last hidden state instead of the cell state. diff --git a/docs/source/modules/models_deep_ensemble.rst b/docs/source/modules/models_deep_ensemble.rst new file mode 100644 index 00000000..bf937d7a --- /dev/null +++ b/docs/source/modules/models_deep_ensemble.rst @@ -0,0 +1,157 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Deep Ensemble +============= + +Overview +-------- + +``deep_ensemble`` builds ``num_members`` (default 5) copies of a registered model (``base_model``, ``base_kwargs``), member ``m`` initialised right after ``torch.manual_seed(seeds[m])`` (default seeds ``0 .. M-1``), and predicts with their uniform mixture: classification and segmentation average the member probabilities (softmax over the channel dimension, or a sigmoid for one-channel binary logits), regression moment-matches the Gaussian mixture of mean/variance members. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 3 + + .. container:: catalog-stat-note + + Classification, Segmentation, Forecasting + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``deep_ensemble`` builds ``num_members`` (default 5) copies of a registered model (``base_model``, ``base_kwargs``), member ``m`` initialised right after ``torch.manual_seed(seeds[m])`` (default seeds ``0 .. M-1``), and predicts with their uniform mixture: classification and segmentation average the member probabilities (softmax over the channel dimension, or a sigmoid for one-channel binary logits), regression moment-matches the Gaussian mixture of mean/variance members. + +``forward`` returns the log of the mixture probability for multi-class outputs (``(batch, 2)`` for ``wildfire_forecasting`` members), the logit of the mixture probability for one-channel binary outputs, and a ``(mean, variance)`` tuple for regression. ``predict_uncertainty`` adds the epistemic variance, aleatoric term, predictive entropy and mutual information of Kondylatos et al. (2025), or the epistemic and aleatoric variances of the Gaussian mixture. + +Members are trained independently (Algorithm 1): ``ensemble.fit`` trains each with its own optimizer and its own data order, optionally with fast-gradient-sign adversarial examples (``fgsm_example``, step ``input_range_epsilon`` = 1% of each input dimension's range). ``mc_dropout_passes`` keeps the members' dropout active at prediction and pools several passes per member, as in Chakravarty (2025). + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles `_ + +Used In +------- + +- `Uncertainty-Aware Deep Learning for Wildfire Danger Forecasting `_ (`repo `__): Kondylatos, Papadopoulos, Camps-Valls & Papoutsis (arXiv 2509.25017). Next-day danger on Mesogeos (1 km, Mediterranean; train 2006-2019, validation 2020, test 2021-2022; two negatives per ignition): deep ensemble of 10 LSTMs (LayerNorm, LSTM 128, linear 128 and 64 with ReLU and dropout 0.5, two outputs) on 45-day windows of 25 features (13 dynamic, 12 static), each trained from its own seed (1, 12, 17, 123, 1234, 2222, 12345, 54321, 77777, 87877 in the released checkpoints) with Adam (lr 0.004, weight decay 0.0063), StepLR(15, 0.1), 30 epochs, batch 256 and an NLL loss scaled by the log burned area. Table 1: precision 0.794, recall 0.760, F1 0.777, AUPRC 0.852, ECE 0.019 (with the aleatoric head: 0.787, 0.768, 0.777, 0.854, 0.022), against F1 0.762, AUPRC 0.840 and ECE 0.031 for one deterministic LSTM. In PyHazards: ``base_model="wildfire_forecasting"``, ``base_kwargs={"hidden_size": 128}``, ``num_members=10``. +- `Spatial Uncertainty Quantification in Wildfire Forecasting for Climate-Resilient Emergency Planning `_: Chakravarty, NeurIPS 2025 workshop Tackling Climate Change with Machine Learning. Deep ensemble of U-TAE models (about 1.1M parameters, dropout 0.1 after the temporal attention) trained with distinct random seeds, each run with MC dropout (20 forward passes) at inference, on WildfireSpreadTS (5-day inputs, vegetation and active-fire features, 128 x 128 crops, AdamW lr 0.01 and weight decay 0.01, weighted BCE, 10,000 steps, batch 32, 12-fold cross-validation). The ensemble size is not stated and no code was released. Calibration, 12-fold mean (Table 2): ECE 0.512 +- 0.018, Brier score 0.265 +- 0.009, NLL 0.731 +- 0.023 (MC dropout 0.536 / 0.294 / 0.805, BNN 0.525 / 0.283 / 0.794). In PyHazards: ``base_model="utae"``, ``task="segmentation"``, ``mc_dropout_passes=20``. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Orion-AI-Lab/uncertainty-wildfires `__ at ``fcfbfb8`` (MIT) +- **Checked configuration:** The deep ensemble of Kondylatos et al. (2025): ten SimpleLSTM members (models/model.py, output_lstm 128, dropout 0.5, 25 features; configs/config_det.json) seeded as in the released checkpoints trained_models/ensembles/no-noisy/ensembles--checkpoint.pth, aggregated by utils/train_functions.py ``uncertainties`` as in test.py (configs_test/config_des.json, num_models 10), also with test-time dropout and several passes per member. PyHazards members are ``wildfire_forecasting`` LSTMs with hidden_size 128 (104,308 parameters each). +- **Parameter count:** 1,043,080 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_deep_ensemble_oracle.py`` +- **Deviation:** Lakshminarayanan et al. released no code. The mean/variance regression path (softplus variance plus 1e-6, Gaussian NLL, moment-matched mixture) and the FGSM adversarial training are rebuilt from the paper's Section 2 and Algorithm 1 and covered by plain tests only; Kondylatos et al. (2025) use neither. +- **Deviation:** ``DeepEnsemble.fit`` is a generic independent-training loop (any loss, an optimizer per member, member-seeded shuffling). It does not reproduce the reference training script (StepLR schedule, burned-area loss scaling, validation monitoring); train the members with that recipe to reproduce the paper. +- **Deviation:** The reference members return logits and ``wildfire_forecasting`` returns log-probabilities; the ensemble applies a softmax to either, so the probabilities are the same (checked). +- **Deviation:** The epistemic term is computed as a population variance (``var(unbiased=False)``) instead of the reference's ``E[p^2] - E[p]^2``: the same quantity without cancellation error, equal within 1e-6 in the oracle test. +- **Deviation:** The aleatoric-noise heads (Collier et al.), Bayes-by-Backprop and MC-dropout-only models of Kondylatos et al. (2025) are not part of this entry. + +Registry Name +------------- + +Primary entrypoint: ``deep_ensemble`` + +Supported Tasks +--------------- + +- Classification +- Segmentation +- Forecasting + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + from pyhazards.models.deep_ensemble import input_range_epsilon + + # Kondylatos et al. (2025): ten next-day danger LSTMs + ensemble = build_model( + name="deep_ensemble", + task="classification", + base_model="wildfire_forecasting", + base_kwargs={"hidden_size": 128}, + num_members=10, + ) + x = torch.randn(4, 45, 25) + log_probs = ensemble(x) # log of the mean member probability, (4, 2) + terms = ensemble.predict_uncertainty(x) + print(terms["probs"].shape, terms["epistemic"].shape, terms["mutual_information"].shape) + + # Algorithm 1: train each member on its own, optionally with FGSM adversarial examples + x_train, y_train = torch.randn(64, 45, 25), torch.randint(0, 2, (64,)) + ensemble.fit( + x_train, + y_train, + loss_fn=torch.nn.NLLLoss(), + optimizer_factory=lambda params: torch.optim.Adam(params, lr=1e-3), + epochs=1, + adversarial_epsilon=input_range_epsilon(x_train), + ) + +Notes +----- + +- Outputs per task: multi-class classification / segmentation give ``log`` of the mixture probability (``exp`` for probabilities; ``nn.NLLLoss`` applies); one-channel binary outputs give the logit of the mixture probability (``sigmoid`` for probabilities); regression gives ``(mean, variance)``. With ``regression_output="gaussian"`` (default, the paper) members must output ``2K`` channels along dim 1, K means then K raw variances; ``regression_output="point"`` uses point-prediction members and their spread as the variance. + +- ``Trainer.fit`` refuses the ensemble (training the averaged output as one network would not be a deep ensemble). Use ``ensemble.fit`` or train each of ``ensemble.members`` separately; ``Trainer.evaluate`` and ``Trainer.predict`` work on the ensemble. + +- The builder restores the global random state after seeding the members, so building an ensemble does not change later random draws. Member ``m`` equals ``build_model(base_model, ...)`` called right after ``torch.manual_seed(seeds[m])``. + +- Cost scales with the number of members (and MC-dropout passes): ten 104k-parameter LSTMs for the Kondylatos configuration, about 11M parameters for ten U-TAE members. + diff --git a/docs/source/modules/models_deeplabv3.rst b/docs/source/modules/models_deeplabv3.rst new file mode 100644 index 00000000..3608e86f --- /dev/null +++ b/docs/source/modules/models_deeplabv3.rst @@ -0,0 +1,135 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +DeepLabV3 +========= + +Overview +-------- + +``deeplabv3`` runs a ResNet encoder at output stride 8 (the strides of ``layer3`` and ``layer4`` replaced by dilation 2 and 4) and applies atrous spatial pyramid pooling to its deepest feature: a 1x1 branch, three 3x3 atrous branches at rates 12, 24 and 36 and an image-pooling branch, each with 256 filters, batch normalisation and ReLU, concatenated and projected by a 1x1 convolution with dropout 0.5. A 3x3 convolution, a 1x1 classifier and bilinear up-sampling by 8 return logits at the input resolution. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``deeplabv3`` runs a ResNet encoder at output stride 8 (the strides of ``layer3`` and ``layer4`` replaced by dilation 2 and 4) and applies atrous spatial pyramid pooling to its deepest feature: a 1x1 branch, three 3x3 atrous branches at rates 12, 24 and 36 and an image-pooling branch, each with 256 filters, batch normalisation and ReLU, concatenated and projected by a 1x1 convolution with dropout 0.5. A 3x3 convolution, a 1x1 classifier and bilinear up-sampling by 8 return logits at the input resolution. + +The implementation reproduced is ``segmentation_models_pytorch.DeepLabV3`` (smp 0.3.2; the code path is identical from 0.2.0 to 0.3.4), because Shadrin et al. describe their models in smp's terms ("encoder backbone ResNet18, number of stages used in encoder equals to 3 ... default values for the other hyperparameters") and report smp's ``micro-imagewise`` metric reduction. It is ported to plain PyTorch with smp's parameter names, creation order and initialisation, so smp state dicts load with ``strict=True``; ``encoder_weights="imagenet"`` loads the ImageNet ResNet and adapts the stem to the input channels the way smp does. + +The builder defaults are Shadrin et al.'s configuration: ResNet-18 with three encoder stages and 58 input channels (the 3-day horizon), on 32 x 32 tiles. With three stages the ASPP runs on the 128-channel, stride-8 output of ``layer2``; smp still builds (and dilates) ``layer3`` and ``layer4``, whose 10,493,440 parameters are kept for state-dict compatibility although the forward pass never uses them. The ``DeepLabV3`` class itself defaults to smp's ResNet-34 with five stages. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Rethinking Atrous Convolution for Semantic Image Segmentation `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Wildfire spreading prediction using multimodal data and deep neural network approach `_: Shadrin et al., Scientific Reports 14:2606 (2024). DeepLabV3 with "encoder backbone ResNet18, number of stages used in encoder equals to 3 ... default values for the other hyperparameters" (smp defaults: 256 ASPP channels, output stride 8, rates 12/24/36, ImageNet encoder weights), compared with U-Net, U-Net++ and MA-Net. 947 fires of 2021-2022 in Krasnoyarsk, Irkutsk and Sakha, split 4:1. Input: 32 x 32 tiles (21 x 21 km at 650 m around the ignition point; the data are first resampled to 128 x 128 at 0.0059435 degrees) with one ignition layer, 21 static layers (17 land-cover masks, elevation, aspect, slope, population), 6 MODIS vegetation layers and 10 ERA5-Land/MODIS weather layers per forecast day: 58 channels for 3 days, 78 for 5. Target: burned-area mask. F1 for the day-3 forecast (micro-imagewise, Table 3) with BCE 0.64, Dice 0.66, focal 0.63, Dice + focal 0.65, generalized Dice 0.66 and Tversky 0.66 (+- 0.004 to 0.006); the selected MA-Net reaches 0.67. Only MA-Net's training setup is given (Adam, lr 3e-3, L2 1e-5, OneCycleLR, 35 epochs, batch 32). No code was released; data on request. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/qubvel-org/segmentation_models.pytorch `__ at ``v0.3.2`` (MIT (the ASPP/decoder file is from torchvision, BSD-3-Clause)) +- **Checked configuration:** smp.DeepLabV3(encoder_name="resnet18", encoder_depth=3, encoder_weights=None, in_channels=58, classes=1) on 2 x 58 x 32 x 32 inputs (Shadrin et al.), plus smp's defaults (ResNet-34, five stages, 26,007,105 parameters), ResNet-18 with four and five stages, and the ImageNet-initialised 58-channel stem. The decoder and 1x1 classifier are also checked against torchvision's DeepLabHead. +- **Parameter count:** 13,220,609 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_deeplabv3_oracle.py`` +- **Deviation:** ``encoder_weights`` defaults to None, so building the model downloads nothing; smp's default (which Shadrin et al. kept) is "imagenet". Pass ``encoder_weights="imagenet"`` to match it. +- **Deviation:** Inputs whose height or width is not divisible by the output stride raise ValueError instead of smp's RuntimeError, and ``encoder_depth`` outside smp's documented range [3, 5] raises ValueError (smp builds such a model, but its fixed x8 up-sampling then no longer restores the input size). + +Registry Name +------------- + +Primary entrypoint: ``deeplabv3`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Shadrin et al. (2024): ResNet-18, three encoder stages, 58 channels for a 3-day horizon. + model = build_model(name="deeplabv3", task="segmentation", in_channels=58) + logits = model(torch.randn(2, 58, 32, 32)) + print(logits.shape) # (2, 1, 32, 32) + + # smp's own defaults (ResNet-34, five stages); encoder_weights="imagenet" downloads ImageNet weights. + smp_default = build_model(name="deeplabv3", task="segmentation", in_channels=3, + encoder_name="resnet34", encoder_depth=5) + +Notes +----- + +- smp's DeepLabV3 differs from the paper's network: it keeps output stride 8 throughout (the paper trains at 16 with rates 6/12/18 and evaluates at 8 with 12/24/36), has no multi-grid, dilates every convolution of the dilated stages including the first block's (torchvision keeps the previous dilation there), adds a 3x3 convolution after the ASPP and dropout 0.5 in the projection (both from torchvision), uses ResNet-18/34 rather than ResNet-50/101, and up-samples the logits with align_corners=True. + +- On Shadrin et al.'s 32 x 32 tiles with three encoder stages the ASPP sees 4 x 4 features, so the rate-12/24/36 branches reach only padding outside their centre tap and act as 1x1 convolutions (the degenerate case discussed in the DeepLabV3 paper). + +- smp 0.3.x never calls its initialize() for DeepLabV3, so the decoder and head keep PyTorch's default initialisation; the port does the same. +- The image-pooling branch has batch normalisation on a 1 x 1 map, so training needs a batch size above 1, as in smp and torchvision. +- Height and width must be divisible by 8. Encoders: resnet18 and resnet34. smp's auxiliary classification head (aux_params) and output activation are not ported. +- This is DeepLabV3, not DeepLabV3+; no wildfire paper in the PyHazards inventory used V3+. diff --git a/docs/source/modules/models_earthfarseer.rst b/docs/source/modules/models_earthfarseer.rst new file mode 100644 index 00000000..a9a9e048 --- /dev/null +++ b/docs/source/modules/models_earthfarseer.rst @@ -0,0 +1,136 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Earthfarseer +============ + +Overview +-------- + +``earthfarseer`` maps ``T`` input frames ``(batch, T, C, H, W)`` to the next ``T`` frames (Wu et al., AAAI 2024). The spatial block FoTF runs a global Fourier transformer (16x16 patches, 12 blocks of width 768 whose token mixing is an adaptive Fourier neural operator, then three transposed convolutions back to pixels) next to a local convolution branch, and lets the two exchange features three times. A strided convolutional encoder (``hid_S`` channels, ``N_S`` layers) compresses each frame; TeDev stacks the frames as channels and runs a U-shaped stack of multi-kernel Inception blocks (``N_T`` down, ``N_T`` up, ``hid_T`` channels) with 12 Fourier blocks at its bottleneck; a mirrored decoder returns to pixels, and the output of a complete SimVP network on the raw input is added. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Forecasting, Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``earthfarseer`` maps ``T`` input frames ``(batch, T, C, H, W)`` to the next ``T`` frames (Wu et al., AAAI 2024). The spatial block FoTF runs a global Fourier transformer (16x16 patches, 12 blocks of width 768 whose token mixing is an adaptive Fourier neural operator, then three transposed convolutions back to pixels) next to a local convolution branch, and lets the two exchange features three times. A strided convolutional encoder (``hid_S`` channels, ``N_S`` layers) compresses each frame; TeDev stacks the frames as channels and runs a U-shaped stack of multi-kernel Inception blocks (``N_T`` down, ``N_T`` up, ``hid_T`` channels) with 12 Fourier blocks at its bottleneck; a mirrored decoder returns to pixels, and the output of a complete SimVP network on the raw input is added. + +The default is the official ``Earthfarseer_model(shape_in=(10, 1, 64, 64))`` (the paper's Moving MNIST setting, 10 -> 10 frames): hid_S 512, hid_T 256, N_S 4, N_T 8, Inception kernels 3/5/7/11 with 8 groups, 157,518,863 parameters. The official code has no license, so the model is written from the paper and permissively licensed parts (OpenSTL's SimVP Inception block, Apache-2.0); parameter names and creation order follow the official code, so its state dicts load with ``strict=True`` and the same seed gives the same weights. + +``task="forecasting"`` returns the frame forecast. ``task="segmentation"`` is a PyHazards adaptation for next-step fire masks: a 1x1 convolution (``segmentation_head``) maps the channels of the first predicted frame to ``out_channels`` logits ``(batch, 1, H, W)``; the Earthfarseer parameters keep their official names at the top level of the state dict. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Earthfarseer: Versatile Spatio-Temporal Dynamical Systems Modeling in One Model `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire `_ (`repo `__): Li et al., NeurIPS 2024 Datasets and Benchmarks. Listed as "Earthfarsser" among the AI baselines of Table 2, trained on simulated wildfire scenarios and tested on simulated and real-world fires (binary fire-area sequences with satellite, topography, vegetation, fuel and weather inputs). Forecast AUPRC / F1 / IoU: 73.4 / 70.6 / 63.5 (simulation) and 62.4 / 60.5 / 49.2 (real world); backtracking: 69.3 / 68.5 / 50.9 and 51.6 / 49.4 / 37.5. Configuration not published: the paper only calls the baselines "commonly used AI models that can be easily adapted", and its repository contains only S2R-FireTr (3 input frames at 256x256), so the input stacking, model size, loss and output head of this baseline are unknown. These numbers are not reproduced by PyHazards. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Alexander-wu/EarthFarseer `__ at ``258d4bb`` (none (no LICENSE file; the README's Apache-2.0 badge links to OpenSTL's licence and does not license this repository); used only as a test oracle, not copied) +- **Checked configuration:** Earthfarseer_model(shape_in=(10, 1, 64, 64)) with its defaults hid_S=512, hid_T=256, N_S=4, N_T=8, incep_ker=[3, 5, 7, 11], groups=8 (timm 0.9.16 as in the official requirements): 157,518,863 parameters, seeded initialisation and outputs compared locally with PYHAZARDS_ORACLE_LARGE=1 (bit-identical in eval and train mode). CI compares three reduced models (other frame counts, channels, sizes, N_S 2/4/6, N_T 2/3, kernels and groups) in which only the hard-coded FoTF transformer width and depth (768, 12) are overridden in the official GF_Block call, plus official state dicts loaded into the builder's forecasting and segmentation models. +- **Parameter count:** 157,518,863 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_earthfarseer_oracle.py`` +- **Deviation:** task="segmentation" (first predicted frame, 1x1 convolution to out_channels logits) is a PyHazards adaptation, not from Sim2Real-Fire, whose baseline heads are unpublished. +- **Deviation:** The official model sizes the TeDev Fourier token grid as int(H / 2 ** (N_S / 2)), plus 1 when H is divisible by 3. Because H must be a multiple of 16, this disagrees with the real latent size, and the official forward fails, whenever H is divisible by 3 (48, 96, ..., 384) or N_S is odd. PyHazards uses the real latent size, which equals the official value wherever the official model runs. +- **Deviation:** The official FoTF builds its transformer for H x H (img_size=H), so non-square inputs fail its patch-embedding assertion; PyHazards builds it for H x W. +- **Deviation:** gf_embed_dim, gf_depth and num_interactions are hard-coded in the official model (768, 12, 3); PyHazards exposes them only to build smaller models (smoke tests). Their defaults give the official network. + +Registry Name +------------- + +Primary entrypoint: ``earthfarseer`` + +Supported Tasks +--------------- + +- Forecasting +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Official default: 10 frames of 1 x 64 x 64 -> the next 10 frames (157.5M parameters). + model = build_model(name="earthfarseer", task="forecasting") + x = torch.randn(2, 10, 1, 64, 64) # (batch, time, channels, height, width) + print(model(x).shape) # (2, 10, 1, 64, 64) + + # PyHazards next-step fire-mask adaptation on 3 frames of 4 channels at 128 x 128. + seg = build_model(name="earthfarseer", task="segmentation", in_channels=4, history=3, img_size=128) + print(seg(torch.randn(2, 3, 4, 128, 128)).shape) # (2, 1, 128, 128) + +Notes +----- + +- The output has as many frames as the input. The paper's temporal projection to other lengths (10 -> 30, 50 -> 50 frames) is not in the released code, so it is not provided. +- Height and width must be multiples of 16 (FoTF patches and its 16x transposed-convolution head) and of the encoder stride; the parameter count depends on the frame count and size (for example 145,121,999 for 3 frames of 1 x 256 x 256). +- Kept from the official code because they change outputs or parameter counts: the same global transformer and local branch are applied seven times inside FoTF; the transformer MLP replaces fc2 by an average pool over groups of four hidden features (fc2 is built but unused); the Fourier operator's second layer computes its imaginary part from the already updated real part; a second encoder (enc) is built but unused; the added SimVP branch (skip_conneciton, spelling kept) has fixed sizes 16 / 256 / 4 / 8. +- Where the paper and the released code differ, PyHazards follows the code: the local branch is one 1x1 transposed convolution (the paper describes 3x3 ConvNormReLU units), the FoTF up-exchange is a transposed convolution and the down-exchange a convolution (the paper states the reverse), and the TeDev kernels are 3/5/7/11 (the paper lists 1/3/7/11). +- Every dropout and stochastic-depth rate is 0 in the official model, so training and evaluation mode give the same outputs (GroupNorm and LayerNorm only). +- No official pretrained weights were found. diff --git a/docs/source/modules/models_earthformer.rst b/docs/source/modules/models_earthformer.rst new file mode 100644 index 00000000..9df24efe --- /dev/null +++ b/docs/source/modules/models_earthformer.rst @@ -0,0 +1,142 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Earthformer +=========== + +Overview +-------- + +``earthformer`` forecasts a sequence of future frames from past frames (Gao et al., NeurIPS 2022). Cuboid attention splits the (time, height, width) tensor into cuboids and attends inside each; the "axial" pattern used for all released models stacks three of them, (T, 1, 1), (1, H, 1) and (1, 1, W), each with a pre-LN feed-forward layer, and optional global vectors exchange information between cuboids. Convolutions with patch merging first reduce the frames (12x for SEVIR), a two-level encoder follows (patch merging between levels), and a non-autoregressive decoder starts from learned query frames (the projected positional embedding), alternates self-attention with cross-attention to the encoder memory of each level and upsamples back to the input resolution. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Forecasting, Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``earthformer`` forecasts a sequence of future frames from past frames (Gao et al., NeurIPS 2022). Cuboid attention splits the (time, height, width) tensor into cuboids and attends inside each; the "axial" pattern used for all released models stacks three of them, (T, 1, 1), (1, H, 1) and (1, 1, W), each with a pre-LN feed-forward layer, and optional global vectors exchange information between cuboids. Convolutions with patch merging first reduce the frames (12x for SEVIR), a two-level encoder follows (patch merging between levels), and a non-autoregressive decoder starts from learned query frames (the projected positional embedding), alternates self-attention with cross-attention to the encoder memory of each level and upsamples back to the input resolution. + +The module is a port of the official ``CuboidTransformerModel`` (Apache-2.0) with its parameter names, creation order and initialisation, so the official state dicts load with ``strict=True`` and the same seed gives the same weights. ``config`` selects an official configuration file: ``sevir`` (earthformer_sevir_v1.yaml, the released SEVIR checkpoint, default), ``sevir_lr``, ``moving_mnist`` / ``nbody`` and ``enso`` (the released ICAR-ENSO checkpoint); any constructor argument can be overridden. ``pretrained="sevir"`` or ``"icarenso2021"`` loads the official weights. + +``task="forecasting"`` maps ``(batch, history, in_channels, H, W)`` to ``(batch, horizon, out_channels, H, W)``; ``task="segmentation"`` is the same network predicting one frame with one channel and returns next-fire-mask logits ``(batch, 1, H, W)``. The official code works in ``(batch, T, H, W, C)``; ``CuboidTransformerModel`` keeps that layout. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Earthformer: Exploring Space-Time Transformers for Earth System Forecasting `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire `_ (`repo `__): Li et al., NeurIPS 2024 Datasets and Benchmarks. Models are trained on about 1M simulated wildfire scenarios (FARSITE, WFDS, WRF-SFIRE) and tested on simulated and about 1K real scenarios; the input is the source sequence of binary fire-area masks with satellite image sequences, topography, vegetation, fuel maps and weather, and the target is the future (forecast) or past (backtracking) mask sequence. Earthformer is one of the "commonly used AI models that can be easily adapted" (Sec. 4.1). Table 2 (AUPRC / F1 / IoU, %): forecast 77.2 / 73.5 / 59.7 on simulated and 65.4 / 61.7 / 50.1 on real-world data; backtracking 71.4 / 63.0 / 48.1 and 53.4 / 51.3 / 41.7. Tables 4 and 6 report the AUPRC without each modality. Configuration not published: the paper and the repository (which contains only S2R-FireTr) give no Earthformer hyperparameters, input stacking, resolution, loss or output head; S2R-FireTr itself uses 3 input frames at 256 x 256. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/amazon-science/earth-forecasting-transformer/blob/7732b03bdb366110563516c3502315deab4c2026/src/earthformer/cuboid_transformer/cuboid_transformer.py `__ at ``7732b03`` (Apache-2.0 (Copyright Amazon.com, Inc. or its affiliates)) +- **Checked configuration:** CuboidTransformerModel built as the official training scripts build it from the model section of scripts/cuboid_transformer/sevir/earthformer_sevir_v1.yaml (13 x 384 x 384 -> 12 frames, base 128 channels, stack-conv down-sampling 3-2-2 to 32 x 32, one axial block per level, 8 global vectors with separate projections and global self-attention, 8,659,677 parameters) and moving_mnist/cfg.yaml (10 x 64 x 64 -> 10, base 64, four blocks per level, no global vectors, 6,702,109), plus sevir/cfg_sevirlr.yaml (1,505,069), enso/earthformer_enso_v1.yaml (1,394,325), six configurations with other patterns and options, and the official earthformer_sevir.pt and earthformer_icarenso2021.pt checkpoints (sha256-pinned Internet Archive copies). Seeded initialisation, eval and train-mode outputs and gradients are compared; architecture checks run at 13 x 48 x 48 and 13 x 50 x 50 (SEVIR) and 10 x 32 x 32 (Moving-MNIST), the checkpoints at 13 x 384 x 384 and 12 x 24 x 48. +- **Parameter count:** 8,659,677 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_earthformer_oracle.py`` +- **Deviation:** task="segmentation" is a PyHazards adaptation, not from Sim2Real-Fire (whose Earthformer setup is unpublished): the network is built with target_shape (1, H, W, 1) and its single predicted frame is returned as (batch, 1, H, W) logits. Parameter names are those of CuboidTransformerModel (no prefix). +- **Deviation:** Earthformer and EarthformerSegmenter take (batch, time, channels, H, W) and permute to the official (batch, time, H, W, channels) layout; CuboidTransformerModel keeps the official layout. Inputs must have exactly the configured shape (ValueError otherwise); the official code also accepts sizes that pad to the same token grid and then returns the configured output size. +- **Deviation:** Three paths that only raise errors in the official code work here: PatchMerging3D pads when only the time axis needs padding (the official test reads "pad_h or pad_h or pad_w"), the CTHW layout of Upsample3DLayer (official: undefined self.output_size), and cuboid cross-attention with padding_type "zeros" or "nearest" when padding is needed (official: undefined mask; here padded entries count as tokens, as in the self-attention mask). None of them is reached by the official configurations. +- **Deviation:** Only CuboidTransformerModel is ported. CuboidTransformerAuxModel and the U-Net decoder (cuboid_transformer_unet_dec.py, used for EarthNet2021 with auxiliary inputs and the earthformer_earthnet2021.pt checkpoint) and the unused DownSampling3D layer are not. + +Registry Name +------------- + +Primary entrypoint: ``earthformer`` + +Supported Tasks +--------------- + +- Forecasting +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Released SEVIR configuration: 13 frames of 384 x 384 VIL (scaled to [0, 1]) -> 12 frames. + model = build_model(name="earthformer", task="forecasting") # 8,659,677 parameters + # Official SEVIR weights (Apache-2.0, downloaded and sha256-checked on first use): + # model = build_model(name="earthformer", task="forecasting", pretrained="sevir") + model.eval() + with torch.no_grad(): + frames = model(torch.rand(1, 13, 1, 384, 384)) # (batch, time, channels, H, W) + print(frames.shape) # (1, 12, 1, 384, 384) + + # Next-fire-mask adaptation (PyHazards): 3 days of 8 channels at 256 x 256 -> one mask logit map. + fire = build_model(name="earthformer", task="segmentation", history=3, in_channels=8, img_size=256) + print(fire(torch.randn(2, 3, 8, 256, 256)).shape) # (2, 1, 256, 256) + +Notes +----- + +- Parameter counts in the paper. The released configurations are smaller than the models in the paper's tables (15.1M on SEVIR, 7.6M on Moving-MNIST, N-body MNIST and ICAR-ENSO), and the official class reproduces the paper's numbers exactly when built from them as follows (checked against the official code): SEVIR with enc_depth = dec_depth = [2, 2], two cuboid attention blocks per level as listed in the paper's Table 9 (the released v1 file has one), gives 13,075,029 without global vectors (13.1M, "w/o global") and 15,082,069 (15.1M) with eight global vectors that share the local q/k/v projections and have no FFN of their own; Moving-MNIST cfg.yaml with "t+h+w" instead of "t+hw" positional embeddings (-90,112) gives 6,611,997 (6.61M, "Axial" / "w/o global") and 7,610,781 (7.61M) with those global vectors; ICAR-ENSO with four blocks per level (the Moving-MNIST architecture, paper Table 8) gives 6,601,293 and 7,600,077 (6.6M / 7.6M). The counts also fix that the decoder self-attention uses no global vectors (which would add parameters); whether the decoder cross-attention and the global self-attention use them does not change the count. The appendix equations show a global FFN, but with it the totals would not match. The released v1 files instead use one block per level, and SEVIR v1 uses separate global projections with global self-attention. + +- Official weights: earthformer_sevir.pt (SEVIR, 34.8 MB) and earthformer_icarenso2021.pt (ICAR-ENSO, 5.7 MB) are plain CuboidTransformerModel state dicts for the sevir and enso presets. The S3 bucket of the README (earthformer.s3.amazonaws.com) answered HTTP 403 on 2026-10-07; pretrained= tries it first and then the Internet Archive capture of 2025-05-17, whose SHA-1 equals the archived original (S3 Last-Modified 2023-07-14), and checks the pinned sha256. The SEVIR model expects VIL divided by 255 in (batch, 13, 1, 384, 384) and was trained with MSE. No Moving-MNIST or N-body weights were released. + +- Behaviour of the official code that is kept because it changes outputs: cuboid patterns are computed from the encoder memory shapes, so the decoder's temporal cuboids hold T_in frames; with T_out < T_in they shrink and the relative-position bias table is sliced as a flattened index (exact when only the outermost non-unit cuboid axis shrinks, as with the axial pattern), and with T_out > T_in (ICAR-ENSO, 12 -> 14) the decoder frames are padded to a multiple of T_in. With padding_type "zeros" (all official files) padded positions take part in attention as zero vectors. z_init_method "zeros" makes the decoder queries the projected positional embedding, independent of the input. + +- Sizes that the initial down-sampling does not divide (for example 256 with the 12x SEVIR stack) are zero-padded inside the patch merging, and the final upsampling returns the configured size. Gradient checkpointing (checkpoint_level 1 or 2) uses the reentrant variant as the official code does; all official configuration files set checkpoint_level 0. + diff --git a/docs/source/modules/models_eqnet.rst b/docs/source/modules/models_eqnet.rst index 649727af..63d53859 100644 --- a/docs/source/modules/models_eqnet.rst +++ b/docs/source/modules/models_eqnet.rst @@ -6,7 +6,7 @@ EQNet Overview -------- -``eqnet`` extends the PyHazards earthquake benchmark stack with a lightweight attention-based picking model. +``eqnet`` takes station gathers ``(batch, stations, 3, samples)`` (E, N, Z at 100 Hz) and, for detection, travel times ``(batch, stations, candidates, 2)`` (P and S, seconds) from every station to every candidate hypocentre; ``eqnet_travel_times`` computes them for a uniform velocity model (the paper's 6 km/s and 3.4 km/s) from station and candidate coordinates in km (``eqnet_candidate_grid``: the paper's ~4 km grid), any travel-time table can be passed instead, and ``station_mask`` marks padded stations. It returns ``{"phase": (batch, stations, 2, samples / 2), "event": (batch, candidates, samples / 32)}`` probabilities (logits with ``logits=True``). At a Glance ----------- @@ -42,11 +42,11 @@ At a Glance .. container:: catalog-stat-value - 1 + 2 .. container:: catalog-stat-note - Phase Picking + Picking, Detection .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,39 @@ At a Glance Description ----------- -``eqnet`` extends the PyHazards earthquake benchmark stack with a lightweight attention-based picking model. +``eqnet`` takes station gathers ``(batch, stations, 3, samples)`` (E, N, Z at 100 Hz) and, for detection, travel times ``(batch, stations, candidates, 2)`` (P and S, seconds) from every station to every candidate hypocentre; ``eqnet_travel_times`` computes them for a uniform velocity model (the paper's 6 km/s and 3.4 km/s) from station and candidate coordinates in km (``eqnet_candidate_grid``: the paper's ~4 km grid), any travel-time table can be passed instead, and ``station_mask`` marks padded stations. It returns ``{"phase": (batch, stations, 2, samples / 2), "event": (batch, candidates, samples / 32)}`` probabilities (logits with ``logits=True``). -The implementation keeps the shared waveform input and two-pick output contract so it can be evaluated alongside ``phasenet`` and ``eqtransformer``. +Feature extraction (Figure 3a, 996,960 parameters): a 1-D ResNet-18 with 32 / 64 / 128 / 256 channels and a final 1x1 convolution to 128 features at 1/32 of the sampling rate, applied to every station. Phase picking (Figure 3b): one sub-network for P on feature channels 0-63 and one for S on 64-127, each two convolution / batch-norm / ReLU layers with x4 upsampling and an output convolution. The shift-and-stack module reads the P features ``t_P`` and the S features ``t_S`` later at every station, so that an event's features align on its origin time at its true location, and averages over stations; the event detection network (Figure 3c) turns the aligned features into an activation over origin time for every candidate. ``extract_picks`` keeps activation peaks above 0.5, ``extract_events`` takes origin times from the peaks of the maximum over candidates and the location as the geometric median of the 20 most activated candidates (Section 2.2). ``EQNetLoss`` is the sum of the three binary cross-entropies (equation 1). + +For single-station picking (the paper's STEAD evaluation) ``annotate`` takes ``(n, 3, samples)`` windows and the ``earthquake.picking`` benchmark scores the P / S picks. There is no multi-station detection benchmark task yet, and no weights exist: EQNet must be trained before use. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Earthquake Benchmark ` -**Mapped benchmark ecosystems:** :doc:`SeisBench ` - External References ------------------- -**Paper:** `An End-To-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning `_ | **Repo:** `Repository `__ +**Paper:** `An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning `_ | **Repo:** `Repository `__ + +Used In +------- + +- `An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning (Zhu, Tai, Mousavi, Bailis & Beroza, JGR Solid Earth 127(3), e2021JB023283, 2022; arXiv:2109.09911) `_: Trained on 99,465 NCEDC events with manual picks at more than 3 stations (AdamW, learning rate 3e-4, weight decay 1e-4, cosine decay; Gaussian targets 1 s wide for picks, 2 s for origin times; negative sampling of candidate locations). Table 1, STEAD test set (~120,000 waveforms, the EQTransformer split), picks = peaks above 0.5, true positive within 0.5 s (protocol "eqtransformer"): P precision 0.96, recall 0.95, F1 0.95, residual mean -0.01 s, std 0.08 s, MAE 0.04 s; S 0.92 / 0.92 / 0.92, 0.01 / 0.11 / 0.07 s. Table 2, Ridgecrest 4-8 July 2019 (stations within 1 degree of the sequence, 6 / 3.4 km/s, 4 km grid): 11,765 events at threshold 0.5; with the SCSN catalogue (8,044 events) as benchmark, precision 0.55, recall 0.83, F1 0.66. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/AI4EPS/EQNet `__ (``af94a08``, Academic and Commercial License (Copyright (c) 2023 Weiqiang Zhu, Zhongwen Zhan): academic and non-commercial use only; no licence before 2023-10-26. Not ported; used only as a test oracle. No EQNet weights were released.); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** Paper Figure 3 and Sections 2.1-2.2 (arXiv 2109.09911): 1,043,619 parameters (feature extractor 996,960, two picking heads of 7,825, event detector 31,009). Verified against code: the feature extractor equals ``ResNet(BasicBlock, [2, 2, 2, 2])`` of ``eqnet/models/resnet1d.py`` at af94a08 (996,960 parameters, same names, same seeded initialisation, equal outputs in evaluation and training mode, batch-norm statistics, gradients); the picking and detection heads equal the author's first ``PhasePicker`` / ``EventDetector`` (``eqnet/models/eqnet.py`` at a9df49a, 2022-07-27, unlicensed) instantiated at the paper's widths ``[64, 32, 16]`` and ``[128, 64, 32]`` (equal outputs with copied weights, same seeded convolution weights). Not verifiable against code: the shift-and-stack module, the P / S feature split and the end-to-end model (tested from the paper's description: synthetic arrivals from a known hypocentre peak at the true candidate and origin time); no numbers of the paper are reproduced (no weights, retraining needed). +- **Parameter count:** 1,043,619 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_eqnet_oracle.py`` +- **Deviation:** Choices the paper leaves open, taken from the author's code: reflect padding, bias-free convolutions before batch normalisation and a biased output convolution, linear x4 interpolation (``align_corners=False``), Kaiming-normal initialisation of the extractor, and no ReLU after its last batch normalisation (the figure caption puts batch normalisation and ReLU after every convolution). +- **Deviation:** PyHazards choices (paper silent, not in any code): the shift-and-stack averages over stations (``station_mask`` excludes padded ones), reads fractional shifts by linear interpolation and treats features outside the window as zero; output sample ``j`` of the picking heads is input sample ``2 j`` and feature sample ``t`` is input sample ``32 t``; peaks of one phase must be 0.5 s apart and events 2 s apart; candidate chunks of ``candidate_chunk`` in evaluation mode bound memory. +- **Deviation:** ``annotate`` standardises each station's window per channel (mean removed, divided by the standard deviation), as the official data reader does; the paper does not describe its normalisation. The component order (E, N, Z) and the 100 Hz rate are assumptions (NCEDC data). +- **Deviation:** The loss sums binary cross-entropies over time as in equations (2)-(4) and averages over stations, candidates and the batch; target generation (Gaussian labels, negative sampling) is not part of the module. Registry Name ------------- @@ -87,7 +105,8 @@ Primary entrypoint: ``eqnet`` Supported Tasks --------------- -- Phase Picking +- Picking +- Detection Programmatic Use ---------------- @@ -96,12 +115,22 @@ Programmatic Use import torch from pyhazards.models import build_model + from pyhazards.models.eqnet import eqnet_candidate_grid, eqnet_travel_times + + model = build_model(name="eqnet", task="detection").eval() # no released weights: train first - model = build_model(name="eqnet", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + waveforms = torch.randn(1, 6, 3, 3072) # (batch, stations, E/N/Z, samples) at 100 Hz + stations = torch.rand(6, 3) * torch.tensor([40.0, 40.0, 0.0]) # station x, y, z in km + candidates = eqnet_candidate_grid((0.0, 40.0), (0.0, 40.0), spacing=4.0, depth=8.0) + travel_times = eqnet_travel_times(stations, candidates) # (1, 6, 121, 2), 6 and 3.4 km/s + with torch.no_grad(): + out = model(waveforms, travel_times) # phase: (1, 6, 2, 1536), event: (1, 121, 96) + events = model.extract_events(out["event"], candidates) + picks = model.extract_picks(out["phase"][0]) # one dict of P / S picks per station Notes ----- -- Outputs are P- and S-arrival sample indices. +- Zhu, Tai, Mousavi, Bailis & Beroza, J. Geophys. Res. Solid Earth 127(3), e2021JB023283 (2022), arXiv:2109.09911. Not the GaMMA association paper (doi:10.1029/2021JB023249) that earlier versions of this card linked. +- The AI4EPS/EQNet repository is now a toolbox of PhaseNet+ / PhaseNet-DAS models; its current picking and detection heads are different networks from the paper's, and it has no shift-and-stack module. +- Breaking change: ``eqnet`` used to be a small transformer regressor returning one (P, S) pair per trace (task ``regression``, arguments ``hidden_dim``, ``num_heads``, ``num_layers``, ``dropout``); it now takes ``task='picking'`` or ``'detection'`` and returns the paper's activation sequences. diff --git a/docs/source/modules/models_eqtransformer.rst b/docs/source/modules/models_eqtransformer.rst index 001e9916..941af265 100644 --- a/docs/source/modules/models_eqtransformer.rst +++ b/docs/source/modules/models_eqtransformer.rst @@ -6,7 +6,7 @@ EQTransformer Overview -------- -``eqtransformer`` is the second earthquake picking baseline in the staged roadmap and shares the synthetic waveform contract used by ``phasenet``. +A deep encoder (seven convolution + max-pooling layers, seven residual CNN blocks, bidirectional LSTM blocks and two transformer blocks with additive self-attention) compresses 6000 samples to 47 time steps. Three decoders read the encoding: the detection decoder directly, the P and S decoders after an LSTM and a local self-attention of width 3; each upsamples back to 6000 samples and ends with a sigmoid. ``forward`` returns ``(batch, 3, 6000)`` probabilities in the order detection, P, S. At a Glance ----------- @@ -63,21 +63,43 @@ At a Glance Description ----------- -``eqtransformer`` is the second earthquake picking baseline in the staged roadmap and shares the synthetic waveform contract used by ``phasenet``. +A deep encoder (seven convolution + max-pooling layers, seven residual CNN blocks, bidirectional LSTM blocks and two transformer blocks with additive self-attention) compresses 6000 samples to 47 time steps. Three decoders read the encoding: the detection decoder directly, the P and S decoders after an LSTM and a local self-attention of width 3; each upsamples back to 6000 samples and ends with a sigmoid. ``forward`` returns ``(batch, 3, 6000)`` probabilities in the order detection, P, S. -The PyHazards adapter focuses on the shared picking interface rather than a full reproduction of the original multitask training pipeline. +``variant="original"`` (default) is the paper model ``EqT_original_model.h5`` (two BiLSTM blocks, 371,639 parameters); ``variant="conservative"`` is ``EqT_model_conservative.h5`` (three BiLSTM blocks, 376,423 parameters), which the authors released later for fewer false positives. Both load with ``pretrained=True`` (downloaded from the official repository at a pinned commit and checked by sha256; MIT-licensed weights) and reproduce the official Keras outputs. + +``annotate`` applies the official per-trace normalisation (remove the mean, divide by the standard deviation of each component); ``extract_picks`` and ``extract_detections`` port the official tester's ``picker`` (detection triggers of at least 10 samples, the earliest S peak and the most probable P peak associated with each event), which the ``earthquake.picking`` benchmark uses. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Earthquake Benchmark ` -**Mapped benchmark ecosystems:** :doc:`pick-benchmark ` +**Mapped benchmark ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` External References ------------------- -**Paper:** `Earthquake Transformer-An attentive deep-learning model for simultaneous earthquake detection and phase picking `_ | **Repo:** `Repository `__ +**Paper:** `Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking `_ (`repo `__): STEAD test set (10% random split, trace names in ModelsAndSampleData/test.npy), paper model, a pick is a true positive when |error| < 0.5 s. Table 1 detection: precision 1.0, recall 1.0, F1 1.0 (detection threshold 0.5). Table 2 P picks: mean error 0.00 s, std 0.03 s, precision 0.99, recall 0.99, F1 0.99, MAE 0.01 s, MAPE 0.00. Table 3 S picks: mean 0.00 s, std 0.11 s, precision 0.99, recall 0.96, F1 0.98, MAE 0.01 s, MAPE 0.00. +- `Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers `_ (`repo `__): Münchmeyer et al., J. Geophys. Res. Solid Earth 127, e2021JB023499 (2022). Retrains SeisBench's PyTorch EQTransformer (the conservative three-BiLSTM architecture, 376,935 parameters because PyTorch LSTMs carry two bias vectors) on each dataset; in-domain phase identification MCC (Table 2): STEAD 1.00, INSTANCE 0.97, ETHZ 0.97, SCEDC 0.96, Iquique 0.99, NEIC 0.96, GEOFON 0.82. These are retrained models, not the released weights. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/smousavi05/EQTransformer `__ at ``a589da6`` (MIT (code and released models)) +- **Checked configuration:** The two released Keras models, EqT_original_model.h5 (paper model, Keras 2.3.0) and EqT_model_conservative.h5 (Keras 2.2.4), loaded with tf.keras.models.load_model and the official custom layers of EQTransformer/core/EqT_utils.py on TensorFlow 2.11, on random input and on the repository's 100 STEAD sample traces (100samples.hdf5); the official ``picker`` on the same probabilities; and SeisBench 0.12.6's EQTransformer with its conversions of both models (GPL-3.0, used only as a second oracle). +- **Parameter count:** 371,639 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_eqtransformer_oracle.py`` +- **Deviation:** The released graphs call SpatialDropout1D (rate 0.2 in the paper model, 0.1 in the conservative one) with ``training=True``, so the official models are random at inference (Monte Carlo dropout; the paper uses dropout "at training and test time"). The port applies it in train mode and, in eval mode, only with ``mc_dropout=True``: by default ``eval()`` outputs are deterministic and equal the official model with that dropout switched off. ``annotate(x, mc_samples=n)`` averages ``n`` passes with it on, as the official tester does with ``estimate_uncertainty=True``. +- **Deviation:** Initial weights cannot match the reference for a seed (TensorFlow and PyTorch draw different random numbers). The port uses the Keras initialisers of every layer (Glorot-uniform kernels, Glorot-normal truncated at two standard deviations for the attention and feed-forward weights, orthogonal recurrent kernels, unit forget bias), which the oracle test compares by distribution. +- **Deviation:** Layout: input ``(batch, 3, 6000)`` and one stacked output ``(batch, 3, 6000)`` instead of Keras' ``(batch, 6000, 3)`` input and three ``(batch, 6000, 1)`` outputs. Other input lengths raise a ``ValueError``; the reference decoder cannot restore them either. +- **Deviation:** Train-mode dropout masks follow Keras (one mask per sequence for the LSTM inputs and recurrent state, per gate in the conservative model's ``implementation=1``), but cannot reproduce Keras' random draws; train-mode outputs were compared with every dropout switched off. +- **Deviation:** The official tester also reports MC-dropout uncertainties (standard deviations over passes); ``extract_picks`` reports probabilities only. Registry Name ------------- @@ -97,11 +119,25 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="eqtransformer", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + # The paper model with its released weights (MIT), downloaded on first use. + model = build_model(name="eqtransformer", task="picking", pretrained=True).eval() + + waveforms = torch.randn(4, 3, 6000) # 60 s at 100 Hz, components E, N, Z, band-passed 1-45 Hz + with torch.no_grad(): + probabilities = model.annotate(waveforms) # (4, 3, 6000): detection, P, S + picks = model.extract_picks(probabilities) # [{"P": [(sample, prob)], "S": [...]}, ...] + events = model.extract_detections(probabilities) # [[(on, off, prob)], ...] + + conservative = build_model(name="eqtransformer", task="picking", variant="conservative") Notes ----- -- Outputs are P- and S-arrival sample indices. +- Inputs follow the training data (STEAD): 60-s windows at 100 Hz with components in the order E, N, Z, band-pass filtered between 1 and 45 Hz. ``annotate`` only normalises; filter real data first. + +- The released models differ from the defaults of ``cred2`` at the pinned commit (e.g. 96/128 filters there). The port follows the graphs stored in the .h5 files. The paper text gives a dropout rate of 0.1; the stored paper model uses 0.2 (the conservative model 0.1). The paper also names a Xavier-normal initialiser; the stored configurations use Glorot-uniform kernels for convolutions and LSTMs and Glorot-normal ones only for the attention and feed-forward weights. + +- The conservative model was saved by Keras 2.2.4, whose LSTMs use ``hard_sigmoid`` gates and ``implementation=1``; the paper model (Keras 2.3.0) uses ``sigmoid`` and ``implementation=2``. The two Keras versions also update BatchNorm's running statistics differently (zero-debiased moving averages in 2.2.4); the port keeps each model's behaviour. + +- Default pick thresholds are those of the official ``tester()`` (detection 0.2, P 0.1, S 0.1). As in the tester's output table, ``extract_picks`` reports the first detected event of each window unless ``all_events=True``. + diff --git a/docs/source/modules/models_firecastnet.rst b/docs/source/modules/models_firecastnet.rst index 26970365..4446fe48 100644 --- a/docs/source/modules/models_firecastnet.rst +++ b/docs/source/modules/models_firecastnet.rst @@ -6,7 +6,7 @@ FireCastNet Overview -------- -``firecastnet`` is a raster wildfire spread baseline that uses a shallow encoder-decoder architecture. +``firecastnet`` predicts whether fire will burn in each 0.25-degree cell during a future 8-day period (horizon 1 to 24 periods) from a time series of Earth-system variables (Michail et al., Scientific Reports 2025). A cube embedding (``Conv3d`` with kernel and stride ``T x 4 x 4`` plus LayerNorm) maps ``T = 24`` steps of the global 720 x 1440 grid (10 SeasFire variables, land-sea mask and cos/sin coordinates) to 64 features on a 1-degree grid. A GraphCast encoder-processor-decoder passes messages between that grid and a multi-mesh made of icosphere levels 0-6 (40,962 nodes, 12 processor layers, hidden size 64). A sub-pixel shuffle turns 16 outputs per 1-degree cell into one logit per 0.25-degree cell. At a Glance ----------- @@ -42,11 +42,11 @@ At a Glance .. container:: catalog-stat-value - 1 + 2 .. container:: catalog-stat-note - Spread + Segmentation, Forecasting .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,22 +63,39 @@ At a Glance Description ----------- -``firecastnet`` is a raster wildfire spread baseline that uses a shallow encoder-decoder architecture. +``firecastnet`` predicts whether fire will burn in each 0.25-degree cell during a future 8-day period (horizon 1 to 24 periods) from a time series of Earth-system variables (Michail et al., Scientific Reports 2025). A cube embedding (``Conv3d`` with kernel and stride ``T x 4 x 4`` plus LayerNorm) maps ``T = 24`` steps of the global 720 x 1440 grid (10 SeasFire variables, land-sea mask and cos/sin coordinates) to 64 features on a 1-degree grid. A GraphCast encoder-processor-decoder passes messages between that grid and a multi-mesh made of icosphere levels 0-6 (40,962 nodes, 12 processor layers, hidden size 64). A sub-pixel shuffle turns 16 outputs per 1-degree cell into one logit per 0.25-degree cell. -The PyHazards implementation is optimized for the shared smoke benchmark rather than the full upstream training stack. +This is a pure PyTorch port of the official code (no DGL). The icosphere multi-mesh and the grid/mesh graphs are generated when the model is built and match the official graphs bit for bit. Parameter names follow the official network, so the released checkpoints load with ``strict=True`` through ``build_model(..., checkpoint=path)``: global ``ts24`` models for horizons 1, 2, 4, 8, 16 and 24 (classification and regression) and per-GFED-region local-area models, which also need their mesh file from the official repository (``icospheres_graph_path``). Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Wildfire Benchmark ` -**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` - External References ------------------- **Paper:** `FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction `_ | **Repo:** `Repository `__ +Used In +------- + +- `FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction (arXiv:2502.01550) `_ (`repo `__): SeasFire datacube (0.25 degree, 8-day steps), years 2002-2017 / 2018 / 2019 for train / validation / test, binary burned area (gwis_ba) at horizon h, one model per horizon, BCE, AdamW lr 1e-3, 50 epochs, batch 1. Global test AUPRC with 24 input steps (Table 2): 0.641 / 0.636 / 0.631 / 0.631 / 0.628 / 0.633 for h = 1 / 2 / 4 / 8 / 16 / 24, ahead of GRU, Conv-GRU, Conv-LSTM, U-TAE and TeleViT; local-area models per GFED region in Table 4 (for example AUST 0.25 at h = 1, against 0.31 for the global model). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/SeasFire/firecastnet `__ at ``dc0d131`` (none at repository level (test oracle only); the ported GraphCast layers are Apache-2.0 (NVIDIA), as is NVIDIA Modulus v0.5.0, which the graph construction follows; checkpoints Apache-2.0 (Hugging Face d-michail/firecastnet-artifacts)) +- **Checked configuration:** Released global classifier firecastnet-cls-ts24-h1.ckpt: 24 steps x 11 inputs (+3 static channels) on the 720 x 1440 grid, Conv3d 24x4x4 to 64 channels with LayerNorm, 1-degree graph grid (180 x 360), icosphere levels 0-6 (40,962 mesh nodes; 327,660 mesh, 100,160 grid-to-mesh and 64,800 mesh-to-grid edges), 12 processor layers, hidden 64, sum aggregation, 16 outputs and PixelShuffle(4); likewise firecastnet-regr-ts24-h1.ckpt and the AUST local-area checkpoint firecastnet-cls-AUST-ts24-h1.ckpt (2,002-node mesh), plus small global configurations with seeded initialisation. All 94 released checkpoint configurations use this network configuration. +- **Parameter count:** 9,087,568 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_firecastnet_oracle.py`` +- **Deviation:** Only the configuration FireCastNet uses is ported: a cube embedding whose temporal patch spans the whole input (embed_cube_time == timeseries_len). The reference's other options (no cube embedding, ViT and L-TAE cube embedders, the recurrent processor used when the embedded cube keeps a time axis, do_concat_trick) appear neither in the paper nor in the released checkpoints and raise an error here. +- **Deviation:** The reference LightningModule accepts a batch size of 1. Here the cube embedding is batched and the graph network runs once per sample, which gives the same per-sample outputs. +- **Deviation:** The reference sizes its DGL bipartite graphs by the largest mesh vertex a grid node links to, so it fails unless the grid reaches the last mesh vertex (in practice, only global grids work). The port counts all mesh vertices, so regional windows also run; outputs on global grids are unchanged. +- **Deviation:** The reference also lists GraphNorm, InstanceNorm, BatchNorm and MessageNorm as norm_type but looks them up in torch.nn, where none exists; only LayerNorm (or none) is accepted here. Non-square patches switch the reference to a ConvTranspose3d up-sampling that fails on its 4-D input; the port requires square patches. +- **Deviation:** Nearest neighbours for the grid/mesh graphs come from a SciPy KD-tree with exact float64 re-ranking instead of scikit-learn; the oracle checks that every graph (edge order and features) is bitwise identical for the global and the local-area meshes. + Registry Name ------------- @@ -87,7 +104,8 @@ Primary entrypoint: ``firecastnet`` Supported Tasks --------------- -- Spread +- Segmentation +- Forecasting Programmatic Use ---------------- @@ -97,11 +115,28 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="firecastnet", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) + # Released configuration: 24 eight-day steps of 11 variables on the global 0.25-degree grid. + model = build_model(name="firecastnet", task="segmentation") # 9,087,568 parameters + # Official weights (huggingface.co/datasets/d-michail/firecastnet-artifacts, Apache-2.0): + # model = build_model(name="firecastnet", task="segmentation", checkpoint="firecastnet-cls-ts24-h1.ckpt") + model.eval() + x = torch.randn(1, 24, 11, 720, 1440) # (batch, time, variables, lat, lon), standardised + with torch.no_grad(): + probability = torch.sigmoid(model(x)) # (1, 1, 720, 1440) + print(probability.shape) Notes ----- -- The smoke configuration uses the single-frame wildfire spread raster fixture. +- Input channels, in order: mslp, tp, vpd, sst, t2m_mean, ssrd, swvl1, lst_day, ndvi, pop_dens, lsm. Preprocessing is done outside the model, as in the official inference script: log(1 + x) for tp and pop_dens, standardisation of the 10 dynamic variables with SeasFire statistics (lsm stays raw), missing values set to -1, and a window of 24 steps ending h periods before the target period. The official inference sets predictions to 0 where lsm < 0.1. + +- The cube LayerNorm normalises over the whole embedded cube (64 x 1 x 180 x 360) with an elementwise affine of that shape: 8,294,400 of the 9,087,568 parameters. A model therefore only runs on the grid it was built for; the default is the global 0.25-degree grid. + +- Kept from the reference because they change outputs: mesh-node features are cos/sin of latitude and longitude in degrees passed to cos/sin without conversion to radians (as in NVIDIA Modulus), and icosphere vertices come from midpoint subdivision of the flat icosahedron with one projection onto the sphere at the end, not a projection after every refinement step as the paper describes. + +- The cos(lat), sin(lon) and cos(lon) channels are appended inside the model (``lat_lon_static_data``). Any latitude/longitude window and resolution can be configured; the smoke test uses a tiny 2.5-degree global grid with icosphere levels 0-2. + +- Local-area checkpoints for BONA and SHSA point to mesh files that are not in the official repository (final_icospheres/icosphere_s3_BONA_6u.json and icospheres-lam/icospheres/icosphere_s3_SHSA_7u_SHAF_2n.json), so they cannot be run as released; their weights still load, since no weight depends on the mesh. + +- A global forward pass on CPU needs about 5 GB of memory (the float32 input alone is 1.1 GB). The paper's AUPRC was not re-evaluated here: that needs the 44 GB SeasFire datacube. + diff --git a/docs/source/modules/models_floodcast.rst b/docs/source/modules/models_floodcast.rst index 42decc16..e8e1c0ec 100644 --- a/docs/source/modules/models_floodcast.rst +++ b/docs/source/modules/models_floodcast.rst @@ -6,7 +6,7 @@ FloodCast Overview -------- -``floodcast`` is the first public inundation model in the staged PyHazards flood roadmap. +``floodcast`` is a compact PyHazards spatiotemporal network that maps ``(batch, history, channels, H, W)`` rasters to a next-step depth raster ``(batch, 1, H, W)``. It is not FloodCast. FloodCast's hydrodynamic module is the sequence-to-sequence GeoPINS: a physics-informed Fourier neural operator solving the 2-D shallow-water equations without training labels, trained per 16-step sequence and marched in time, with hard-encoded inflow boundaries. At a Glance ----------- @@ -31,7 +31,7 @@ At a Glance .. container:: catalog-stat-value - Implemented + Experimental Adapter .. container:: catalog-stat-note @@ -42,11 +42,11 @@ At a Glance .. container:: catalog-stat-value - 1 + 2 .. container:: catalog-stat-note - Inundation + Forecasting, Segmentation .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,32 @@ At a Glance Description ----------- -``floodcast`` is the first public inundation model in the staged PyHazards flood roadmap. +``floodcast`` is a compact PyHazards spatiotemporal network that maps ``(batch, history, channels, H, W)`` rasters to a next-step depth raster ``(batch, 1, H, W)``. It is not FloodCast. FloodCast's hydrodynamic module is the sequence-to-sequence GeoPINS: a physics-informed Fourier neural operator solving the 2-D shallow-water equations without training labels, trained per 16-step sequence and marched in time, with hard-encoded inflow boundaries. -The adapter uses shared raster tensors so it can be benchmarked through the ``flood.inundation`` evaluator without dataset-specific glue code. +Why it is not rebuilt from the paper (arXiv 2403.12226v1, the only open version; read in full): the paper gives the GeoPINS layout (MLP lift, FNO layers, MLP projection; GELU and a layer normalisation after each FNO layer in its PDE experiments), four space-time FNO layers with spatial modes 32 and temporal modes 4 for the flood model, the GeoPC loss (continuity and momentum residuals with Manning friction, initial-condition weight 10, finite differences) and the training schedule, but not the channel widths of the flood model (only the toy PDE experiments list widths 16 / 24 / 24 / 32 / 32), not the lifting / projection widths, and only "3 input channels: coordinate x, time t and initial condition" for a 2-D problem with three state variables. The released repository holds toy PDE examples and empty placeholders for the flood model and has no licence. A rebuild would therefore guess its size; it would be neither the paper's model nor checkable. + +FloodCastBench's supervised FNO baseline (Xu et al., Scientific Data 12:431, 2025: 4 Fourier layers, the 12 lowest modes, width 20, one-shot over 19 steps from the initial depth plus coordinates and time; FNO+ adds terrain and rainfall) is not added either: FloodCastBench released only its data-generation code (no model code, no licence), so there is nothing to verify a port against, and the paper leaves the temporal modes open. The smoke configuration scores this stand-in on ``flood_inundation_synthetic`` (random rasters). Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Flood Benchmark ` -**Mapped benchmark ecosystems:** :doc:`FloodCastBench ` - External References ------------------- -**Paper:** `Large-scale flood modeling and forecasting with FloodCast `_ | **Repo:** `Repository `__ +**Paper:** `Large-scale flood modeling and forecasting with FloodCast `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Large-scale flood modeling and forecasting with FloodCast `_ (`repo `__): Xu, Shi, Bamber, Ouyang and Zhu, Water Research 264:122162 (2024); arXiv 2403.12226. 2022 Pakistan flood (85,616.5 km2, 18-31 August), 480 m grid, 300 s steps, 14-day simulation against a finite-difference hydrodynamic benchmark: average MAPE 14.93% and MAE 0.0610 m (depth >= 0 m), MAE 0.0589 m (>= 0.1 m), 0.0452 m (>= 0.5 m) (Table 5); MAE 0.3615 m against SAR-derived depths on 30 August (hydrodynamics 0.4203 m). The repository has no licence and does not contain the flood model. +- `FloodCastBench: A Large-Scale Dataset and Foundation Models for Flood Modeling and Forecasting `_ (`repo `__): Xu, Shi, Zhao and Zhu, Scientific Data 12:431 (2025); data Zenodo 10.5281/zenodo.14017092 (21.6 GB, CC BY 4.0). Table 4 (RMSE / NSE), low-fidelity 480 m (Pakistan): U-Net 0.079399 / 0.991705, FNO 0.002232 / 0.999993, FNO+ 0.002107 / 0.999994; high-fidelity 60 m (Australia): U-Net 0.566626 / 0.560984, FNO 0.004258 / 0.999975, FNO+ 0.003941 / 0.999979. Only the data-generation code is released. + +Reproduction +------------ + +Not yet verified against a reference implementation. Registry Name ------------- @@ -87,7 +98,8 @@ Primary entrypoint: ``floodcast`` Supported Tasks --------------- -- Inundation +- Forecasting +- Segmentation Programmatic Use ---------------- @@ -105,3 +117,5 @@ Notes ----- - Outputs are next-horizon inundation depth rasters. +- Experimental: kept under its published name only as a placeholder; do not report its results as FloodCast's. A faithful entry needs the flood-model code (or the widths) from the authors. + diff --git a/docs/source/modules/models_forefire.rst b/docs/source/modules/models_forefire.rst deleted file mode 100644 index cc0f3b6a..00000000 --- a/docs/source/modules/models_forefire.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. - -ForeFire Adapter -================ - -Overview --------- - -``forefire`` is a deterministic raster adapter that approximates simulator-style front propagation through fixed diffusion kernels. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Wildfire - - .. container:: catalog-stat-note - - Public catalog grouping used for this model. - - .. grid-item-card:: Maturity - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Implemented - - .. container:: catalog-stat-note - - Catalog maturity label used on the index page. - - .. grid-item-card:: Tasks - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - Spread - - .. grid-item-card:: Benchmark Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :doc:`Wildfire Benchmark ` - - .. container:: catalog-stat-note - - Primary benchmark-family link used for compatible evaluation coverage. - - -Description ------------ - -``forefire`` is a deterministic raster adapter that approximates simulator-style front propagation through fixed diffusion kernels. - -PyHazards exposes it as a benchmarkable baseline through the standard model registry. - -Benchmark Compatibility ------------------------ - -**Primary benchmark family:** :doc:`Wildfire Benchmark ` - -**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` - -External References -------------------- - -**Paper:** `ForeFire: A Modular, Scriptable C++ Simulation Engine and Library for Wildland-Fire Spread `_ | **Repo:** `Repository `__ - -Registry Name -------------- - -Primary entrypoint: ``forefire`` - -Supported Tasks ---------------- - -- Spread - -Programmatic Use ----------------- - -.. code-block:: python - - import torch - from pyhazards.models import build_model - - model = build_model(name="forefire", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) - -Notes ------ - -- This adapter is deterministic and does not learn parameters during the smoke test. diff --git a/docs/source/modules/models_fourcastnet_tc.rst b/docs/source/modules/models_fourcastnet_tc.rst deleted file mode 100644 index 3515efc7..00000000 --- a/docs/source/modules/models_fourcastnet_tc.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. - -FourCastNet TC Adapter -====================== - -Overview --------- - -``fourcastnet_tc`` completes the first wave of experimental foundation-weather storm adapters in the staged roadmap. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Tropical Cyclone - - .. container:: catalog-stat-note - - Public catalog grouping used for this model. - - .. grid-item-card:: Maturity - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Experimental Adapter - - .. container:: catalog-stat-note - - Catalog maturity label used on the index page. - - .. grid-item-card:: Tasks - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - Track + Intensity - - .. grid-item-card:: Benchmark Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :doc:`Tropical Cyclone Benchmark ` - - .. container:: catalog-stat-note - - Primary benchmark-family link used for compatible evaluation coverage. - - -Description ------------ - -``fourcastnet_tc`` completes the first wave of experimental foundation-weather storm adapters in the staged roadmap. - -The PyHazards version is intentionally lightweight and uses the same trajectory output contract as the other storm baselines. - -Benchmark Compatibility ------------------------ - -**Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` - -**Mapped benchmark ecosystems:** :doc:`IBTrACS ` - -External References -------------------- - -**Paper:** `FourCastNet: A Global Data-driven High-resolution Weather Model using Adaptive Fourier Neural Operators `_ | **Repo:** `Repository `__ - -Registry Name -------------- - -Primary entrypoint: ``fourcastnet_tc`` - -Supported Tasks ---------------- - -- Track + Intensity - -Programmatic Use ----------------- - -.. code-block:: python - - import torch - from pyhazards.models import build_model - - model = build_model(name="fourcastnet_tc", task="regression", input_dim=8, history=6, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) - -Notes ------ - -- Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity. diff --git a/docs/source/modules/models_google_flood_forecasting.rst b/docs/source/modules/models_google_flood_forecasting.rst index ea8999be..cd93ab04 100644 --- a/docs/source/modules/models_google_flood_forecasting.rst +++ b/docs/source/modules/models_google_flood_forecasting.rst @@ -6,7 +6,7 @@ Google Flood Forecasting Overview -------- -``google_flood_forecasting`` is a compact sequence-to-node forecasting baseline for flood streamflow prediction. +``google_flood_forecasting`` is a port of ``MeanEmbeddingForecastLSTM`` from google-research/flood-forecasting (googlehydrology). Static attributes are embedded by an FC network; each weather product (input group) is embedded with the static embedding by its own FC network, and the group embeddings are averaged with a NaN-aware mean so that a product that is missing on a day is skipped. A hindcast LSTM runs over the averaged hindcast embeddings, and a forecast LSTM over the averaged forecast embeddings and the hindcast LSTM's outputs. The CMAL head returns, for every day, a mixture of three asymmetric Laplace distributions (``mu``, ``b``, ``tau``, ``pi``); ``point_prediction`` gives the mixture mean. At a Glance ----------- @@ -63,9 +63,11 @@ At a Glance Description ----------- -``google_flood_forecasting`` is a compact sequence-to-node forecasting baseline for flood streamflow prediction. +``google_flood_forecasting`` is a port of ``MeanEmbeddingForecastLSTM`` from google-research/flood-forecasting (googlehydrology). Static attributes are embedded by an FC network; each weather product (input group) is embedded with the static embedding by its own FC network, and the group embeddings are averaged with a NaN-aware mean so that a product that is missing on a day is skipped. A hindcast LSTM runs over the averaged hindcast embeddings, and a forecast LSTM over the averaged forecast embeddings and the hindcast LSTM's outputs. The CMAL head returns, for every day, a mixture of three asymmetric Laplace distributions (``mu``, ``b``, ``tau``, ``pi``); ``point_prediction`` gives the mixture mean. -The PyHazards implementation uses a transformer encoder over per-node history windows and returns one forecast value per node. +``config="floodhub"`` (default) is the released FloodHub model (Gauch et al. 2025 architecture): 84 Caravan / HydroATLAS attributes, hindcast products HRES, GraphCast, IMERG and CPC over 365 days, forecast products HRES and GraphCast over the 365 days plus 7 lead days, hidden size 512 (3,402,832 parameters). ``pretrained=True`` downloads and loads the released weights (13.6 MB, Apache-2.0 repository). Inputs are ``x_s`` (batch, 84), ``x_d_hindcast`` (batch, 365, 9) and ``x_d_forecast`` (batch, 372, 7), as tensors in the configured feature order or as googlehydrology's per-feature dicts. + +``config="streamflow"`` keeps the architecture but uses one input group of ``n_dynamic`` daily forcings, ``n_static`` attributes and no lead time, so that the model reads the PyHazards streamflow layout ``{"x_d", "x_s"}`` (``camels_us_streamflow``, ``caravan_streamflow``) and is scored by the flood benchmark from the mixture mean. This is a PyHazards adaptation, not a Google configuration. Benchmark Compatibility ----------------------- @@ -77,7 +79,27 @@ Benchmark Compatibility External References ------------------- -**Paper:** `Global Flood Forecasting at a Fine Catchment Resolution using Machine Learning `_ | **Repo:** `Repository `__ +**Paper:** `How to deal w___ missing input data `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Global prediction of extreme floods in ungauged watersheds `_ (`repo `__): Nearing, Cohen, Dube, Gauch, Gilon, Harrigan, Hassidim, Klotz, Kratzert, Metzger, Nevo, Pappenberger, Prudhomme, Shalev, Shenzis, Tekalign, Weitzner and Matias, Nature 627:559-563 (2024). The earlier FloodHub model, a hindcast/forecast LSTM with a state handoff (hidden size 256, one asymmetric Laplacian output, 0-7 day lead times, ensemble of 3) trained on 5,680 gauges. Forecasts for extreme events (1- to 10-year return periods) at up to 5 days lead time in ungauged basins had precision and recall similar to or better than GloFAS nowcasts; medians are given in figures only. That handoff model is not ported here. +- `How to deal w___ missing input data `_: Gauch, Kratzert, Klotz, Nearing, Cohen and Gilon, HESS 29:6221-6235 (2025). Introduces the masked-mean input embedding of this model and compares it with input replacing and attention on 531 CAMELS-US basins (three forcing products, hidden size 256, 365-day inputs, NSE* loss); the masked mean performs best by a small margin. Results are reported as figures (median NSE and KGE versus the fraction of missing inputs). +- `google-research/flood-forecasting: released FloodHub model `_: The released run was trained on 1982-2023 for all 15,955 listed Caravan + MultiMet basins (no temporal hold-out). Its test_metrics.csv (median NSE 0.688, median KGE 0.659 over 10,137 basins) is therefore in-sample, and Google states it must not be used as a benchmark. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/google-research/flood-forecasting `__ at ``cdda28d`` (Apache-2.0) +- **Checked configuration:** googlehydrology/modelzoo/mean_embedding_forecast_lstm.py built from pretrained-models/google-floodhub-settings-110-epochs/config.yml (84 statics; hindcast groups hres, graphcast, imerg, cpc; forecast groups hres, graphcast; seq_length 365, lead_time 7, hidden_size 512, CMAL with 3 components, output_dropout 0.4, initial_forget_bias 3, Xavier / orthogonal initialisation; 3,402,832 parameters) and the released model_epoch110.pt (sha256 90280f06...3fdba, strict load after removing the ``_orig_mod.`` prefix). +- **Parameter count:** 3,402,832 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_google_flood_forecasting_oracle.py`` +- **Deviation:** Constructor arguments replace the googlehydrology Config; group order follows the configuration, as in the reference. +- **Deviation:** Not ported: the data-assimilation hooks of ``forward`` (``assimilation_overrides``, ``assimilation_slice``, ``return_embeddings``) and the hot-start state files (``save_state``, ``load_state_from_disk``). Without them the forward pass is the reference's. +- **Deviation:** The release normalises inputs with its scaler.zarr, which PyHazards does not read; the googlehydrology tester also reduces 7,500 samples of the mixture to their median, whereas the PyHazards flood benchmark scores the closed-form mixture mean (``point_prediction``). +- **Deviation:** ``config="streamflow"`` (one shared input group, ``lead_time=0``) is a PyHazards adaptation for the streamflow layout; the oracle test checks that it equals googlehydrology with the same settings. Registry Name ------------- @@ -97,17 +119,17 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="google_flood_forecasting", - task="regression", - input_dim=2, - out_dim=1, - history=4, - ) - preds = model({"x": torch.randn(2, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="google_flood_forecasting", task="regression", pretrained=False) + out = model({ + "x_s": torch.randn(2, 84), + "x_d_hindcast": torch.randn(2, 365, 9), # hres (5), graphcast (2), imerg, cpc + "x_d_forecast": torch.randn(2, 372, 7), # hres (5), graphcast (2) incl. 7 lead days + }) + print(out["mu"].shape, model.point_prediction(out).shape) # (2, 372, 3) (2, 372, 1) Notes ----- -- The smoke path uses the same streamflow-style graph fixture as the other flood baselines. +- Missing data: a NaN anywhere in a product's features on a day removes that product from the mean of that day; a day where all products are missing makes every later output NaN (the LSTM state is undefined), exactly as in the reference. + +- The smoke configuration runs ``config="streamflow"`` on ``flood_streamflow_synthetic``. diff --git a/docs/source/modules/models_gpd.rst b/docs/source/modules/models_gpd.rst index 12607c77..77016221 100644 --- a/docs/source/modules/models_gpd.rst +++ b/docs/source/modules/models_gpd.rst @@ -6,7 +6,7 @@ GPD Overview -------- -``gpd`` provides a lightweight earthquake picking adapter with the same waveform-to-pick interface used across the PyHazards earthquake benchmarks. +``gpd`` classifies a 400-sample window (4 s at 100 Hz, channels N, E, Z, scaled by its maximum absolute amplitude) into P, S and noise. The network has four blocks of convolution (32 / 64 / 128 / 256 filters, kernels 21 / 15 / 11 / 9), batch normalisation, ReLU and 2x max pooling, followed by two 200-unit dense layers with batch normalisation and a three-way softmax (1,741,003 parameters). At a Glance ----------- @@ -63,22 +63,42 @@ At a Glance Description ----------- -``gpd`` provides a lightweight earthquake picking adapter with the same waveform-to-pick interface used across the PyHazards earthquake benchmarks. +``gpd`` classifies a 400-sample window (4 s at 100 Hz, channels N, E, Z, scaled by its maximum absolute amplitude) into P, S and noise. The network has four blocks of convolution (32 / 64 / 128 / 256 filters, kernels 21 / 15 / 11 / 9), batch normalisation, ReLU and 2x max pooling, followed by two 200-unit dense layers with batch normalisation and a three-way softmax (1,741,003 parameters). -This adapter is intended as a reproducible low-cost baseline rather than an exact port of every original training detail. +``annotate`` slides the classifier over longer traces in steps of 10 samples, as ``gpd_predict.py`` does, and ``extract_picks`` turns the P and S probability sequences into picks: a trigger starts when a probability reaches 0.95 and ends when it falls below 0.1, and the window with the highest probability in the trigger gives the pick at its centre. Module names are the Keras layer names, and the released weights (``model_pol_best.hdf5``, MIT) load with ``pretrained=True``. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Earthquake Benchmark ` -**Mapped benchmark ecosystems:** :doc:`pick-benchmark ` +**Mapped benchmark ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` External References ------------------- **Paper:** `Generalized Seismic Phase Detection with Deep Learning `_ | **Repo:** `Repository `__ +Used In +------- + +- `Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking `_ (`repo `__): Applies the pretrained GPD (trained on 4.5M Southern California windows) to the STEAD test set; a pick counts as a true positive within 0.5 s of the manual pick. Table 2 (P): mean 0.03 s, std 0.10 s, precision 0.81, recall 0.80, F1 0.81, MAE 0.08 s, MAPE 0.01. Table 3 (S): mean 0.03 s, std 0.14 s, precision 0.81, recall 0.83, F1 0.82, MAE 0.10 s, MAPE 0.01. +- `Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers `_ (`repo `__): Muenchmeyer et al., JGR Solid Earth 127:e2021JB023499 (2022). GPD (SeisBench's port, same 1,741,003 parameters) retrained on each dataset; in-domain phase identification MCC (Table 2): ETHZ 0.92, INSTANCE 0.95, Iquique 0.98, SCEDC 0.93, STEAD 0.99, GEOFON 0.67, NEIC 0.84. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/interseismic/generalized-phase-detection `__ at ``ea81ef1`` (MIT (code and released weights, Copyright (c) 2018 Zachary E. Ross)) +- **Checked configuration:** The Keras 2.2.2 network of model_pol.json with the released weights model_pol_best.hdf5, run on TensorFlow 2.11 (tf.keras) from the JSON's inner Sequential config, and the gpd_predict.py pipeline (ObsPy linear detrend and 3-20 Hz band-pass, 400-sample windows every 10 samples, per-window max normalisation, trigger_onset(0.95, 0.1), argmax pick) on the shipped Anza 2016 station AZ.TRO data; SeisBench 0.12.6's GPD with its conversion of the same weights as a second reference. +- **Parameter count:** 1,741,003 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_gpd_oracle.py`` +- **Deviation:** The release wraps the network in Keras multi-GPU Lambda / Concatenate layers (stored as Python 3.6 bytecode). They only split the batch across GPUs and are not ported; the oracle is the inner Sequential network, unchanged. +- **Deviation:** An all-zero window, which gpd_predict.py divides by zero (NaN probabilities), is left at zero by ``annotate`` and classified normally. +- **Deviation:** Filtering is not part of ``annotate``: gpd_predict.py band-passes whole traces at 3-20 Hz (and the training data were high-passed at 2 Hz), so callers must filter their traces the same way. +- **Deviation:** Inputs are ``(batch, channels, samples)`` instead of Keras' ``(batch, samples, channels)``; the feature map is transposed before flattening so that the Keras dense_1 kernel loads unchanged. +- **Deviation:** Initial weights follow the Keras scheme (Glorot-uniform kernels, zero biases) but cannot match TensorFlow's random draws; the oracle compares their bounds and spread. + Registry Name ------------- @@ -97,11 +117,22 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="gpd", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + # Window classifier: 4-s windows at 100 Hz, channels N, E, Z -> P / S / noise probabilities. + model = build_model(name="gpd", task="classification") # pretrained=True loads model_pol_best.hdf5 + model.eval() + windows = torch.randn(8, 3, 400) + windows = windows / windows.abs().amax(dim=(1, 2), keepdim=True) + probabilities = model(windows) # (8, 3) + + # Picking a 60-s band-passed (3-20 Hz) trace with the official sliding window. + with torch.no_grad(): + annotations = model.annotate(torch.randn(1, 3, 6000), stride=10) # (1, 3, 561) + picks = model.extract_picks(annotations) # [{"P": [(sample, prob), ...], "S": [...]}] Notes ----- -- The adapter keeps a simple two-output pick interface for shared evaluation. +- Channel order N, E, Z (gpd_predict.py stacks the N, E and Z files in that order). SeisBench's conversion of the same weights takes Z, N, E: it permuted the first convolution's input channels, which the oracle test confirms. +- Class order P, S, noise. The repository's picker uses a 0.95 trigger threshold (``min_proba``); the paper reports detections above 0.98. +- Batch normalisation reproduces Keras 2.2.2, which trained the released weights: the moving variance is updated with the factor n / (n - 1 - eps) and a zero-debiased moving average (decay 0.99), checked against TensorFlow's assign_moving_average. +- On 18 minutes of the shipped Anza 2016 data (08:02-08:20 UTC), the port's picks are identical to the official Keras pipeline and, inside the slice, to the shipped anza2016.out (33 P and 96 S picks). diff --git a/docs/source/modules/models_graphcast_tc.rst b/docs/source/modules/models_graphcast_tc.rst deleted file mode 100644 index 4d267deb..00000000 --- a/docs/source/modules/models_graphcast_tc.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. - -GraphCast TC Adapter -==================== - -Overview --------- - -``graphcast_tc`` is an experimental foundation-weather adapter that keeps the shared storm trajectory interface while remaining lightweight enough for CI. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Tropical Cyclone - - .. container:: catalog-stat-note - - Public catalog grouping used for this model. - - .. grid-item-card:: Maturity - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Experimental Adapter - - .. container:: catalog-stat-note - - Catalog maturity label used on the index page. - - .. grid-item-card:: Tasks - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - Track + Intensity - - .. grid-item-card:: Benchmark Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :doc:`Tropical Cyclone Benchmark ` - - .. container:: catalog-stat-note - - Primary benchmark-family link used for compatible evaluation coverage. - - -Description ------------ - -``graphcast_tc`` is an experimental foundation-weather adapter that keeps the shared storm trajectory interface while remaining lightweight enough for CI. - -The PyHazards version is intentionally wrapper-style and should be treated as an adapter contract rather than a full reproduction of the original weather model. - -Benchmark Compatibility ------------------------ - -**Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` - -**Mapped benchmark ecosystems:** :doc:`IBTrACS ` - -External References -------------------- - -**Paper:** `GraphCast: Learning skillful medium-range global weather forecasting `_ | **Repo:** `Repository `__ - -Registry Name -------------- - -Primary entrypoint: ``graphcast_tc`` - -Supported Tasks ---------------- - -- Track + Intensity - -Programmatic Use ----------------- - -.. code-block:: python - - import torch - from pyhazards.models import build_model - - model = build_model(name="graphcast_tc", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) - -Notes ------ - -- Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity. diff --git a/docs/source/modules/models_hurricast.rst b/docs/source/modules/models_hurricast.rst index 8fa01259..3c9744e5 100644 --- a/docs/source/modules/models_hurricast.rst +++ b/docs/source/modules/models_hurricast.rst @@ -6,7 +6,7 @@ Hurricast Overview -------- -``hurricast`` is the first basin-specific storm baseline in the staged PyHazards roadmap and operates on storm-history sequences. +``hurricast`` forecasts one lead time, 24 hours, from the last 8 three-hourly steps (t-21 h ... t) of a storm: ``target="intensity"`` the maximum sustained wind (1-minute, kt) and ``target="displacement"`` the latitude / longitude change (degrees; ``forecast()`` adds it to the current position). Inputs are a mapping with ``x_stat`` ``(batch, 8, 30)``, the 30 statistical features per step of the official feature tables (``HURRICAST_STAT_FEATURES``), ``x_viz`` ``(batch, 8, 9, 25, 25)``, ERA5 u, v and geopotential at 225, 500 and 700 hPa on 25 x 25 one-degree maps around the storm, and ``position`` for track forecasts. ``hurricast_ibtracs_era5`` builds them from IBTrACS and the user's ERA5 data. At a Glance ----------- @@ -42,11 +42,11 @@ At a Glance .. container:: catalog-stat-value - 1 + 2 .. container:: catalog-stat-note - Track + Intensity + Track + Intensity, Intensity .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,9 +63,11 @@ At a Glance Description ----------- -``hurricast`` is the first basin-specific storm baseline in the staged PyHazards roadmap and operates on storm-history sequences. +``hurricast`` forecasts one lead time, 24 hours, from the last 8 three-hourly steps (t-21 h ... t) of a storm: ``target="intensity"`` the maximum sustained wind (1-minute, kt) and ``target="displacement"`` the latitude / longitude change (degrees; ``forecast()`` adds it to the current position). Inputs are a mapping with ``x_stat`` ``(batch, 8, 30)``, the 30 statistical features per step of the official feature tables (``HURRICAST_STAT_FEATURES``), ``x_viz`` ``(batch, 8, 9, 25, 25)``, ERA5 u, v and geopotential at 225, 500 and 700 hPa on 25 x 25 one-degree maps around the storm, and ``position`` for track forecasts. ``hurricast_ibtracs_era5`` builds them from IBTrACS and the user's ERA5 data. -This initial adapter focuses on the shared tropical-cyclone forecasting interface and is intended as a reproducible starting point before broader storm-model breadth. +Stage 1 (the official ``ExperimentalHurricast``, written from the paper): per step a CNN (three 3 x 3 convolutions with BatchNorm and ReLU, two max poolings, dense layers 4096-576-256-128) embeds the maps; the first 14 statistical features are prepended and a Transformer decoder (2 layers, 2 heads, width 142, feed-forward 128, sinusoidal positions, mean pooling, tanh) reads the sequence; a linear layer predicts the standardised target. 2,969,771 parameters for intensity, 2,969,914 for displacement; the released code's other presets (``transformer_config_4`` / ``_68`` / ``_noviz``, recurrent ``lstm_config*``, ``split_encoder_config``) are available through ``decoder_config`` / ``encoder_config``. + +Stage 2: XGBoost (one regressor per target) on the flattened statistics (every numerical feature of the 8 steps and the categorical ones of the first step, 128 values) followed by the 142-d decoder output of the frozen network, with the defaults of the official ``train_xgb_*`` functions (depth 8, 140 trees, learning rate 0.15, subsample 0.7, minimum child weight 5). ``Hurricast.fit`` standardises the targets, trains the network (MSE + L2, Adam, batch 64) and then XGBoost; ``predictor="network"`` predicts with the network's head instead, ``use_embeddings=False`` is HUML-(stat, xgb). Benchmark Compatibility ----------------------- @@ -77,7 +79,26 @@ Benchmark Compatibility External References ------------------- -**Paper:** `Hurricane Forecasting: A Novel Multimodal Machine Learning Framework `_ | **Repo:** `Repository `__ +**Paper:** `Hurricane Forecasting: A Novel Multimodal Machine Learning Framework `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Boussioux, Zeng, Guenais and Bertsimas, Weather and Forecasting 37(6), 817-831 (2022); preprint arXiv 2011.06125v4 `_ (`repo `__): 24-hour forecasts on 2016-2019 North Atlantic (NA) and Eastern Pacific (EP) cases with concurrent ATCF operational forecasts, models trained on all basins 1980-2011 (validation 2012-2015). Track MAE (Table 5, EP 837 / NA 899 cases): HUML-(stat/viz, xgb/cnn/transfo) 72 / 109 km, HUML-(stat/viz, xgb/cnn/gru) 72 / 111 km, HUML-(stat, xgb) 81 / 144 km; HWRF 67 / 75 km, CLP5 121 / 201 km. Intensity MAE (Table 6, EP 877 / NA 899 cases): 10.3 / 10.4 kt (cnn/transfo), 10.3 / 10.8 kt (cnn/gru), 10.6 / 10.7 kt (stat, xgb); Decay-SHIPS 11.7 / 10.2 kt, HWRF 10.6 / 9.7 kt. Not reproduced by PyHazards (the ERA5 maps of the ~134,000 training cases are not part of the tests). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/leobix/hurricast `__ (``b1b303a``, none (no LICENSE file; the README claims MIT and links a LICENSE that does not exist). Used only as a test oracle, never copied.); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** ExperimentalHurricast(encoder full_encoder_config, decoder ExpTRANSFORMER transformer_config) from src/models/experimental_models.py and scripts/config.py: 2,969,771 (intensity) / 2,969,914 (displacement) parameters; for every preset of scripts/config.py (8 decoders x full / split encoders, both targets) the same state-dict keys, identical initial weights for the same seed, equal outputs and embeddings in eval and train mode (BatchNorm statistics, dropout) and equal gradients; official state dicts load with strict=True into Hurricast.network. The L2 term equals src/utils/run.py compute_l2 and a training step of fit_network equals src/run.py train_epoch (displacement target); the XGBoost feature columns equal the rule of notebooks/Compute_results_*_Round2.ipynb, its defaults those of scripts/run_embeddings.py, and the XGBoost stage predicts exactly as XGBRegressor (xgboost 3.2.0) fitted the official way. The storm cut, interpolated WMO wind / pressure, wind category and displacements of hurricast_ibtracs_era5 equal src/utils/data_processing.py on real IBTrACS rows. +- **Parameter count:** 2,969,771 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_hurricast_oracle.py`` +- **Deviation:** Paper and released code differ; the code is followed where it is the executable reference: the CNN's dense layers are 4096-576-256-128 (paper Fig. A1: 576-128), the decoder input is [statistics, embedding] (paper text: [embedding, statistics]), and the network reads 14 statistical features (the paper's text says 31; its d_model = 142 = 128 + 14 agrees with the code). +- **Deviation:** The paper's GRU decoder (two unidirectional GRU layers, all 8 hidden states concatenated, dense 1024-512-128-c, embedding = second dense output) is not in the released code and is not provided (the activations of its dense layers are not specified). The released recurrent presets (bidirectional LSTM / GRU / RNN reading the last hidden state: lstm_config, lstm_config_4layers, lstm_config_best_dis, lstm_config_test_dis) are. +- **Deviation:** Training is reimplemented from the paper and src/run.py: MSE plus 2 / batch * 0.01 * sum of squared weights, Adam (1e-3 intensity, 4e-4 track), batch 64, 30 epochs, the epoch with the lowest validation MSE kept. The official loop compared (batch, 1) intensity outputs with (batch,) targets, which nn.MSELoss broadcasts to all (batch x batch) pairs; PyHazards compares matching shapes. +- **Deviation:** The XGBoost hyperparameters are given in the paper only as ranges (depth 6-9, 100-300 trees, learning rate 0.03-0.15, subsample 0.6-0.9, column sampling 0.7-1, minimum child weight 1-5) and varied per task and basin in the Round2 notebooks; the defaults of the official train_xgb_* functions are used. Library defaults of xgboost >= 2 (histogram trees, estimated base score) differ from the 2020-21 xgboost 1.x. +- **Deviation:** Not provided: the tensor-decomposition embeddings (HUML-(stat/viz, xgb/td)), the ElasticNet ensemble and the consensus with operational forecasts (HUML-ensemble, HUML/OP-average), and the code's intensity-category classifier. The official ExpTRANSFORMER's "unroll" pooling (unused by every preset) gives the predictor the wrong width; here it gets n_out_unroll. Official forward(..., xgb=True) fails (a tuple reaches the predictor); here only get_embeddings takes xgb. Registry Name ------------- @@ -88,6 +109,7 @@ Supported Tasks --------------- - Track + Intensity +- Intensity Programmatic Use ---------------- @@ -97,18 +119,23 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="hurricast", - task="regression", - input_dim=8, - horizon=5, - output_dim=3, - ) + # The paper's best model: CNN + Transformer embeddings, then XGBoost (needs pyhazards[xgboost]). + model = build_model(name="hurricast", task="regression", target="intensity") + inputs = { + "x_stat": torch.randn(64, 8, 30), # 8 three-hourly steps x 30 IBTrACS features + "x_viz": torch.randn(64, 8, 9, 25, 25), # u, v, z at 225 / 500 / 700 hPa, 25 x 25 degrees + } + model.fit(inputs, 60 + 20 * torch.randn(64), epochs=1) # network, then XGBoost on its embeddings + print(model(inputs).shape) # (64, 1): wind 24 h ahead - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # Real data: IBTrACS + ERA5 maps around the storms (user-provided netCDF / zarr). + # from pyhazards.datasets import load_dataset + # data = load_dataset("hurricast_ibtracs_era5", path="ibtracs.ALL.list.v04r01.csv", era5="era5_pl.nc").load() Notes ----- -- Outputs are lead-time sequences of latitude, longitude, and intensity targets. +- The official repository has no LICENSE file; nothing is copied from it. Its released configuration values (scripts/config.py presets, XGBoost defaults) are used as data. +- Inputs must be standardised as for training: hurricast_ibtracs_era5 standardises LAT, LON, WMO wind and pressure, distance to land, speed and the displacements with training statistics (paper Table 2) and leaves cyclic encodings and categories as they are, so the network's 14 features are standardised as in the official run_embeddings.py; each map channel is standardised over samples, steps and pixels. +- The XGBoost stage is not in state_dict(); use Hurricast.save / Hurricast.load (joblib). Embeddings are always computed with the network in eval mode. +- No trained weights were released, and the ERA5 tensors (> 30 GB) are not hosted. diff --git a/docs/source/modules/models_hydrographnet.rst b/docs/source/modules/models_hydrographnet.rst index da02a757..c1f08cfb 100644 --- a/docs/source/modules/models_hydrographnet.rst +++ b/docs/source/modules/models_hydrographnet.rst @@ -6,7 +6,7 @@ HydroGraphNet Overview -------- -``hydrographnet`` is the PyHazards entrypoint for flood forecasting on irregular meshes with graph-structured hydrologic state updates. +``hydrographnet`` is a port of PhysicsNeMo's ``MeshGraphKAN``, the HydroGraphNet model: a Fourier Kolmogorov-Arnold network encodes the 16 node features, an MLP encodes the 3 edge features, 15 residual message-passing blocks update edges (MLP on edge, source and destination) and nodes (MLP on the sum of incoming messages and the node), and an MLP decodes the normalised changes of water depth and volume over one 20-minute step. Every MLP has two hidden layers of 128 and ReLU, and all but the decoder end in LayerNorm (2,318,722 parameters). It takes ``(node_features (N, 16), edge_features (E, 3), edge_index (2, E))`` (or a PyTorch Geometric graph, or a mesh batch mapping) and returns ``(N, 2)``; ``rollout`` runs the example's autoregressive inference, feeding ``last + change`` back into the depth / volume windows and the next inflow and precipitation into the forcing columns. At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Streamflow + Inundation .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,41 @@ At a Glance Description ----------- -``hydrographnet`` is the PyHazards entrypoint for flood forecasting on irregular meshes with graph-structured hydrologic state updates. +``hydrographnet`` is a port of PhysicsNeMo's ``MeshGraphKAN``, the HydroGraphNet model: a Fourier Kolmogorov-Arnold network encodes the 16 node features, an MLP encodes the 3 edge features, 15 residual message-passing blocks update edges (MLP on edge, source and destination) and nodes (MLP on the sum of incoming messages and the node), and an MLP decodes the normalised changes of water depth and volume over one 20-minute step. Every MLP has two hidden layers of 128 and ReLU, and all but the decoder end in LayerNorm (2,318,722 parameters). It takes ``(node_features (N, 16), edge_features (E, 3), edge_index (2, E))`` (or a PyTorch Geometric graph, or a mesh batch mapping) and returns ``(N, 2)``; ``rollout`` runs the example's autoregressive inference, feeding ``last + change`` back into the depth / volume windows and the next inflow and precipitation into the forcing columns. -In PyHazards, this model is typically paired with the ERA5-based hydrograph adapter ``load_hydrograph_data`` for end-to-end smoke validation. +``HydroGraphNetLoss`` / ``hydrographnet_physics_loss`` port the example's training loss: MSE plus a volume-continuity penalty on the total predicted volume against inflow, effective precipitation and the next step's volume (delta_t 1200 s, weight 1). Parameter names, initialisation, outputs, the physics loss and the rollout equal PhysicsNeMo's. + +Data: ``hydrographnet_white_river`` reads a local copy of the official White River dataset (HEC-RAS simulations on a 4,787-cell mesh near Muncie, Indiana, Zenodo 14969507, CC BY 4.0) exactly like PhysicsNeMo's ``HydroGraphDataset`` (node features, k=4 nearest-neighbour graph, normalisation, physics data, rollout targets); ``flood_mesh_synthetic`` produces random data in the same layout. The flood benchmark (``flood.inundation``) rolls every test hydrograph out and scores depths in metres. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Flood Benchmark ` -**Mapped benchmark ecosystems:** :doc:`HydroBench ` +**Mapped benchmark ecosystems:** :doc:`HydroGraphNet White River ` External References ------------------- -**Paper:** `Interpretable physics-informed graph neural networks for flood forecasting `_ +**Paper:** `Interpretable physics-informed graph neural networks for flood forecasting `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Interpretable physics-informed graph neural networks for flood forecasting `_ (`repo `__): Taghizadeh, Zandsalimi, Nabian, Shafiee-Jood and Alemazkoor, Computer-Aided Civil and Infrastructure Engineering 40(18):2629-2649 (2025). White River near Muncie, Indiana: 4,787-cell HEC-RAS mesh, boundary inflow hydrographs and rainfall; 30-step (10-hour) rollouts. The abstract reports a 67% lower prediction error than a baseline GNN, near-zero mass-balance error and a 58% higher critical success index for major floods; the full text (and its absolute numbers) could not be accessed, so no paper numbers are reproduced here. The official code is the PhysicsNeMo example, contributed by the first author. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/NVIDIA/physicsnemo `__ at ``eb7a329`` (Apache-2.0) +- **Checked configuration:** examples/weather/flood_modeling/hydrographnet (conf/config.yaml, train.py, inference.py, utils.py): MeshGraphKAN(16, 3, 2) with the PhysicsNeMo defaults (processor_size 15, hidden 128, 2 hidden layers per MLP, ReLU, LayerNorm, sum aggregation, 5 harmonics, do_concat_trick False), 2,318,722 parameters; HydroGraphDataset(prefix M80, n_time_steps 2, k 4, noise_type none, return_physics True); physics loss weight 1, delta_t 1200 s; rollout length 30. Oracle: physicsnemo/models/meshgraphnet/meshgraphkan.py (last changed in dcad4372dc166d3d57e7572943a9c5934684c885), torch_geometric + torch_scatter. +- **Parameter count:** 2,318,722 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_hydrographnet_oracle.py`` +- **Deviation:** Graphs are an ``edge_index`` tensor (PyTorch Geometric graphs are accepted) and messages are summed with ``index_add_`` instead of ``torch_scatter``; outputs agree to float precision. Batching several meshes is ``hydrograph_collate`` (PyG ``Batch`` layout). +- **Deviation:** Not ported (unused by the HydroGraphNet configuration): ``do_concat_trick`` (MeshGraphEdgeMLPSum), ``recompute_activation`` (nvFuser SiLU), gradient checkpointing of the processor, Transformer Engine LayerNorm, and the dataset's training noise options (only ``noise_type: none``) including the ``pushforward`` training branch. +- **Deviation:** The White River release has no test list (the example reads ``Test/test.txt``, which is not published, and ``train.txt`` lists all 500 hydrographs), so ``hydrographnet_white_river`` needs the test hydrographs as ``test_ids`` and drops them from the training list. It does not overwrite the release's normalisation-statistics files as the example's training run does, and does not subsample hydrographs (the example samples 500 at random only when more are listed). +- **Deviation:** No official weights were released, so no pretrained checkpoint is checked. Registry Name ------------- @@ -87,7 +107,7 @@ Primary entrypoint: ``hydrographnet`` Supported Tasks --------------- -- Streamflow +- Inundation Programmatic Use ---------------- @@ -95,25 +115,23 @@ Programmatic Use .. code-block:: python import torch + from pyhazards.datasets import load_dataset from pyhazards.models import build_model - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, - ) - - batch = { - "x": torch.randn(1, 3, 6, 2), - "adj": torch.eye(6).unsqueeze(0), - "coords": torch.randn(6, 2), - } - preds = model(batch) - print(preds.shape) + data = load_dataset("flood_mesh_synthetic", micro=True).load() # or hydrographnet_white_river + model = build_model(name="hydrographnet", task="regression") # PhysicsNeMo MeshGraphKAN(16, 3, 2) + inputs, target = data.get_split("train").inputs[0] + delta = model(inputs["node_features"], inputs["edge_features"], inputs["edge_index"]) + print(delta.shape) # (nodes, 2): change of normalised depth and volume + + start, truth = data.get_split("test").inputs[0] + out = model.rollout(start["node_features"], start["edge_features"], start["edge_index"], start["inflow"], start["precipitation"]) + print(out["water_depth"].shape) # (rollout steps, nodes) Notes ----- -- The smoke test uses a synthetic graph batch so it stays CPU-safe in CI. +- Training recipe of the example (``scripts/train_hydrographnet.py``): batch 1, Adam with learning rate 1e-4 (the configured weight decay 1e-4 is not passed to the optimizer), the learning rate multiplied by 0.9999979 after every batch, 100 epochs, MSE + physics loss. + +- Rollout quirk kept from inference.py: after the first step the forcing columns hold the inflow and precipitation of the step being predicted, while training windows hold those of the first window step. The example prints the rollout RMSE of normalised depth; the flood benchmark reports it in metres (``rollout_rmse``) and keeps both per-step curves in the report metadata. + diff --git a/docs/source/modules/models_logistic_regression.rst b/docs/source/modules/models_logistic_regression.rst new file mode 100644 index 00000000..703e1585 --- /dev/null +++ b/docs/source/modules/models_logistic_regression.rst @@ -0,0 +1,121 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Logistic Regression (pixel) +=========================== + +Overview +-------- + +``logistic_regression`` scores every pixel with a linear function of the ``kernel_size x kernel_size`` window of input features around it, implemented as one ``Conv2d`` with ``kernel_size // 2`` padding; the sigmoid is applied by the loss. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``logistic_regression`` scores every pixel with a linear function of the ``kernel_size x kernel_size`` window of input features around it, implemented as one ``Conv2d`` with ``kernel_size // 2`` padding; the sigmoid is applied by the loss. + +This is exactly the WildfireSpreadTS logistic-regression baseline (``Conv2d(C, 1, kernel_size=3, padding=1)``, 361 parameters for 40 channels). Next Day Wildfire Spread fits the same model on 3x3 neighbourhoods with scikit-learn instead of gradient descent. Multi-day input ``(batch, time, channels, height, width)`` is flattened to ``time * channels`` channels. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data `_ (`repo `__): Same model on 12 features x 3x3 neighbourhoods (109 parameters), fitted with scikit-learn LogisticRegression and a no-fire class weight; reported test AUC-PR 19.8%. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/SebastianGer/WildfireSpreadTS `__ at ``f62dc49`` (MIT) +- **Checked configuration:** src/models/LogisticRegression.py with n_channels=40 (all features, one day). +- **Parameter count:** 361 +- **Verified:** parameter count, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_wildfirespreadts_oracle.py`` + +Registry Name +------------- + +Primary entrypoint: ``logistic_regression`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + model = build_model(name="logistic_regression", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) + +Notes +----- + +- WildfireSpreadTS trains it with Dice loss and AdamW (lr 0.1). diff --git a/docs/source/modules/models_neuralhydrology_ealstm.rst b/docs/source/modules/models_neuralhydrology_ealstm.rst index 7004c06d..9443357b 100644 --- a/docs/source/modules/models_neuralhydrology_ealstm.rst +++ b/docs/source/modules/models_neuralhydrology_ealstm.rst @@ -6,7 +6,7 @@ EA-LSTM Overview -------- -``neuralhydrology_ealstm`` complements the plain LSTM adapter with a lightweight static gating path inspired by EA-LSTM style hydrology models. +``neuralhydrology_ealstm`` is a port of NeuralHydrology's ``EALSTM`` (the same network as the paper code). The input gate ``i = sigmoid(W_s x_s + b_s)`` is computed once from the static attributes and applied at every step; the forget, output and cell gates come from the dynamic inputs and the previous hidden state. It reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}`` and returns ``y_hat`` (batch, time, n_targets) and the per-step states ``h_n`` and ``c_n``. At a Glance ----------- @@ -63,21 +63,39 @@ At a Glance Description ----------- -``neuralhydrology_ealstm`` complements the plain LSTM adapter with a lightweight static gating path inspired by EA-LSTM style hydrology models. +``neuralhydrology_ealstm`` is a port of NeuralHydrology's ``EALSTM`` (the same network as the paper code). The input gate ``i = sigmoid(W_s x_s + b_s)`` is computed once from the static attributes and applied at every step; the forget, output and cell gates come from the dynamic inputs and the previous hidden state. It reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}`` and returns ``y_hat`` (batch, time, n_targets) and the per-step states ``h_n`` and ``c_n``. -It keeps the same graph-temporal input contract as the rest of the flood streamflow roadmap. +Defaults are the paper's: 5 extended-Maurer forcings, 27 CAMELS attributes, hidden size 256, output dropout 0.4, forget-gate bias 5, 270-day windows (208,641 parameters). The official 2019 EA-LSTM checkpoints load through ``checkpoint=``. Data: ``camels_us_streamflow`` or ``caravan_streamflow``, scored by the flood benchmark's per-basin NSE / KGE. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Flood Benchmark ` -**Mapped benchmark ecosystems:** :doc:`WaterBench ` +**Mapped benchmark ecosystems:** :doc:`CAMELS-US `, :doc:`Caravan ` External References ------------------- -**Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ +**Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ (`repo `__): Kratzert, Klotz, Shalev, Klambauer, Hochreiter and Nearing, HESS 23:5089-5110 (2019). 531 CAMELS-US basins, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30, 8 seeds. Table 2, EA-LSTM, NSE* loss: single model mean NSE 0.67 (+/-0.006), median 0.71 (+/-0.005), 3 (+/-1) basins with NSE <= 0; ensemble of 8: mean 0.70, median 0.74, 2 basins. MSE loss: single median 0.71, ensemble median 0.74. Table 3 (447 basins): single median 0.714, ensemble median 0.742. The flood benchmark reproduces Table 2 from the official stored simulations (gated oracle test). +- `NeuralHydrology - A Python library for Deep Learning research in hydrology `_ (`repo `__): Kratzert, Gauch, Nearing and Klotz, Journal of Open Source Software 7(71):4050 (2022); the EALSTM implementation that PyHazards ports. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/neuralhydrology/neuralhydrology `__ at ``ea94a40`` (BSD-3-Clause) +- **Checked configuration:** neuralhydrology/modelzoo/ealstm.py (EALSTM) with a regression head: 5 dynamic inputs, 27 static attributes, hidden_size 256, output_dropout 0.4, initial_forget_bias 5 (208,641 parameters, the same as the 2019 code). Official weights: the 16 EA-LSTM runs of Kratzert et al. (2019) on HydroShare (doi 10.4211/hs.83ea5312635e44dc824eeb99eda12f06, CC BY 4.0), written by papercode/ealstm.py of kratzert/ealstm_regional_modeling @ d118158 (Apache-2.0). +- **Parameter count:** 208,641 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_neuralhydrology_oracle.py`` +- **Deviation:** Only the configuration of the paper is ported: NeuralHydrology's optional embedding networks, basin one-hot encoding and probabilistic heads are not available on this model. +- **Deviation:** Dynamic inputs are one tensor ``x_d`` (batch, time, n_dynamic) instead of a dict of per-feature tensors (same network input). +- **Deviation:** Initialisation follows NeuralHydrology: the input gate is a default ``nn.Linear``, whereas the 2019 paper code initialises ``weight_sh`` orthogonally. Seeded weights therefore match NeuralHydrology, not the 2019 code; trained 2019 checkpoints load exactly (``weight_sh`` transposed into ``input_gate.weight``). Registry Name ------------- @@ -97,11 +115,17 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="neuralhydrology_ealstm", task="regression", input_dim=2, out_dim=1) - preds = model({"x": torch.randn(1, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="neuralhydrology_ealstm", task="regression") # Kratzert et al. (2019) + out = model({"x_d": torch.randn(2, 270, 5), "x_s": torch.randn(2, 27)}) + print(out["y_hat"].shape, out["h_n"].shape) # (2, 270, 1) (2, 270, 256) Notes ----- -- This adapter focuses on the entity-aware gating contract, not exact repo parity. +- Same training recipe as the paper's LSTM (Adam 1e-3 / 5e-4 / 1e-4, 30 epochs, batch 256, gradient clipping 1, NSE* or MSE loss on the last time step); PyHazards does not ship the NSE* loss yet. + +- To apply the official 2019 checkpoints to real data, permute ``x_s`` from PyHazards' alphabetical attribute order to ``pyhazards.datasets.flood.KRATZERT2019_CHECKPOINT_STATIC_ORDER`` and normalise the forcings with the 2019 code's fixed scaler (papercode/datautils.py). + +- The recurrence is a Python loop over time steps, as in the reference, so it is slower than the cuDNN-backed LSTM on long sequences. + +- The smoke configuration runs on ``flood_streamflow_synthetic`` (random basins, 30-day windows). diff --git a/docs/source/modules/models_neuralhydrology_lstm.rst b/docs/source/modules/models_neuralhydrology_lstm.rst index 8379c935..5ac7c118 100644 --- a/docs/source/modules/models_neuralhydrology_lstm.rst +++ b/docs/source/modules/models_neuralhydrology_lstm.rst @@ -6,7 +6,7 @@ NeuralHydrology LSTM Overview -------- -``neuralhydrology_lstm`` is the first community-style hydrology baseline in the PyHazards flood roadmap. +``neuralhydrology_lstm`` is a port of NeuralHydrology's ``CudaLSTM`` with its regression head. It reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}``: the static attributes are concatenated to the dynamic inputs at every day, a single-layer LSTM runs over the sequence, and dropout plus a linear head give a discharge value for every day. Like the reference it returns a dict with ``y_hat`` (batch, time, n_targets), ``lstm_output`` and the final states ``h_n`` and ``c_n``; streamflow evaluation uses the last day of each window. At a Glance ----------- @@ -63,21 +63,43 @@ At a Glance Description ----------- -``neuralhydrology_lstm`` is the first community-style hydrology baseline in the PyHazards flood roadmap. +``neuralhydrology_lstm`` is a port of NeuralHydrology's ``CudaLSTM`` with its regression head. It reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}``: the static attributes are concatenated to the dynamic inputs at every day, a single-layer LSTM runs over the sequence, and dropout plus a linear head give a discharge value for every day. Like the reference it returns a dict with ``y_hat`` (batch, time, n_targets), ``lstm_output`` and the final states ``h_n`` and ``c_n``; streamflow evaluation uses the last day of each window. -The adapter consumes the shared graph-temporal streamflow batch format and produces next-step nodewise discharge predictions. +Defaults are the "LSTM with static inputs" of Kratzert et al. (2019): 5 extended-Maurer forcings, 27 CAMELS attributes, hidden size 256, output dropout 0.4, forget-gate bias initialised to 5, used on 270-day windows (297,217 parameters). ``n_static=0`` gives their "LSTM without static inputs". Parameter names, initialisation and outputs equal NeuralHydrology's, and the official 2019 checkpoints load through ``checkpoint=`` (converted from the paper code's single-bias layout). + +Data: ``camels_us_streamflow`` (the paper's setup, from a local CAMELS-US copy) or ``caravan_streamflow``; both normalise inputs as NeuralHydrology does and are scored by the flood benchmark's per-basin NSE / KGE. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Flood Benchmark ` -**Mapped benchmark ecosystems:** :doc:`Caravan ` +**Mapped benchmark ecosystems:** :doc:`CAMELS-US `, :doc:`Caravan ` External References ------------------- -**Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ +**Paper:** `Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ (`repo `__): Kratzert, Klotz, Shalev, Klambauer, Hochreiter and Nearing, HESS 23:5089-5110 (2019). One LSTM for 531 CAMELS-US basins: 5 extended-Maurer forcings + 27 attributes, hidden 256, dropout 0.4, 270-day windows, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30, NSE* or MSE loss, 8 seeds. Table 2, LSTM with static inputs, NSE* loss: single model mean NSE 0.69 (+/-0.013), median 0.73 (+/-0.002), 2 (+/-1) basins with NSE <= 0; ensemble of 8: mean 0.72, median 0.76. MSE loss: median 0.73 (single), 0.76 (ensemble). Without static inputs (NSE*): median 0.59 (single), 0.64 (ensemble). The flood benchmark reproduces all of these from the official stored simulations (gated oracle test). +- `NeuralHydrology - A Python library for Deep Learning research in hydrology `_ (`repo `__): Kratzert, Gauch, Nearing and Klotz, Journal of Open Source Software 7(71):4050 (2022). The library whose CudaLSTM, regression head, CAMELS-US / Caravan readers and metrics PyHazards ports. +- `Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks `_: Kratzert, Klotz, Brenner, Schulz and Herrnegger, HESS 22:6005-6022 (2018). The LSTM rainfall-runoff model, there with 2 layers of 20 cells, 365-day windows and 5 Daymet forcings, trained per basin (mean NSE 0.63 over 241 basins in experiment 1). That two-layer variant is not a CudaLSTM configuration and is not provided. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/neuralhydrology/neuralhydrology `__ at ``ea94a40`` (BSD-3-Clause) +- **Checked configuration:** neuralhydrology/modelzoo/cudalstm.py (CudaLSTM) with a regression head, built from a Config with 5 dynamic inputs, the 27 static attributes, hidden_size 256, output_dropout 0.4 and initial_forget_bias 5 (297,217 parameters; 269,569 without static inputs). Official weights: the 16 LSTM runs of Kratzert et al. (2019) on HydroShare (doi 10.4211/hs.83ea5312635e44dc824eeb99eda12f06, CC BY 4.0), written by papercode/lstm.py of kratzert/ealstm_regional_modeling @ d118158. +- **Parameter count:** 297,217 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_neuralhydrology_oracle.py`` +- **Deviation:** Only the configuration of the paper is ported: NeuralHydrology's optional static / dynamic embedding networks, basin one-hot encoding, evolving attributes, autoregressive inputs and the GMM / CMAL / UMAL heads are not available on this model. +- **Deviation:** Dynamic inputs are one tensor ``x_d`` (batch, time, n_dynamic) instead of a dict of per-feature tensors; NeuralHydrology concatenates the dict in configuration order, so the network input is the same. +- **Deviation:** The 2019 checkpoints have one bias per gate (gate order f, i, o, g); the conversion puts it into ``bias_ih_l0`` with a zero ``bias_hh_l0``, which gives the same outputs (checked to 1e-6 on all three model types). The port therefore has 1,024 more parameters than the 2019 LSTM (296,193), as NeuralHydrology's CudaLSTM does. +- **Deviation:** The default ``initial_forget_bias`` is 5 (the 2019 code); NeuralHydrology's default is None (no special initialisation) and its example configurations use 3. Registry Name ------------- @@ -97,11 +119,15 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="neuralhydrology_lstm", task="regression", input_dim=2, out_dim=1) - preds = model({"x": torch.randn(1, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="neuralhydrology_lstm", task="regression") # Kratzert et al. (2019) + out = model({"x_d": torch.randn(2, 270, 5), "x_s": torch.randn(2, 27)}) + print(out["y_hat"].shape) # (2, 270, 1): discharge for every day; the last day is the prediction Notes ----- -- The smoke test uses the shared synthetic streamflow dataset shape. +- Training recipe of the paper (not part of the model): Adam, learning rate 1e-3 (5e-4 after epoch 10, 1e-4 after epoch 20), 30 epochs, batch 256, gradient clipping at norm 1, loss on the last time step, NSE* (squared error weighted by 1 / (std of the basin's training discharge + 0.1)^2) or MSE. PyHazards does not ship the NSE* loss yet. + +- The 2019 checkpoints expect the 27 attributes in the column order of their ``attributes.db`` (``pyhazards.datasets.flood.KRATZERT2019_CHECKPOINT_STATIC_ORDER``), while PyHazards (like NeuralHydrology) sorts static attributes alphabetically; permute ``x_s`` accordingly, and normalise the forcings with the 2019 code's fixed scaler (papercode/datautils.py), before applying them to real data. + +- The smoke configuration runs on ``flood_streamflow_synthetic`` (random basins, 30-day windows). diff --git a/docs/source/modules/models_pangu_tc.rst b/docs/source/modules/models_pangu_tc.rst deleted file mode 100644 index d7ec2240..00000000 --- a/docs/source/modules/models_pangu_tc.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. - -Pangu TC Adapter -================ - -Overview --------- - -``pangu_tc`` adds a second foundation-weather reference path behind the shared tropical-cyclone evaluator. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Tropical Cyclone - - .. container:: catalog-stat-note - - Public catalog grouping used for this model. - - .. grid-item-card:: Maturity - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Experimental Adapter - - .. container:: catalog-stat-note - - Catalog maturity label used on the index page. - - .. grid-item-card:: Tasks - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - Track + Intensity - - .. grid-item-card:: Benchmark Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :doc:`Tropical Cyclone Benchmark ` - - .. container:: catalog-stat-note - - Primary benchmark-family link used for compatible evaluation coverage. - - -Description ------------ - -``pangu_tc`` adds a second foundation-weather reference path behind the shared tropical-cyclone evaluator. - -The implementation is intentionally lightweight and should be interpreted as an adapter contract for forecast-field driven storm evaluation. - -Benchmark Compatibility ------------------------ - -**Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` - -**Mapped benchmark ecosystems:** :doc:`IBTrACS ` - -External References -------------------- - -**Paper:** `Accurate medium-range global weather forecasting with 3D neural networks `_ | **Repo:** `Repository `__ - -Registry Name -------------- - -Primary entrypoint: ``pangu_tc`` - -Supported Tasks ---------------- - -- Track + Intensity - -Programmatic Use ----------------- - -.. code-block:: python - - import torch - from pyhazards.models import build_model - - model = build_model(name="pangu_tc", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) - -Notes ------ - -- Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity. diff --git a/docs/source/modules/models_phasenet.rst b/docs/source/modules/models_phasenet.rst index 780512f6..bd064b9a 100644 --- a/docs/source/modules/models_phasenet.rst +++ b/docs/source/modules/models_phasenet.rst @@ -6,7 +6,7 @@ PhaseNet Overview -------- -``phasenet`` is the first earthquake picking baseline in the staged PyHazards roadmap and is paired with the synthetic waveform dataset for smoke validation. +``phasenet`` maps waveforms ``(batch, 3, samples)`` (E, N, Z at 100 Hz, any length) to softmax probabilities ``(batch, 3, samples)`` of noise, P and S. The network is a U-Net: an input convolution and five depths (8, 16, 32, 64, 128 channels) of kernel-7 convolutions with batch normalisation and ReLU, stride-4 convolutions on the way down, stride-4 transposed convolutions with cropped skip connections on the way up, and a 1x1 output convolution. At a Glance ----------- @@ -63,21 +63,41 @@ At a Glance Description ----------- -``phasenet`` is the first earthquake picking baseline in the staged PyHazards roadmap and is paired with the synthetic waveform dataset for smoke validation. +``phasenet`` maps waveforms ``(batch, 3, samples)`` (E, N, Z at 100 Hz, any length) to softmax probabilities ``(batch, 3, samples)`` of noise, P and S. The network is a U-Net: an input convolution and five depths (8, 16, 32, 64, 128 channels) of kernel-7 convolutions with batch normalisation and ReLU, stride-4 convolutions on the way down, stride-4 transposed convolutions with cropped skip connections on the way up, and a 1x1 output convolution. -This initial adapter focuses on the shared waveform-to-pick interface and does not claim exact reproduction of the original PhaseNet training stack. +It is a port of the official TensorFlow code (``phasenet/model.py``) with the released configuration, including TensorFlow's asymmetric "same" padding, so the official checkpoint ``model/190703-214543`` loads with ``strict=True`` (``pretrained="original"``, read without TensorFlow) and reproduces the official outputs. ``annotate`` applies the official per-window normalisation and ``extract_picks`` the official peak picking (probability above 0.5, peaks at least 0.5 s apart). Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Earthquake Benchmark ` -**Mapped benchmark ecosystems:** :doc:`SeisBench ` +**Mapped benchmark ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` External References ------------------- -**Paper:** `PhaseNet: A Deep-Neural-Network-Based Seismic Arrival Time Picking Method `_ | **Repo:** `Repository `__ +**Paper:** `PhaseNet: a deep-neural-network-based seismic arrival-time picking method `_ | **Repo:** `Repository `__ + +Used In +------- + +- `PhaseNet: a deep-neural-network-based seismic arrival-time picking method (Zhu & Beroza, GJI 216(1):261-273, 2019) `_ (`repo `__): Table 1, NCEDC test set (78,592 three-component 30-s recordings, 100 Hz), picks = probability peaks above 0.5, true positive if |dt| < 0.1 s: P precision 0.939, recall 0.857, F1 0.896; S precision 0.853, recall 0.755, F1 0.801; residual mean / standard deviation over |dt| < 0.5 s: P 2.068 / 51.530 ms, S 3.311 / 82.858 ms. Reproduce the scoring with protocol "phasenet". +- `Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking (Mousavi et al., Nat. Commun. 11:3952, 2020) `_ (`repo `__): Tables 2-3, STEAD test set, the released PhaseNet, true positive if |dt| < 0.5 s: P precision 0.96, recall 0.96, F1 0.96, MAE 0.07 s; S precision 0.96, recall 0.93, F1 0.94, MAE 0.09 s (protocol "eqtransformer"). +- `Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers (Münchmeyer et al., JGR Solid Earth 127, e2021JB023499, 2022) `_ (`repo `__): In-domain phase-identification MCC (Table 2): STEAD 0.99, INSTANCE 0.94, ETHZ 0.91, SCEDC 0.91, Iquique 0.96, NEIC 0.81, GEOFON 0.51. These were obtained with SeisBench's earlier 23,305-parameter PhaseNet variant retrained per dataset, not with this architecture or the original weights, and with pick-benchmark's own tasks, which PyHazards does not implement. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/AI4EPS/PhaseNet `__ at ``62005c6`` (MIT (code and released checkpoint; Copyright (c) 2021 Weiqiang Zhu)) +- **Checked configuration:** ``UNet(ModelConfig(), mode="pred")`` from ``phasenet/model.py`` (depths 5, filters_root 8, kernel 7, pool 4, 3 classes; the graph-building fields of ``model/190703-214543/config.log``) on TensorFlow 2.11 (the release in the repository's env.yaml), restored from ``model/190703-214543/model_95.ckpt`` as ``phasenet/predict.py`` does; also SeisBench 0.12.6's PhaseNet with its conversion of the same checkpoint (second oracle). +- **Parameter count:** 268,443 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_phasenet_oracle.py`` +- **Deviation:** The paper's Figure 5 shows channel widths 8, 11, 16, 22, 32 and no batch normalisation; the released code and checkpoint use 8, 16, 32, 64, 128 with batch normalisation (268,443 parameters). The port follows the code and the checkpoint; the figure's variant is not provided. +- **Deviation:** Layout ``(batch, channels, samples)`` instead of TensorFlow's ``(batch, samples, 1, channels)``; TensorFlow variable ``Scope/layer/kernel`` is the PyTorch parameter ``Scope.layer.weight`` (kernels transposed). The checkpoint is read by a pure-Python TensorBundle reader, checked against ``tf.train.load_checkpoint``. +- **Deviation:** Initial values follow the reference scheme (Glorot-uniform kernels, zero biases) but cannot equal TensorFlow's random draws; the oracle compares bounds and spread. +- **Deviation:** Not ported: the training pipeline (data readers, label generation, augmentation) and the continuous-data predictor (``normalize_long`` sliding normalisation, overlapping windows, amplitude extraction). ``annotate`` normalises each window as a whole, as the reader does for 30-s training and test windows. Registry Name ------------- @@ -97,16 +117,18 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="phasenet", - task="regression", - in_channels=3, - ) + # Official weights (MIT), downloaded from the pinned repository commit on first use: + # model = build_model(name="phasenet", task="picking", pretrained="original") + model = build_model(name="phasenet", task="picking").eval() - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + waveforms = torch.randn(4, 3, 3000) # 30 s at 100 Hz, channels E, N, Z + with torch.no_grad(): + probabilities = model.annotate(waveforms) # (4, 3, 3000): noise, P, S + picks = model.extract_picks(probabilities) # [{"P": [(sample, prob), ...], "S": [...]}, ...] Notes ----- -- Outputs are P- and S-arrival sample indices in the current smoke-test adapter. +- Inputs are three components in E, N, Z order at 100 Hz; ``forward`` expects normalised windows, ``annotate`` normalises raw ones (mean removed, divided by the standard deviation per channel). +- ``forward(x, logits=True)`` returns the pre-softmax output used by the official cross-entropy loss. +- The released checkpoint (trained 2019-07-03) post-dates the paper; whether it is the model behind GJI Table 1, and which data it was trained on, is not documented. diff --git a/docs/source/modules/models_prithvi_burnscars.rst b/docs/source/modules/models_prithvi_burnscars.rst new file mode 100644 index 00000000..bace8010 --- /dev/null +++ b/docs/source/modules/models_prithvi_burnscars.rst @@ -0,0 +1,141 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Prithvi-EO-2.0 BurnScars +======================== + +Overview +-------- + +``prithvi_burnscars`` is the released Prithvi-EO-2.0-300M-BurnScars model. Its encoder is the Prithvi-EO-2.0-300M masked-autoencoder ViT (ViT-L/16 with a 3D patch embedding and fixed 3D sin/cos positions, pretrained on 4.2M multi-temporal HLS samples). The outputs of encoder blocks 6, 12, 18 and 24 are reshaped to maps, turned into a four-level pyramid (learned transposed convolutions up, max pooling down) and decoded by a U-Net decoder (512, 256, 128, 64 channels) into two classes: not burned and burn scar. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Unmapped + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``prithvi_burnscars`` is the released Prithvi-EO-2.0-300M-BurnScars model. Its encoder is the Prithvi-EO-2.0-300M masked-autoencoder ViT (ViT-L/16 with a 3D patch embedding and fixed 3D sin/cos positions, pretrained on 4.2M multi-temporal HLS samples). The outputs of encoder blocks 6, 12, 18 and 24 are reshaped to maps, turned into a four-level pyramid (learned transposed convolutions up, max pooling down) and decoded by a U-Net decoder (512, 256, 128, 64 channels) into two classes: not burned and burn scar. + +The modules are a plain-PyTorch port of the official ``prithvi_mae.py`` and of TerraTorch 0.99.8 with segmentation_models_pytorch 0.4.0, the stack the checkpoint was trained with, keeping TerraTorch's parameter names. ``pretrained=True`` downloads the 1.3 GB checkpoint from Hugging Face (pinned revision and sha256, cached in torch.hub's checkpoint directory) and loads it with ``strict=True``; no weights ship with PyHazards. Without it the model is randomly initialised exactly like TerraTorch's. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** Not yet mapped. + +External References +------------------- + +**Paper:** `Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Prithvi-EO-2.0-300M-BurnScars (model card) `_ (`repo `__): The released checkpoint (Apache-2.0): TerraTorch fine-tune with a UNetDecoder instead of the paper's UperNet, 512 x 512 chips, cross-entropy with ignore index -1, AdamW lr 1e-4, new non-overlapping train/val/test splits published with the model, best of five runs by validation loss. Test IoU (burn scar) 87.52, test mIoU 93.00; validation IoU 84.28, mIoU 90.95. +- `Prithvi 100M burn scar (Roy et al., Hugging Face 2023, doi:10.57967/hf/0953) `_ (`repo `__): The first-generation burn-scar fine-tune (Prithvi-EO-1.0-100M, ViT-B, MMSegmentation, 50 epochs): IoU 0.73 on the burn-scar class and 0.96 overall accuracy. A different architecture and checkpoint; not the model built here. +- `Foundation Models for Generalist Geospatial Artificial Intelligence `_ (`repo `__): Prithvi-100M (v1) paper, Table 3: wildfire scar mapping on HLS Burn Scars, IoU (fire scar) 73.62, mIoU 84.84, against 71.01 / 83.55 for a U-Net baseline. +- `HLS Burn Scars dataset `_: 805 HLS scenes of 512 x 512 pixels over the contiguous US (2018-2021) with MTBS burn-scar masks, CC-BY-4.0; the fine-tuning and evaluation data of this model. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/torchgeo/terratorch `__ at ``0.99.8`` (Apache-2.0) +- **Checked configuration:** EncoderDecoderFactory with the model_args of burn_scars_config.yaml (Hugging Face revision a3f2c41) under TerraTorch 0.99.8, segmentation_models_pytorch 0.4.0 and timm 1.0.15, at random initialisation and with the official Prithvi_EO_V2_300M_BurnScars.pt (sha256 0c5f9334...) loaded strictly after removing the Lightning "model." prefix. On the Hugging Face example chip T10SEH.2018190 the logits are identical (max absolute difference 0) and 79.5 % of the pixels are predicted burned. +- **Parameter count:** 324,204,674 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_prithvi_oracle.py`` +- **Deviation:** Padding: TerraTorch 0.99.8 reflect-pads the bottom/right edge to a multiple of the patch size (16) and then fails in the U-Net decoder whenever the token grid is odd; the port pads to a multiple of 32 (as later TerraTorch releases do, but at the bottom/right), which gives identical outputs for every size the reference accepts. +- **Deviation:** Non-square inputs: TerraTorch 0.99.8 swaps height and width when resizing the position table and reshapes tokens as a square grid, so non-square inputs fail or come out scrambled. The port uses the true (H, W) token grid, as the official prithvi_mae.py does. Square inputs, including the official 512 x 512 chips, are unaffected. +- **Deviation:** With num_classes=1 TerraTorch squeezes the class dimension; the port keeps (B, 1, H, W). + +Registry Name +------------- + +Primary entrypoint: ``prithvi_burnscars`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + from pyhazards.models.prithvi_burnscars import BURN_SCARS_MEAN, BURN_SCARS_STD + + # Official weights: about 1.3 GB, downloaded once from Hugging Face. + model = build_model(name="prithvi_burnscars", task="segmentation", pretrained=True).eval() + reflectance = torch.rand(1, 6, 512, 512) # HLS Blue, Green, Red, NIR narrow, SWIR 1, SWIR 2 in 0-1 + mean = torch.tensor(BURN_SCARS_MEAN)[:, None, None] + std = torch.tensor(BURN_SCARS_STD)[:, None, None] + with torch.no_grad(): + logits = model((reflectance - mean) / std) + burn_scar = logits.argmax(dim=1) # 1 = burn scar + print(logits.shape) # (1, 2, 512, 512) + +Notes +----- + +- Post-fire mapping, not forecasting: the model maps burned area in one image taken after a fire. It is not linked to the wildfire benchmark's danger or spread tasks, which it does not solve. + +- Input: HLS surface reflectance in 0-1 (digital numbers / 10000) of Blue, Green, Red, NIR narrow, SWIR 1 and SWIR 2, standardised per band with BURN_SCARS_MEAN and BURN_SCARS_STD; shape (B, 6, H, W) or (B, 6, 1, H, W). The official chips are 512 x 512. Pixels labelled -1 (no data, clouds) were ignored in training. + +- Newer TerraTorch releases (checked: 1.2.13 with smp 0.5.0) resize the last U-Net block to the skip resolution instead of upsampling it by two. With the same weights that changes the logits by up to 1.6 and 0.37 % of the predicted pixels on the example chip. PyHazards keeps the training-time behaviour: the official demo pins TerraTorch 0.99.8, and the checkpoint was written by Lightning 2.5.0.post0, which 0.99.8 pins. + +- The Prithvi-EO-2.0 paper (Table V) reports a different set-up: UperNet decoder, chips resized to 448 and cropped to 224, mean of ten seeds; test mIoU 88.6 and burn-scar IoU 79.9 for the 300M encoder. The test metrics were not re-evaluated in PyHazards. + +- Weights are cached in torch.hub's checkpoint directory (cache_dir= overrides it); pass weights_path= to load an existing copy offline, and set HF_ENDPOINT to use a Hugging Face mirror. + diff --git a/docs/source/modules/models_prithvi_eo_2_tl.rst b/docs/source/modules/models_prithvi_eo_2_tl.rst new file mode 100644 index 00000000..e7496d83 --- /dev/null +++ b/docs/source/modules/models_prithvi_eo_2_tl.rst @@ -0,0 +1,136 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Prithvi-EO-2.0-TL +================= + +Overview +-------- + +Prithvi-EO-2.0 (IBM, NASA and Julich Supercomputing Centre) is a ViT masked autoencoder pretrained on 4.2M Harmonized Landsat Sentinel-2 samples of four time steps. The TL variants add sin/cos encodings of each frame's acquisition date (year, day of year) and of the scene's latitude and longitude, each multiplied by a learned scale, to the patch tokens. ``prithvi_eo_2_tl`` ports the official ``prithvi_mae.py`` encoder; ``pretrained=True`` loads the released 300M-TL (ViT-L/16) or 600M-TL (ViT-H/14) weights, downloaded from Hugging Face on first use and never bundled. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Unmapped + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +Prithvi-EO-2.0 (IBM, NASA and Julich Supercomputing Centre) is a ViT masked autoencoder pretrained on 4.2M Harmonized Landsat Sentinel-2 samples of four time steps. The TL variants add sin/cos encodings of each frame's acquisition date (year, day of year) and of the scene's latitude and longitude, each multiplied by a learned scale, to the patch tokens. ``prithvi_eo_2_tl`` ports the official ``prithvi_mae.py`` encoder; ``pretrained=True`` loads the released 300M-TL (ViT-L/16) or 600M-TL (ViT-H/14) weights, downloaded from Hugging Face on first use and never bundled. + +Because PyHazards builders return a task model, the encoder is wrapped in the segmentation recipe of the official Prithvi-EO-2.0 burn-scar fine-tune (TerraTorch EncoderDecoderFactory: four encoder blocks at the per-size indices of the official configs, a learned feature pyramid, a U-Net decoder and a 1x1 head). Only the encoder is pretrained; the neck, decoder and head are randomly initialised and need fine-tuning. Inputs are ``(B, C, T, H, W)`` with optional ``temporal_coords`` ``(B, T, 2)`` and ``location_coords`` ``(B, 2)``; with ``num_frames`` T > 1 the frames are stacked along channels as in the official multi-temporal configs. ``model.encoder.forward_features`` returns the raw tokens of every block, and ``pyhazards.models.PrithviMAE`` is the full autoencoder for reconstruction. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** Not yet mapped. + +External References +------------------- + +**Paper:** `Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Prithvi-EO-2.0-300M-TL (model card) `_: The released 300M-TL pretraining checkpoint and prithvi_mae.py (Apache-2.0): 224 x 224 crops of four frames, 6 HLS bands, patch 1x16x16, mask ratio 0.75, time and location encodings with learned scales. The 600M-TL checkpoint is ibm-nasa-geospatial/Prithvi-EO-2.0-600M-TL. +- `Prithvi-EO-2.0-300M-BurnScars (model card) `_: Source of the segmentation head recipe (SelectIndices, ReshapeTokensToImage, LearnedInterpolateToPyramidal, UNetDecoder [512, 256, 128, 64]); that checkpoint uses the non-TL 300M encoder and is available as prithvi_burnscars. +- `Prithvi-EO-2.0-300M-TL-Sen1Floods11 (model card) `_: Official flood-mapping fine-tune of the 300M-TL encoder with a UperNet decoder (not ported). The paper reports Sen1Floods11 test mIoU 90.0 and water IoU 82.6 for 300M-TL, 90.3 and 83.1 for 600M-TL (Table IV). + +Reproduction +------------ + +- **Reference implementation:** `https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL `__ at ``63adbd3`` (Apache-2.0) +- **Checked configuration:** prithvi_mae.py PrithviMAE with the 300M-TL config.json (ViT-L 1024/24/16, decoder 512/8/16, 4 frames) loaded strictly with the official Prithvi_EO_V2_300M_TL.pt (sha256 3629cedf...): identical loss, reconstructions and masks with and without coordinates (330,419,716 parameters). The registry model's encoder (303,886,338 parameters) loaded from the same file matches TerraTorch 0.99.8's prithvi_eo_v2_300_tl backbone, and the full model matches TerraTorch's EncoderDecoderFactory with the burn-scar recipe at random initialisation, for one and three frames. The 600M-TL architecture is checked against TerraTorch at reduced depth. +- **Parameter count:** 324,204,676 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_prithvi_oracle.py`` +- **Deviation:** When the position table has to be rebuilt for a different number of frames (more than one) and resized, prithvi_mae.py fails on a ``view`` of a non-contiguous tensor; the port uses ``reshape`` (as later TerraTorch releases do). +- **Deviation:** Integer temporal or location coordinates are converted to float; the reference asserts a float dtype. +- **Deviation:** TerraTorch 0.99.8's PixelWiseModel cannot pad 5-D input, so multi-temporal segmentation is checked module by module (encoder, necks, decoder, head) against the reference. Padding, non-square inputs and num_classes=1 follow prithvi_burnscars (same deviations). +- **Deviation:** The registry model loads the encoder part of the pretraining checkpoint and, like TerraTorch, rebuilds the fixed sin/cos position table for its own frame count instead of copying the checkpoint's; the stored table equals the rebuilt one up to float32 rounding (4.6e-7). + +Registry Name +------------- + +Primary entrypoint: ``prithvi_eo_2_tl`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Pretrained 300M-TL encoder (about 1.3 GB, downloaded once) + burn-scar head to fine-tune. + model = build_model(name="prithvi_eo_2_tl", task="segmentation", num_frames=2, pretrained=True) + x = torch.randn(1, 6, 2, 224, 224) # (B, C, T, H, W), standardised HLS bands + temporal_coords = torch.tensor([[[2020.0, 150], [2020.0, 250]]]) # (year, day of year) per frame + location_coords = torch.tensor([[37.5, -120.0]]) # (latitude, longitude) + logits = model(x, temporal_coords=temporal_coords, location_coords=location_coords) + print(logits.shape) # (1, 2, 224, 224) + +Notes +----- + +- Pretraining normalisation: HLS digital numbers standardised with PRITHVI_EO_V2_MEAN and PRITHVI_EO_V2_STD (pyhazards.models.prithvi), bands Blue, Green, Red, NIR narrow, SWIR 1, SWIR 2. Coordinates are optional; the encodings were randomly dropped during pretraining. + +- variant="600m" selects the 600M-TL encoder (patch 14, blocks 8/16/24/32 feed the head). Its weights are pinned by revision and sha256 but were not downloaded for the oracle comparison; the 300M-TL weights were. + +- The paper reports wildfire scar mapping (Table V, UperNet decoder, 224 x 224 crops, ten seeds) test mIoU 89.3 and burn-scar IoU 81.1 for 300M-TL, 90.5 and 83.2 for 600M-TL. These are fine-tunes that were not released; nothing here was re-trained. + +- The burn-scar head maps burned area after a fire; it is not linked to the wildfire benchmark's danger or spread tasks. + diff --git a/docs/source/modules/models_rainformer.rst b/docs/source/modules/models_rainformer.rst new file mode 100644 index 00000000..75d29021 --- /dev/null +++ b/docs/source/modules/models_rainformer.rst @@ -0,0 +1,136 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Rainformer +========== + +Overview +-------- + +``rainformer`` stacks the input frames as channels and maps them to as many future frames (Bai et al., IEEE GRSL 2022). Four encoder stages (patch merging by 4, 2, 2, 2) and four decoder stages (patch expanding, concatenation with the encoder skip) each contain a feature-extraction balance module: a global unit of a window and a shifted-window self-attention block (each followed by channel attention), a local unit of two convolution-BatchNorm-ReLU layers and CBAM channel/spatial attention, and a gate fusion unit that mixes them as ``Z * global + R * local`` with sigmoid gates computed from both. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Forecasting, Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``rainformer`` stacks the input frames as channels and maps them to as many future frames (Bai et al., IEEE GRSL 2022). Four encoder stages (patch merging by 4, 2, 2, 2) and four decoder stages (patch expanding, concatenation with the encoder skip) each contain a feature-extraction balance module: a global unit of a window and a shifted-window self-attention block (each followed by channel attention), a local unit of two convolution-BatchNorm-ReLU layers and CBAM channel/spatial attention, and a gate fusion unit that mixes them as ``Z * global + R * local`` with sigmoid gates computed from both. + +The default is the official KNMI model of ``train.py``: 9 -> 9 frames of 288 x 288, hidden 96, heads 3/6/12/24, head dim 32, window 9, relative position bias; 187,661,990 parameters (104,976 of them the fixed shifted-window masks). The official code has no license, so the model is written from the paper and from the MIT-licensed Swin implementation the official code builds on (berniwal/swin-transformer-pytorch). Parameter names and creation order follow the official ``Net``, so the released KNMI checkpoint loads with ``strict=True`` and the same seed gives the same weights. + +``task="forecasting"`` takes ``(batch, T, C, H, W)`` (or the official ``(batch, T * C, H, W)``) and returns the next ``T`` frames. ``task="segmentation"`` is a PyHazards adaptation for next-step fire masks: a 1x1 convolution (``segmentation_head``) maps the channels of the first predicted frame to ``out_channels`` logits ``(batch, 1, H, W)``; the Rainformer parameters keep their official names at the top level of the state dict. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Rainformer: Features Extraction Balanced Network for Radar-Based Precipitation Nowcasting `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire `_ (`repo `__): Li et al., NeurIPS 2024 Datasets and Benchmarks. The strongest AI baseline of Table 2, trained on simulated wildfire scenarios and tested on simulated and real-world fires (binary fire-area sequences with satellite, topography, vegetation, fuel and weather inputs). Forecast AUPRC / F1 / IoU: 79.7 / 78.8 / 69.6 (simulation) and 67.2 / 65.5 / 52.0 (real world); backtracking: 73.3 / 71.9 / 57.0 and 54.6 / 52.4 / 42.9 (S2R-FireTr: 87.3 / 83.2 / 71.2 and 72.9 / 69.6 / 56.4 for forecasting). Configuration not published: the paper only calls the baselines "commonly used AI models that can be easily adapted", and its repository contains only S2R-FireTr (3 input frames at 256x256), so the input stacking, window size, loss and output head of this baseline are unknown. These numbers are not reproduced by PyHazards. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Zjut-MultimediaPlus/Rainformer `__ at ``c4e04e9`` (none (no LICENSE file; used only as a test oracle, not copied); the KNMI checkpoint states no licence and is used only as test data; the ported Swin parts are MIT (berniwal/swin-transformer-pytorch c921ebf914c6ea9734bb260ada395e3746c85402)) +- **Checked configuration:** Net(input_channel=9, hidden_dim=96, downscaling_factors=(4, 2, 2, 2), layers=(2, 2, 2, 2), heads=(3, 6, 12, 24), head_dim=32, window_size=9, relative_pos_embedding=True) from train.py at 288 x 288 (einops 0.8.2): 187,661,990 parameters; seeded initialisation, eval/train outputs, gradients and BatchNorm statistics compared locally with PYHAZARDS_ORACLE_LARGE=1, and the released KNMI checkpoint (model1_1_100.pt from the repository's Google Drive link, sha256-pinned, 751 MB) loaded with strict=True into both models with identical outputs (all bit-identical). CI compares three narrow 288 x 288 models (hidden 8-16, windows 9 and 3, with and without relative position bias, two FEBM groups in stage 1 or 3). +- **Parameter count:** 187,661,990 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_rainformer_oracle.py`` +- **Deviation:** task="segmentation" (first predicted frame, 1x1 convolution to out_channels logits) is a PyHazards adaptation, not from Sim2Real-Fire, whose baseline heads are unpublished. +- **Deviation:** The official Net hard-codes the stage feature maps for 288 x 288 inputs (72/36/18/9 and back), which fixes the shapes of the gate LayerNorms; it runs only at that size with downscaling factors (4, 2, 2, 2). PyHazards derives the stage sizes from img_size and raises ValueError unless every stage map is divisible by window_size. Sim2Real-Fire's 256 x 256 frames give 64/32/16/8 maps, which window 9 does not divide, so Sim2Real-Fire must have changed the window size or the input size; which one is not published (unverified). Its own S2R-FireTr encoder uses the same Swin stage settings (hidden 96, heads 3/6/12, head dim 32) with window 8 at 256 x 256, and window_size=8 works here (181,876,886 parameters). +- **Deviation:** Input in the PyHazards layout (batch, time, channels, H, W) is flattened time-major to the official (batch, time * channels, H, W) and reshaped back; the official layout is also accepted. The relative-position index is a non-persistent buffer (it moves with the model's device) instead of a plain tensor attribute; the state dict is unchanged. + +Registry Name +------------- + +Primary entrypoint: ``rainformer`` + +Supported Tasks +--------------- + +- Forecasting +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Official KNMI configuration: 9 radar frames of 288 x 288 -> the next 9 frames. + model = build_model(name="rainformer", task="forecasting") + # model.load_state_dict(torch.load("model1_1_100.pt", map_location="cpu")) # official KNMI weights + x = torch.rand(1, 9, 1, 288, 288) # (batch, time, channels, height, width) + print(model(x).shape) # (1, 9, 1, 288, 288) + + # PyHazards next-step fire-mask adaptation on 256 x 256 frames (window 8 divides 64/32/16/8). + seg = build_model(name="rainformer", task="segmentation", in_channels=4, history=3, img_size=256, window_size=8) + print(seg(torch.randn(1, 3, 4, 256, 256)).shape) # (1, 1, 256, 256) + +Notes +----- + +- The gate LayerNorms normalise over (channels, height, width) with elementwise affine weights (27,371,520 of the default parameters), so a model only runs at the img_size it was built for and its parameter count depends on that size. +- Kept from the official code because they change outputs or parameter counts: the gate fusion unit computes Z * g + R * l (the paper's Eq. 8 also convolves g and l; those convolutions, conv_2 and conv_3, are built but unused); every window attention is followed by a channel attention with separate average- and max-pool MLPs; the relative position bias is one table shared by all heads; decoder blocks use an MLP of only twice their width; the shifted-window masks are parameters without gradient. +- With layers > 2 per stage, the official stage applies every FEBM group to the same stage input and keeps only the last group's output; PyHazards reproduces this. The official layers = (2, 2, 2, 2) has one group per stage. +- The official KNMI checkpoint (Google Drive file 1LyLOJI9sf1sdZE1FwyTLPEGEcUuvXQc3, model1_1_100.pt, sha256 e3d5e4e59b32f13a74c7ffdc02ae65f9da3362c036b60e73e46dffe8721ae6b2) states no licence and is not redistributed by PyHazards. train.py feeds KNMI rain maps multiplied by 4783 / 100 * 12. +- The official train.py uses Adam with learning rate 1e-3 and ReduceLROnPlateau, batch 24, and a balanced-MAE loss; the paper states 1e-4 and batch 16. +- Earthformer (Gao et al., NeurIPS 2022) benchmarks re-sized Rainformer variants on SEVIR (184.0M parameters) and Moving MNIST (19.2M); those configurations are not in the official repository. diff --git a/docs/source/modules/models_random_forest.rst b/docs/source/modules/models_random_forest.rst new file mode 100644 index 00000000..ecee716c --- /dev/null +++ b/docs/source/modules/models_random_forest.rst @@ -0,0 +1,142 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Random Forest +============= + +Overview +-------- + +``random_forest`` is a scikit-learn ``RandomForestClassifier(n_estimators=100, max_depth=10, min_samples_split=2, min_samples_leaf=1, random_state=123)`` (Breiman, 2001) with the configuration of the official random-forest notebook of Kondylatos et al. (GRL 2022). It takes the daily tensor ``(batch, 10, 25)`` of the ``wildfire_forecasting`` LSTM (10 dynamic, 5 static and 10 land-cover columns per day) or ready-made features ``(batch, 35)``, and returns ``(batch, 2)`` log-probabilities over (no fire, fire). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Classification, Forecasting + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``random_forest`` is a scikit-learn ``RandomForestClassifier(n_estimators=100, max_depth=10, min_samples_split=2, min_samples_leaf=1, random_state=123)`` (Breiman, 2001) with the configuration of the official random-forest notebook of Kondylatos et al. (GRL 2022). It takes the daily tensor ``(batch, 10, 25)`` of the ``wildfire_forecasting`` LSTM (10 dynamic, 5 static and 10 land-cover columns per day) or ready-made features ``(batch, 35)``, and returns ``(batch, 2)`` log-probabilities over (no fire, fire). + +Daily tensors are turned into the paper's instance features exactly as the notebook does: the mean of the 10 dynamic variables over the ten days (ignoring missing values), the dynamic variables on the last day (t-1), the 5 static variables and the 10 Corine Land Cover fractions. ``kondylatos_instance_features`` exposes that construction. + +The model is an ``nn.Module`` wrapper (``EstimatorModule``) around the fitted forest, not a neural network: fit it with ``model.fit(inputs, targets)``, after which ``forward`` returns the log of ``predict_proba``. It has no parameters, its outputs carry no gradient, and ``pyhazards.engine.Trainer.fit`` refuses it with an explanation; ``Trainer.evaluate`` and ``Trainer.predict`` work on the fitted model. ``task="regression"`` builds the matching ``RandomForestRegressor``. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Random Forests `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Wildfire Danger Prediction and Understanding With Deep Learning `_ (`repo `__): Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. Instance-based data set of the daily 1 km Greek / Eastern Mediterranean datacube (dynamic inputs at day t-1, their average over days t-1..t-10, static features); 40,554 training samples (2009-2018, two negatives per positive), test years 2020 (3,684 samples) and 2021 (13,221). Random forest test results (Table 1, 2020 / 2021): precision 0.843 / 0.880, recall 0.603 / 0.697, F1 0.703 / 0.778 (TP 740 / 3,073, FP 138 / 418, TN 2,318 / 8,396, FN 488 / 1,334), below XGBoost (F1 0.782 / 0.786) and the LSTM (0.804 / 0.879). +- `Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data `_ (`repo `__): Huot et al., IEEE TGRS 2022. A per-pixel scikit-learn random forest on the 12 features of a pixel and its 8 neighbours, maximum depth 15 (swept over 1-20 on validation AUC-PR), the 'no fire' class weighted by (examples / 'no fire' examples) x 5, other hyperparameters at the scikit-learn defaults: test AUC-PR 22.5%, precision 26.3%, recall 46.9% (Table II). Not the configuration of this entry; pass ``max_depth``, ``random_state`` and ``class_weight`` to the builder to approximate it. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Orion-AI-Lab/wildfire_forecasting `__ at ``2b18bcf`` (MIT) +- **Checked configuration:** notebooks/RF.ipynb: RandomForestClassifier(n_estimators=100, max_depth=10, min_samples_split=2, min_samples_leaf=1, random_state=123) fitted on the 35 instance features the notebook builds from FireDataset_npy(access_mode='temporal', clc='vec') with the 10 dynamic and 5 static variables of the paper. The oracle test runs the notebook's own cells on synthetic data and requires identical features, predicted probabilities and labels; the PyHazards input is the LSTM's daily tensor built by the reference combine_dynamic_static_inputs. +- **Verified:** forward outputs +- **Oracle test:** ``tests/oracle/test_classical_oracle.py`` +- **Deviation:** The notebook reads (dynamic, static, land cover) separately from the dataset; PyHazards reads the concatenated daily tensor of ``wildfire_forecasting`` (or ready-made features) and takes the static and land-cover values from its last day. The values are the same because that tensor repeats them over the ten days. +- **Deviation:** The reference repository does not pin scikit-learn; the oracle compares the two under the installed release (1.7.2 when checked). + +Registry Name +------------- + +Primary entrypoint: ``random_forest`` + +Supported Tasks +--------------- + +- Classification +- Forecasting + +Programmatic Use +---------------- + +.. code-block:: python + + from pyhazards.datasets import load_dataset + from pyhazards.models import build_model + + data = load_dataset("wildfire_danger_synthetic", samples=120).load() + train, test = data.get_split("train"), data.get_split("test") + + model = build_model(name="random_forest", task="classification") + model.fit(train.inputs, train.targets) # (n, 10, 25) daily tensors -> 35 features + log_probs = model(test.inputs) + danger = log_probs.exp()[:, 1] # = model.predict_proba(test.inputs)[:, 1] + print(log_probs.shape) # (18, 2) + + model.save("random_forest.joblib") # EstimatorModule.load(path); joblib = pickle, trusted files only + +Notes +----- + +- Not trained by gradient descent: ``Trainer.fit`` raises ``TypeError``; call ``model.fit(inputs, targets)`` on the whole training split (the notebook fits on the training set only and uses neither the validation split nor early stopping). Calling the model before ``fit`` raises ``sklearn.exceptions.NotFittedError``. + +- ``forward`` returns ``log(predict_proba)``; a forest often gives a class probability of exactly 0, which becomes ``-inf``. ``predict_proba`` and ``predict`` return the scikit-learn arrays; the notebook reports precision, recall and F1 of ``predict`` (threshold 0.5) and AUROC / AUPRC of the fire probability. + +- ``state_dict()`` is empty, so torch checkpoints do not contain the trees. Persist the fitted model with ``model.save(path)`` and ``EstimatorModule.load(path)`` (joblib). Loading unpickles the file and can execute code: only load files you trust. + +- Features are computed in float64 like the notebook. The notebook uses the dataset's float64 values while ``combine_dynamic_static_inputs`` casts the LSTM input to float32, so pass float64 daily tensors to reproduce the notebook's features bit for bit. + +- At the pinned commit the dataset class validates on 2020 and tests on 2021, so the notebook's training split is 2009-2019; the paper trains on 2009-2018, validates on 2019 and tests on 2020 and 2021. Its negatives are drawn with an unseeded ``random.sample`` and its training loader shuffles, so the paper's forest cannot be rebuilt exactly; the same samples in the same order give the same forest. + +- The benchmark smoke configs evaluate models without training, so this entry has none: fit the model first and pass it to ``BenchmarkRunner.run(model=...)``. With ``task="regression"`` the same hyperparameters are used, which no paper prescribes. + diff --git a/docs/source/modules/models_resnet18_unet.rst b/docs/source/modules/models_resnet18_unet.rst new file mode 100644 index 00000000..432d9287 --- /dev/null +++ b/docs/source/modules/models_resnet18_unet.rst @@ -0,0 +1,124 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +ResNet-18 U-Net +=============== + +Overview +-------- + +``resnet18_unet`` pairs a torchvision-style ResNet-18 encoder with the U-Net decoder of segmentation_models_pytorch: five nearest-neighbour upsampling blocks with skip connections and two Conv-BN-ReLU layers each, followed by a 3x3 segmentation head. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``resnet18_unet`` pairs a torchvision-style ResNet-18 encoder with the U-Net decoder of segmentation_models_pytorch: five nearest-neighbour upsampling blocks with skip connections and two Conv-BN-ReLU layers each, followed by a 3x3 segmentation head. + +The network is a plain-PyTorch re-implementation of ``smp.Unet("resnet18")`` from segmentation_models_pytorch 0.3.2, the version WildfireSpreadTS pins, with the same initialisation and parameter names. ``encoder_weights="imagenet"`` loads the ImageNet ResNet-18 checkpoint and adapts the first convolution to the input channels the way smp does. Multi-day input ``(batch, time, channels, height, width)`` is flattened to ``time * channels`` channels. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `U-Net: Convolutional Networks for Biomedical Image Segmentation `_ | **Repo:** `Repository `__ + +Used In +------- + +- `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ (`repo `__): smp.Unet("resnet18", encoder_weights=None) on 1 or 5 days of 40 channels, with static features kept for the last day only (120 channels for 5 days), Dice loss, AdamW lr 1e-3; 14.4M parameters for one day and 14.7M for five (paper Table 5). +- `Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark `_: Same network with ImageNet encoder weights and focal loss (WACV 2026); test AP 0.455-0.472. +- `Deep Residual Learning for Image Recognition `_: ResNet-18 encoder. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/qubvel-org/segmentation_models.pytorch `__ at ``v0.3.2`` (MIT) +- **Checked configuration:** smp.Unet(encoder_name="resnet18", encoder_weights=None, in_channels=40, classes=1) as in WildfireSpreadTS src/models/SMPModel.py, plus the ImageNet-initialised stem for 40 channels. +- **Parameter count:** 14,444,241 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_wildfirespreadts_oracle.py`` + +Registry Name +------------- + +Primary entrypoint: ``resnet18_unet`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + model = build_model(name="resnet18_unet", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) + +Notes +----- + +- Height and width must be divisible by 32. +- encoder_name='resnet34' gives the ResNet-34 variant. diff --git a/docs/source/modules/models_saf_net.rst b/docs/source/modules/models_saf_net.rst index 4d99da2f..3599436d 100644 --- a/docs/source/modules/models_saf_net.rst +++ b/docs/source/modules/models_saf_net.rst @@ -6,7 +6,7 @@ SAF-Net Overview -------- -``saf_net`` adds an intensity-oriented storm baseline to the shared ``tc.track_intensity`` evaluator. +``saf_net`` predicts one number per storm and time: the (MinMax-scaled) maximum sustained wind 24 hours ahead, in the Northwest Pacific (CMA best track). It does not forecast tracks. The wide input is 96 CLIPER-style predictors from the best track (current and past positions, pressures and winds, their changes and climatology factors); the deep input is ERA-Interim u and v wind on a 31 x 31 storm-centred grid at 1000, 750, 500 and 250 hPa for t, t-6, t-12 and t-18 h, as a tensor ``(batch, 2, 4, 31, 31, 4)``. At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Track + Intensity + Forecasting .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,38 @@ At a Glance Description ----------- -``saf_net`` adds an intensity-oriented storm baseline to the shared ``tc.track_intensity`` evaluator. +``saf_net`` predicts one number per storm and time: the (MinMax-scaled) maximum sustained wind 24 hours ahead, in the Northwest Pacific (CMA best track). It does not forecast tracks. The wide input is 96 CLIPER-style predictors from the best track (current and past positions, pressures and winds, their changes and climatology factors); the deep input is ERA-Interim u and v wind on a 31 x 31 storm-centred grid at 1000, 750, 500 and 250 hPa for t, t-6, t-12 and t-18 h, as a tensor ``(batch, 2, 4, 31, 31, 4)``. -The adapter keeps full trajectory outputs so it can use the same report format as the other PyHazards storm models. +For every time step, three convolution stages (64, 128, 256 channels, 2x2 max pooling), shared by a u branch, a v branch and a fused branch, are each followed by a spatial-attention block; learnable cross weights mix u and v and fuse weights merge the result into the fused branch. The four 128-d time features and the 96 wide predictors go through two fully connected layers with ReLU. 880,233 parameters. + +The official code has no license, so the module is written from the paper; the official notebook network and checkpoint are used only as test oracle. Parameter names follow the official state dict, so the released checkpoint (``model_saver/SAF_Net.pkl``) loads with ``strict=True``. ``forward(wide, deep)`` also accepts ``{"wide": ..., "deep": ...}``; the benchmark scores it with ``tc.intensity``, mapping the scaled output back to m/s with the dataset's ``prediction_transform``. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` -**Mapped benchmark ecosystems:** :doc:`TCBench Alpha ` - External References ------------------- -**Paper:** `SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction `_ | **Repo:** `Repository `__ +**Paper:** `SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Official notebook outputs (SAF-Net.ipynb, released checkpoint) `_ (`repo `__): 24-hour intensity MAE on the CMA Northwest Pacific test years with the released weights: 2015 4.38, 2016 4.90, 2017 3.91, 2018 4.02 m/s (mean of the years 4.30 m/s); trained on 2000-2014 (8,406 cases, 2,747 test cases). The paper's own tables (Elsevier) were not read; not reproduced by PyHazards, because the ERA-Interim crops are only on the authors' Google Drive. +- `Tropical cyclone intensity forecasting using model knowledge guided deep learning model (TCIF-fusion) `_ (`repo `__): Wang, Li and Zheng, Environmental Research Letters 19, 024006 (2024), Table 2: SAF-Net 24-hour intensity MAE 4.30 m/s on 2015-2018 Northwest Pacific cases, as a comparison baseline. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/xuguangning1218/TI_Prediction `__ (``651ccc4``, none (no LICENSE file; the notebook network and checkpoint are used only as a test oracle, never copied)); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** The Net class of SAF-Net.ipynb (ahead_times = [0, 1, 2, 3], 24-hour lead): 880,233 parameters; the same seed gives identical initial weights; outputs equal in eval mode and in train mode (BatchNorm batch statistics, updated running statistics, gradients); the released model_saver/SAF_Net.pkl loads with strict=True into both and gives the same outputs on real 2015-2018 wide predictors from the repository's CMA_test_24h.csv (with random deep inputs, since the ERA-Interim crops are not public). +- **Parameter count:** 880,233 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_saf_net_oracle.py`` +- **Deviation:** The official network reads the number of time steps from the notebook global ``ahead_times``; here it is the ``num_times`` argument (default 4). ``wide_dim``, ``num_levels`` and ``grid_size`` are arguments too; only the defaults are checked. +- **Deviation:** Training is not part of the module: the notebook uses L1 loss, Adam (learning rate 7e-4), batch 128, 128 epochs, a new random 10 % validation split every epoch and keeps the weights with the lowest validation loss. Registry Name ------------- @@ -87,7 +104,7 @@ Primary entrypoint: ``saf_net`` Supported Tasks --------------- -- Track + Intensity +- Forecasting Programmatic Use ---------------- @@ -97,11 +114,16 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="saf_net", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + model = build_model(name="saf_net", task="regression") + wide = torch.rand(2, 96) # MinMax-scaled best-track predictors + deep = torch.rand(2, 2, 4, 31, 31, 4) # (batch, [u, v], level, lat, lon, time) + print(model(wide, deep).shape) # (2, 1): scaled 24-hour maximum wind + # model.load_state_dict(torch.load("SAF_Net.pkl", map_location="cpu")) # official checkpoint (no licence) Notes ----- -- Track channels are retained so the shared storm evaluator can score all baselines consistently. +- Kept from the official network because it changes outputs: the fused stage-3 features pass through the stage-3 attention block twice; fc1 has no activation; the output ReLU keeps scaled predictions non-negative. +- The notebook fits the MinMax scalers of the inputs and the target on the training and test years together (test-set information leaks into the scaling); a reproduction of its numbers has to do the same. +- The official checkpoint and the CMA data in the repository have no licence; PyHazards does not redistribute them. ERA-Interim is a retired ECMWF product. +- No PyHazards loader reads the official CMA / ERA-Interim preprocessed files yet; safnet_cma_era_interim_synthetic gives random inputs in their layout for smoke tests. diff --git a/docs/source/modules/models_segformer.rst b/docs/source/modules/models_segformer.rst new file mode 100644 index 00000000..4d2c2244 --- /dev/null +++ b/docs/source/modules/models_segformer.rst @@ -0,0 +1,139 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +SegFormer +========= + +Overview +-------- + +``segformer`` encodes the input with a four-stage Mix Transformer (MiT): overlapping patch embeddings, efficient self-attention whose keys and values are spatially reduced, and Mix-FFN layers whose depth-wise convolution replaces positional encodings, so any input size works. An all-MLP head projects the four stages to a common width, upsamples them to 1/4 resolution, fuses them and predicts per-pixel logits (Xie et al., NeurIPS 2021). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``segformer`` encodes the input with a four-stage Mix Transformer (MiT): overlapping patch embeddings, efficient self-attention whose keys and values are spatially reduced, and Mix-FFN layers whose depth-wise convolution replaces positional encodings, so any input size works. An all-MLP head projects the four stages to a common width, upsamples them to 1/4 resolution, fuses them and predicts per-pixel logits (Xie et al., NeurIPS 2021). + +The network is a plain-PyTorch port of Hugging Face transformers' SegFormer (4.57.6) with the same module names, initialisation and outputs: ``SegformerForSemanticSegmentation`` state dicts and the ``nvidia/mit-b*`` ImageNet encoders load with ``strict=True``. ``variant`` selects MiT-B0 to B5 (decoder width 256 for B0/B1, 768 for B2-B5). The logits are resized to the input size by default; ``raw_logits()`` returns the 1/4-resolution decoder output. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark `_: Lahrichi, Bova, Johnson & Malof, WACV 2026. SegFormer-B2 trained on 128x128 WildfireSpreadTS crops without padding, encoder initialised from nvidia/mit-b2 (ImageNet-1k), decoder from scratch, focal loss (alpha = inverse positive-pixel frequency, gamma = 2), AdamW, batch 64, 10k iterations, learning rate from a grid search on one fold. One day (Veg 7, Multi 33, All 40 channels) or five days concatenated on channels with the WildfireSpreadTS layout (static features only on the last day; 120 channels for All). Reported 27.5M (T=1) and 27.7M (T=5) parameters, matching B2 with 40 and 120 input channels (27,463,425 and 27,714,305). Mean test AP over 12 folds 0.433 / 0.436 / 0.423 (T=1, Veg / Multi / All) and 0.439 / 0.436 / 0.430 (T=5), below the paper's ResNet-18 U-Net. The paper does not say how the 3-channel mit-b2 patch embedding was adapted to the wildfire channels. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/huggingface/transformers/blob/v4.57.6/src/transformers/models/segformer/modeling_segformer.py `__ at ``v4.57.6`` (Apache-2.0) +- **Checked configuration:** SegformerForSemanticSegmentation with the MiT-B0 (3 channels, 150 classes) and MiT-B2 (40 channels, 1 class, the WSTS+ setting) configurations of nvidia/mit-b*, SegformerModel (B0, 5 channels), and the revision-pinned Hub checkpoints nvidia/mit-b0 (ImageNet-1k encoder, also adapted to 1/7/40 channels and compared with smp 0.3.2 patch_first_conv) and nvidia/segformer-b0-finetuned-ade-512-512 (ADE20K, compared with transformers' post_process_semantic_segmentation). +- **Parameter count:** 27,463,425 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_segformer_oracle.py`` +- **Deviation:** forward() resizes the logits from 1/4 resolution to the input size (bilinear, align_corners=False), as transformers' post-processing and loss and mmseg's inference do outside the network; SegformerForSemanticSegmentation itself returns the 1/4-resolution logits, available here from raw_logits() or with upsample=False. +- **Deviation:** With encoder_weights and in_channels other than 3, the first patch embedding is adapted the way segmentation_models_pytorch adapts ImageNet encoders (RGB filters repeated over the channels and scaled by 3 / in_channels; summed for one channel). transformers' from_pretrained(..., ignore_mismatched_sizes=True) would re-initialise it instead; WSTS+ does not say which it did. +- **Deviation:** Only logits are returned: no loss from labels, attention maps or output dataclasses (SegformerModel returns the four stage outputs as a list). transformers' deprecated reshape_last_stage=False and head pruning are not supported. + +Registry Name +------------- + +Primary entrypoint: ``segformer`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # SegFormer-B2 as in WSTS+: 40 channels (one day, all features), one output. + model = build_model(name="segformer", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) + print(model.raw_logits(torch.randn(2, 40, 128, 128)).shape) # (2, 1, 32, 32) + + # ImageNet-1k MiT-B2 encoder (non-commercial NVIDIA weights, downloaded on request). + pretrained = build_model(name="segformer", task="segmentation", in_channels=40, encoder_weights="imagenet") + +Notes +----- + +- NVIDIA licenses the SegFormer and MiT weights (``nvidia/mit-b*``, ``nvidia/segformer-*``) for non-commercial use only (NVIDIA Source Code License for SegFormer). PyHazards does not bundle them; encoder_weights="imagenet" downloads the revision-pinned nvidia/mit- checkpoint from the Hugging Face Hub, and a local pytorch_model.bin or model.safetensors path also works. + +- load_hf_state_dict() loads transformers state dicts: SegformerForSemanticSegmentation into the whole model; SegformerForImageClassification (``nvidia/mit-b*``: the "segformer." prefix is removed and the ImageNet classifier dropped) and SegformerModel into model.segformer. + +- Like transformers, every LayerNorm uses eps=1e-5. The official MiT uses 1e-6 in the Transformer blocks and stage norms; with the ADE20K B0 weights this changes logits by up to about 6e-3 (99.99% argmax agreement on random input). + +- Mix-FFN expansion is 4 in every stage, as in the released code and checkpoints; the paper's Table 6 lists 8 for stages 1-2 of B0-B4. The decode-head dropout is element-wise as in transformers, where mmseg uses channel-wise Dropout2d; this only matters in training. + +- Height and width must be at least 29; they need not be multiples of 32. +- Multi-day input (batch, time, channels, height, width) is flattened time-major to time * channels. The deduplicated WildfireSpreadTS layout (120 channels for five days of all features) is built by the data pipeline and passed as (batch, 120, height, width). + diff --git a/docs/source/modules/models_swin_unet.rst b/docs/source/modules/models_swin_unet.rst new file mode 100644 index 00000000..58c2fbec --- /dev/null +++ b/docs/source/modules/models_swin_unet.rst @@ -0,0 +1,131 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +Swin-Unet +========= + +Overview +-------- + +``swin_unet`` encodes the input with four Swin Transformer stages joined by patch merging, decodes it with mirrored Swin stages joined by patch-expanding layers and skip connections, and upsamples the last decoder tokens 4x into per-pixel logits (Cao et al., ECCV Workshops 2022). The default is Swin-Unet-Tiny: patch 4, embedding 96, depths (2, 2, 2, 2), heads (3, 6, 12, 24), window 7, input 224x224, drop-path rate 0.2. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``swin_unet`` encodes the input with four Swin Transformer stages joined by patch merging, decodes it with mirrored Swin stages joined by patch-expanding layers and skip connections, and upsamples the last decoder tokens 4x into per-pixel logits (Cao et al., ECCV Workshops 2022). The default is Swin-Unet-Tiny: patch 4, embedding 96, depths (2, 2, 2, 2), heads (3, 6, 12, 24), window 7, input 224x224, drop-path rate 0.2. + +The implementation is written from the paper and from the MIT-licensed Swin Transformer code, because the official Swin-Unet repository has no license. Parameter names and creation order match the official ``SwinTransformerSys``, so its state dicts load with ``strict=True`` and seeded initialisation is identical. ``pretrained="imagenet"`` reproduces the official initialisation: the Swin-T ImageNet-1k checkpoint fills the encoder and, mirrored, the decoder. Multi-day input ``(batch, time, channels, height, width)`` is flattened to ``time * channels`` channels, as WSTS+ does for its 5-day models. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `Swin-Unet: Unet-like Pure Transformer for Medical Image Segmentation `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark `_: Lahrichi, Bova, Johnson and Malof (WACV 2026). SwinUnet-Tiny with in_chans set to 7, 33 or 40 (Veg, Multi, All feature sets; times 5 for 5-day input), 128x128 WildfireSpreadTS tiles zero-padded to 224x224, Swin-T ImageNet initialisation (Hugging Face swin-tiny-patch4-window7-224), focal loss, AdamW, batch 64, 10k iterations. Mean test AP over 12 leave-one-year-out folds: 0.432 / 0.437 / 0.424 (1 day) and 0.447 / 0.453 / 0.435 (5 days) for Veg / Multi / All; 27.2M parameters (1 day). +- `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_ (`repo `__): Swin-T blocks and the ImageNet-1k checkpoint used for initialisation (MIT). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/HuCaoFighting/Swin-Unet `__ at ``f48f623`` (none (no LICENSE file; used only as a test oracle, not copied)) +- **Checked configuration:** SwinUnet(config) from configs/swin_tiny_patch4_window7_224_lite.yaml with IN_CHANS 40 and one class (the WSTS+ All-features setting) and with IN_CHANS 3 and nine classes (Synapse, 27,168,900 parameters), plus SwinUnet.load_from with the Swin-T ImageNet-1k checkpoint (swin_tiny_patch4_window7_224.pth, microsoft/Swin-Transformer release v1.0.0, MIT, sha256 pinned) for 40 and 3 input channels. +- **Parameter count:** 27,224,964 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_swin_oracle.py`` +- **Deviation:** The official wrapper repeats a one-channel input to three channels. Here that happens only when the model has three input channels; for other channel counts the official code would fail. +- **Deviation:** Only the ImageNet branch of the official load_from is provided. Its other branch (fine-tuning from a saved Swin-Unet checkpoint, dropping the output layer) is covered by load_state_dict, since parameter names match. + +Registry Name +------------- + +Primary entrypoint: ``swin_unet`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + import torch.nn.functional as F + from pyhazards.models import build_model + + # WSTS+ "All" features (40 channels); pretrained="imagenet" loads the Swin-T initialisation. + model = build_model(name="swin_unet", task="segmentation", in_channels=40) + x = torch.randn(2, 40, 128, 128) + logits = model(F.pad(x, (0, 96, 0, 96)))[..., :128, :128] # zero-pad 128 -> 224 as WSTS+ + print(logits.shape) # (2, 1, 128, 128) + +Notes +----- + +- Inputs must be img_size x img_size (224 by default); WSTS+ zero-pads its 128x128 tiles. The padding layout is not stated in the paper. +- The decoder mirrors the encoder depths. The official DECODER_DEPTHS option and the depths_decoder argument have no effect in the official code, so they are not exposed. +- Decoder blocks reuse the stochastic-depth rates of the matching encoder stage, as in the official code. +- With pretrained weights, tensors whose shape differs from Swin-T (the patch embedding when in_channels != 3) keep their random initialisation, as in the official load_from. +- WSTS+ loaded the Hugging Face release of Swin-T (microsoft/swin-tiny-patch4-window7-224, a conversion of the ImageNet-1k model); PyHazards loads the original microsoft/Swin-Transformer checkpoint with the official Swin-Unet key mapping. diff --git a/docs/source/modules/models_swin_unetr.rst b/docs/source/modules/models_swin_unetr.rst new file mode 100644 index 00000000..9e75a452 --- /dev/null +++ b/docs/source/modules/models_swin_unetr.rst @@ -0,0 +1,133 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +SwinUNETR +========= + +Overview +-------- + +``swin_unetr`` is SwinUNETR (Hatamizadeh et al., BrainLes 2021): a four-stage Swin Transformer with shifted-window attention and patch merging encodes the input, and its five feature levels feed a convolutional U-Net decoder of residual blocks. The implementation is MONAI's (1.3.2, Apache-2.0; the authors' official code uses it), ported to plain PyTorch with MONAI's module names, so MONAI state dicts load with ``strict=True``; MONAI's ``"merging"`` / ``"mergingv2"`` patch merging and SwinUNETR-v2 blocks (``use_v2``) are included. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``swin_unetr`` is SwinUNETR (Hatamizadeh et al., BrainLes 2021): a four-stage Swin Transformer with shifted-window attention and patch merging encodes the input, and its five feature levels feed a convolutional U-Net decoder of residual blocks. The implementation is MONAI's (1.3.2, Apache-2.0; the authors' official code uses it), ported to plain PyTorch with MONAI's module names, so MONAI state dicts load with ``strict=True``; MONAI's ``"merging"`` / ``"mergingv2"`` patch merging and SwinUNETR-v2 blocks (``use_v2``) are included. + +With the defaults (``spatial_dims=3``) the model is TS-SatFire's SwinUNETR-3D, which modifies MONAI's file: patches of (1, 2, 2) and attention windows of (T, 4, 4), so every window spans the whole time series; patch merging that only merges even-sized dimensions (with T = 6 the first stage halves time to 3 and later stages keep it); optional Swin-V2 attention (``attn_version="v2"``); feature size 36, batch norm and two-class logits averaged over time. ``spatial_dims=2`` gives TS-SatFire's SwinUNETR-2D, which is stock MONAI (patch 2, window 7, feature size 48). + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Swin UNETR: Swin Transformers for Semantic Segmentation of Brain Tumors in MRI Images `_ | **Repo:** `Repository `__ + +Used In +------- + +- `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ (`repo `__): SwinUNETR-3D from the repository's modified MONAI copy (patch (1, 2, 2), window (T, 4, 4), even-dimension patch merging, window attention "v1", feature size 36) on 256x256 tiles of daily VIIRS and auxiliary data, 43 channels for next-day progression prediction, T in {2, 4, 6}, logits averaged over time; prediction trained with Dice + weighted CE (1:1, class weights [1, 446.78]), learning rate 0.001, batch 8 (paper text). The number of heads (a command-line argument) is not published. Paper Table 3 (6 input days; arXiv 2412.11555): 33.2M parameters, F1 0.797 / 0.855 / 0.374 and IoU 0.688 / 0.768 / 0.331 on active fire / burned area / prediction; Table 4 (seeds 42-44): prediction F1 0.371 +/- 0.003, IoU 0.332 +/- 0.003; Table 5 (prediction, T = 6 / 4 / 2): F1 0.374 / 0.354 / 0.366. SwinUNETR-2D (stock MONAI, feature size 48) has 25.2M parameters and F1 0.774 / 0.829 on active fire / burned area. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Project-MONAI/MONAI `__ at ``1.3.2`` (Apache-2.0) +- **Checked configuration:** TS-SatFire's SwinUNETR(image_size=(T, H, W), patch_size=(1, 2, 2), window_size=(T, 4, 4), in_channels=43, out_channels=2, depths=(2, 2, 2, 2), num_heads=(3, 3, 3, 3), feature_size=36, norm_name="batch", attn_version="v1") from spatial_models/swinunetr/ at da75732 (an adapted MONAI SwinUNETR; the repository has no license and is used only as a test oracle), with its outputs averaged over time, at T = 6 (and T = 2, 3, 4 for the other merging plans) on 32x32 tiles, at (6, 256, 256) for the parameter count (33,191,942), and with attn_version="v2"; MONAI 1.3.2 SwinUNETR(spatial_dims=2, in_channels=8, feature_size=48, norm_name="batch") for the 2D baseline (25,151,996 parameters, forward at 64x64); and 2D/3D MONAI configurations with "merging" and "mergingv2", use_v2, instance norm, dropout, attention dropout, stochastic depth, gradient checkpointing and unnormalised features. +- **Parameter count:** 33,191,942 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_swin_unetr_oracle.py`` +- **Deviation:** TS-SatFire's autoregressive attention (``attn_version="ar"``, AutoregressiveAttention.py, a causal temporal mask on Swin-V2 attention) is not ported: the prediction script hard-codes ``attn_version="v1"``. The temporal mask TS-SatFire computes in every 3D stage is only used by that attention, so it is not computed here either. +- **Deviation:** TS-SatFire's number of heads (``-nh``) is not published; the default 3 per stage is a PyHazards choice. Table 3's 33.2M is consistent with any of 3, 4, 6 or 12 heads (33.19M to 33.23M with 43 channels; 33.15M to 33.19M with 8). +- **Deviation:** TS-SatFire averages the 3D logits over time in its training script; here that read-out is part of the model (``time_reduction="mean"``), which also takes ``(batch, time, channels, H, W)`` instead of ``(batch, channels, time, H, W)``. +- **Deviation:** ``downsample`` takes ``"merging"``, ``"mergingv2"`` or ``"ts_satfire"`` but not a custom module, and MONAI's ``load_from`` helper for its self-supervised Swin-ViT checkpoint is not ported (state dicts load directly). +- **Deviation:** Gradient checkpointing follows MONAI; TS-SatFire's copy calls its block with the wrong number of arguments when ``use_checkpoint=True``. Swin-V2 attention with a window size of 1 (division by zero in the reference) and inputs that do not fit the merging plan fixed by ``img_size`` (a concatenation error in the reference) raise ValueError. + +Registry Name +------------- + +Primary entrypoint: ``swin_unetr`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # TS-SatFire SwinUNETR-3D prediction model for 6 days of 43 channels on 256x256 tiles. + model = build_model(name="swin_unetr", task="segmentation", in_channels=43, history=6) + logits = model(torch.randn(1, 6, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) + + # TS-SatFire's single-image SwinUNETR-2D (stock MONAI). + model_2d = build_model(name="swin_unetr", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 256, 256)).shape) # (1, 2, 256, 256) + +Notes +----- + +- With downsample='ts_satfire' the merging plan is fixed by img_size = (history, image_size, image_size): a stage merges a dimension only if its size there is even (T = 6: time 6 -> 3 at the first stage; T = 4: 4 -> 2 -> 1; T = 2: 2 -> 1; odd T: never). +- Height and width must be multiples of 32 (patch 2 times four merges); MONAI's merging modes also halve time four times, so they need T divisible by 16. +- TS-SatFire's Swin-V2 attention normalises its 3D relative coordinates with [:, :, :, i] indexing, which in 3D scales entries of the width axis rather than each coordinate; this is kept. +- MONAI quirks are kept: the 3D 'merging' mode concatenates two of the eight neighbours twice and two never, and window attention indexes its bias table with [:n, :n] when a window is shrunk to the feature size. +- num_heads may be one int for every stage, as in TS-SatFire's scripts. diff --git a/docs/source/modules/models_swinlstm.rst b/docs/source/modules/models_swinlstm.rst new file mode 100644 index 00000000..f2496e20 --- /dev/null +++ b/docs/source/modules/models_swinlstm.rst @@ -0,0 +1,145 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +SwinLSTM +======== + +Overview +-------- + +``swinlstm`` replaces the convolutions of ConvLSTM with Swin Transformer blocks. Each frame is cut into 2x2 patches and embedded. In a SwinLSTM cell the patch tokens and the previous hidden state are layer-normalised, concatenated and projected back to the token width, passed through (shifted-)window attention blocks, and the result F updates a simplified LSTM: ``C_t = sigmoid(F) * (tanh(F) + C_{t-1})``, ``H_t = sigmoid(F) * tanh(C_t)``. A 3x3 transposed convolution with stride 2 and a sigmoid reconstruct the next frame. SwinLSTM-D (``variant="d"``, the default) has four cells joined by patch merging and patch expanding (embedding 128, window 4, heads 4 and 8); SwinLSTM-B (``variant="b"``) has cells at a single resolution. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Forecasting, Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``swinlstm`` replaces the convolutions of ConvLSTM with Swin Transformer blocks. Each frame is cut into 2x2 patches and embedded. In a SwinLSTM cell the patch tokens and the previous hidden state are layer-normalised, concatenated and projected back to the token width, passed through (shifted-)window attention blocks, and the result F updates a simplified LSTM: ``C_t = sigmoid(F) * (tanh(F) + C_{t-1})``, ``H_t = sigmoid(F) * tanh(C_t)``. A 3x3 transposed convolution with stride 2 and a sigmoid reconstruct the next frame. SwinLSTM-D (``variant="d"``, the default) has four cells joined by patch merging and patch expanding (embedding 128, window 4, heads 4 and 8); SwinLSTM-B (``variant="b"``) has cells at a single resolution. + +``forward`` runs the official rollout: a warm-up phase over the first ``T_in - 1`` frames, then autoregressive prediction starting from the last input frame, each predicted frame being the next input. ``include_warmup=True`` also returns the warm-up predictions, which the official L2 loss compares with the shifted input frames; ``step`` is the official single-step forward. The port matches the official code in eval and train mode (stochastic depth), and the released Moving-MNIST SwinLSTM-D weights load with ``strict=True``. + +Sim2Real-Fire compares SwinLSTM with other forecasters for fire-area forecasting and backtracking but published no configuration for it. ``task="segmentation"`` is a PyHazards adaptation that predicts one next-step fire mask from a sequence of rasters. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `SwinLSTM: Improving Spatiotemporal Prediction Accuracy using Swin Transformer and LSTM `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire `_ (`repo `__): Configuration not published: the paper lists SwinLSTM among "commonly used AI models that can be easily adapted" but gives no hyperparameters, input stacking, loss or output head, and the repository contains only S2R-FireTr. Trained on 1M simulated scenarios and tested on simulated and about 1K real fires (binary fire-area sequences with satellite, topography, vegetation, fuel and weather inputs). Table 2, AUPRC / F1 / IoU (%): forecast 77.1 / 71.2 / 56.2 (simulation) and 62.5 / 60.3 / 48.9 (real); backtracking 72.5 / 65.3 / 52.4 (simulation) and 53.8 / 49.5 / 40.3 (real). Modality ablations in Tables 4 and 6. Not reproduced here. +- `A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA) `_ (`repo `__): Not this model. WildfireIA's "SwinLSTM" baseline (train.py SwinLSTMClassifier at aba9be9, MIT) is a ConvLSTM cell between two window-attention blocks (48 channels, a strided convolutional stem with BatchNorm, ``nn.MultiheadAttention`` in 5x5 windows without shifts or relative position bias) with global pooling and an MLP to one score, on 29x29 event patches. Initial-attack failure prediction: AUPRC 51.7 +/- 1.2, AUROC 85.7 +/- 0.9 (Table 3); containment duration: MAE 36.3 h (Table 6). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/SongTang-x/SwinLSTM `__ at ``4425bcf`` (MIT (code and the released weights in Pretrained/)) +- **Checked configuration:** configs.py defaults, which are the Moving-MNIST setting of paper Table 1: SwinLSTM-D, 64x64x1 frames, patch 2, embedding 128, depths_down [2, 6], depths_up [6, 2], heads [4, 8], window 4, drop-path rate 0.1, 10 -> 10 frames. Checked with the released weights Pretrained/trained_model_state_dict (functions.model_forward_multi_layer rollout, single steps and the segmentation adaptation), with seeded initialisation and a train-mode rollout (stochastic depth); SwinLSTM-B with the configs.py defaults (depths [12], 2,778,417 parameters) and the Human3.6m setting (128x128x3, 2,781,747), a two-cell SwinLSTM-B and a two-level SwinLSTM-D with two input channels, each with seeded initialisation and eval and train rollouts (functions.model_forward_single_layer / model_forward_multi_layer). +- **Parameter count:** 20,191,969 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_swinlstm_oracle.py`` +- **Deviation:** ``patch_size`` must be 2. The reference reconstruction layer (3x3 transposed convolution, stride 2) restores the input size only for 2x2 patches, so the released code cannot run the paper's patch-4 settings (KTH, TaxiBJ) either; other patch sizes raise ``ValueError``. +- **Deviation:** The model's ``forward`` takes the whole sequence ``(batch, T_in, C, H, W)`` and runs the rollout of the official ``functions.py`` (warm-up, then autoregressive prediction); the reference model's ``forward`` is one time step, available here as ``step`` with the same arguments and return values. +- **Deviation:** The reference SwinLSTM-D constructor passes no dropout or drop-path arguments (dropout 0, attention dropout 0 and drop-path rate 0.1 are fixed); here they are arguments with those defaults. Zero initial states take the input's dtype (the reference creates float32 zeros). +- **Deviation:** ``task="segmentation"`` (SwinLSTMSegmenter) is a PyHazards adaptation, not from Sim2Real-Fire: the reconstruction layer has one output channel (``out_chans``; every other parameter has the shape of the forecasting model), the input frames go through the reference rollout with one prediction step, and that frame is returned before the final sigmoid, as logits ``(batch, 1, H, W)``. Its state dict keys are those of the forecasting model (no prefix). + +Registry Name +------------- + +Primary entrypoint: ``swinlstm`` + +Supported Tasks +--------------- + +- Forecasting +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + import torch.nn.functional as F + from pyhazards.models import build_model + + # Official Moving-MNIST SwinLSTM-D: 10 frames of 64x64x1 in [0, 1] -> the next 10 frames. + model = build_model(name="swinlstm", task="forecasting") # 20,191,969 parameters + # Released weights: model.load_state_dict(torch.load("Pretrained/trained_model_state_dict")) + inputs, targets = torch.rand(2, 10, 1, 64, 64), torch.rand(2, 10, 1, 64, 64) + future = model(inputs) # (2, 10, 1, 64, 64) + + # Official training objective: L2 over the 9 warm-up and 10 predicted frames. + outputs = model(inputs, include_warmup=True) # (2, 19, 1, 64, 64) + loss = F.mse_loss(outputs, torch.cat([inputs[:, 1:], targets], dim=1)) + + # PyHazards adaptation: next-day fire-mask logits from 3 daily rasters with 6 channels. + seg = build_model(name="swinlstm", task="segmentation", in_channels=6, img_size=64) + logits = seg(torch.randn(2, 3, 6, 64, 64)) # (2, 1, 64, 64) + +Notes +----- + +- With the official ``depths_up`` [6, 2] the decoder runs 2 Swin blocks at the deepest level and 6 at the next, because the reference indexes ``depths_up`` (and the head counts) from the deepest level: the network has 2 + 6 blocks on the way down and 2 + 6 on the way up, where paper Table 1 lists (2, 6, 6, 2). Decoder cells also take their level's stochastic-depth rates in reverse block order. Both are kept, since the released weights follow them. + +- ``Upsample.patch_embed`` is created by the reference but never used in its forward pass; it is kept (896 parameters) so that the official checkpoint loads with ``strict=True``. + +- Frames are expected in [0, 1] (pixels / 255 for Moving MNIST); predictions are sigmoid outputs. Any frame size whose token grid (size / 2) can be halved once per level and split into whole windows works; Sim2Real-Fire's 256x256 frames give 128, 64 and 32 tokens per side. + +- Sanity check of the released weights through this port: MSE 18.8 per frame (squared error summed over the 64x64 pixels, averaged over the 10 predicted frames) on 32 sequences generated by the official Moving_MNIST class from MNIST digits 10000-13000. The paper reports 17.7 on the standard Moving MNIST test set, which was not re-evaluated here. + diff --git a/docs/source/modules/models_tcif_fusion.rst b/docs/source/modules/models_tcif_fusion.rst index f9c46589..693966f1 100644 --- a/docs/source/modules/models_tcif_fusion.rst +++ b/docs/source/modules/models_tcif_fusion.rst @@ -6,7 +6,7 @@ TCIF-fusion Overview -------- -``tcif_fusion`` combines multiple feature streams behind the shared storm forecasting interface used throughout the PyHazards cyclone roadmap. +``tcif_fusion`` predicts one number per storm and time, the maximum sustained wind (2-minute, m/s) 24 hours ahead, for Northwest Pacific typhoons; it does not forecast tracks. Inputs (a mapping, channels last as in the official notebook): ERA5 ``u``, ``v``, ``w`` ``(batch, 25, 25, 5, 4)`` - 25 x 25 one-degree grid, 5 six-hourly times, 200 / 500 / 850 / 1000 hPa - and ``sst`` ``(batch, 25, 25, 5, 1)``; ``all``, the four fields concatenated to ``(batch, 25, 25, 65)`` (built by ``era5_all`` when absent); ``his``, 30 history features; ``ir``, GridSat-B1 infrared images ``(batch, 224, 224, 5)``. At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Track + Intensity + Forecasting .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,40 @@ At a Glance Description ----------- -``tcif_fusion`` combines multiple feature streams behind the shared storm forecasting interface used throughout the PyHazards cyclone roadmap. +``tcif_fusion`` predicts one number per storm and time, the maximum sustained wind (2-minute, m/s) 24 hours ahead, for Northwest Pacific typhoons; it does not forecast tracks. Inputs (a mapping, channels last as in the official notebook): ERA5 ``u``, ``v``, ``w`` ``(batch, 25, 25, 5, 4)`` - 25 x 25 one-degree grid, 5 six-hourly times, 200 / 500 / 850 / 1000 hPa - and ``sst`` ``(batch, 25, 25, 5, 1)``; ``all``, the four fields concatenated to ``(batch, 25, 25, 65)`` (built by ``era5_all`` when absent); ``his``, 30 history features; ``ir``, GridSat-B1 infrared images ``(batch, 224, 224, 5)``. -The adapter focuses on the fusion contract and evaluator compatibility rather than full reproduction of the original training stack. +Each ERA5 field runs through three 3-D blocks (three 3 x 3 x 5 convolutions with 128 / 256 / 512 filters, 2 x 2 x 2 max pooling with stride (2, 2, 1)); a fusion branch adds the four fields' features after every block and runs blocks 2 and 3 on the sums; ALL runs through three 2-D blocks. The flattened maps (212,992 values) go through Dense 256 and 15, the history through Dense 32 and 64, the IR images through a VGG-19 (64-128-256-512-512 filters, Dense 1024-1024-15); two residual blocks of three dense layers (256, 128) and a linear output follow. 299,588,223 parameters (``all_channels=85``, the notebook's graph: 299,611,263). + +The model-knowledge (MK) step of the paper is provided as functions: ``model_knowledge_heatmaps`` computes Grad-CAM heatmaps of a trained model's inputs and ``apply_model_knowledge`` multiplies the inputs by their absolute values; a second TCIF-fusion trained on the guided inputs is the MK-guided model the paper evaluates. The benchmark scores the model with ``tc.intensity``. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` -**Mapped benchmark ecosystems:** :doc:`TCBench Alpha ` - External References ------------------- -**Paper:** `Tropical cyclone intensity forecasting using model knowledge guided deep learning model `_ | **Repo:** `Repository `__ +**Paper:** `Tropical cyclone intensity forecasting using model knowledge guided deep learning model `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Wang, Li and Zheng, Environmental Research Letters 19, 024006 (2024), open access (CC BY 4.0) `_ (`repo `__): Northwest Pacific, CMA/STI best track 1979-2019 (90 % training, 10 % validation; 20,533 samples 1979-2021 with ERA5 and GridSat-B1), independent test 2020-2021, 24-hour intensity MAE: MK-guided TCIF-fusion 3.56 m/s (2020 3.64, 2021 3.51). Input ablation (Table 1, MK-guided): HIS+U+V+W 3.87, +SST 3.74, +IR 3.69, +IR+SST 3.56 m/s. Official forecasts 2020 / 2021 (Table 2): CMA 4.50 / 4.30, JMA 4.50 / 4.30, JTWC 4.90 / 4.60, ECMWF-IFS 6.70 / 8.00, NCEP-GFS 4.70 / 5.90 m/s; landfalling TCs 2020 4.55 m/s. Not reproduced by PyHazards (no reader for the CMA / ERA5 / GridSat-B1 inputs yet). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/wangchong96/TCIF-fusion `__ (``4b5fafc``, none (no LICENSE file; the notebooks are used only as a test oracle, never copied)); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** TCIF_fusion() of TCIF-fusion.ipynb. The notebooks do not run as published (TensorFlow 1 session code, no data loading, a validation list with one input too many); the graph functions (F3d, F2d, VGG192d, TCIF_fusion) are executed unchanged with Keras 3.12.4 on the PyTorch backend. The parameter count of every layer and the total, 299,611,263, equal the summary the authors' own run printed in "obtain model knowledge.ipynb" (Keras 2 / TensorFlow 1.14); with the Keras weights copied (layer by layer, names of that summary) the outputs equal the Keras graph for the notebook's 85-channel ALL input and for the paper's 65 channels (299,588,223 parameters, the input shape substituted). The training settings equal the notebook's compile / fit call, and the gradient the MK example starts from (forecast w.r.t. the SST input, averaged over the batch and the horizontal axes) equals the Keras model's. +- **Parameter count:** 299,588,223 +- **Verified:** parameter count, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_tcif_fusion_oracle.py`` +- **Deviation:** ALL channels: the notebook's graph has an 85-channel ALL input; the paper's Figure 1 draws it as 25 x 25 x 65, exactly U, V, W (5 times x 4 levels each) and SST (5 times) concatenated, and the notebook's MK example allocates 65 channels. The default follows the paper (65; ALL = U, V, W, SST flattened over time and level, time-major - the order is not documented); all_channels=85 rebuilds the notebook graph, whose extra 20 channels are not described anywhere. +- **Deviation:** Figure 1 draws a Flatten + Dense(15) per branch and a 90-d concatenation before Dense 256 and 15, and a single Flatten + Dense(15) after the IR VGG; the notebook concatenates the six flattened maps (212,992 values) into one Dense(256) -> Dense(15) and gives the VGG Dense 1024-1024-15. The notebook (which the printed summary confirms) is followed. +- **Deviation:** Initialisation has Keras' distributions (glorot-uniform kernels, zero biases; checked) but not its random draws, which come from TensorFlow's generator. No trained weights were released (the notebook saves ./CMA/TCIF-fusion-best-uvwssthsat-1.h5, which is not in the repository); load_keras_weights maps such a file's layers by their names. +- **Deviation:** Model knowledge: the paper multiplies the inputs by the absolute Grad-CAM heatmaps of a first model; the notebook's example only takes the gradient w.r.t. one input (SST), averages it over the batch and the horizontal axes and then stores the raw input (it also passes the SST array as the IR input). PyHazards completes the Grad-CAM recipe the example follows (heatmap = channel mean of the input weighted by the averaged gradient), applies no normalisation (none is described), guides U, V, W, SST and IR (the inputs of the paper's Figure 2), rebuilds ALL from the guided fields and leaves the history unchanged. +- **Deviation:** Training is not part of the module: the notebook uses the MAE loss, Adam (learning rate 1e-4), batch 512, 100 epochs, ReduceLROnPlateau (factor 0.5, patience 10, minimum 1e-6) and keeps the best validation checkpoint (TCIF_TRAINING). The input-ablation models of Table 1 (TCIF-1 to TCIF-3) are not provided, and the notebook's unused (and broken) attention helpers are not ported. Registry Name ------------- @@ -87,7 +106,7 @@ Primary entrypoint: ``tcif_fusion`` Supported Tasks --------------- -- Track + Intensity +- Forecasting Programmatic Use ---------------- @@ -96,12 +115,23 @@ Programmatic Use import torch from pyhazards.models import build_model + from pyhazards.models.tcif_fusion import apply_model_knowledge, model_knowledge_heatmaps + + model = build_model(name="tcif_fusion", task="regression") # 299,588,223 parameters (about 1.2 GB) + inputs = { + "u": torch.randn(1, 25, 25, 5, 4), "v": torch.randn(1, 25, 25, 5, 4), "w": torch.randn(1, 25, 25, 5, 4), + "sst": torch.rand(1, 25, 25, 5, 1), # ALL (25, 25, 65) is built from these + "his": torch.rand(1, 30), + "ir": torch.rand(1, 224, 224, 5), + } + print(model(inputs).shape) # (1, 1): 24-hour intensity - model = build_model(name="tcif_fusion", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # MK-guided training: train a first model, then train a second one on the guided inputs. + guided = apply_model_knowledge(inputs, model_knowledge_heatmaps(model, inputs)) Notes ----- -- Outputs are shared storm forecast trajectories over the configured horizon. +- The ALL input is not a heat-map input: Figure 1 labels it ALL and builds it from U, V, W and SST (the inventory had read inputs_h as the model-knowledge heatmaps). Model knowledge enters by multiplying the inputs. +- The 30 history features (left_input; Figure 1: historical wind speed and pressure) are defined only in the paper's supplementary material, which could not be retrieved; the CMA best track, ERA5 and GridSat-B1 crops have no PyHazards reader yet, and tcif_fusion_synthetic gives random inputs in their layout for smoke tests. +- The full model needs about 1.2 GB for its weights and roughly 10^11 multiply-adds per sample; the size arguments of the builder (grid_size, ir_size, widths, vgg_filters, vgg_fc) only exist to build small copies for smoke tests. diff --git a/docs/source/modules/models_tcn.rst b/docs/source/modules/models_tcn.rst new file mode 100644 index 00000000..051b9c3f --- /dev/null +++ b/docs/source/modules/models_tcn.rst @@ -0,0 +1,133 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +TCN +=== + +Overview +-------- + +``tcn`` maps a ``(batch, time, features)`` sequence through residual blocks of two causal dilated 1D convolutions (dilation ``2 ** i`` at level ``i``), each with weight normalisation, ReLU and dropout, with a 1x1 convolution on the residual path when the width changes. The output at step ``t`` only depends on steps up to ``t``. A linear head reads the last time step (``readout="last"``, sequence classification or regression) or every step (``readout="sequence"``). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Classification, Forecasting + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``tcn`` maps a ``(batch, time, features)`` sequence through residual blocks of two causal dilated 1D convolutions (dilation ``2 ** i`` at level ``i``), each with weight normalisation, ReLU and dropout, with a 1x1 convolution on the residual path when the width changes. The output at step ``t`` only depends on steps up to ``t``. A linear head reads the last time step (``readout="last"``, sequence classification or regression) or every step (``readout="sequence"``). + +The implementation is a port of ``TemporalConvNet`` / ``TemporalBlock`` / ``Chomp1d`` from the official locuslab/TCN code with the linear heads of its example tasks. Weight normalisation uses ``torch.nn.utils.parametrizations.weight_norm`` instead of the deprecated hook-based ``torch.nn.utils.weight_norm``; the computation and initialisation are identical, official state dicts load with ``strict=True``, and ``to_official_state_dict`` converts back. + +No wildfire study using this network was found. The "TCN" of the WildfireIA benchmark is a different, non-causal design (see Used In) and is not what this model implements. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling `_ | **Repo:** `Repository `__ + +Used In +------- + +- `A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA) `_ (`repo `__): Not this model. WildfireIA's TCN baseline (train.py TCNClassifier at aba9be9, MIT) has three non-causal residual blocks (kernel 3 with symmetric padding, dilations 1/2/4, 128 channels, BatchNorm instead of weight normalisation, no ReLU after the residual sum), mean-pools over the T=5 daily weather / fire-danger steps and concatenates a static-feature MLP before an MLP head. Initial-attack failure prediction on 38,128 FPA-FOD fires: AUPRC 50.4 +/- 0.3, AUROC 83.7 +/- 0.5 (Table 3); containment duration: MAE 36.1 h (Table 6). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/locuslab/TCN `__ at ``2f8c2b8`` (MIT) +- **Checked configuration:** Adding problem TCN(2, 1, [30] * 8, kernel_size=7, dropout=0.0) (add_test.py defaults, the builder defaults here); sequential MNIST TCN(1, 10, [25] * 8, kernel_size=7, dropout=0.05) in eval and train mode (66,910 parameters); the per-step heads of copy memory (TCN(1, 10, [10] * 8, kernel_size=8)) and polyphonic music (TCN(88, 88, [150] * 4, kernel_size=5, dropout=0.25)); causality of TemporalConvNet. +- **Parameter count:** 96,001 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_tcn_oracle.py`` +- **Deviation:** Weight normalisation is ``torch.nn.utils.parametrizations.weight_norm``, so g and v are stored as ``.parametrizations.weight.original0`` / ``original1`` instead of ``weight_g`` / ``weight_v``. Official state dicts load unchanged (PyTorch renames the keys while loading) and ``to_official_state_dict`` gives the official names; outputs are identical. +- **Deviation:** ``TCN`` takes ``(batch, time, features)`` and transposes it to the official ``(batch, channels, length)``; ``TemporalConvNet`` keeps the official layout. +- **Deviation:** Heads return raw scores: the sequential-MNIST model's ``log_softmax`` and the music model's ``sigmoid`` (in float64) are left to the loss. +- **Deviation:** Kernel sizes below 2 raise ValueError at construction; in the official code ``Chomp1d(0)`` returns an empty sequence and the next convolution raises a RuntimeError. + +Registry Name +------------- + +Primary entrypoint: ``tcn`` + +Supported Tasks +--------------- + +- Classification +- Forecasting + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # Event classification from 5 days of 12 weather / fire-danger features. + model = build_model( + name="tcn", task="classification", input_dim=12, out_dim=2, + hidden_dim=32, num_levels=3, kernel_size=2, dropout=0.2, + ) + logits = model(torch.randn(8, 5, 12)) # (batch, days, features) + print(logits.shape) # (8, 2) + +Notes +----- + +- As in the official code, init_weights draws N(0, 0.01) into the computed weights of the weight-normalised convolutions, and weight normalisation discards them: those convolutions keep PyTorch's default initialisation, and only the 1x1 residual convolutions (and the head with head_init='normal') are N(0, 0.01). The draws are kept so a seed gives the official parameters. +- Defaults reproduce the official adding-problem model (input_dim 2, 8 levels x 30 channels, kernel 7, no dropout). Paper Table 2 lists per-task settings of about 70K parameters, e.g. adding problem T=600: hidden_dim=24, num_levels=8, kernel_size=8. +- The receptive field is 1 + 2 (kernel_size - 1)(2^num_levels - 1) steps (3,061 with the defaults); short wildfire histories need far fewer levels. +- head_init='default' keeps PyTorch's Linear initialisation, as the official sequential-MNIST and music models do; readout='sequence' returns (batch, time, out_dim). diff --git a/docs/source/modules/models_trajgru.rst b/docs/source/modules/models_trajgru.rst new file mode 100644 index 00000000..5c3c8363 --- /dev/null +++ b/docs/source/modules/models_trajgru.rst @@ -0,0 +1,144 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +TrajGRU +======= + +Overview +-------- + +TrajGRU replaces the fixed state-to-state convolution of ConvGRU with L learned links: a small convolutional network predicts L flow fields from the current input and the previous state, the state is bilinearly warped along each field, and a 1x1 convolution mixes the warped copies into the reset gate, update gate and candidate. ``trajgru`` is the paper's encoder-forecaster: each frame (with x/y coordinates and a constant channel appended) is embedded by a strided convolution and encoded by three RNN blocks joined by strided convolutions; the forecaster blocks start from the encoder's final states, the top one runs without input, transposed convolutions pass outputs down, and a transposed convolution, a 3x3 convolution and a 1x1 convolution produce each frame. Activations are leaky ReLUs (slope 0.2). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Forecasting, Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +TrajGRU replaces the fixed state-to-state convolution of ConvGRU with L learned links: a small convolutional network predicts L flow fields from the current input and the previous state, the state is bilinearly warped along each field, and a 1x1 convolution mixes the warped copies into the reset gate, update gate and candidate. ``trajgru`` is the paper's encoder-forecaster: each frame (with x/y coordinates and a constant channel appended) is embedded by a strided convolution and encoded by three RNN blocks joined by strided convolutions; the forecaster blocks start from the encoder's final states, the top one runs without input, transposed convolutions pass outputs down, and a transposed convolution, a 3x3 convolution and a 1x1 convolution produce each frame. Activations are leaky ReLUs (slope 0.2). + +``config="hko7"`` (default) is the HKO-7 benchmark model (480x480 radar maps, 5 -> 20 frames, blocks of 64 / 192 / 192 channels with 13 / 13 / 9 links); ``config="movingmnist"`` is the TrajGRU-L13 of the MovingMNIST++ experiments (64x64, 10 -> 10, 64 / 96 / 96 channels, 13 links). ``layer_type="ConvGRU"`` gives the paper's ConvGRU baseline in the same encoder-forecaster. Parameter names map one-to-one to the MXNet names, so the released checkpoints load with ``load_hko7_params``, and outputs match the official code on them. + +No wildfire study using TrajGRU was found. Its inventory entry had been merged with the Conv-GRU baseline of FireCastNet, which is a different model (``convgru``); WildfireIA names TrajGRU only among spatiotemporal templates in its related work. It is offered as a sequence architecture for fire-spread rasters; ``task="segmentation"`` is a PyHazards adaptation for next-step fire masks. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Deep Learning for Precipitation Nowcasting: A Benchmark and A New Model `_ | **Repo:** `Repository `__ + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/sxjscience/HKO-7 `__ at ``57b987b`` (MIT (code and released checkpoints)) +- **Checked configuration:** The official encoder and forecaster networks, built by encoder_forecaster_build_networks from the official configuration files and run on MXNet 1.9.1: HKO-7 TrajGRU (trajgru_55_55_33_1_64_1_192_1_192_13_13_9_b4.yml) and ConvGRU with their released checkpoints (480x480, 5 -> 20 frames); the seven MovingMNIST++ models of paper Table 1 (TrajGRU L5 / L9 / L13 / L17, ConvGRU K3-D2 / K5 / K7) with their released checkpoints (64x64, 10 -> 10); parameter names and shapes of all nine; random non-zero flow layers; stacked cells (encoder); encoder states carried over between batches; the warp against MXNet's GridGenerator and BilinearSampler; and the initialisation scheme. +- **Parameter count:** 12,150,053 +- **Verified:** parameter count, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_trajgru_oracle.py`` +- **Deviation:** The reference is symbolic MXNet code that its authors tested on MXNet 0.12. It was run on MXNet 1.9.1, the last release of the retired project, not on 0.12. +- **Deviation:** Initial weights cannot match for a seed, since MXNet and PyTorch draw different random numbers. The port applies the reference scheme (``MSRAPrelu(slope=0.2)``: Gaussian weights with std ``sqrt(2 / 1.04 / fan_avg)``, zero biases, zero flow output layers so that every link starts as the identity warp), which the oracle test compares by distribution. +- **Deviation:** Inputs are ``(batch, T, C, H, W)`` and outputs ``(batch, T_out, out_channels, H, W)``; the reference uses ``(T, batch, ...)``. ``in_channels`` and ``out_channels`` (1 and 1 in the reference) are arguments. +- **Deviation:** Not ported: the dynamic-filter (DFN) output of the ConvGRU-K5-DFN MovingMNIST++ experiment, zoneout and the GAN blocks (``dbrnn``), none of which a TrajGRU configuration or released checkpoint uses. +- **Deviation:** Several cells per block (``stack_num`` > 1, with residual connections and reversed forecaster states) follow the reference code, but only the encoder could be checked: the reference forecaster fails to bind such networks on MXNet 1.9.1. Every released configuration uses one cell per block. +- **Deviation:** Frame sizes must let the decoder restore every encoder feature map (480x480 for ``hko7``, multiples of 4 for ``movingmnist``); other sizes raise a ``ValueError`` that names the mismatch, where the reference fails in shape inference. +- **Deviation:** ``task="segmentation"`` (TrajGRUSegmenter) is a PyHazards adaptation, not from any wildfire paper: the encoder-forecaster predicts one frame and its linear output is returned as logits ``(batch, out_channels, H, W)``. Its state dict keys are those of the forecasting model. + +Registry Name +------------- + +Primary entrypoint: ``trajgru`` + +Supported Tasks +--------------- + +- Forecasting +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + from pyhazards.models.trajgru import load_hko7_params + + # HKO-7 TrajGRU: 5 radar frames of 480x480 (pixel / 255) -> the next 20 frames. + model = build_model(name="trajgru", task="forecasting") # 12,150,053 parameters + # Released checkpoints (MXNet .params), e.g. with mxnet installed: + # params = {**mx.nd.load("encoder_net-79999.params"), **mx.nd.load("forecaster_net-79999.params")} + # load_hko7_params(model, params) + future = model(torch.rand(1, 5, 1, 480, 480)) # (1, 20, 1, 480, 480) + + # MovingMNIST++ TrajGRU-L13 (64x64, 10 -> 10) and the paper's ConvGRU baseline. + l13 = build_model(name="trajgru", task="forecasting", config="movingmnist") # 4,000,397 + convgru = build_model(name="trajgru", task="forecasting", config="movingmnist", + layer_type="ConvGRU", h2h_kernel=5) # 4,767,505 + + # PyHazards adaptation: next-day fire-mask logits from 5 daily 64x64 rasters with 6 channels. + seg = build_model(name="trajgru", task="segmentation", config="movingmnist", in_channels=6) + logits = seg(torch.randn(2, 5, 6, 64, 64)) # (2, 1, 64, 64) + +Notes +----- + +- Paper Table 1 lists the MovingMNIST++ parameter counts. The code reproduces 3.42M (Traj-L9), 4.00M (Traj-L13), 4.77M (Conv-K5-D1) and 8.01M (Conv-K7-D1); it gives 2.60M for Conv-K3-D2 and 2.84M for Traj-L5, the two values swapped in the table, and 4.58M for Traj-L17, which the table lists as 4.77M. + +- Warp direction: the code samples the previous state at the position minus the flow (``GridGenerator(-flow)``), the paper's Eq. 5 at the position plus the flow. The flows are learned, so the two only differ in the sign of the flow layer; the port follows the code, which the released weights need. + +- The model appends normalised x and y coordinates and a channel of ones to every frame (the reference ``_pre_encode_frame``), so ``econv1`` sees ``in_channels + 3`` channels. The reference feeds pixel values / 255; outputs have no activation. + +- Training (outside the model): HKO-7 uses balanced MSE + MAE weighted by rain-rate thresholds and masks, Adam (lr 1e-4, beta1 0.5), gradient clipping 50, batch 4, 100k iterations; MovingMNIST++ uses MSE, clipping 1 and 200k iterations. The MovingMNIST++ script resets the encoder states once and then starts every batch from the previous batch's final encoder states; ``forward(x, initial_states=..., return_states=True)`` reproduces this (checked against the reference). + diff --git a/docs/source/modules/models_tropicalcyclone_mlp.rst b/docs/source/modules/models_tropicalcyclone_mlp.rst index 7c0b4c3c..991cb6a3 100644 --- a/docs/source/modules/models_tropicalcyclone_mlp.rst +++ b/docs/source/modules/models_tropicalcyclone_mlp.rst @@ -6,7 +6,7 @@ Tropical Cyclone MLP Overview -------- -``tropicalcyclone_mlp`` complements ``hurricast`` with a lighter-weight hurricane baseline that uses the same storm-history input contract. +``tropicalcyclone_mlp`` is the operational 24-hour intensity model of Xu et al. (Weather and Forecasting 2021). It maps one forecast time's 121 standardised SHIPS predictors (initial intensity ``vs0``, 18 GOES PSLV, 21 MTPW and 20 IR00 predictors, 0-24 h averages of the SHIPS environmental predictors and the 12-hour intensity change ``DELV-12``; the order is ``SHIPS_PREDICTORS``) to one number, the 24-hour change of the maximum sustained wind (``dvs24``, knots). It does not forecast tracks. At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Track + Intensity + Intensity .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,40 @@ At a Glance Description ----------- -``tropicalcyclone_mlp`` complements ``hurricast`` with a lighter-weight hurricane baseline that uses the same storm-history input contract. +``tropicalcyclone_mlp`` is the operational 24-hour intensity model of Xu et al. (Weather and Forecasting 2021). It maps one forecast time's 121 standardised SHIPS predictors (initial intensity ``vs0``, 18 GOES PSLV, 21 MTPW and 20 IR00 predictors, 0-24 h averages of the SHIPS environmental predictors and the 12-hour intensity change ``DELV-12``; the order is ``SHIPS_PREDICTORS``) to one number, the 24-hour change of the maximum sustained wind (``dvs24``, knots). It does not forecast tracks. -The adapter is useful for practical low-cost intensity and trajectory experiments in basin-filtered settings. +The network is a port of ``models.mlp`` of the official Keras code (BSD-2-Clause): Dense(2048, sigmoid) -> Dense(2048, ReLU) -> Dense(1, linear), 4,448,257 parameters, with Keras' default glorot-uniform kernels and zero biases. Layers are named ``dense``, ``dense_1`` and ``dense_2`` like the Keras layers, and ``load_keras_weights`` copies a Keras model's ``get_weights()``. + +Data: ``ships_xu2021`` reads the authors' predictor table (Zenodo 4784610, CC BY 4.0) and builds the official leave-one-year-out folds; the benchmark scores it with the ``tc.intensity`` task (MAE / RMSE in knots, per test year and their mean). Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` -**Mapped benchmark ecosystems:** :doc:`TCBench Alpha ` +**Mapped benchmark ecosystems:** :doc:`SHIPS Predictors (Xu et al. 2021) ` External References ------------------- -**Paper:** `Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ | **Repo:** `Repository `__ +**Paper:** `Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Xu et al. (2021), Weather and Forecasting 36(4), 1453-1470 (full text: OSTI 1818206) `_ (`repo `__): The paper's own evaluation (Table 5), Atlantic basin, 24-hour intensity change: leave-one-year-out tests on 2010-2018 operational predictors (2,464 six-hourly cases) MAE 8.37 kt, RMSE 11.42 kt, R2 0.75; independent 2019-2020 test (828 cases) MAE 8.22 kt, RMSE 11.07 kt, R2 0.83. NHC references on the same cases (2010-18 / 2019-20 MAE): SHIPS 10.42 / 10.51, DSHP 9.37 / 8.69, LGEM 9.21 / 8.98, HWFI 8.83 / 8.08, OFCL 8.16 / 7.45 kt. Not reproduced by PyHazards. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/wenweixu/tropicalcyclone_MLP `__ at ``7380059`` (BSD-2-Clause (Copyright (c) 2021, Wenwei Xu); ported with the notice kept) +- **Checked configuration:** models.mlp(input_shape=(121,)) from the pinned models.py, executed with Keras 3.12.4 on the PyTorch backend (the original Keras 2.2.4 / TensorFlow 1.12 stack no longer installs; only Adam(lr=) is mapped to learning_rate=): 4,448,257 parameters, layer activations sigmoid / relu / linear, MAE loss and Adam 1e-4; the official weights copied into the port give the same outputs (rtol 1e-5) on random inputs and on real standardised predictors (tests/fixtures/ships_xu2021); the predictor list equals utils.hand_features. +- **Parameter count:** 4,448,257 +- **Verified:** parameter count, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_tropicalcyclone_mlp_oracle.py`` +- **Deviation:** Initialisation has Keras' distribution (glorot-uniform kernels, zero biases; checked against the official model) but not its random draws, which come from TensorFlow's generator; the same seed does not give the official initial weights. +- **Deviation:** No trained weights were released, so the paper's numbers are not reproduced. Training is not part of the module: the official setup is MAE loss, Adam (learning rate 1e-4), batch 32, up to 1000 epochs with early stopping on a random 10 % validation split (min_delta 0.05 kt, patience 10, best weights restored), 40 seed pairs (randomseed.bat). +- **Deviation:** ``hidden_dims`` / ``activations`` can build other widths; only the default (the official 24-hour model) is checked. The paper's 6-hour model (9 predictors, ReLU layers 128-256-128-256-256, scikit-learn MLPRegressor) is not in the official repository. Registry Name ------------- @@ -87,7 +106,7 @@ Primary entrypoint: ``tropicalcyclone_mlp`` Supported Tasks --------------- -- Track + Intensity +- Intensity Programmatic Use ---------------- @@ -96,12 +115,19 @@ Programmatic Use import torch from pyhazards.models import build_model + from pyhazards.models.tropicalcyclone_mlp import SHIPS_PREDICTORS + + model = build_model(name="tropicalcyclone_mlp", task="regression") + predictors = torch.randn(4, len(SHIPS_PREDICTORS)) # standardised SHIPS predictors, official order + print(model(predictors).shape) # (4, 1): 24-hour change of the maximum wind (kt) - model = build_model(name="tropicalcyclone_mlp", task="regression", input_dim=8, history=6) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # Real data: ships_xu2021 reads train_global_fill_REA_na_wo_img_scaled.csv (Zenodo 4784610). + # from pyhazards.datasets import load_dataset + # fold = load_dataset("ships_xu2021", path="train_global_fill_REA_na_wo_img_scaled.csv", leave_out_year=2018).load() Notes ----- -- Outputs are lead-time sequences of latitude, longitude, and intensity targets. +- Inputs must be the standardised predictors of the authors' table (train_global_fill_REA_na_wo_img_scaled.csv, standardised by the reanalysis STD); the operational 2019 / 2020 files of the Zenodo record are not standardised. +- The official loyo_testing.py reads train_global_fill_REA_na_wo_img_scaled_w2020.csv, which is not in the Zenodo record; ships_xu2021 reads the published train_global_fill_REA_na_wo_img_scaled.csv. +- The dvs24 targets of the table are in knots but not whole numbers (e.g. 5.004258), as published. diff --git a/docs/source/modules/models_tropicyclonenet.rst b/docs/source/modules/models_tropicyclonenet.rst index dba1fe62..c7143caa 100644 --- a/docs/source/modules/models_tropicyclonenet.rst +++ b/docs/source/modules/models_tropicyclonenet.rst @@ -6,7 +6,7 @@ TropiCycloneNet Overview -------- -``tropicyclonenet`` extends the shared storm benchmark stack beyond the hurricane-only presets. +``tropicyclonenet`` is the generator of TropiCycloneNet (Nature Communications 2025). It observes 8 six-hourly steps (48 h) of a storm: the best-track longitude, latitude, central pressure and maximum wind (normalised, plus their 6-hourly steps), 500 hPa geopotential crops resized to 64 x 64, and the TCND Env-Data features (wind, intensity class, motion speed, month, location bins, 12/24-hour motion direction and 24-hour intensity change). A 3D U-Net extrapolates the geopotential frames, LSTM encoders combine the track with the frame embeddings, and the Env-T-Net transformer summarises the environment. At a Glance ----------- @@ -63,21 +63,44 @@ At a Glance Description ----------- -``tropicyclonenet`` extends the shared storm benchmark stack beyond the hurricane-only presets. +``tropicyclonenet`` is the generator of TropiCycloneNet (Nature Communications 2025). It observes 8 six-hourly steps (48 h) of a storm: the best-track longitude, latitude, central pressure and maximum wind (normalised, plus their 6-hourly steps), 500 hPa geopotential crops resized to 64 x 64, and the TCND Env-Data features (wind, intensity class, motion speed, month, location bins, 12/24-hour motion direction and 24-hour intensity change). A 3D U-Net extrapolates the geopotential frames, LSTM encoders combine the track with the frame embeddings, and the Env-T-Net transformer summarises the environment. -The PyHazards adapter keeps a single storm-history to forecast-trajectory interface so it can share the same evaluator as ``hurricast``. +Six LSTM decoders (generators) roll out the next four steps (6, 12, 18, 24 h) of relative displacements. A chooser network gives logits over the six decoders; every sample draws a decoder from them and a 16-d Gaussian noise vector, so the model outputs a set of samples (6 in the paper). The module keeps the official forward signature and outputs (relative steps, GPH frames, chooser logits, sampled decoder indices); ``forecast(batch)`` adds the official post-processing (cumulative sum from the last observation, de-normalisation) and returns latitude / longitude (degrees), pressure (hPa) and wind (m/s) shaped (storms, samples, 4). ``TrajectoryDiscriminator`` is the paper's discriminator. + +Port of the CC BY 4.0 code release (Zenodo 10.5281/zenodo.15024028), with module names unchanged: 4,767,195 generator and 231,009 discriminator parameters, and the released checkpoint loads with ``strict=True`` (``load_tropicyclonenet_checkpoint`` checks its sha256 first). Data: ``tropicyclonenet_dataset`` reads the TCND files in the official loader's layout. + +Metric definition: the paper reports, for each lead time, the smallest error among the 6 samples, taken separately for track distance, pressure and wind (so the three minima can come from different samples), averaged over storms; the track distance uses 111 km per degree with the longitude difference scaled by the cosine of the observed latitude. The PyHazards evaluator reports these as ``best_of_k_*`` (``track_distance: tcn_equirectangular`` gives the paper's distance; the default is great-circle, which differs by well under 1 % at these distances) and, for comparison with single-forecast models, the errors of the sample mean. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Tropical Cyclone Benchmark ` -**Mapped benchmark ecosystems:** :doc:`TropiCycloneNet-Dataset ` +**Mapped benchmark ecosystems:** :doc:`TropiCycloneNet Dataset ` External References ------------------- -**Paper:** `Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ | **Repo:** `Repository `__ +**Paper:** `Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Huang et al. (2025), Nature Communications 16, 5923, Table 4 `_ (`repo `__): The paper's own evaluation on TCND (trained on all six basins, 1950-2016; test 2017-2021): Western Pacific best-of-6 track error 22.98 / 43.83 / 66.41 / 93.76 km and wind error 0.72 / 1.09 / 1.43 / 1.75 m/s at 6 / 12 / 18 / 24 h. Against agency forecasts (12 h / 24 h): North Atlantic 41.79 / 98.22 km and 1.35 / 2.14 m/s (NHC OFCL 39.11 / 58.97 km, 2.97 / 4.42 m/s); Eastern Pacific 29.58 / 70.63 km and 1.22 / 1.97 m/s; Western Pacific 43.83 / 93.76 km (CMA 52.27 / 74.18 km). TCN_M's numbers are best-of-6 errors, the agencies' are single deterministic forecasts. Whether the released 16,000-iteration checkpoint is the one behind Table 4 is not stated; not reproduced by PyHazards. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/xiaochengfuhuo/TropiCycloneNet `__ at ``de9cf0e`` (CC BY 4.0 (Zenodo 10.5281/zenodo.15024028, TropiCycloneNet.zip git b4e7101, whose TCNM/*.py are identical to the pinned GitHub commit up to line endings; the GitHub repository itself has no LICENSE file). Checkpoint checkpoint_with_model_16000.pt: CC BY 4.0, sha256 68575d1d10fcd2d44eba2d54d0625410f5108cd3bf5d7b3e15df7491ba9f6215.) +- **Checked configuration:** TrajectoryGenerator / TrajectoryDiscriminator with the checkpoint's args (obs_len 8, pred_len 4, embedding_dim 32, encoder/decoder h_dim 64, mlp_dim 128, noise_dim (16,), gaussian, noise_mix_type ped, no pooling, pool_every_timestep False, bottleneck_dim 16, batch_norm 0, discriminator h_dim 128), run on the CPU (its .cuda() calls redirected): parameter counts and seeded initial weights equal; the released g_state / d_state load with strict=True; with the same seed the all-decoder outputs, GPH frames, chooser logits, sampled decoder indices and discriminator scores are equal in eval mode, and the all-decoder outputs and BatchNorm statistics in train mode; with official_sample_loop=True the sampled forward pass is equal too; forecast() equals relative_to_abs + toNE; the best-of-k metrics equal evaluate_model_Me.py's per-lead errors; the TCND reader equals TrajectoryDataset + seq_collate. +- **Parameter count:** 4,767,195 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_tropicyclonenet_oracle.py`` +- **Deviation:** Sampling loop: for each sample the official forward visits decoder indices 0 .. (number of distinct sampled indices - 1) instead of the distinct indices themselves, so storms whose sampled decoder is not visited keep the placeholder value 1 for every step (a 1-unit normalised step = 5 degrees of longitude, 50 hPa, 25 m/s); with the evaluation batch of 96 storms this is rare, with small batches common. PyHazards visits the sampled decoders by default; ``official_sample_loop=True`` reproduces the released code exactly (oracle-tested). +- **Deviation:** Device-agnostic: the official code calls .cuda() for hidden states and noise; the port allocates them on the input's device. Noise is still drawn from the CPU generator and moved, as the official torch.randn(...).cuda() does, so seeds give the same noise. The sampled decoder indices are returned as a tensor instead of a numpy array. +- **Deviation:** ``pooling_type`` other than None and ``obs_len`` / ``pred_len`` other than 8 / 4 raise ValueError: the official social-pooling branches are empty (the forward would fail on mismatched sizes), and the GPH U-Net's output length (an 18-step temporal kernel over 28 stacked frames) only fits 8 + 4 steps. +- **Deviation:** ``forward`` also takes a dict (``obs_traj``, ``obs_traj_rel``, ``image_obs``, ``env_data`` or the nine Env-Data keys at the top level, optional ``seq_start_end``, which defaults to one storm per sequence); ``user_noise`` is honoured with ``all_g_out=True`` (the official forward ignores it). +- **Deviation:** Training (GAN losses, best-of-k variety loss, chooser training) is not part of the module. Registry Name ------------- @@ -95,13 +118,19 @@ Programmatic Use .. code-block:: python import torch - from pyhazards.models import build_model + from pyhazards.datasets.tc import synthetic_tcnd_batch + from pyhazards.models import build_model, load_tropicyclonenet_checkpoint - model = build_model(name="tropicyclonenet", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + model = build_model(name="tropicyclonenet", task="regression").eval() + # model = load_tropicyclonenet_checkpoint("checkpoint_with_model_16000.pt").eval() # Zenodo 15024028 + batch = synthetic_tcnd_batch(2)["inputs"] # TCND layout; real data: load_dataset("tropicyclonenet_dataset", root=...) + with torch.no_grad(): + forecast = model.forecast(batch, num_samples=6) + print(forecast["lat"].shape, forecast["wind"].shape) # (2, 6, 4): storms, samples, 6-24 h Notes ----- -- Outputs are lead-time sequences of latitude, longitude, and intensity targets. +- Inputs follow the TCND normalisation: lon = 5 x + 180 (degrees east), lat = 5 y, pressure = 50 p + 960 (hPa), wind = 25 w + 40 (m/s, 2-minute mean); GPH frames are 500 hPa geopotential resized to 64 x 64 and scaled with the range (44490.578125, 58768.4486860389). +- Unused official modules are kept so the checkpoint loads: a second Env-T-Net (env_net), the time_embedding layers of the encoders and decoders. +- The released checkpoint (55.7 MB, CC BY 4.0) is downloaded by the user or the oracle workflow and never bundled; its g_state equals g_best_state, and the official evaluation script loads g_state. diff --git a/docs/source/modules/models_ts_satfire.rst b/docs/source/modules/models_ts_satfire.rst new file mode 100644 index 00000000..87f2dd47 --- /dev/null +++ b/docs/source/modules/models_ts_satfire.rst @@ -0,0 +1,125 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +TS-SatFire Baselines +==================== + +Overview +-------- + +``ts_satfire`` builds one of the next-day wildfire progression baselines of the TS-SatFire dataset, configured as in its prediction script. TS-SatFire is a dataset paper; its prediction baselines are MONAI networks run in 3D over (time, height, width). ``baseline`` selects ``unet3d``, ``attention_unet3d``, ``unetr3d`` or ``swinunetr3d`` (default; the model behind the paper's seed and time-length studies). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``ts_satfire`` builds one of the next-day wildfire progression baselines of the TS-SatFire dataset, configured as in its prediction script. TS-SatFire is a dataset paper; its prediction baselines are MONAI networks run in 3D over (time, height, width). ``baseline`` selects ``unet3d``, ``attention_unet3d``, ``unetr3d`` or ``swinunetr3d`` (default; the model behind the paper's seed and time-length studies). + +Each architecture is also available on its own (``unet3d``, ``attention_unet``, ``unetr``, ``swin_unetr``) with configurable hyperparameters; this entry fixes them to the TS-SatFire values. The input is ``(batch, T, 43, 256, 256)``: 27 VIIRS, weather, forecast, topography and fuel bands with the 17-class land cover one-hot encoded in place, over T in {2, 4, 6} days. The two-class logits are averaged over time to ``(batch, 2, 256, 256)``, as in the script. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ | **Repo:** `Repository `__ + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/zhaoyutim/TS-SatFire `__ at ``da75732`` (none (no LICENSE file; used only as a test oracle; the networks are ported from MONAI 1.3.2, Apache-2.0)) +- **Checked configuration:** run_spatial_temp_model_pred.py with n_channel 43, two classes and T days: UNet and AttentionUnet (spatial_dims=3, channels (64, 128, 256, 512, 1024), strides (1, 2, 2)), UNETR (img_size (T, 256, 256), patch (1, 16, 16), feature size 16, hidden 384, MLP 1536, batch norm) and SwinUNETR (patch (1, 2, 2), window (T, 4, 4), feature size 36 (-ed), 3 heads per stage (-nh), batch norm, attn_version "v1") from the repository's spatial_models, outputs averaged over time. Parameter counts at T = 6, 256x256 (unet3d 31,712,970, attention_unet3d 94,555,506, unetr3d 28,816,866, swinunetr3d 33,191,942; Table 3: 31.7M, 94.5M, 34.8M, 33.2M); names, seeded initialisation and eval / train-mode outputs at T = 2 on 32x32 tiles for CPU speed. +- **Parameter count:** 33,191,942 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_ts_satfire_oracle.py`` +- **Deviation:** The released prediction script cannot build ``unetr3d``: it reads an undefined ``args.unetr_version`` and passes ``kernel_size_up_down=(1, 2, 2)``, which the released unetr.py does not accept (it hard-codes that value). The preset builds the released file's network with the script's default widths (hidden 384, MLP 1536, as in the paper text); ``unetr_version="v0"`` gives the script's alternative 768 / 3072. +- **Deviation:** UNETR feature size: the script uses 16, the paper text says 36 was picked for UNETR and SwinUNETR; the preset follows the script (``feature_size`` overrides it). Table 3's 34.8M for UNETR-3D is the 8-channel AF/BA configuration with feature size 36 (34,806,506 parameters), not the prediction model (28,816,866; 38,282,426 with feature size 36). +- **Deviation:** SwinUNETR's heads per stage (the script's ``-nh``) are not published; the preset uses 3 (``num_heads``). Any of 3, 4, 6 or 12 gives Table 3's 33.2M. +- **Deviation:** TS-SatFire averages the logits over time in its training loop; here that read-out is part of the model (``time_reduction="mean"``), which also takes ``(batch, T, channels, H, W)`` instead of ``(batch, channels, T, H, W)``. + +Registry Name +------------- + +Primary entrypoint: ``ts_satfire`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # SwinUNETR-3D, the paper's reference prediction model, for 6 days of 43 channels. + model = build_model(name="ts_satfire", task="segmentation", baseline="swinunetr3d", history=6) + logits = model(torch.randn(1, 6, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) + + # The other baselines: "unet3d", "attention_unet3d", "unetr3d". + unet = build_model(name="ts_satfire", task="segmentation", baseline="unet3d", history=4) + +Notes +----- + +- Paper Table 3 (prediction, 6 days; F1 / IoU): U-Net-3D 0.375 / 0.338, Attention-U-Net-3D 0.354 / 0.312, UNETR-3D 0.371 / 0.336, SwinUNETR-3D 0.374 / 0.331. Table 4 (SwinUNETR-3D, seeds 42-44): F1 0.371 +/- 0.003, IoU 0.332 +/- 0.003. +- Paper training for prediction: Dice + weighted cross-entropy (1:1, class weights [1, 446.78]) with learning rate 0.001 and batch 64 (U-Net-3D), 4 (UNETR-3D) or 8 (SwinUNETR-3D); Dice loss, learning rate 0.0012 and batch 8 for Attention-U-Net-3D. The released script uses MONAI's DiceLoss(sigmoid=True) with Adam for all four. +- UNETR-3D and SwinUNETR-3D are built for exactly (history, image_size, image_size); the U-Nets need height and width divisible by 16. +- The two output channels are the not-burning / burning one-hot target of TS-SatFire's FireDataset; the script scores channel 1 after a sigmoid and a 0.5 threshold. diff --git a/docs/source/modules/models_unet.rst b/docs/source/modules/models_unet.rst new file mode 100644 index 00000000..88a32804 --- /dev/null +++ b/docs/source/modules/models_unet.rst @@ -0,0 +1,133 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +U-Net +===== + +Overview +-------- + +``unet`` rebuilds the network of the paper's Fig. 1: four 2x2 max-pooling steps and four 2x2 up-convolutions, 64-128-256-512-1024 channels, two unpadded 3x3 convolutions with ReLU per level, concatenation of each up-sampled map with the centre-cropped feature map of the same level, a final 1x1 convolution, dropout (p = 0.5) at the end of the contracting path and the paper's Gaussian initialisation with standard deviation sqrt(2/N). It has 31,030,658 parameters for one input channel and two classes. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``unet`` rebuilds the network of the paper's Fig. 1: four 2x2 max-pooling steps and four 2x2 up-convolutions, 64-128-256-512-1024 channels, two unpadded 3x3 convolutions with ReLU per level, concatenation of each up-sampled map with the centre-cropped feature map of the same level, a final 1x1 convolution, dropout (p = 0.5) at the end of the contracting path and the paper's Gaussian initialisation with standard deviation sqrt(2/N). It has 31,030,658 parameters for one input channel and two classes. + +The paper's valid convolutions make the output smaller than the input (572 x 572 -> 388 x 388); the paper tiles large images with mirrored borders (overlap-tile). ``unet_output_size`` and ``unet_input_size`` in ``pyhazards.models.unet`` give the sizes, and valid inputs are 16k + 60 pixels (k >= 8). ``padding="same"`` zero-pads the 3x3 convolutions so the output keeps the input size, for fixed-size wildfire tiles; that is a PyHazards option, not the paper's network. + +The authors released a Caffe network without a license, so nothing was copied from it. It is used as a test oracle: ``variant="phseg_v5"`` builds the released network (a ReLU after each up-convolution, 128 output channels in the last up-convolution, 31,100,354 parameters), its trained weights load with ``strict=True`` under the Caffe layer names, and the outputs match the release run through OpenCV's Caffe importer. The release also fixed the details the paper leaves open (concatenation order, centred crop, dropout placement, up-convolution initialisation). + +No wildfire study in the PyHazards inventory used this network. WildfireSpreadTS's U-Net is segmentation_models_pytorch's ResNet-18 U-Net (``resnet18_unet``), TS-SatFire's is MONAI's residual-unit UNet (ported separately as ``unet3d``), and Shadrin et al. (2024) cite Ronneberger et al. for a ResNet-18 U-Net with three encoder stages. ``unet`` is the reference architecture. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `U-Net: Convolutional Networks for Biomedical Image Segmentation `_ | **Repo:** `Repository `__ + +Reproduction +------------ + +- **Reference implementation:** `https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/u-net-release-2015-10-02.tar.gz `__ (``u-net-release-2015-10-02``, no license stated; fetched at test time only, nothing copied); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** Paper Fig. 1 and Sections 2-3: 1 input channel, 2 classes, 572 x 572 input -> 388 x 388 output, feature maps 568/280/136/64/28 on the contracting path and 52/100/196/388 on the expansive path. The oracle test checks the released phseg_v5 network (``variant="phseg_v5"``): every layer of phseg_v5-train.prototxt against the module of the same name, the release's patched Gaussian weight filler, loading of phseg_v5.caffemodel with strict=True (31,100,354 parameters), and outputs against OpenCV 4.10's Caffe runtime on a random 572 x 572 tile and on the first 444 x 892 tile of the release's sample image (max abs difference about 1e-5 for outputs up to 11). +- **Parameter count:** 31,030,658 +- **Verified:** parameter count, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_unet_oracle.py`` +- **Deviation:** The default follows the paper's Fig. 1 where it and the release differ: the release applies a ReLU after every up-convolution and gives its last up-convolution 128 output channels instead of 64 (31,100,354 instead of 31,030,658 parameters); ``variant="phseg_v5"`` reproduces it. +- **Deviation:** Input sizes for which a 2x2 max-pooling would see an odd size raise ValueError: the paper requires even sizes there (Sec. 2) and the release's tiling script only uses such sizes. On other sizes the release's Caffe would still run, pooling in ceil mode and cropping with fixed offsets, so its skip connections would be misaligned by half a pixel. +- **Deviation:** ``padding="same"`` (zero-padded 3x3 convolutions, input divisible by 16, output size equal to the input) is a PyHazards option for fixed-size wildfire tiles and is not in the paper. + +Registry Name +------------- + +Primary entrypoint: ``unet`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + from pyhazards.models.unet import unet_input_size, unet_output_size + + # The paper's network: valid convolutions, 572 x 572 tile -> 388 x 388 two-class logits. + model = build_model(name="unet", task="segmentation", in_channels=1, out_channels=2).eval() + print(unet_output_size(572), unet_input_size(388)) # 388 572 + with torch.no_grad(): + print(model(torch.randn(1, 1, 572, 572)).shape) # (1, 2, 388, 388) + + # Same-size output for 64 x 64 wildfire tiles (not the paper's valid convolutions). + tiles = build_model(name="unet", task="segmentation", in_channels=12, out_channels=1, padding="same") + print(tiles(torch.randn(2, 12, 64, 64)).shape) # (2, 1, 64, 64) + +Notes +----- + +- Returns logits. The paper's energy function is a pixel-wise softmax with a weighted cross-entropy (class-balancing weights plus a border term with w0 = 10 and sigma = 5 pixels); the weight map depends on instance labels and is not part of the model. +- Module names follow the Caffe layer names of the release (conv_d0a-b -> conv_d0a_b, upconv_d4c_u3a, ..., conv_u0d-score -> conv_u0d_score). The up-sampled map comes first in each concatenation, then the skip feature. +- Dropout (p = 0.5, training only) follows the last ReLU of the 512- and 1024-channel levels. As in the release, where it is applied in place, the dropped-out 512-channel map also feeds the skip connection. +- Weights are drawn from N(0, 2/n) with n the number of weights per output unit and biases start at zero, as in the release's patched Caffe filler. For the 2x2 up-convolutions this is n = 4 x output channels. +- Training in the paper: SGD with momentum 0.99, one large tile per batch, elastic-deformation augmentation. Reported results: ISBI 2012 EM segmentation warping error 0.000353 and Rand error 0.0382; ISBI 2015 cell tracking IoU 0.9203 (PhC-U373) and 0.7756 (DIC-HeLa). +- The model takes (batch, channels, height, width); stack time steps into channels for multi-day wildfire input. diff --git a/docs/source/modules/models_unet3d.rst b/docs/source/modules/models_unet3d.rst new file mode 100644 index 00000000..8905acd5 --- /dev/null +++ b/docs/source/modules/models_unet3d.rst @@ -0,0 +1,134 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +U-Net-3D (MONAI) +================ + +Overview +-------- + +``unet3d`` is MONAI's ``UNet``: an encoder-decoder in which each level down-samples with one strided convolution and up-samples with one strided transposed convolution applied to the concatenation of the skip feature and the up-sampled deeper feature, each followed by instance norm, dropout and PReLU. MONAI documents it as the "enhanced" residual U-Net of Kerfoot et al. (2018); with ``num_res_units > 0`` every unit becomes a residual unit. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``unet3d`` is MONAI's ``UNet``: an encoder-decoder in which each level down-samples with one strided convolution and up-samples with one strided transposed convolution applied to the concatenation of the skip feature and the up-sampled deeper feature, each followed by instance norm, dropout and PReLU. MONAI documents it as the "enhanced" residual U-Net of Kerfoot et al. (2018); with ``num_res_units > 0`` every unit becomes a residual unit. + +TS-SatFire calls it U-Net / U-Net-3D, but with ``num_res_units=0`` (its setting) it is neither Ronneberger et al.'s U-Net nor Cicek et al.'s 3D U-Net (2016): there is one convolution per level and side instead of two, no max pooling, no batch norm and no residual connection. The port follows MONAI 1.3.2 with its parameter names, so MONAI state dicts load with ``strict=True``. + +With the defaults (``spatial_dims=3``) the model is TS-SatFire's U-Net-3D: input ``(batch, time, channels, H, W)``, 3D convolutions over (time, H, W) with stride (1, 2, 2) at every level so time is never down-sampled, widths 64-1024, and two-class logits averaged over time to ``(batch, 2, H, W)``. ``spatial_dims=2`` gives TS-SatFire's single-image U-Net (stride 2 at every level, input ``(batch, channels, H, W)``). + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `Left-Ventricle Quantification Using Residual U-Net `_ | **Repo:** `Repository `__ + +Used In +------- + +- `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ (`repo `__): U-Net-3D from the repository's modified MONAI copy (channels 64-1024, stride (1, 2, 2) at every level, num_res_units 0) on 256x256 tiles of daily VIIRS and auxiliary data, 43 channels after the land-cover one-hot for next-day progression prediction, T in {2, 4, 6}, logits averaged over time; prediction trained with Dice + weighted CE (1:1, class weights [1, 446.78]), learning rate 0.001, batch 64 (paper text). Paper Table 3 (6 input days; arXiv 2412.11555): 31.7M parameters, F1 0.748 / 0.834 / 0.375 and IoU 0.628 / 0.746 / 0.338 on active fire / burned area / prediction. The 2D U-Net (stock MONAI, stride 2) has 10.6M parameters and F1 0.731 / 0.789 on active fire / burned area. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Project-MONAI/MONAI `__ at ``1.3.2`` (Apache-2.0) +- **Checked configuration:** TS-SatFire's UNet(spatial_dims=3, in_channels=43, out_channels=2, channels=(64, 128, 256, 512, 1024), strides=(1, 2, 2)) from spatial_models/unet.py at da75732 (MONAI 1.3.2 code whose only change is one stride shared by all levels; the repository has no license and is used only as a test oracle), with its outputs averaged over time; MONAI 1.3.2 UNet(spatial_dims=2, in_channels=8, out_channels=2, same channels, strides=(2, 2, 2, 2)) for the 2D baseline (10,552,458 parameters); and 1D/2D/3D MONAI configurations with residual units, batch norm, ReLU, dropout, larger kernels and non-uniform per-level strides. Forward passes use 32x32 (3D, T=2) and 64x64 (2D) inputs instead of 256x256 to keep the CPU test fast. +- **Parameter count:** 31,712,970 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_unet3d_oracle.py`` +- **Deviation:** TS-SatFire averages the 3D logits over time in its training script (``outputs.mean(2)``); here that read-out is part of the model (``time_reduction="mean"``), which also takes PyHazards' ``(batch, time, channels, H, W)`` layout instead of ``(batch, channels, time, H, W)``. +- **Deviation:** Activations and norms are given by name and limited to ``"prelu"`` / ``"relu"`` and ``"instance"`` / ``"batch"`` (or ``None``); MONAI also accepts other layer names and ``(name, kwargs)`` tuples. ``dropout`` is a rate (MONAI's default ``dropout_dim=1``). +- **Deviation:** Configurations the reference rejects late or not at all -- too few strides, even kernel sizes, spatial sizes not divisible by the stride product (a size-mismatch RuntimeError in the reference) -- raise ValueError up front. +- **Deviation:** The paper reports 31.7M parameters for U-Net-3D across all three tasks; the prediction configuration with 43 input channels has 31,712,970 (31,652,490 with the 8-channel active-fire / burned-area input). + +Registry Name +------------- + +Primary entrypoint: ``unet3d`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # TS-SatFire U-Net-3D prediction model: 43 channels, logits averaged over the input days. + model = build_model(name="unet3d", task="segmentation", in_channels=43) + logits = model(torch.randn(1, 4, 43, 64, 64)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 64, 64) + + # TS-SatFire's single-image 2D U-Net. + model_2d = build_model(name="unet3d", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 64, 64)).shape) # (1, 2, 64, 64) + +Notes +----- + +- Every spatial size must be divisible by the product of the strides along that dimension: 16 for height and width with the default four levels; time is never down-sampled. +- The default two output channels follow TS-SatFire (sigmoid Dice loss on both in its released script); use out_channels=1 for a single-logit binary head. +- time_reduction='none' returns per-date maps (batch, classes, time, H, W), as TS-SatFire uses for its active-fire and burned-area tasks. +- strides follow MONAI (one entry per level, each an int or one value per dimension); stride_mode='shared' takes TS-SatFire's single strides=(1, 2, 2) literally and builds the same network as strides=[(1, 2, 2)] * 4. +- The top decoder unit is a bare transposed convolution (no norm or activation), so the output is unnormalised logits, as in MONAI. diff --git a/docs/source/modules/models_unetr.rst b/docs/source/modules/models_unetr.rst new file mode 100644 index 00000000..c33f1732 --- /dev/null +++ b/docs/source/modules/models_unetr.rst @@ -0,0 +1,127 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +UNETR +===== + +Overview +-------- + +``unetr`` is UNETR (Hatamizadeh et al., WACV 2022): a 12-layer ViT encodes non-overlapping patches, and the tokens of layers 3, 6, 9 and 12 are reshaped to feature maps, up-sampled by transposed convolutions and merged into a convolutional decoder with residual blocks. The implementation is MONAI's (1.3.2, Apache-2.0; the authors' official code builds on it), ported to plain PyTorch with MONAI's module names, so MONAI state dicts load with ``strict=True``. + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Segmentation + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``unetr`` is UNETR (Hatamizadeh et al., WACV 2022): a 12-layer ViT encodes non-overlapping patches, and the tokens of layers 3, 6, 9 and 12 are reshaped to feature maps, up-sampled by transposed convolutions and merged into a convolutional decoder with residual blocks. The implementation is MONAI's (1.3.2, Apache-2.0; the authors' official code builds on it), ported to plain PyTorch with MONAI's module names, so MONAI state dicts load with ``strict=True``. + +With the defaults (``spatial_dims=3``) the model is TS-SatFire's UNETR-3D: input ``(batch, time, channels, H, W)`` built for ``img_size = (history, 256, 256)``, patches of (1, 16, 16) so that tokens never span several days, (1, 2, 2) transposed convolutions, a (1, 3, 3) kernel in ``decoder3``, feature size 16, hidden size 384, MLP 1536, batch norm, and two-class logits averaged over time. ``spatial_dims=2`` gives TS-SatFire's UNETR-2D, which is stock MONAI (patch 16) with the same widths. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `UNETR: Transformers for 3D Medical Image Segmentation `_ | **Repo:** `Repository `__ + +Used In +------- + +- `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ (`repo `__): UNETR-3D from the repository's modified MONAI copy (patch (1, 16, 16), (1, 2, 2) up-sampling, (1, 3, 3) decoder3 kernel) on 256x256 tiles of daily VIIRS and auxiliary data, 43 channels for next-day progression prediction, T in {2, 4, 6}, logits averaged over time; prediction trained with Dice + weighted CE (1:1, class weights [1, 446.78]), learning rate 0.001, batch 4 (paper text). The paper picks feature size 36 for UNETR and SwinUNETR, but its prediction script builds UNETR-3D with feature size 16. Paper Table 3 (6 input days; arXiv 2412.11555): 34.8M parameters, F1 0.811 / 0.823 / 0.371 and IoU 0.706 / 0.736 / 0.336 on active fire / burned area / prediction. UNETR-2D (stock MONAI, hidden 384, MLP 1536, feature size 16) has 23.52M parameters and F1 0.733 / 0.837 on active fire / burned area. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Project-MONAI/MONAI `__ at ``1.3.2`` (Apache-2.0) +- **Checked configuration:** TS-SatFire's UNETR(in_channels=43, out_channels=2, img_size=(T, H, W), spatial_dims=3, norm_name="batch", feature_size=16, patch_size=(1, 16, 16), hidden_size=384, mlp_dim=1536) from spatial_models/unetr/unetr.py at da75732 (MONAI 1.3.2 code with a patch_size argument and hard-coded (1, 2, 2) up-sampling and (1, 3, 3) decoder3 kernel; the repository has no license and is used only as a test oracle), with its outputs averaged over time, built for (T, H, W) = (2, 32, 32) for the forward checks and at (6, 256, 256) on the meta device for the parameter counts (28,816,866 for prediction; 34,806,506 for the 8-channel, feature-size-36 AF/BA configuration); MONAI 1.3.2 UNETR(spatial_dims=2, in_channels=8, feature_size=16, hidden_size=384, mlp_dim=1536, norm_name="batch") for the 2D baseline (23,521,186 parameters at 256x256, forward at 64x64); and 2D/3D MONAI configurations with instance norm, dropout, qkv bias, perceptron patch embedding, plain blocks and attention-matrix saving. +- **Parameter count:** 28,816,866 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_unetr_oracle.py`` +- **Deviation:** The released TS-SatFire unetr.py has no ``kernel_size_up_down`` argument: it hard-codes (1, 2, 2) for every transposed convolution, while the prediction script passes ``kernel_size_up_down=(1, 2, 2)`` (and reads an undefined ``args.unetr_version``), so the script cannot build UNETR-3D as released. Here ``kernel_size_up_down`` is an argument (MONAI's 2 by default); at (1, 2, 2) it gives the released file's network exactly. +- **Deviation:** Feature size: the paper says 36 was picked for UNETR and SwinUNETR, the prediction script uses 16. The defaults follow the prediction script. Table 3's 34.8M is the AF/BA configuration of the paper text (8 channels, feature size 36, T = 6: 34,806,506 parameters); the prediction configuration has 28,816,866 (38,282,426 with feature size 36). +- **Deviation:** TS-SatFire averages the 3D logits over time in its training script; here that read-out is part of the model (``time_reduction="mean"``), which also takes ``(batch, time, channels, H, W)`` instead of ``(batch, channels, time, H, W)``. +- **Deviation:** The ViT classification head (``classification=True``) is not ported because UNETR never builds it; the deprecated ``pos_embed`` argument is dropped. Inputs must have exactly ``img_size`` (ValueError; the reference fails with a shape error), and configurations whose decoder could not return to the input resolution (patch size not equal to ``kernel_size_up_down ** 4``) raise ValueError up front. + +Registry Name +------------- + +Primary entrypoint: ``unetr`` + +Supported Tasks +--------------- + +- Segmentation + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + # TS-SatFire UNETR-3D prediction model for 4 days of 43 channels on 256x256 tiles. + model = build_model(name="unetr", task="segmentation", in_channels=43, history=4) + logits = model(torch.randn(1, 4, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) + +Notes +----- + +- The position embedding fixes the input size: the model is built for img_size = (history, image_size, image_size) and accepts only that size. +- Each patch-size entry must equal kernel_size_up_down ** 4 (16 = 2 ** 4 in height and width, 1 = 1 ** 4 in time), so the four up-sampling steps return to the input resolution. +- Pass hidden_size=768, mlp_dim=3072 for the prediction script's 'v0' widths or MONAI's defaults (also norm_name='instance'). +- time_reduction='none' returns per-date maps (batch, classes, time, H, W). diff --git a/docs/source/modules/models_urbanfloodcast.rst b/docs/source/modules/models_urbanfloodcast.rst index 6d52cdb2..08b9dc0a 100644 --- a/docs/source/modules/models_urbanfloodcast.rst +++ b/docs/source/modules/models_urbanfloodcast.rst @@ -6,7 +6,7 @@ UrbanFloodCast Overview -------- -``urbanfloodcast`` adds an urban-focused raster baseline to the PyHazards inundation benchmark stack. +``urbanfloodcast`` is the DNO of the paper (DNO-3, the default of the official code): the 5 inputs per cell and output step (current depth and x / y unit discharge, the rainfall of that step and the terrain) plus a (y, x, t) grid are lifted to width 10, passed through three U-NO operator blocks (spectral convolution + point-wise MLP + point-wise linear branch, InstanceNorm, GELU) that go to 3/4 of the spatial grid, then to twice the time steps, then back to the input grid with concatenated skips, and projected to depth and the two discharges: ``(batch, Sy, Sx, T, 1, 5)`` -> ``(batch, Sy, Sx, T, 3)``, all ``T`` (24, i.e. 2 hours) steps in one shot. 4,470,437 parameters (complex Fourier weights counted once; 8,937,637 real numbers). Like any Fourier operator it accepts other grid sizes (``Sy, Sx >= 27``, ``T >= 14`` for its fixed modes). At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Inundation + Forecasting .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,40 @@ At a Glance Description ----------- -``urbanfloodcast`` adds an urban-focused raster baseline to the PyHazards inundation benchmark stack. +``urbanfloodcast`` is the DNO of the paper (DNO-3, the default of the official code): the 5 inputs per cell and output step (current depth and x / y unit discharge, the rainfall of that step and the terrain) plus a (y, x, t) grid are lifted to width 10, passed through three U-NO operator blocks (spectral convolution + point-wise MLP + point-wise linear branch, InstanceNorm, GELU) that go to 3/4 of the spatial grid, then to twice the time steps, then back to the input grid with concatenated skips, and projected to depth and the two discharges: ``(batch, Sy, Sx, T, 1, 5)`` -> ``(batch, Sy, Sx, T, 3)``, all ``T`` (24, i.e. 2 hours) steps in one shot. 4,470,437 parameters (complex Fourier weights counted once; 8,937,637 real numbers). Like any Fourier operator it accepts other grid sizes (``Sy, Sx >= 27``, ``T >= 14`` for its fixed modes). -The implementation keeps the shared spatiotemporal tensor contract used by the synthetic inundation smoke dataset. +The official repository has no licence, so the model is written from the paper and from U-NO (BSD-2) and FNO (MIT) building blocks; parameter names follow the official model, whose state dicts load with ``strict=True``, and parameters, seeded initialisation, outputs and gradients equal the official code. + +Data: :func:`pyhazards.datasets.flood.urbanfloodcast.prepare_urbanfloodcast_event` builds the official one-shot inputs from an event tensor (checked against the official ``flood_data``). PyHazards does not read the Berlin benchmark rasters yet (Zenodo 10.5281/zenodo.15700880, 7.3 GB GeoTIFF, CC BY 4.0); ``urbanfloodcast_synthetic`` generates random events in the same layout. The flood benchmark scores relative L2, NSE, Pearson r and depth CSI at 1 / 10 / 50 cm as the official test loop does. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Flood Benchmark ` -**Mapped benchmark ecosystems:** :doc:`FloodCastBench ` - External References ------------------- -**Paper:** `UrbanFloodCast: WMO Urban Flooding Forecasting Challenge `_ | **Repo:** `Repository `__ +**Paper:** `Urban flood modeling and forecasting with deep neural operator and transfer learning `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Urban flood modeling and forecasting with deep neural operator and transfer learning `_ (`repo `__): Xu, De Vos, Shi, Rüther, Bronstert and Zhu, Journal of Hydrology 661:133705 (2025). UrbanFloodCast benchmark: hydrodynamic simulations of 125 design storms over two areas of Berlin (seen regions / unseen rainfall events, unseen rainfall distributions, zero-shot downscaling), 24 future 5-minute steps from the current state. Official training (DNO_main.py): batch 1, 100 epochs, Adam 1e-3 with weight decay 1e-4, cosine annealing per step, relative L2 loss on the masked outputs. The paper is paywalled and was not read, so its numbers (and which DNO variant it headlines) are not reproduced. +- `U-NO: U-shaped Neural Operators `_ (`repo `__): Rahman, Ross and Azizzadenesheli, arXiv:2204.11127 (2022). Source of the operator blocks (integral_operators.py, BSD-2-Clause) that the DNO extends with a point-wise MLP branch. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/HydroPML/UrbanFloodCast `__ (``f08846a``, none (no licence; used only as a test oracle, never vendored)); not ported, the model is rebuilt from the paper and the release serves as a test oracle. +- **Paper configuration:** DNO/models/DNO.py (DNO-3) as DNO_main.py builds it: DNO(num_channels=5, width=10, initial_step=1, pad=False, factor=1) after torch.manual_seed(1); inputs (batch, 433, 692, 24, 1, 5) for Berlin, T=24, strategy oneshot. Data pipeline and metrics: DNO/utils25.py (flood_data, LpLoss, nse, corr, critical_success_index). +- **Parameter count:** 4,470,437 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_urbanfloodcast_oracle.py`` +- **Deviation:** Only ``pad=0`` (the default) is supported: the official ``--time_pad`` option overwrites the padding on every call and crops twice the padded length, so the output no longer has T steps and the official training script fails with it. +- **Deviation:** The deeper DNO-4 and DNO-5 variants of the repository and the transfer-learning models (fine-tuning and domain-adaptation TL-DNO with its discriminator) are not provided. +- **Deviation:** The point-wise branch of each operator block is a 1x1x1 convolution plus trilinear resampling, as in the DNO; the current U-NO code additionally low-pass filters it. +- **Deviation:** No official weights were released, so no pretrained checkpoint is checked. Registry Name ------------- @@ -87,7 +106,7 @@ Primary entrypoint: ``urbanfloodcast`` Supported Tasks --------------- -- Inundation +- Forecasting Programmatic Use ---------------- @@ -97,11 +116,14 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model(name="urbanfloodcast", task="regression", in_channels=3, history=4) - preds = model(torch.randn(2, 4, 3, 16, 16)) - print(preds.shape) + model = build_model(name="urbanfloodcast", task="regression") # DNO-3, 4,470,437 parameters + x = torch.randn(1, 32, 32, 24, 1, 5) # (batch, Sy, Sx, T, T_in, depth / qx / qy / rainfall / terrain) + print(model(x).shape) # (1, 32, 32, 24, 3): depth, qx, qy at every future step Notes ----- -- Outputs are next-horizon inundation depth rasters. +- Input quirks of the official pipeline, kept by ``prepare_urbanfloodcast_event``: the terrain is L2-normalised along the x axis (``F.normalize`` over dimension 1); missing terrain is meant to be set to ``max + 30`` but ``torch.max`` propagates NaN, so a missing terrain cell turns the whole terrain channel to NaN (the official TIFF conversion fills the DEM first). + +- Pearson r of the official evaluation divides the population covariance by the product of sample standard deviations; the benchmark reproduces it. + diff --git a/docs/source/modules/models_utae.rst b/docs/source/modules/models_utae.rst new file mode 100644 index 00000000..93f682c4 --- /dev/null +++ b/docs/source/modules/models_utae.rst @@ -0,0 +1,126 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +U-TAE +===== + +Overview +-------- + +``utae`` encodes every date of a satellite image time series with a shared convolutional encoder, collapses time at the lowest resolution with a Lightweight Temporal Attention Encoder (L-TAE), reuses the attention masks to aggregate the skip connections, and decodes to per-pixel scores (Sainte Fare Garnot & Landrieu, ICCV 2021). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 1 + + .. container:: catalog-stat-note + + Spread + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``utae`` encodes every date of a satellite image time series with a shared convolutional encoder, collapses time at the lowest resolution with a Lightweight Temporal Attention Encoder (L-TAE), reuses the attention masks to aggregate the skip connections, and decodes to per-pixel scores (Sainte Fare Garnot & Landrieu, ICCV 2021). + +The implementation is a port of the official utae-paps code, which WildfireSpreadTS vendors unchanged. Parameter names match the reference, so the official PASTIS checkpoints load with ``strict=True``. Acquisition dates go in ``batch_positions`` (day of year in WildfireSpreadTS); when omitted, ``0..T-1`` is used. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` + +External References +------------------- + +**Paper:** `Panoptic Segmentation of Satellite Image Time Series with Convolutional Temporal Attention Networks `_ | **Repo:** `Repository `__ + +Used In +------- + +- `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ (`repo `__): Default U-TAE with out_conv (32, 1), 5 days x 40 channels with day-of-year positions, BCE with positive-class weight, AdamW lr 0.01; best baseline in the paper (test AP 0.372 on vegetation features). + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/VSainteuf/utae-paps `__ at ``987874e`` (MIT) +- **Checked configuration:** UTAE(input_dim=40, out_conv=[32, 1]) with the remaining defaults (WildfireSpreadTS), and UTAE(input_dim=10, out_conv=[32, 20]) loaded with the official PASTIS fold-1 weights (Zenodo 5172293, CC-BY-4.0). +- **Parameter count:** 1,099,011 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_wildfirespreadts_oracle.py`` +- **Deviation:** To read the output shape for padded dates, the reference runs each shared encoder block once more on an all-zero batch. That pass is skipped here; with the default GroupNorm it has no effect on outputs. + +Registry Name +------------- + +Primary entrypoint: ``utae`` + +Supported Tasks +--------------- + +- Spread + +Programmatic Use +---------------- + +.. code-block:: python + + import torch + from pyhazards.models import build_model + + model = build_model(name="utae", task="segmentation", in_channels=40) + x = torch.randn(2, 5, 40, 128, 128) + day_of_year = torch.tensor([[150, 151, 152, 153, 154]] * 2, dtype=torch.float32) + scores = model(x, batch_positions=day_of_year) + print(scores.shape) # (2, 1, 128, 128) + +Notes +----- + +- Height and width must be divisible by 8 with the default three down-sampling stages. +- As in the reference code, the output block ends with BatchNorm and ReLU, so scores are non-negative. +- Dates whose frame equals pad_value (default 0) everywhere are treated as padding. diff --git a/docs/source/modules/models_wavecastnet.rst b/docs/source/modules/models_wavecastnet.rst index 51a41fef..4475e579 100644 --- a/docs/source/modules/models_wavecastnet.rst +++ b/docs/source/modules/models_wavecastnet.rst @@ -6,7 +6,7 @@ WaveCastNet Overview -------- -``wavecastnet`` is the PyHazards entrypoint for dense-grid earthquake wavefield forecasting based on the ConvLEM encoder-decoder design described by Lyu et al. (2025). +``wavecastnet`` maps a wavefield history ``(batch, 3, time, height, width)`` to the next ``future_seq`` frames ``(batch, 3, future_seq, height, width)``. Every frame is embedded by three stride-2 ``Conv2d -> BatchNorm2d -> LeakyReLU`` layers (3 -> 36 -> 72 -> 144 channels, grid / 8); two stacked ConvLEM cells with reset gate and per-pixel peepholes encode the sequence, two more, started from the encoder states, decode the forecast; each latent frame is reconstructed by a transposed convolution, ``PixelShuffle(4)`` and a 3x3 convolution. ``variant="sparse"`` (``AEConvLEM_sparse``) reads the wavefield at station grid points, zeroes a random subset of the stations (masked-autoencoder training, also applied in evaluation) and embeds the station vector with two fully connected layers and two convolutions. At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Wavefield Forecasting + Forecasting .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,21 +63,39 @@ At a Glance Description ----------- -``wavecastnet`` is the PyHazards entrypoint for dense-grid earthquake wavefield forecasting based on the ConvLEM encoder-decoder design described by Lyu et al. (2025). +``wavecastnet`` maps a wavefield history ``(batch, 3, time, height, width)`` to the next ``future_seq`` frames ``(batch, 3, future_seq, height, width)``. Every frame is embedded by three stride-2 ``Conv2d -> BatchNorm2d -> LeakyReLU`` layers (3 -> 36 -> 72 -> 144 channels, grid / 8); two stacked ConvLEM cells with reset gate and per-pixel peepholes encode the sequence, two more, started from the encoder states, decode the forecast; each latent frame is reconstructed by a transposed convolution, ``PixelShuffle(4)`` and a 3x3 convolution. ``variant="sparse"`` (``AEConvLEM_sparse``) reads the wavefield at station grid points, zeroes a random subset of the stations (masked-autoencoder training, also applied in evaluation) and embeds the station vector with two fully connected layers and two convolutions. -This implementation focuses on the core dense-grid forecasting path and keeps data loading outside the model so users can adapt it to their own simulation or sensor pipelines. +It is a port of the official PyTorch code with the official parameter names, creation order and initialisation. The released dense checkpoint ``best_lem_dense_.pt`` loads with ``strict=True`` (``pretrained="dense"``) and reproduces the official outputs. As in the official code, the decoder's first input is uniform random noise in training and evaluation, so forecasts are random: pass ``generator=torch.Generator().manual_seed(...)`` (or ``decoder_noise=``) to ``forward`` / ``rollout`` for repeatable outputs. ``rollout`` repeats the forecast on its own output like the official validation (30 input frames, six calls of 30 frames and one of 15: 101.4 s at 0.52 s per frame). ``WaveCastNetLoss`` is the official training loss and ``pyhazards.metrics.wavefield`` the official ACC / RFNE / RMSE. Benchmark Compatibility ----------------------- **Primary benchmark family:** :doc:`Earthquake Benchmark ` -**Mapped benchmark ecosystems:** :doc:`AEFA `, :doc:`pyCSEP ` - External References ------------------- -**Paper:** `Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning `_ +**Paper:** `Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning (Lyu et al., Nature Communications 16:10622, 2025; arXiv:2405.20516) `_ (`repo `__): SW4 viscoelastic simulations (<= 0.5 Hz) of 960 point sources (M < 4.5) on the Hayward fault, X / Y / Z velocities on a 344 x 224 grid (300 m), 0.26 s sampling, split by epicentre per depth (README: 300 training, 45 validation, 30 test events). Table 1a, 5.7 s after the onset, ACC / RFNE: dense input 0.98 / 0.20, sparse input (101 ShakeAlert stations) 0.93 / 0.36. Table 1b (finite-fault ruptures): M4.5 0.95 / 0.35 down to M7.0 0.53 / 0.86. The data (all_test.npy 16 GB, all_validation.npy 24 GB, larger training file; shapes (events, 3, 376, 256, 461), cropped to 344 x 224 by the official loader) are on the authors' Google Drive; PyHazards has no reader for them yet. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/dwlyu/WaveCastNet `__ at ``c859e04`` (MIT (code; Copyright (c) 2023 dwlyu). The Google Drive checkpoints carry no licence statement.) +- **Checked configuration:** ``AEConvLEM_dense(dt=1, num_channels=3, num_kernels=144, kernel_size=(3, 3), padding=(1, 1), activation="tanh", frame_size=(43, 28))`` and ``AEConvLEM_sparse(..., mask_mode=1, mask_ratio=1 - 101/564)`` from ``src/models_earthquake`` (README and load_pretrained_model.ipynb), ``Huber`` of ``earthquake_train.py`` and ``Validation_pixel.py``. Dense: 10,093,242 parameters (embedding 209,844, reconstruction 331,920, four ConvLEM cells of 2,387,808, output convolution 246); sparse with the 564 stations of filtered_coord.npy: 16,535,430. Checked: names and shapes, seeded initialisation, outputs in evaluation and training mode (exactly equal), batch-norm statistics and gradients, the rolling validation forecast, the two cell variants, the released dense checkpoint (strict load, equal outputs), the released sparse checkpoint (strict load with 558 stations, equal outputs), the loss and the metrics. +- **Parameter count:** 10,093,242 +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs, official pretrained weights +- **Oracle test:** ``tests/oracle/test_wavecastnet_oracle.py`` +- **Deviation:** The released sparse checkpoint ``best_lem_irr_mask_shakealert_.pt`` was trained on 558 stations, but the repository's ``filtered_coord.npy`` lists 564 (the paper mentions 558), and the 101 ShakeAlert stations (``shakealert_coords.npy``) are not a subset of them; how they were fed to the model is not in the released code. The checkpoint therefore cannot be used for real forecasts and is not offered by ``pretrained``; it is only loaded in the oracle test (with 558 arbitrary stations). +- **Deviation:** Station masking is one uniform draw per (sample, station) compared with ``mask_ratio`` (the code), not an exact 80 % without replacement (the paper's wording). ``station_mask=`` replaces the draw. +- **Deviation:** Without masking (``mask_mode=False``) the official ``Encoder1d`` calls a removed attention layer and crashes; the port then uses all stations unmasked. +- **Deviation:** Station coordinates, the grid size and the horizon are constructor arguments instead of hard-coded NERSC paths and the 344 x 224 grid; the sparse layers scale with the grid (hidden width ``(H/4)(W/4)/4``); only the official sizes are checked. ``num_kernels`` must equal ``48 * channels`` as in the official embedding. +- **Deviation:** The diagnostic ``return_dt`` output (gate histograms) is not ported; outputs are stacked instead of written into a float32 zero tensor (same values for float32 inputs). +- **Deviation:** Training is not part of the module: the official script uses Adam (learning rate 5e-4), StepLR (25 epochs, gamma 0.5), 100 epochs, batch 64, 30-frame inputs and targets subsampled by 2 from 461-step sequences, the delta-0.2 Huber variant, and keeps the weights with the lowest validation loss. Registry Name ------------- @@ -87,7 +105,7 @@ Primary entrypoint: ``wavecastnet`` Supported Tasks --------------- -- Wavefield Forecasting +- Forecasting Programmatic Use ---------------- @@ -97,25 +115,22 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="wavecastnet", - task="regression", - in_channels=3, - height=32, - width=24, - temporal_in=6, - temporal_out=4, - hidden_dim=32, - num_layers=1, - dropout=0.0, - ) - - x = torch.randn(2, 3, 6, 32, 24) - y = model(x) - print(y.shape) + # Official dense checkpoint (no licence stated), downloaded and checked by sha256 on first use: + # model = build_model(name="wavecastnet", task="forecasting", pretrained="dense") + model = build_model(name="wavecastnet", task="forecasting", height=64, width=48, future_seq=4).eval() + + history = torch.randn(1, 3, 6, 64, 48) # (batch, X/Y/Z velocity, time, height, width) + with torch.no_grad(): + forecast = model(history, generator=torch.Generator().manual_seed(0)) # (1, 3, 4, 64, 48) + long = model.rollout(history, 10, generator=torch.Generator().manual_seed(0)) # (1, 3, 10, 64, 48) + print(forecast.shape, long.shape) Notes ----- -- The PyHazards version currently targets dense-grid forecasting rather than the paper's sparse-sensor variants. -- The smoke test uses reduced spatial and temporal sizes so it stays CPU-safe in CI. +- Lyu, Nakata, Ren, Mahoney, Pitarka, Nakata & Erichson, Nature Communications 16:10622 (2025); arXiv:2405.20516. Official code: dwlyu/WaveCastNet (MIT). +- Forecasts are random because the decoder starts from uniform noise (official behaviour, also in evaluation); the earthquake.forecasting benchmark passes a seeded generator (param ``seed``). +- The official model is tied to its grid: height and width must be multiples of 8 and equal the construction values (per-pixel peepholes on the H/8 x W/8 latent grid). +- ``WaveCastNetLoss()`` is the training loss of the code (Huber variant with delta 0.2: standard Huber / delta + delta / 2); ``variant='paper'`` gives equation (4) of the paper. +- WaveCastNet forecasts ground-motion wavefields. It is not related to AEFA (an earthquake-occurrence forecasting dataset) or pyCSEP (tests of earthquake-rate forecasts), which earlier versions of the catalog linked to it. +- Breaking change: the former builder arguments ``temporal_in``, ``temporal_out``, ``hidden_dim``, ``num_layers`` and ``dropout`` are gone (any input length, horizon ``future_seq``), the task is ``forecasting`` (``regression`` still accepted) and ``ConvLEMCell`` takes ``frame_size`` and uses the official parameter names. diff --git a/docs/source/modules/models_wildfire_aspp.rst b/docs/source/modules/models_wildfire_aspp.rst index 1f411824..b1651479 100644 --- a/docs/source/modules/models_wildfire_aspp.rst +++ b/docs/source/modules/models_wildfire_aspp.rst @@ -6,7 +6,7 @@ CNN-ASPP Overview -------- -``wildfire_aspp`` is the backward-compatible public PyHazards entrypoint for the CNN + ASPP wildfire spread model. +``wildfire_aspp`` reimplements CNN-ASPP (Marjani et al., IEEE GRSL 2024): two 3x3 convolutions with 64 and 128 filters, four parallel 3x3 atrous convolutions with 32 filters and dilation rates 1, 3, 6 and 12, two 3x3 convolutions with 32 filters, batch normalisation and a 1x1 output convolution, all at full 64x64 resolution with ReLU activations (paper Section II-C and Fig. 2). At a Glance ----------- @@ -63,9 +63,9 @@ At a Glance Description ----------- -``wildfire_aspp`` is the backward-compatible public PyHazards entrypoint for the CNN + ASPP wildfire spread model. +``wildfire_aspp`` reimplements CNN-ASPP (Marjani et al., IEEE GRSL 2024): two 3x3 convolutions with 64 and 128 filters, four parallel 3x3 atrous convolutions with 32 filters and dilation rates 1, 3, 6 and 12, two 3x3 convolutions with 32 filters, batch normalisation and a 1x1 output convolution, all at full 64x64 resolution with ReLU activations (paper Section II-C and Fig. 2). -PyHazards keeps the alias for compatibility while the implementation delegates to the native ``wildfire_cnn_aspp`` builder under the hood. +The authors did not release code, so the network is rebuilt from the paper; it has 274,657 parameters for the 12 Next Day Wildfire Spread input channels. The paper's final sigmoid is left to the loss, and Keras defaults are used where the paper is silent (Glorot-uniform initialisation, BatchNorm epsilon 1e-3 and momentum 0.99). Benchmark Compatibility ----------------------- @@ -77,7 +77,21 @@ Benchmark Compatibility External References ------------------- -**Paper:** `Application of Explainable Artificial Intelligence in Predicting Wildfire Spread `_ +**Paper:** `Application of Explainable Artificial Intelligence in Predicting Wildfire Spread: An ASPP-Enabled CNN Approach `_ + +Used In +------- + +- `Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data `_: Training and evaluation data in the CNN-ASPP paper (64x64 tiles, 12 channels; 8,616 training and 685 validation samples), with the Tversky loss (0.7 on false negatives, 0.3 on false positives), batch size 8, learning rate 4e-4; reported OA 96.46, recall 99.37, precision 93.51, F1 96.35 (paper Table I). + +Reproduction +------------ + +- **Reference implementation:** none released; rebuilt from the paper. +- **Paper configuration:** Section II-C and Fig. 2 of the paper: 12 x 64 x 64 input, conv 64 and 128, atrous branches of 32 filters at dilation 1, 3, 6, 12, conv 32, conv 32, BatchNorm, 1x1 conv. +- **Parameter count:** 274,657 +- **Deviation:** Returns logits; the paper's last layer applies the sigmoid. +- **Deviation:** The paper does not state the concatenation order of the atrous branches, the padding or the initialisation; PyHazards concatenates in dilation order 1, 3, 6, 12, uses zero padding that keeps the 64x64 size (as in Fig. 2), and Keras default initialisation. Registry Name ------------- @@ -98,18 +112,16 @@ Programmatic Use import torch from pyhazards.models import build_model + from pyhazards.models.wildfire_aspp import TverskyLoss - model = build_model( - name="wildfire_aspp", - task="segmentation", - in_channels=12, - ) - - x = torch.randn(2, 12, 64, 64) - logits = model(x) - print(logits.shape) + model = build_model(name="wildfire_aspp", task="segmentation", in_channels=12) + logits = model(torch.randn(2, 12, 64, 64)) + loss = TverskyLoss(alpha=0.3, beta=0.7)(logits, torch.randint(0, 2, (2, 1, 64, 64))) + print(logits.shape, float(loss)) Notes ----- -- ``wildfire_cnn_aspp`` remains available as an alias for the same public model. +- No reference implementation was released; this is a reimplementation from the paper text and Fig. 2. +- TverskyLoss weights false positives with alpha and false negatives with beta; the paper's setting is alpha=0.3, beta=0.7. +- ``wildfire_cnn_aspp`` is an alias for the same model. diff --git a/docs/source/modules/models_wildfire_forecasting.rst b/docs/source/modules/models_wildfire_forecasting.rst index 82a6b73a..75a2d2a3 100644 --- a/docs/source/modules/models_wildfire_forecasting.rst +++ b/docs/source/modules/models_wildfire_forecasting.rst @@ -6,7 +6,7 @@ Wildfire Forecasting Overview -------- -``wildfire_forecasting`` is a compact GRU-attention forecaster for weekly wildfire activity windows. +``wildfire_forecasting`` builds one of the two deep models of Kondylatos et al. (GRL 2022) for next-day wildfire danger in Greece and the Eastern Mediterranean. ``variant="lstm"`` (default) reads the ten-day series of 25 features of one cell, ``(batch, 10, 25)``; ``variant="convlstm"`` reads the ten-day block of 25 x 25 cells centred on it, ``(batch, 10, 25, 25, 25)``. Both return ``(batch, 2)`` log-probabilities over (no fire, fire). At a Glance ----------- @@ -46,7 +46,7 @@ At a Glance .. container:: catalog-stat-note - Forecasting + Classification .. grid-item-card:: Benchmark Family :class-card: catalog-stat-card @@ -63,9 +63,11 @@ At a Glance Description ----------- -``wildfire_forecasting`` is a compact GRU-attention forecaster for weekly wildfire activity windows. +``wildfire_forecasting`` builds one of the two deep models of Kondylatos et al. (GRL 2022) for next-day wildfire danger in Greece and the Eastern Mediterranean. ``variant="lstm"`` (default) reads the ten-day series of 25 features of one cell, ``(batch, 10, 25)``; ``variant="convlstm"`` reads the ten-day block of 25 x 25 cells centred on it, ``(batch, 10, 25, 25, 25)``. Both return ``(batch, 2)`` log-probabilities over (no fire, fire). -The PyHazards implementation targets smoke-testable next-window size-group prediction through the shared wildfire benchmark flow. +The 25 features per day are 10 dynamic variables (NDVI, day and night land surface temperature, soil moisture index, and ERA5-Land maximum 2 m temperature, dew point, surface pressure and wind speed, total precipitation and minimum relative humidity), 5 static variables (elevation, slope, distance to roads and waterways, population density) and the 10 Corine Land Cover class fractions, concatenated in that order; static variables and land cover are repeated over the ten days. + +The implementation is a port of ``SimpleLSTM`` and ``SimpleConvLSTM`` from the official code. Parameter names and initialisation order match the reference, so its state dicts load with ``strict=True``; ``hidden_size`` defaults to the paper runs (64 for the LSTM, 32 for the ConvLSTM). The paper's random forest and XGBoost baselines are the separate ``random_forest`` and ``xgboost`` entries, which read the same daily tensors. Benchmark Compatibility ----------------------- @@ -75,7 +77,25 @@ Benchmark Compatibility External References ------------------- -**Paper:** `Wildfire Danger Prediction and Understanding with Deep Learning `_ | **Repo:** `Repository `__ +**Paper:** `Wildfire Danger Prediction and Understanding With Deep Learning `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Wildfire Danger Prediction and Understanding With Deep Learning `_ (`repo `__): Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. Daily 1 km datacube of Greece and the Eastern Mediterranean, 2009-2021 (data sets: Zenodo 6528394); target = cell inside a burned area larger than 30 ha from a fire that started that day; two negatives per positive, sampled on fire-free days and stratified by land cover. Train 2009-2018, validation 2019, test 2020 and 2021. Test F1 (Table 1, 2020 / 2021): LSTM 0.804 / 0.879 (precision 0.861 / 0.904, recall 0.755 / 0.855), ConvLSTM 0.806 / 0.871 (precision 0.923 / 0.950, recall 0.716 / 0.804); random forest 0.703 / 0.778 and XGBoost 0.782 / 0.786 for comparison. +- `Deep Learning Methods for Daily Wildfire Danger Forecasting `_: Prapas, Kondylatos et al., NeurIPS 2021 workshop paper, the precursor on the same datacube (train 2009-2018, validation 2019, test 2020). Same LSTM layer sizes (LSTM 64, linear 64-32); its ConvLSTM had 16 filters and a 16-8 linear head, which this entry does not reproduce. Test F1 0.751 (LSTM) and 0.714 (ConvLSTM), AUROC 0.920 and 0.926. + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/Orion-AI-Lab/wildfire_forecasting `__ at ``2b18bcf`` (MIT) +- **Checked configuration:** SimpleLSTM (hidden_size 64, 1 layer, dropout 0.5; 29,652 parameters) and SimpleConvLSTM (hidden_size 32, 1 layer, dropout 0.5, 25x25 patches; 372,212 parameters) from wildfire_forecasting/models/modules/fire_modules.py with 10 dynamic + 5 static features and the 10-d land-cover vector (clc='vec'), as set in configs/experiment/lstm_temporal_cls.yaml and clstm_spatiotemporal_cls.yaml, which the repository names as the paper's hyperparameters. The model code is unchanged since the v0.1-alpha release cited by the paper (Zenodo 6524771). +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_wildfire_forecasting_oracle.py`` +- **Deviation:** The ConvLSTM's first linear layer is sized from ``patch_size`` (default 25) instead of the hard-coded ``25 // 2``; identical for the paper's 25x25 patches. +- **Deviation:** Hyperparameters are constructor arguments (``input_dim``, ``hidden_size``, ``lstm_layers``, ``dropout``) instead of an ``hparams`` dict whose input size is counted from feature-name lists. +- **Deviation:** The ConvLSTM recurrence is ``pyhazards.models.convlstm.ConvLSTM`` rather than a copy of the repository's ``convlstm.py`` (from ndrplz/ConvLSTM_pytorch): same gates, zero initial state and parameter names, outputs equal in the oracle test. The reference's ``dilation`` option, always 1 in ``SimpleConvLSTM``, is not exposed. +- **Deviation:** The reference LightningModule's ``attention=True`` option refers to an undefined ``SimpleLSTMAttention`` class and crashes; it is not ported. Registry Name ------------- @@ -85,7 +105,7 @@ Primary entrypoint: ``wildfire_forecasting`` Supported Tasks --------------- -- Forecasting +- Classification Programmatic Use ---------------- @@ -95,17 +115,24 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="wildfire_forecasting", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) - preds = model(torch.randn(2, 12, 7)) - print(preds.shape) + lstm = build_model(name="wildfire_forecasting", task="classification") + log_probs = lstm(torch.randn(4, 10, 25)) + danger = log_probs.exp()[:, 1] # probability of fire + print(log_probs.shape) # (4, 2) + + convlstm = build_model(name="wildfire_forecasting", task="classification", variant="convlstm") + print(convlstm(torch.randn(4, 10, 25, 25, 25)).shape) # (4, 2) Notes ----- -- This public adapter is exercised on the weekly wildfire smoke benchmark. +- The output is log-probabilities, as in the reference (``log_softmax`` over two classes). The reference trains with ``nn.NLLLoss`` (class weights 0.5 / 0.5, i.e. unweighted); ``nn.CrossEntropyLoss`` gives the same loss because ``log_softmax`` is idempotent. The paper calls this a binary cross-entropy loss. + +- Paper training settings (repository experiment configs): Adam, StepLR(step 15, gamma 0.1), batch 256, 30 epochs; LSTM lr 1e-3 and weight decay 1e-3, ConvLSTM lr 1e-4 and weight decay 0.01. Features are min-max scaled; missing dynamic values take the sample's mean over time (LSTM) or space (ConvLSTM), other missing values become -1, missing land cover 0. + +- The LSTM is the default: the paper builds its danger maps and explainability analysis on it, its F1 is within 0.01 of the ConvLSTM in both test years, and it is about 12 times smaller. + +- At the pinned commit the repository's dataset class validates on 2020 and tests on 2021 (``val_year = 2020``), whereas the paper validates on 2019 and tests on 2020 and 2021. + +- PyHazards does not load the Greek datacube yet; the smoke config uses the synthetic ``wildfire_danger_synthetic`` dataset (``access_mode='temporal'`` or ``'spatiotemporal'``). + diff --git a/docs/source/modules/models_wildfire_fpa.rst b/docs/source/modules/models_wildfire_fpa.rst index b5890f79..7a3da936 100644 --- a/docs/source/modules/models_wildfire_fpa.rst +++ b/docs/source/modules/models_wildfire_fpa.rst @@ -77,6 +77,11 @@ External References **Paper:** `Developing risk assessment framework for wildfire in the United States `_ +Reproduction +------------ + +Not yet verified against a reference implementation. + Registry Name ------------- diff --git a/docs/source/modules/models_wildfire_mamba.rst b/docs/source/modules/models_wildfire_mamba.rst index 0912fc54..7e94b637 100644 --- a/docs/source/modules/models_wildfire_mamba.rst +++ b/docs/source/modules/models_wildfire_mamba.rst @@ -79,6 +79,11 @@ External References **Paper:** `Mamba: Linear-Time Sequence Modeling with Selective State Spaces `_ +Reproduction +------------ + +Not yet verified against a reference implementation. + Registry Name ------------- diff --git a/docs/source/modules/models_wildfirespreadts.rst b/docs/source/modules/models_wildfirespreadts.rst index ec85fdfe..70946090 100644 --- a/docs/source/modules/models_wildfirespreadts.rst +++ b/docs/source/modules/models_wildfirespreadts.rst @@ -1,12 +1,12 @@ .. This file is generated by scripts/render_model_docs.py. Do not edit by hand. -WildfireSpreadTS -================ +WildfireSpreadTS Baselines +========================== Overview -------- -``wildfirespreadts`` models wildfire spread as a sequence-to-mask prediction task. +``wildfirespreadts`` builds one of the learned baselines of the WildfireSpreadTS benchmark for next-day active-fire segmentation, configured exactly as in the benchmark code. ``baseline`` selects ``logistic_regression``, ``resnet18_unet``, ``convlstm`` or ``utae`` (default). At a Glance ----------- @@ -63,9 +63,9 @@ At a Glance Description ----------- -``wildfirespreadts`` models wildfire spread as a sequence-to-mask prediction task. +``wildfirespreadts`` builds one of the learned baselines of the WildfireSpreadTS benchmark for next-day active-fire segmentation, configured exactly as in the benchmark code. ``baseline`` selects ``logistic_regression``, ``resnet18_unet``, ``convlstm`` or ``utae`` (default). -The PyHazards adapter uses a compact 3D convolution stack that consumes short raster history windows and predicts the next spread mask. +Each baseline is also available on its own (``logistic_regression``, ``resnet18_unet``, ``convlstm``, ``utae``) with configurable hyperparameters; this entry fixes them to the benchmark values. ``in_channels`` is the number of features per day (40 with all features) and ``history`` the number of days that the U-Net and logistic regression flatten into channels. Benchmark Compatibility ----------------------- @@ -77,7 +77,15 @@ Benchmark Compatibility External References ------------------- -**Paper:** `WildfireSpreadTS: A Dataset of Multi-Modal Time Series for Wildfire Spread Prediction `_ | **Repo:** `Repository `__ +**Paper:** `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ | **Repo:** `Repository `__ + +Reproduction +------------ + +- **Reference implementation:** `https://github.com/SebastianGer/WildfireSpreadTS `__ at ``f62dc49`` (MIT) +- **Checked configuration:** src/models (LogisticRegression, SMPModel, ConvLSTMLightning, UTAELightning) with 40 input channels; parameter counts 361 / 14,444,241 / 240,449 / 1,099,011 match paper Table 5. +- **Verified:** parameter count, seeded initialisation, parameter names and shapes, forward outputs +- **Oracle test:** ``tests/oracle/test_wildfirespreadts_oracle.py`` Registry Name ------------- @@ -97,16 +105,14 @@ Programmatic Use import torch from pyhazards.models import build_model - model = build_model( - name="wildfirespreadts", - task="segmentation", - history=4, - in_channels=6, - ) - logits = model(torch.randn(2, 4, 6, 16, 16)) - print(logits.shape) + model = build_model(name="wildfirespreadts", task="segmentation", baseline="utae", in_channels=40) + x = torch.randn(2, 5, 40, 128, 128) + day_of_year = torch.tensor([[150, 151, 152, 153, 154]] * 2, dtype=torch.float32) + print(model(x, batch_positions=day_of_year).shape) # (2, 1, 128, 128) Notes ----- -- The smoke dataset uses temporal wildfire spread tensors rather than single-frame rasters. +- The benchmark trains on random 128x128 crops; ConvLSTM is evaluated by tiling 128x128 crops. +- For the multi-day U-Net, the 20 static features (topography, land-cover one-hot) are kept for the last day only, as in the benchmark (remove_duplicate_features): 120 input channels and 14,695,121 parameters for 5 days. +- Training losses differ per baseline: Dice (logistic regression, U-Net), Jaccard (ConvLSTM), weighted BCE (U-TAE). diff --git a/docs/source/modules/models_wrf_sfire.rst b/docs/source/modules/models_wrf_sfire.rst deleted file mode 100644 index 85546f73..00000000 --- a/docs/source/modules/models_wrf_sfire.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. - -WRF-SFIRE Adapter -================= - -Overview --------- - -``wrf_sfire`` approximates simulator-style spread transport with a fixed diffusion and terrain-moisture modulation layer. - -At a Glance ------------ - -.. grid:: 1 2 4 4 - :gutter: 2 - :class-container: catalog-grid - - .. grid-item-card:: Hazard Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Wildfire - - .. container:: catalog-stat-note - - Public catalog grouping used for this model. - - .. grid-item-card:: Maturity - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - Implemented - - .. container:: catalog-stat-note - - Catalog maturity label used on the index page. - - .. grid-item-card:: Tasks - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - 1 - - .. container:: catalog-stat-note - - Spread - - .. grid-item-card:: Benchmark Family - :class-card: catalog-stat-card - - .. container:: catalog-stat-value - - :doc:`Wildfire Benchmark ` - - .. container:: catalog-stat-note - - Primary benchmark-family link used for compatible evaluation coverage. - - -Description ------------ - -``wrf_sfire`` approximates simulator-style spread transport with a fixed diffusion and terrain-moisture modulation layer. - -The PyHazards adapter is designed for consistent smoke benchmarking rather than full physical simulation. - -Benchmark Compatibility ------------------------ - -**Primary benchmark family:** :doc:`Wildfire Benchmark ` - -**Mapped benchmark ecosystems:** :doc:`WildfireSpreadTS ` - -External References -------------------- - -**Paper:** `Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011 `_ | **Repo:** `Repository `__ - -Registry Name -------------- - -Primary entrypoint: ``wrf_sfire`` - -Supported Tasks ---------------- - -- Spread - -Programmatic Use ----------------- - -.. code-block:: python - - import torch - from pyhazards.models import build_model - - model = build_model(name="wrf_sfire", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) - -Notes ------ - -- This smoke-path adapter keeps the simulator slot benchmarkable without external binaries. diff --git a/docs/source/modules/models_xgboost.rst b/docs/source/modules/models_xgboost.rst new file mode 100644 index 00000000..70042347 --- /dev/null +++ b/docs/source/modules/models_xgboost.rst @@ -0,0 +1,130 @@ +.. This file is generated by scripts/render_model_docs.py. Do not edit by hand. + +XGBoost +======= + +Overview +-------- + +``xgboost`` wraps ``xgboost.XGBClassifier`` (Chen & Guestrin, KDD 2016), the second tree baseline of Kondylatos et al. (GRL 2022). Like ``random_forest`` it takes the ``wildfire_forecasting`` daily tensor ``(batch, 10, 25)`` or ready-made features ``(batch, 35)``, builds the paper's instance features (ten-day mean and last-day value of the 10 dynamic variables, 5 static variables, 10 land-cover fractions), and returns ``(batch, 2)`` log-probabilities over (no fire, fire). + +At a Glance +----------- + +.. grid:: 1 2 4 4 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hazard Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Wildfire + + .. container:: catalog-stat-note + + Public catalog grouping used for this model. + + .. grid-item-card:: Maturity + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + Implemented + + .. container:: catalog-stat-note + + Catalog maturity label used on the index page. + + .. grid-item-card:: Tasks + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + 2 + + .. container:: catalog-stat-note + + Classification, Forecasting + + .. grid-item-card:: Benchmark Family + :class-card: catalog-stat-card + + .. container:: catalog-stat-value + + :doc:`Wildfire Benchmark ` + + .. container:: catalog-stat-note + + Primary benchmark-family link used for compatible evaluation coverage. + + +Description +----------- + +``xgboost`` wraps ``xgboost.XGBClassifier`` (Chen & Guestrin, KDD 2016), the second tree baseline of Kondylatos et al. (GRL 2022). Like ``random_forest`` it takes the ``wildfire_forecasting`` daily tensor ``(batch, 10, 25)`` or ready-made features ``(batch, 35)``, builds the paper's instance features (ten-day mean and last-day value of the 10 dynamic variables, 5 static variables, 10 land-cover fractions), and returns ``(batch, 2)`` log-probabilities over (no fire, fire). + +The paper gives the XGBoost hyperparameters only in its Supporting Information (Text S2), which has not been read, and the official repository has no XGBoost code. This entry therefore uses the library defaults of xgboost 3.2.0 (100 boosting rounds, maximum depth 6, learning rate 0.3, histogram trees with 256 bins, no subsampling, L2 regularisation 1, binary logistic objective). Any of them can be overridden through the builder. + +``xgboost`` is an optional dependency (``pip install 'pyhazards[xgboost]'``, or the CPU-only ``xgboost-cpu``), imported only when the model is built. As for ``random_forest``, the module is fitted with ``model.fit(inputs, targets)`` and refused by ``Trainer.fit``. + +Benchmark Compatibility +----------------------- + +**Primary benchmark family:** :doc:`Wildfire Benchmark ` + +External References +------------------- + +**Paper:** `XGBoost: A Scalable Tree Boosting System `_ | **Repo:** `Repository `__ + +Used In +------- + +- `Wildfire Danger Prediction and Understanding With Deep Learning `_ (`repo `__): Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. XGBoost on the instance-based data set (dynamic inputs at day t-1, their average over days t-1..t-10, static features) of the daily 1 km Greek / Eastern Mediterranean datacube; train 2009-2018, test 2020 and 2021. Hyperparameters in Supporting Information Text S2 (not read). Test results (Table 1, 2020 / 2021): precision 0.852 / 0.867, recall 0.723 / 0.720, F1 0.782 / 0.786 (TP 888 / 3,172, FP 154 / 488, TN 2,302 / 8,326, FN 340 / 1,235); random forest F1 0.703 / 0.778, LSTM 0.804 / 0.879. + +Reproduction +------------ + +- **Reference implementation:** none released; rebuilt from the paper. +- **Paper configuration:** Kondylatos et al. (2022), Section 3: XGBoost on the instance-based features. PyHazards builds the features as the official random-forest notebook (notebooks/RF.ipynb) does and uses xgboost.XGBClassifier() with the defaults of xgboost 3.2.0; tests/oracle/test_classical_oracle.py checks that its predictions equal those of XGBClassifier() 3.2.0 fitted on the notebook's features. +- **Oracle test:** ``tests/oracle/test_classical_oracle.py`` +- **Deviation:** Hyperparameters are pending the paper's Supporting Information (Text S2, behind the Wiley site and not read): the xgboost 3.2.0 library defaults are used, which need not match the paper's model or reproduce its scores. +- **Deviation:** The library defaults depend on the xgboost release (2.0 switched to histogram trees and an estimated base score); other releases may give different predictions. + +Registry Name +------------- + +Primary entrypoint: ``xgboost`` + +Supported Tasks +--------------- + +- Classification +- Forecasting + +Programmatic Use +---------------- + +.. code-block:: python + + from pyhazards.datasets import load_dataset + from pyhazards.models import build_model + + data = load_dataset("wildfire_danger_synthetic", samples=120).load() + train, test = data.get_split("train"), data.get_split("test") + + model = build_model(name="xgboost", task="classification") # needs pyhazards[xgboost] + model.fit(train.inputs, train.targets) + print(model(test.inputs).shape) # (18, 2) log-probabilities + +Notes +----- + +- Install with ``pip install 'pyhazards[xgboost]'`` (``xgboost>=2.0``) or ``pip install xgboost-cpu`` (same module, no CUDA/NCCL wheels). Without it, building the model raises an ``ImportError`` that says so, and the catalog smoke test is skipped. + +- ``n_jobs`` defaults to all available cores (``OMP_NUM_THREADS`` caps it); pass ``n_jobs`` on shared machines. + +- The fitting, ``forward``, persistence (``save`` / ``EstimatorModule.load``, joblib) and ``Trainer`` behaviour are those of ``random_forest``. + diff --git a/docs/source/pyhazards_benchmarks.rst b/docs/source/pyhazards_benchmarks.rst index 82ec8635..1cabc9a0 100644 --- a/docs/source/pyhazards_benchmarks.rst +++ b/docs/source/pyhazards_benchmarks.rst @@ -29,7 +29,7 @@ At a Glance .. container:: catalog-stat-value - 12 + 10 .. container:: catalog-stat-note @@ -40,7 +40,7 @@ At a Glance .. container:: catalog-stat-value - 7 + 8 .. container:: catalog-stat-note @@ -51,7 +51,7 @@ At a Glance .. container:: catalog-stat-value - 27 + 23 .. container:: catalog-stat-note @@ -86,11 +86,11 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-meta-row - **Key Metrics:** Accuracy, Macro F1, AUC, PR-AUC, +5 more + **Key Metrics:** Accuracy, Macro F1, AUC, PR-AUC, +6 more .. container:: catalog-meta-row - **Coverage:** 8 smoke configs | 8 models | 1 ecosystem + **Coverage:** 7 smoke configs | 29 models | 1 ecosystem .. container:: catalog-link-row @@ -101,11 +101,11 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-entry-summary - Shared PyHazards evaluator family for earthquake phase-picking and wavefield-forecasting runs. + Shared PyHazards evaluator for seismic phase picking (pick metrics of the PhaseNet and EQTransformer papers) and ground-motion wavefield forecasting (ACC / RFNE of WaveCastNet). .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-secondary:`Wavefield Forecasting` :bdg-info:`Synthetic-backed` + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-secondary:`Wavefield Forecasting` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -113,11 +113,11 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-meta-row - **Key Metrics:** P-pick MAE, S-pick MAE, Precision, Recall, +3 more + **Key Metrics:** P Precision, P Recall, P F1, P Residual Mean, +22 more .. container:: catalog-meta-row - **Coverage:** 5 smoke configs | 5 models | 4 ecosystems + **Coverage:** 5 smoke configs | 5 models | 2 ecosystems .. container:: catalog-link-row @@ -128,11 +128,11 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-entry-summary - Shared PyHazards evaluator family for streamflow forecasting and inundation prediction. + Shared PyHazards evaluator for daily streamflow (per-basin NSE, KGE and the other NeuralHydrology metrics) and for inundation depth on rasters and flood meshes (depth errors, CSI, relative L2, NSE, autoregressive mesh rollouts). .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-secondary:`Inundation` :bdg-info:`Synthetic-backed` + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-secondary:`Inundation` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -140,11 +140,11 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-meta-row - **Key Metrics:** MAE, RMSE, NSE, KGE, +3 more + **Key Metrics:** NSE, KGE, Alpha-NSE, Beta-NSE, +12 more .. container:: catalog-meta-row - **Coverage:** 6 smoke configs | 6 models | 4 ecosystems + **Coverage:** 6 smoke configs | 6 models | 3 ecosystems .. container:: catalog-link-row @@ -155,23 +155,23 @@ coverage counts into a scan-friendly catalog. .. container:: catalog-entry-summary - Shared PyHazards evaluator family for tropical cyclone and hurricane track-intensity forecasting. + Shared PyHazards evaluator for tropical cyclone forecasts: great-circle track error in km and intensity errors in the dataset's units, per lead time, plus single-lead intensity regression. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-info:`Synthetic-backed` + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-secondary:`Intensity` :bdg-success:`Real-backed` .. container:: catalog-meta-row - **Tasks:** Track + Intensity + **Tasks:** Track + Intensity, Intensity .. container:: catalog-meta-row - **Key Metrics:** Track Error, Intensity MAE + **Key Metrics:** Track Error (km), Intensity MAE, Pressure MAE, Best-of-k Track Error (km), +4 more .. container:: catalog-meta-row - **Coverage:** 8 smoke configs | 8 models | 3 ecosystems + **Coverage:** 5 smoke configs | 5 models | 4 ecosystems .. container:: catalog-link-row @@ -199,27 +199,27 @@ status without opening the detail pages first. * - Wildfire - :doc:`Wildfire Benchmark ` - Danger, Spread - - Accuracy, Macro F1, AUC, PR-AUC, +5 more - - 8 models + - Accuracy, Macro F1, AUC, PR-AUC, +6 more + - 29 models - Synthetic-backed * - Earthquake - :doc:`Earthquake Benchmark ` - Phase Picking, Wavefield Forecasting - - P-pick MAE, S-pick MAE, Precision, Recall, +3 more + - P Precision, P Recall, P F1, P Residual Mean, +22 more - 5 models - - Synthetic-backed + - Real-backed * - Flood - :doc:`Flood Benchmark ` - Streamflow, Inundation - - MAE, RMSE, NSE, KGE, +3 more + - NSE, KGE, Alpha-NSE, Beta-NSE, +12 more - 6 models - - Synthetic-backed + - Real-backed * - Tropical Cyclone - :doc:`Tropical Cyclone Benchmark ` - - Track + Intensity - - Track Error, Intensity MAE - - 8 models - - Synthetic-backed + - Track + Intensity, Intensity + - Track Error (km), Intensity MAE, Pressure MAE, Best-of-k Track Error (km), +4 more + - 5 models + - Real-backed Benchmark Ecosystems -------------------- @@ -260,11 +260,11 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** IoU, F1, Burned-area MAE + **Key Metrics:** Average Precision, IoU, F1, Burned-area MAE .. container:: catalog-meta-row - **Coverage:** 5 smoke configs | 5 models + **Coverage:** 2 smoke configs | 8 models .. container:: catalog-link-row @@ -287,47 +287,16 @@ and the models currently mapped to that ecosystem. :gutter: 2 :class-container: catalog-grid - .. grid-item-card:: AEFA - :class-card: catalog-entry-card - - .. container:: catalog-entry-summary - - AEFA-style forecasting dataset support for the shared earthquake forecasting path. - - .. container:: catalog-chip-row - - :bdg-primary:`Earthquake` :bdg-secondary:`Wavefield Forecasting` :bdg-info:`Synthetic-backed` - - .. container:: catalog-meta-row - - **Benchmark Family:** :doc:`Earthquake Benchmark ` - - .. container:: catalog-meta-row - - **Key Metrics:** MAE, MSE - - .. container:: catalog-meta-row - - **Coverage:** 1 smoke config | 1 model - - .. container:: catalog-link-row - - **View Details:** :doc:`AEFA ` - - .. container:: catalog-link-row - - **Paper:** `AEFA `_ - .. grid-item-card:: pick-benchmark :class-card: catalog-entry-card .. container:: catalog-entry-summary - pick-benchmark-compatible waveform picking support routed through the shared earthquake evaluator. + The SeisBench picking benchmark of Münchmeyer et al. (2022). Its datasets can be read with ``seisbench_waveforms``; its own three evaluation tasks are not implemented in PyHazards. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-info:`Synthetic-backed` + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-warning:`Experimental` .. container:: catalog-meta-row @@ -335,11 +304,11 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** P-pick MAE, S-pick MAE, Precision, Recall, +1 more + **Key Metrics:** P F1, S F1 .. container:: catalog-meta-row - **Coverage:** 2 smoke configs | 2 models + **Coverage:** 2 smoke configs | 3 models .. container:: catalog-link-row @@ -347,49 +316,18 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **Paper:** `pick-benchmark `_ - - .. grid-item-card:: pyCSEP - :class-card: catalog-entry-card - - .. container:: catalog-entry-summary - - pyCSEP-style forecasting report export for the earthquake forecasting smoke path. - - .. container:: catalog-chip-row - - :bdg-primary:`Earthquake` :bdg-secondary:`Wavefield Forecasting` :bdg-info:`Synthetic-backed` - - .. container:: catalog-meta-row - - **Benchmark Family:** :doc:`Earthquake Benchmark ` - - .. container:: catalog-meta-row - - **Key Metrics:** MAE, MSE - - .. container:: catalog-meta-row - - **Coverage:** 1 smoke config | 1 model - - .. container:: catalog-link-row - - **View Details:** :doc:`pyCSEP ` - - .. container:: catalog-link-row - - **Paper:** `pyCSEP `_ + **Paper:** `Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers (Münchmeyer et al., J. Geophys. Res. Solid Earth 127, e2021JB023499, 2022) `_ | **Repo:** `Repository `__ .. grid-item-card:: SeisBench :class-card: catalog-entry-card .. container:: catalog-entry-summary - SeisBench-shaped waveform picking support for the shared earthquake benchmark family. + SeisBench-format waveform datasets (STEAD, INSTANCE, ETHZ, ...) read by PyHazards' own ``seisbench_waveforms`` reader and scored by the earthquake picking evaluator. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-info:`Synthetic-backed` + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -397,11 +335,11 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** P-pick MAE, S-pick MAE, Precision, Recall, +1 more + **Key Metrics:** P Precision, P Recall, P F1, P-pick MAE, +4 more .. container:: catalog-meta-row - **Coverage:** 2 smoke configs | 2 models + **Coverage:** 1 smoke config | 3 models .. container:: catalog-link-row @@ -409,7 +347,7 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **Paper:** `SeisBench - A Toolbox for Machine Learning in Seismology `_ | **Repo:** `Repository `__ + **Paper:** `SeisBench - A Toolbox for Machine Learning in Seismology (Woollam et al., Seismological Research Letters 93(3):1695-1709, 2022) `_ | **Repo:** `Repository `__ .. tab-item:: Flood @@ -424,16 +362,16 @@ and the models currently mapped to that ecosystem. :gutter: 2 :class-container: catalog-grid - .. grid-item-card:: Caravan + .. grid-item-card:: CAMELS-US :class-card: catalog-entry-card .. container:: catalog-entry-summary - Caravan-style streamflow benchmark coverage for the shared flood streamflow evaluator. + The CAMELS-US benchmark of Kratzert et al. (2019): 531 basins, extended Maurer forcings, 27 attributes, test 1989-1999, scored per basin with NSE and the FDC metrics. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-info:`Synthetic-backed` + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -441,7 +379,7 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** MAE, RMSE, NSE, KGE + **Key Metrics:** NSE, Mean NSE, Basins with NSE <= 0, Alpha-NSE, +4 more .. container:: catalog-meta-row @@ -449,22 +387,22 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **View Details:** :doc:`Caravan ` + **View Details:** :doc:`CAMELS-US ` .. container:: catalog-link-row - **Paper:** `Caravan - A global community dataset for large-sample hydrology `_ | **Repo:** `Repository `__ + **Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ - .. grid-item-card:: FloodCastBench + .. grid-item-card:: Caravan :class-card: catalog-entry-card .. container:: catalog-entry-summary - FloodCastBench-style inundation benchmark coverage for the shared flood inundation evaluator. + Caravan, the global large-sample hydrology dataset, read from a local copy and scored with the per-basin streamflow metrics. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Inundation` :bdg-info:`Synthetic-backed` + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -472,30 +410,30 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** Pixel MAE, IoU, F1 + **Key Metrics:** NSE, KGE, Mean NSE .. container:: catalog-meta-row - **Coverage:** 2 smoke configs | 2 models + **Coverage:** 2 smoke configs | 3 models .. container:: catalog-link-row - **View Details:** :doc:`FloodCastBench ` + **View Details:** :doc:`Caravan ` .. container:: catalog-link-row - **Paper:** `FloodCastBench `_ + **Paper:** `Caravan - A global community dataset for large-sample hydrology `_ | **Repo:** `Repository `__ - .. grid-item-card:: HydroBench + .. grid-item-card:: HydroGraphNet White River :class-card: catalog-entry-card .. container:: catalog-entry-summary - HydroBench-style streamflow diagnostics coverage for the shared flood streamflow evaluator. + HEC-RAS flood simulations on the 4,787-cell White River mesh (HydroGraphNet, Taghizadeh et al. 2025), rolled out autoregressively and scored as water depth in metres. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-info:`Synthetic-backed` + :bdg-primary:`Flood` :bdg-secondary:`Inundation` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -503,7 +441,7 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** MAE, RMSE, NSE, KGE + **Key Metrics:** Rollout Rmse, Pixel MAE, RMSE, Csi 10Cm, +1 more .. container:: catalog-meta-row @@ -511,66 +449,66 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **View Details:** :doc:`HydroBench ` + **View Details:** :doc:`HydroGraphNet White River ` .. container:: catalog-link-row - **Paper:** `HydroBench `_ + **Paper:** `Interpretable physics-informed graph neural networks for flood forecasting `_ | **Repo:** `Repository `__ - .. grid-item-card:: WaterBench + + .. tab-item:: Tropical Cyclone + + .. container:: catalog-section-note + + Ecosystem cards describe the external benchmark or data protocol + surfaced on this page and show how it maps back to the shared + PyHazards benchmark family. + + .. grid:: 1 1 2 2 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: IBTrACS :class-card: catalog-entry-card .. container:: catalog-entry-summary - WaterBench-style streamflow benchmark coverage for the shared flood evaluator. + Best-track ground truth from NOAA NCEI's IBTrACS v04 for track and intensity forecasts scored by the shared tropical cyclone evaluator. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-info:`Synthetic-backed` + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-secondary:`Intensity` :bdg-success:`Real-backed` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` .. container:: catalog-meta-row - **Key Metrics:** MAE, RMSE, NSE, KGE + **Key Metrics:** Track Error (km), Intensity MAE, Pressure MAE .. container:: catalog-meta-row - **Coverage:** 1 smoke config | 1 model + **Coverage:** 0 smoke configs | 1 model .. container:: catalog-link-row - **View Details:** :doc:`WaterBench ` + **View Details:** :doc:`IBTrACS ` .. container:: catalog-link-row - **Paper:** `WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting `_ | **Repo:** `Repository `__ - - - .. tab-item:: Tropical Cyclone - - .. container:: catalog-section-note - - Ecosystem cards describe the external benchmark or data protocol - surfaced on this page and show how it maps back to the shared - PyHazards benchmark family. - - .. grid:: 1 1 2 2 - :gutter: 2 - :class-container: catalog-grid + **Paper:** `IBTrACS `_ - .. grid-item-card:: IBTrACS + .. grid-item-card:: SHIPS Predictors (Xu et al. 2021) :class-card: catalog-entry-card .. container:: catalog-entry-summary - IBTrACS-backed storm benchmark coverage for the shared tropical cyclone evaluator. + The standardised SHIPS predictor table of Xu et al. (2021) with 24-hour intensity-change targets and the official leave-one-year-out folds, scored with the intensity task. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-info:`Synthetic-backed` + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Intensity` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -578,30 +516,30 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** Track Error, Intensity MAE + **Key Metrics:** Intensity MAE, Intensity RMSE, Mean Yearly Intensity MAE .. container:: catalog-meta-row - **Coverage:** 4 smoke configs | 4 models + **Coverage:** 1 smoke config | 1 model .. container:: catalog-link-row - **View Details:** :doc:`IBTrACS ` + **View Details:** :doc:`SHIPS Predictors (Xu et al. 2021) ` .. container:: catalog-link-row - **Paper:** `IBTrACS `_ + **Paper:** `Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ | **Repo:** `Repository `__ .. grid-item-card:: TCBench Alpha :class-card: catalog-entry-card .. container:: catalog-entry-summary - TCBench Alpha-style storm benchmark coverage for the shared tropical cyclone evaluator. + TCBench (Gomez et al. 2026): 2023 cyclone tracks of Pangu-Weather, FourCastNet v2 and AIFS extracted with TempestExtremes, matched to IBTrACS and scored by direct position error and intensity errors. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-info:`Synthetic-backed` + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -609,11 +547,11 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** Track Error, Intensity MAE + **Key Metrics:** Track Error (km), Intensity MAE, Pressure MAE .. container:: catalog-meta-row - **Coverage:** 3 smoke configs | 3 models + **Coverage:** 0 smoke configs | 0 models .. container:: catalog-link-row @@ -621,18 +559,18 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **Paper:** `TCBench Alpha `_ + **Paper:** `TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale `_ | **Repo:** `Repository `__ - .. grid-item-card:: TropiCycloneNet-Dataset + .. grid-item-card:: TropiCycloneNet Dataset :class-card: catalog-entry-card .. container:: catalog-entry-summary - TropiCycloneNet-Dataset-backed storm benchmark coverage for the shared tropical cyclone evaluator. + TCND (Huang et al. 2025): six-basin best tracks, Env-Data and ERA5 geopotential, read exactly like the official TropiCycloneNet loader and scored with the paper's best-of-6 errors. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-info:`Synthetic-backed` + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Real-backed` .. container:: catalog-meta-row @@ -640,7 +578,7 @@ and the models currently mapped to that ecosystem. .. container:: catalog-meta-row - **Key Metrics:** Track Error, Intensity MAE + **Key Metrics:** Track Error (km), Intensity MAE, Pressure MAE, Best-of-k Track Error (km), +2 more .. container:: catalog-meta-row @@ -648,11 +586,11 @@ and the models currently mapped to that ecosystem. .. container:: catalog-link-row - **View Details:** :doc:`TropiCycloneNet-Dataset ` + **View Details:** :doc:`TropiCycloneNet Dataset ` .. container:: catalog-link-row - **Paper:** `TropiCycloneNet-Dataset `_ + **Paper:** `Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ | **Repo:** `Repository `__ @@ -676,19 +614,17 @@ and :doc:`pyhazards_reports` for comparable benchmark exports. :maxdepth: 1 :hidden: - benchmarks/aefa + benchmarks/camels_us benchmarks/caravan benchmarks/earthquake_benchmark benchmarks/flood_benchmark - benchmarks/floodcastbench - benchmarks/hydrobench + benchmarks/hydrographnet_white_river benchmarks/ibtracs benchmarks/pick_benchmark - benchmarks/pycsep benchmarks/seisbench + benchmarks/ships_xu2021 benchmarks/tcbench_alpha benchmarks/tropical_cyclone_benchmark benchmarks/tropicyclonenet_dataset - benchmarks/waterbench benchmarks/wildfire_benchmark benchmarks/wildfirespreadts_ecosystem diff --git a/docs/source/pyhazards_datasets.rst b/docs/source/pyhazards_datasets.rst index 31b4f17a..a54330fd 100644 --- a/docs/source/pyhazards_datasets.rst +++ b/docs/source/pyhazards_datasets.rst @@ -30,7 +30,7 @@ At a Glance .. container:: catalog-stat-value - 20 + 41 .. container:: catalog-stat-note @@ -41,7 +41,7 @@ At a Glance .. container:: catalog-stat-value - 10 + 12 .. container:: catalog-stat-note @@ -52,7 +52,7 @@ At a Glance .. container:: catalog-stat-value - 12 + 22 .. container:: catalog-stat-note @@ -73,7 +73,7 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-section-note - Cross-hazard meteorology and imagery sources that support multiple PyHazards workflows, inspections, and forcing pipelines. + Cross-hazard meteorology, imagery, snow and population sources: some feed PyHazards inspections and forcing pipelines, others are external references. .. rubric:: Implemented Datasets @@ -143,6 +143,60 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `Schmit et al. (2017). A closer look at the ABI on the GOES-R series. `_ + .. grid-item-card:: HRRR + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + NOAA's 3 km, hourly updated, convection-allowing forecast model for the United States, archived on AWS since July 2014. + + .. container:: catalog-chip-row + + :bdg-secondary:`Weather Forecast` :bdg-info:`Gridded forecast fields` + + .. container:: catalog-meta-row + + **Coverage:** Conterminous United States; an Alaska domain from July 2018 + + .. container:: catalog-meta-row + + **Update Cadence:** Every hour for CONUS; every 3 hours for Alaska + + .. container:: catalog-link-row + + **Details:** :doc:`HRRR ` + + .. container:: catalog-link-row + + **Primary Source:** `Dowell et al. (2022). The High-Resolution Rapid Refresh (HRRR): An Hourly Updating Convection-Allowing Forecast Model. Part I: Motivation and System Description. Weather and Forecasting 37(8), 1371-1395. `_ + + .. grid-item-card:: LandScan Global + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + ORNL's annual 30 arc-second global grid of ambient (24-hour average) population, an exposure layer for hazard impact studies. + + .. container:: catalog-chip-row + + :bdg-secondary:`Population Exposure` :bdg-info:`Gridded population rasters (WGS84 geographic)` + + .. container:: catalog-meta-row + + **Coverage:** Global + + .. container:: catalog-meta-row + + **Update Cadence:** Annual releases (LandScan Global 2024 was published in August 2025) + + .. container:: catalog-link-row + + **Details:** :doc:`LandScan Global ` + + .. container:: catalog-link-row + + **Primary Source:** `Lebakula et al. (2025). LandScan Global 2024. Oak Ridge National Laboratory. `_ + .. grid-item-card:: MERRA-2 :class-card: catalog-entry-card @@ -174,12 +228,66 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `Gelaro et al. (2017). The Modern-Era Retrospective Analysis for Research and Applications, Version 2 (MERRA-2). `_ + .. grid-item-card:: NDFD + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The National Weather Service's gridded official forecasts, including relative humidity, wind, Red Flag Warnings and SPC fire-weather outlook grids, archived since 2004. + + .. container:: catalog-chip-row + + :bdg-secondary:`Weather Forecast` :bdg-info:`Gridded forecast fields` + + .. container:: catalog-meta-row + + **Coverage:** United States and territories + + .. container:: catalog-meta-row + + **Update Cadence:** As often as every 30 minutes, depending on the element + + .. container:: catalog-link-row + + **Details:** :doc:`NDFD ` + + .. container:: catalog-link-row + + **Primary Source:** `Glahn and Ruth (2003). The New Digital Forecast Database of the National Weather Service. Bulletin of the American Meteorological Society 84(2), 195-202. `_ + + .. grid-item-card:: SNODAS + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + NOAA NOHRSC's daily 1 km snow analysis (snow water equivalent, depth, melt, sublimation) for the conterminous United States, distributed by NSIDC since 2003. + + .. container:: catalog-chip-row + + :bdg-secondary:`Snow Analysis` :bdg-info:`Regular latitude-longitude grid` + + .. container:: catalog-meta-row + + **Coverage:** Masked version, conterminous United States and some Canadian basins (24.95-52.875 N, 124.733-66.942 W); unmasked version extends into Canada and Mexico + + .. container:: catalog-meta-row + + **Update Cadence:** Daily + + .. container:: catalog-link-row + + **Details:** :doc:`SNODAS ` + + .. container:: catalog-link-row + + **Primary Source:** `National Operational Hydrologic Remote Sensing Center (2004). Snow Data Assimilation System (SNODAS) Data Products at NSIDC, Version 1. NSIDC. `_ + .. tab-item:: Wildfire .. container:: catalog-section-note - Wildfire datasets span authoritative incident records, active-fire detections, fuels, burn severity, and forecast-ready benchmark adapters. + Wildfire datasets span authoritative incident records, perimeters, active-fire detections, smoke, fuels, burn severity, exposure, and forecast-ready benchmark adapters. .. rubric:: Implemented Datasets @@ -187,6 +295,64 @@ primary source, and the most relevant inspection or registry surface. :gutter: 2 :class-container: catalog-grid + .. grid-item-card:: CAL FIRE FRAP Fire Perimeters + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + California's historical wildfire perimeter archive, maintained by CAL FIRE's Fire and Resource Assessment Program, with fires back to 1878. + + .. container:: catalog-chip-row + + :bdg-secondary:`Historical Perimeters` :bdg-info:`Fire perimeter polygons` + + .. container:: catalog-meta-row + + **Coverage:** California + + .. container:: catalog-meta-row + + **Update Cadence:** Annual, each spring, adding the previous fire season (release firep25_1, April 2026) + + .. container:: catalog-link-row + + **Details:** :doc:`CAL FIRE FRAP Fire Perimeters ` + + .. container:: catalog-link-row + + **Primary Source:** `CAL FIRE FRAP (2026). Fire Perimeters, release firep25_1 (metadata). `_ + + .. grid-item-card:: FIgLib SmokeBench + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The SmokeBench evaluation images -- HPWREN FIgLib camera frames with the SmokeyNet smoke boxes -- for prompting multimodal LLMs to classify and localize early wildfire smoke. + + .. container:: catalog-chip-row + + :bdg-secondary:`Smoke Detection Benchmark` :bdg-info:`Fixed-camera RGB photographs with smoke bounding boxes` + + .. container:: catalog-meta-row + + **Coverage:** Southern California (HPWREN camera network) + + .. container:: catalog-meta-row + + **Update Cadence:** Static evaluation set (FIgLib itself keeps adding sequences) + + .. container:: catalog-meta-row + + **Inspection:** ``python -m pyhazards.datasets.figlib_smokebench.inspection --root /path/to/figlib --download`` + + .. container:: catalog-link-row + + **Details:** :doc:`FIgLib SmokeBench ` + + .. container:: catalog-link-row + + **Primary Source:** `Qi, T., Li, W., Barnes, N. (2026). SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection. WACV 2026. `_ + .. grid-item-card:: FIRMS :class-card: catalog-entry-card @@ -220,7 +386,7 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-link-row - **Primary Source:** `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product. `_ + **Primary Source:** `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product. `_ .. grid-item-card:: FPA-FOD Tabular :class-card: catalog-entry-card @@ -292,6 +458,60 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `PyHazards FPA-FOD weekly adaptation for the wildfire forecasting path. `_ + .. grid-item-card:: GeoMAC Historical Perimeters + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Wildfire perimeters processed by the USGS GeoMAC service from 2000 to 2019, now distributed by the National Interagency Fire Center. + + .. container:: catalog-chip-row + + :bdg-secondary:`Historical Perimeters` :bdg-info:`Fire perimeter polygons` + + .. container:: catalog-meta-row + + **Coverage:** United States (the 2019 layer covers the conterminous 48 states and Alaska) + + .. container:: catalog-meta-row + + **Update Cadence:** Static archive (GeoMAC was retired on 30 April 2020) + + .. container:: catalog-link-row + + **Details:** :doc:`GeoMAC Historical Perimeters ` + + .. container:: catalog-link-row + + **Primary Source:** `National Interagency Fire Center. Historic Perimeters Combined 2000-2018 GeoMAC (NIFC Open Data). `_ + + .. grid-item-card:: GOES-R ABI Fire/Hot Spot Characterization (FDCF) + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + NOAA's GOES-R ABI Level-2 fire detection and characterization product on the full-disk scan, every 10 minutes since April 2019, openly distributed on AWS. + + .. container:: catalog-chip-row + + :bdg-secondary:`Active Fire Detections` :bdg-info:`Raster imagery time series on the ABI fixed grid` + + .. container:: catalog-meta-row + + **Coverage:** The full disk of each GOES satellite (GOES-East and GOES-West positions over the Americas) + + .. container:: catalog-meta-row + + **Update Cadence:** Continuous operational production + + .. container:: catalog-link-row + + **Details:** :doc:`GOES-R ABI Fire/Hot Spot Characterization (FDCF) ` + + .. container:: catalog-link-row + + **Primary Source:** `Schmidt (2020). Monitoring Fires with the GOES-R Series. In The GOES-R Series, Elsevier, 145-163. `_ + .. grid-item-card:: LANDFIRE :class-card: catalog-entry-card @@ -362,6 +582,68 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `Eidenshink et al. (2007). A project for monitoring trends in burn severity. `_ + .. grid-item-card:: NOAA HMS Smoke Polygons + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Analyst-drawn smoke plume outlines from NOAA's Hazard Mapping System, produced daily since August 2005. + + .. container:: catalog-chip-row + + :bdg-secondary:`Smoke Plumes` :bdg-info:`Analyst-drawn smoke polygons` + + .. container:: catalog-meta-row + + **Coverage:** North America, Hawaii and the Caribbean + + .. container:: catalog-meta-row + + **Update Cadence:** Daily + + .. container:: catalog-link-row + + **Details:** :doc:`NOAA HMS Smoke Polygons ` + + .. container:: catalog-link-row + + **Primary Source:** `Ruminski and Kondragunta (2006). Monitoring fire and smoke emissions with the hazard mapping system. Proc. SPIE 6412. `_ + + .. grid-item-card:: Track-O Wildfire Occurrence + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Daily fire / no-fire grids from NASA FIRMS detections with gridded weather and LANDFIRE fuel covariates, built locally for gridded wildfire-danger experiments. + + .. container:: catalog-chip-row + + :bdg-secondary:`Occurrence Benchmark` :bdg-info:`Daily latitude-longitude grids` + + .. container:: catalog-meta-row + + **Coverage:** The weather grid's extent (global for MERRA-2); the LANDFIRE fuel layer covers the conterminous United States only + + .. container:: catalog-meta-row + + **Update Cadence:** Built by the user from downloaded source files; PyHazards downloads nothing for it + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('wildfire_track_o_raster', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Wildfire Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Track-O Wildfire Occurrence ` + + .. container:: catalog-link-row + + **Primary Source:** `Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product: Algorithm description and initial assessment. `_ + .. grid-item-card:: WFIGS :class-card: catalog-entry-card @@ -397,6 +679,68 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `National Interagency Fire Center. Wildland Fire Incident Geospatial Services (WFIGS). `_ + .. grid-item-card:: Wildfire Risk to Communities: Housing Density + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + USDA Forest Service 30 m rasters of housing-unit density, exposure and wildfire risk for populated areas of the United States (2nd edition, 2024). + + .. container:: catalog-chip-row + + :bdg-secondary:`Exposure and Risk` :bdg-info:`Gridded raster layers` + + .. container:: catalog-meta-row + + **Coverage:** Conterminous United States, Alaska and Hawaii (per-state files and CONUS mosaics) + + .. container:: catalog-meta-row + + **Update Cadence:** Edition-based (2nd edition published June 2024, metadata corrected September 2024) + + .. container:: catalog-link-row + + **Details:** :doc:`Wildfire Risk to Communities: Housing Density ` + + .. container:: catalog-link-row + + **Primary Source:** `Jaffe, Scott, Callahan, Dillon, Karau and Lazarz (2024). Wildfire Risk to Communities: Spatial datasets of wildfire risk for populated areas in the United States. 2nd Edition. Forest Service Research Data Archive. `_ + + .. grid-item-card:: WRF-SFIRE Outputs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Fire-grid outputs of the coupled WRF-SFIRE atmosphere-fire model, read from wrfout files into spread rasters. + + .. container:: catalog-chip-row + + :bdg-secondary:`Simulator Outputs` :bdg-info:`Fire-grid raster time series` + + .. container:: catalog-meta-row + + **Coverage:** Any WRF domain the user configures + + .. container:: catalog-meta-row + + **Update Cadence:** Generated by the user's own WRF-SFIRE runs + + .. container:: catalog-meta-row + + **Inspection:** ``python -m pyhazards.datasets.wrf_sfire.inspection --path /path/to/wrfout_d01_*`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Wildfire Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`WRF-SFIRE Outputs ` + + .. container:: catalog-link-row + + **Primary Source:** `Mandel, Beezley and Kochanski (2011). Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011. Geoscientific Model Development 4:591-610. `_ + .. tab-item:: Flood @@ -410,110 +754,110 @@ primary source, and the most relevant inspection or registry surface. :gutter: 2 :class-container: catalog-grid - .. grid-item-card:: Caravan + .. grid-item-card:: CAMELS-US :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed streamflow benchmark adapter aligned to the Caravan large-sample hydrology ecosystem. + Reader for a local copy of CAMELS-US (671 US catchments, daily forcings, USGS streamflow and catchment attributes) in the setup of Kratzert et al. (2019), as NeuralHydrology reads it. .. container:: catalog-chip-row - :bdg-secondary:`Streamflow Benchmark` :bdg-info:`Graph-temporal basin or node sequences` + :bdg-secondary:`Streamflow Benchmark` :bdg-info:`Daily basin time series with static attributes` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned streamflow forecasting samples + **Coverage:** 671 catchments in the contiguous United States (531 in the Kratzert et al. 2019 benchmark) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Static research dataset (extended Maurer forcings released separately in 2019) .. container:: catalog-meta-row - **Registry:** ``load_dataset('caravan_streamflow', ...)`` + **Registry:** ``load_dataset('camels_us_streamflow', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`Caravan ` + **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`CAMELS-US ` .. container:: catalog-link-row - **Details:** :doc:`Caravan ` + **Details:** :doc:`CAMELS-US ` .. container:: catalog-link-row - **Primary Source:** `Caravan - A global community dataset for large-sample hydrology `_ + **Primary Source:** `Addor, Newman, Mizukami and Clark (2017). The CAMELS data set: catchment attributes and meteorology for large-sample studies. HESS 21:5293-5313. `_ - .. grid-item-card:: FloodCastBench + .. grid-item-card:: Caravan :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed inundation benchmark adapter aligned to the FloodCastBench evaluation ecosystem. + Reader for a local copy of Caravan, the global large-sample hydrology dataset (daily ERA5-Land forcings, catchment attributes and observed streamflow), in NeuralHydrology's sample layout. .. container:: catalog-chip-row - :bdg-secondary:`Inundation Benchmark` :bdg-info:`Raster inundation sequences` + :bdg-secondary:`Streamflow Benchmark` :bdg-info:`Daily basin time series with static attributes` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned flood inundation samples + **Coverage:** 6,830 catchments in the original release (Australia, Brazil, Canada, Chile, Great Britain, Central Europe, United States) plus extensions .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Versioned Zenodo releases (netCDF and CSV editions) plus community extensions .. container:: catalog-meta-row - **Registry:** ``load_dataset('floodcastbench_inundation', ...)`` + **Registry:** ``load_dataset('caravan_streamflow', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`FloodCastBench ` + **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`Caravan ` .. container:: catalog-link-row - **Details:** :doc:`FloodCastBench ` + **Details:** :doc:`Caravan ` .. container:: catalog-link-row - **Primary Source:** `FloodCastBench `_ + **Primary Source:** `Kratzert et al. (2023). Caravan - A global community dataset for large-sample hydrology. Scientific Data 10:61. `_ - .. grid-item-card:: HydroBench + .. grid-item-card:: HydroGraphNet White River :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed streamflow diagnostics adapter aligned to the HydroBench ecosystem. + Reader for a local copy of the HydroGraphNet dataset (HEC-RAS flood simulations on a 4,787-cell mesh of the White River near Muncie, Indiana), read as PhysicsNeMo's HydroGraphDataset reads it. .. container:: catalog-chip-row - :bdg-secondary:`Streamflow Benchmark` :bdg-info:`Graph-temporal basin or node sequences` + :bdg-secondary:`Inundation Benchmark` :bdg-info:`Unstructured 2-D mesh cells with a k-nearest-neighbour graph` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned streamflow forecasting samples + **Coverage:** White River near Muncie, Indiana, USA .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Static research dataset (released 2025-03-05) .. container:: catalog-meta-row - **Registry:** ``load_dataset('hydrobench_streamflow', ...)`` + **Registry:** ``load_dataset('hydrographnet_white_river', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`HydroBench ` + **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`HydroGraphNet White River ` .. container:: catalog-link-row - **Details:** :doc:`HydroBench ` + **Details:** :doc:`HydroGraphNet White River ` .. container:: catalog-link-row - **Primary Source:** `HydroBench `_ + **Primary Source:** `Taghizadeh, Zandsalimi, Nabian, Shafiee-Jood and Alemazkoor (2025). Interpretable physics-informed graph neural networks for flood forecasting. Computer-Aided Civil and Infrastructure Engineering 40(18):2629-2649. `_ .. grid-item-card:: NOAA Flood Events :class-card: catalog-entry-card @@ -550,40 +894,75 @@ primary source, and the most relevant inspection or registry surface. **Primary Source:** `NOAA National Centers for Environmental Information. Storm Events Database Documentation. `_ - .. grid-item-card:: WaterBench + .. grid-item-card:: Synthetic Mesh Hydrographs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random mesh fields and toy hydrographs in the HydroGraphNet (White River) layout, for smoke tests of hydrographnet and of mesh inundation rollouts. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Graph-temporal basin or node sequences` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('flood_mesh_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Flood Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic Mesh Hydrographs ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/flood/hydrograph.py) `_ + + .. grid-item-card:: Synthetic Urban Flood Events :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed streamflow benchmark adapter aligned to the WaterBench ecosystem. + Random urban flood events in the UrbanFloodCast one-shot layout (current state, rainfall and terrain in; depth and discharges of 24 steps out), for smoke tests of urbanfloodcast. .. container:: catalog-chip-row - :bdg-secondary:`Streamflow Benchmark` :bdg-info:`Graph-temporal basin or node sequences` + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Raster inundation sequences` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned streamflow forecasting samples + **Coverage:** None (synthetic) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Generated on every load .. container:: catalog-meta-row - **Registry:** ``load_dataset('waterbench_streamflow', ...)`` + **Registry:** ``load_dataset('urbanfloodcast_synthetic', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Flood Benchmark `, :doc:`WaterBench ` + **Related Benchmarks:** :doc:`Flood Benchmark ` .. container:: catalog-link-row - **Details:** :doc:`WaterBench ` + **Details:** :doc:`Synthetic Urban Flood Events ` .. container:: catalog-link-row - **Primary Source:** `WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting `_ + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/flood/urbanfloodcast.py) `_ .. tab-item:: Earthquake @@ -598,110 +977,110 @@ primary source, and the most relevant inspection or registry surface. :gutter: 2 :class-container: catalog-grid - .. grid-item-card:: AEFA Forecast + .. grid-item-card:: SeisBench-format Waveforms :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed dense-grid forecasting adapter aligned to the AEFA earthquake forecasting workflow. + Reader for labelled three-component waveform datasets in the SeisBench format (STEAD, INSTANCE, ETHZ, ... as distributed for SeisBench) and in STEAD's own CSV + HDF5 layout. .. container:: catalog-chip-row - :bdg-secondary:`Forecast Benchmark` :bdg-info:`Dense-grid wavefield tensors` + :bdg-secondary:`Waveform Benchmark` :bdg-info:`Three-component station waveform windows` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned earthquake forecasting samples + **Coverage:** Dataset dependent (STEAD global; INSTANCE Italy) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Static benchmark releases downloaded by the user .. container:: catalog-meta-row - **Registry:** ``load_dataset('aefa_forecast', ...)`` + **Registry:** ``load_dataset('seisbench_waveforms', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`AEFA ` + **Related Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`SeisBench `, :doc:`pick-benchmark ` .. container:: catalog-link-row - **Details:** :doc:`AEFA Forecast ` + **Details:** :doc:`SeisBench-format Waveforms ` .. container:: catalog-link-row - **Primary Source:** `AEFA `_ + **Primary Source:** `Woollam, J., Münchmeyer, J., Tilmann, F., et al. (2022). SeisBench - A Toolbox for Machine Learning in Seismology. Seismological Research Letters 93(3):1695-1709. `_ - .. grid-item-card:: pick-benchmark + .. grid-item-card:: Synthetic Phase-Picking Waveforms :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed waveform picking adapter aligned to the pick-benchmark evaluation ecosystem. + Synthetic three-component windows with P and S wavelets for picking smoke runs. Not real data. .. container:: catalog-chip-row - :bdg-secondary:`Waveform Benchmark` :bdg-info:`Multichannel waveform windows` + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Three-component waveform windows` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned earthquake phase-picking samples + **Coverage:** Not applicable (synthetic) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Generated on load from a fixed seed .. container:: catalog-meta-row - **Registry:** ``load_dataset('pick_benchmark_waveforms', ...)`` + **Registry:** ``load_dataset('earthquake_waveforms_synthetic', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`pick-benchmark ` + **Related Benchmarks:** :doc:`Earthquake Benchmark ` .. container:: catalog-link-row - **Details:** :doc:`pick-benchmark ` + **Details:** :doc:`Synthetic Phase-Picking Waveforms ` .. container:: catalog-link-row - **Primary Source:** `pick-benchmark `_ + **Primary Source:** `PyHazards synthetic phase-picking generator (no external source). `_ - .. grid-item-card:: SeisBench + .. grid-item-card:: Synthetic Wavefield Sequences :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed waveform picking adapter aligned to the SeisBench ecosystem. + Synthetic X / Y / Z ground-velocity wavefields of point sources for wavefield-forecasting smoke runs. Not real data. .. container:: catalog-chip-row - :bdg-secondary:`Waveform Benchmark` :bdg-info:`Multichannel waveform windows` + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Regular grid of three-component velocity frames` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned earthquake phase-picking samples + **Coverage:** Not applicable (synthetic) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Generated on load .. container:: catalog-meta-row - **Registry:** ``load_dataset('seisbench_waveforms', ...)`` + **Registry:** ``load_dataset('earthquake_wavefield_synthetic', ...)`` .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Earthquake Benchmark `, :doc:`SeisBench ` + **Related Benchmarks:** :doc:`Earthquake Benchmark ` .. container:: catalog-link-row - **Details:** :doc:`SeisBench ` + **Details:** :doc:`Synthetic Wavefield Sequences ` .. container:: catalog-link-row - **Primary Source:** `SeisBench - A Toolbox for Machine Learning in Seismology `_ + **Primary Source:** `PyHazards synthetic wavefield generator (no external source). `_ .. tab-item:: Tropical Cyclone @@ -716,12 +1095,47 @@ primary source, and the most relevant inspection or registry surface. :gutter: 2 :class-container: catalog-grid + .. grid-item-card:: Hurricast IBTrACS + ERA5 Inputs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The inputs of Hurricast (Boussioux et al. 2022): 30 IBTrACS statistical features and nine storm-centred ERA5 maps per 3-hour step, 8 steps per sample, with the 24-hour intensity or position as target. + + .. container:: catalog-chip-row + + :bdg-secondary:`Model Inputs (best track + reanalysis)` :bdg-info:`Storm-centred sequences of feature vectors and 25 x 25 one-degree maps` + + .. container:: catalog-meta-row + + **Coverage:** All IBTrACS basins (the paper reports test scores for the North Atlantic and Eastern Pacific) + + .. container:: catalog-meta-row + + **Update Cadence:** Follows the user's IBTrACS and ERA5 files + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('hurricast_ibtracs_era5', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`IBTrACS ` + + .. container:: catalog-link-row + + **Details:** :doc:`Hurricast IBTrACS + ERA5 Inputs ` + + .. container:: catalog-link-row + + **Primary Source:** `Boussioux, L., C. Zeng, T. Guenais and D. Bertsimas (2022). Hurricane Forecasting: A Novel Multimodal Machine Learning Framework. Weather and Forecasting 37(6), 817-831. `_ + .. grid-item-card:: IBTrACS :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed storm-track adapter aligned to the IBTrACS tropical cyclone archive. + NOAA NCEI's International Best Track Archive for Climate Stewardship (v04r01), read from its CSV or netCDF files into best-track forecasting windows. .. container:: catalog-chip-row @@ -729,11 +1143,11 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned tropical cyclone track and intensity samples + **Coverage:** All tropical cyclone basins (NA, SA, EP, WP, NI, SI, SP) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Updated by NCEI several times a week; PyHazards reads the file the user downloads .. container:: catalog-meta-row @@ -749,30 +1163,271 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-link-row - **Primary Source:** `IBTrACS `_ + **Primary Source:** `Knapp, K. R., M. C. Kruk, D. H. Levinson, H. J. Diamond and C. J. Neumann (2010). The International Best Track Archive for Climate Stewardship (IBTrACS): Unifying tropical cyclone best track data. Bulletin of the American Meteorological Society 91, 363-376. `_ - .. grid-item-card:: TCBench Alpha + .. grid-item-card:: SHIPS Predictors (Xu et al. 2021) :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed storm-track benchmark adapter aligned to the TCBench Alpha ecosystem. + The standardised SHIPS predictor table of Xu et al. (2021) with 24-hour intensity-change targets, read into the official leave-one-year-out folds. .. container:: catalog-chip-row - :bdg-secondary:`Track Benchmark` :bdg-info:`Storm-track history sequences` + :bdg-secondary:`Intensity Benchmark` :bdg-info:`Tabular feature vectors` + + .. container:: catalog-meta-row + + **Coverage:** Atlantic test basin; global training basins (AL, EP, WP, SH, ...) + + .. container:: catalog-meta-row + + **Update Cadence:** Static release (2021) + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('ships_xu2021', ...)`` .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned tropical cyclone track and intensity samples + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`SHIPS Predictors (Xu et al. 2021) ` + + .. container:: catalog-link-row + + **Primary Source:** `Xu, W., K. Balaguru, A. August, N. Lalo, N. Hodas, M. DeMaria and D. Judi (2021). Deep Learning Experiments for Tropical Cyclone Intensity Forecasts. Weather and Forecasting 36(4), 1453-1470. `_ + + .. grid-item-card:: Synthetic Hurricast Inputs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random inputs in the hurricast_ibtracs_era5 layout (8 steps of 30 statistical features and 9 maps of 25 x 25) for smoke tests of hurricast. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Feature sequences and image sequences` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('hurricast_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic Hurricast Inputs ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: Synthetic SAF-Net Inputs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random inputs in the SAF-Net layout (96 wide predictors and (2, 4, 31, 31, 4) u/v wind cubes) for smoke tests of saf_net. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Tabular feature vectors` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('safnet_cma_era_interim_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic SAF-Net Inputs ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: Synthetic SHIPS Predictors + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random inputs in the layout of ships_xu2021 (121 predictors, 24-hour intensity change in knots) for smoke tests of tropicalcyclone_mlp. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Tabular feature vectors` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('ships_xu2021_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic SHIPS Predictors ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: Synthetic Storm Histories + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random storm-history features and lat / lon / intensity targets for smoke tests of the generic experimental storm adapters (hurricast, tcif_fusion). + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Storm-track history sequences` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('tc_tracks_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic Storm Histories ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: Synthetic TCIF-fusion Inputs + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random inputs in the TCIF-fusion layout (ERA5 U, V, W, SST, ALL, 30 history features, infrared images; channels last) for smoke tests of tcif_fusion. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Gridded fields, images and feature vectors` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('tcif_fusion_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic TCIF-fusion Inputs ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: Synthetic TCND Samples + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Random inputs in the TropiCycloneNet (TCND) layout with random-walk targets for smoke tests of tropicyclonenet. + + .. container:: catalog-chip-row + + :bdg-secondary:`Synthetic Smoke Data` :bdg-info:`Storm-track history sequences` + + .. container:: catalog-meta-row + + **Coverage:** None (synthetic) + + .. container:: catalog-meta-row + + **Update Cadence:** Generated on every load + + .. container:: catalog-meta-row + + **Registry:** ``load_dataset('tropicyclonenet_dataset_synthetic', ...)`` + + .. container:: catalog-meta-row + + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Details:** :doc:`Synthetic TCND Samples ` + + .. container:: catalog-link-row + + **Primary Source:** `PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) `_ + + .. grid-item-card:: TCBench Alpha + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Weather-model cyclone tracks (Pangu-Weather, FourCastNet v2, AIFS; 2023) matched to IBTrACS, with the raw forecast fields they were tracked in; read by pyhazards.forecasts at a pinned revision. + + .. container:: catalog-chip-row + + :bdg-secondary:`Track Benchmark` :bdg-info:`Storm-track tables and global gridded forecast fields` .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Coverage:** Global tropical cyclones present in IBTrACS .. container:: catalog-meta-row - **Registry:** ``load_dataset('tcbench_alpha', ...)`` + **Update Cadence:** Static release (PyHazards pins revision 0124d14d) .. container:: catalog-meta-row @@ -784,14 +1439,14 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-link-row - **Primary Source:** `TCBench Alpha `_ + **Primary Source:** `Gomez, M. et al. (2026). TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale. arXiv:2601.23268. `_ - .. grid-item-card:: TropiCycloneNet-Dataset + .. grid-item-card:: TropiCycloneNet Dataset :class-card: catalog-entry-card .. container:: catalog-entry-summary - Synthetic-backed storm-track benchmark adapter aligned to the TropiCycloneNet-Dataset ecosystem. + The TropiCycloneNet Dataset (TCND) of Huang et al. (2025) - best tracks, environmental features and ERA5 500 hPa geopotential for 3,630 storms in six basins - read in the layout of the official TropiCycloneNet loader. .. container:: catalog-chip-row @@ -799,11 +1454,11 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-meta-row - **Coverage:** Benchmark-aligned tropical cyclone track and intensity samples + **Coverage:** Six basins (EP, NA, NI, SI, SP, WP) .. container:: catalog-meta-row - **Update Cadence:** Generated locally for smoke and benchmark-alignment runs + **Update Cadence:** Static releases (Zenodo 15009527 dataset, 17104690 training data) .. container:: catalog-meta-row @@ -811,15 +1466,15 @@ primary source, and the most relevant inspection or registry surface. .. container:: catalog-meta-row - **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`TropiCycloneNet-Dataset ` + **Related Benchmarks:** :doc:`Tropical Cyclone Benchmark `, :doc:`TropiCycloneNet Dataset ` .. container:: catalog-link-row - **Details:** :doc:`TropiCycloneNet-Dataset ` + **Details:** :doc:`TropiCycloneNet Dataset ` .. container:: catalog-link-row - **Primary Source:** `TropiCycloneNet-Dataset `_ + **Primary Source:** `Huang, C., P. Mu, J. Zhang, S. Chan, S. Zhang, H. Yan, S. Chen and C. Bai (2025). Benchmark dataset and deep learning method for global tropical cyclone forecasting. Nature Communications 16, 5923. `_ @@ -856,16 +1511,16 @@ hazard group before branching into the full catalog. **Start with:** :doc:`Caravan ` - Synthetic-backed streamflow benchmark adapter aligned to the Caravan large-sample hydrology ecosystem. + Reader for a local copy of Caravan, the global large-sample hydrology dataset (daily ERA5-Land forcings, catchment attributes and observed streamflow), in NeuralHydrology's sample layout. **Primary Surface:** Registry: ``load_dataset('caravan_streamflow', ...)`` .. grid-item-card:: Earthquake :class-card: catalog-detail-card - **Start with:** :doc:`SeisBench ` + **Start with:** :doc:`SeisBench-format Waveforms ` - Synthetic-backed waveform picking adapter aligned to the SeisBench ecosystem. + Reader for labelled three-component waveform datasets in the SeisBench format (STEAD, INSTANCE, ETHZ, ... as distributed for SeisBench) and in STEAD's own CSV + HDF5 layout. **Primary Surface:** Registry: ``load_dataset('seisbench_waveforms', ...)`` @@ -874,7 +1529,7 @@ hazard group before branching into the full catalog. **Start with:** :doc:`IBTrACS ` - Synthetic-backed storm-track adapter aligned to the IBTrACS tropical cyclone archive. + NOAA NCEI's International Best Track Archive for Climate Stewardship (v04r01), read from its CSV or netCDF files into best-track forecasting windows. **Primary Surface:** Registry: ``load_dataset('ibtracs_tracks', ...)`` @@ -909,21 +1564,42 @@ model and evaluation coverage. datasets/era5 datasets/goesr + datasets/hrrr + datasets/landscan_population datasets/merra2 + datasets/ndfd + datasets/nohrsc_snodas + datasets/frap_fire_perimeters + datasets/figlib_smokebench datasets/firms datasets/fpa_fod_tabular datasets/fpa_fod_weekly + datasets/geomac_historical + datasets/goesr_fdcf datasets/landfire datasets/mtbs + datasets/hms_smoke + datasets/wildfire_track_o datasets/wfigs + datasets/wrc_housing_density + datasets/wrf_sfire + datasets/camels_us_streamflow datasets/caravan_streamflow - datasets/floodcastbench_inundation - datasets/hydrobench_streamflow + datasets/hydrographnet_white_river datasets/noaa_flood - datasets/waterbench_streamflow - datasets/aefa_forecast - datasets/pick_benchmark_waveforms + datasets/flood_mesh_synthetic + datasets/urbanfloodcast_synthetic datasets/seisbench_waveforms + datasets/earthquake_waveforms_synthetic + datasets/earthquake_wavefield_synthetic + datasets/hurricast_ibtracs_era5 datasets/ibtracs_tracks + datasets/ships_xu2021 + datasets/hurricast_synthetic + datasets/safnet_cma_era_interim_synthetic + datasets/ships_xu2021_synthetic + datasets/tc_tracks_synthetic + datasets/tcif_fusion_synthetic + datasets/tropicyclonenet_dataset_synthetic datasets/tcbench_alpha datasets/tropicyclonenet_dataset diff --git a/docs/source/pyhazards_forecasts.rst b/docs/source/pyhazards_forecasts.rst new file mode 100644 index 00000000..b91e8b4c --- /dev/null +++ b/docs/source/pyhazards_forecasts.rst @@ -0,0 +1,220 @@ +Foundation Weather Models +========================= + +Overview +-------- + +FourCastNet, GraphCast and Pangu-Weather are global medium-range weather models (36-75 million +parameters, 0.25-degree global fields, 6-hourly steps). They are not tropical cyclone models: their +cyclone results come from running a **tracker** on their forecast fields and scoring the tracks against +best tracks. PyHazards therefore does not list them as models and does not reimplement them. Earlier +releases registered ``fourcastnet_tc``, ``graphcast_tc`` and ``pangu_tc``, which were 15K-152K-parameter +networks with no forecast fields, weights or tracker; they were removed. + +:mod:`pyhazards.forecasts` provides the pipeline instead: + +#. **Forecast fields or tracks** from where they are officially published (TCBench, WeatherBench 2), or + from the real models run through NVIDIA earth2studio, which you install yourself. +#. **Trackers**: the TempestExtremes rules TCBench uses (checked against the official binaries) and the + ECMWF-style tracker described in the Pangu-Weather and GraphCast papers. +#. **Matching and scoring** against IBTrACS: great-circle track error in km, wind error in knots and + pressure error in hPa per lead time (the ``tc`` benchmark's metrics), optionally computed exactly as + TCBench's evaluation computes them. + +These entries appear as ``Foundation model pipeline`` on :doc:`appendix_a_coverage`. + +The models +---------- + +.. list-table:: + :widths: 14 30 28 28 + :header-rows: 1 + :class: dataset-list + + * - Model + - Code and weights (licences) + - Paper's cyclone evaluation + - PyHazards routes + * - FourCastNet + - `NVlabs/FourCastNet `_ (BSD-3-Clause); 74,691,840-parameter + AFNO; NERSC v0 weights (licence not stated). earth2studio's ``FCN`` is a 26-variable retrain + (HF ``nvidia/fourcastnet1``, Apache-2.0 model card). + - Qualitative only (Hurricane Michael 2018 ensemble, eye = MSLP minimum; Pathak et al. 2022, Sec. 3.1). + - Run with earth2studio (``fourcastnet``); TCBench's 2023 tracks and fields of FourCastNet v2 + (``fourcastnet_v2``: SFNO-small, a different model). WeatherBench 2 has no FourCastNet forecasts. + * - GraphCast + - `google-deepmind/weathernext `_ (Apache-2.0, JAX); + 36,348,131 parameters used (paper: 36.7M); weights CC BY 4.0 per the README since 2026-08-06 + (the checkpoint metadata still says CC BY-NC-SA 4.0). + - Modified ECMWF tracker (never released) on 2018-2021 forecasts, homogeneous comparison with HRES, + median and mean geodesic error to 5 days; numbers only in figures (Lam et al. 2023, supplement 8.1). + - WeatherBench 2 forecasts (2018 from the paper's 1979-2017 model, and 2020); earth2studio + (``graphcast_operational``, ``graphcast_small``); :data:`~pyhazards.forecasts.GRAPHCAST_TRACKER`. + * - Pangu-Weather + - `198808xc/Pangu-Weather `_ (no code licence; ONNX + inference only); about 64.2M learnable parameters per lead-time model; **weights CC BY-NC-SA 4.0, + commercial use forbidden**. + - ECMWF-style tracker on 88 named 2018 cyclones (TC2018): mean direct position error 120.29 km at + 3 days and 195.65 km at 5 days (HRES 162.28 / 272.10 km) (Bi et al., arXiv:2211.02556, Sec. 4.2.2). + - TCBench's 2023 tracks and raw fields (``pangu``); WeatherBench 2 forecasts 2018-2022; earth2studio + (``pangu_6``, ``pangu_24``); :data:`~pyhazards.forecasts.PANGU_TRACKER` or the TCBench rules. + +The same information is available in code as :data:`pyhazards.forecasts.FOUNDATION_MODELS`. PyHazards +never downloads, bundles or redistributes model weights or forecasts; everything is read at run time +from the providers. Forecasts derived from the Pangu-Weather weights inherit their non-commercial terms. + +Trackers +-------- + +**TempestExtremes rules (TCBench).** :func:`~pyhazards.forecasts.detect_nodes` and +:func:`~pyhazards.forecasts.stitch_nodes` implement the DetectNodes / StitchNodes options of TCBench's +``dev/TempestExtremes_example.sh`` (MSLP minima merged within 6 degrees, a 200 Pa closed MSLP contour +within 5.5 degrees, a 58.8 m2 s-2 warm-core closed contour of z300 - z500 within 6.5 degrees; nodes +linked within 8 degrees, tracks of at least 12 h with 10 m wind >= 10 m/s at two points and +\|lat\| <= 50 at one). The code is written from the published algorithm (Ullrich and Zarzycki 2017; +Ullrich et al. 2021); the official C++ tools are used only as the test oracle. + +**ECMWF-style tracker (Pangu-Weather and GraphCast papers).** :func:`~pyhazards.forecasts.follow_cyclone` +follows one cyclone from its observed position: candidates are MSLP local minima within 445 km (of the +current position for Pangu-Weather, of a first guess mixing the last displacement and the 200-850 hPa +steering wind for ECMWF / GraphCast), checked for 850 hPa vorticity above 5e-5 s-1 within 278 km, a +thickness maximum when extratropical and 10 m wind above 8 m/s when over land. The GraphCast preset uses +the hyper-parameters the supplement marks in bold (222.5 km candidate radius, 208.5 km check radius, +50-50 first guess, no turn of 90 degrees or more). Neither paper released its tracker, so this is a +re-implementation of their text; what the text leaves open (the definition of "extratropical", the +land mask, grid-point positions) is a documented parameter. + +Verification +------------ + +Run with ``tests/oracle/test_tempest_oracle.py``, ``tests/oracle/test_tcbench_evaluation_oracle.py`` +and ``tests/oracle/test_forecasts_weather_oracle.py`` (oracle suites ``tc-tracking`` and ``weather``), +plus ``tests/test_forecasts_*.py``: + +* **Tracker vs official TempestExtremes v2.4.2** (built from source): identical nodes, printed values + and track files on synthetic fields with cyclones in both hemispheres, across the dateline and near + the pole, for TCBench's options and for variants (diagonal connectivity, regional grids, + ``--maxgap``, threshold counts). +* **Tracker vs TCBench's released tracks**: on TCBench's raw Pangu-Weather fields for the forecasts of + 2023-01-15 12 UTC, 2023-05-07 00 UTC, 2023-07-16 12 UTC and 2023-10-19 12 UTC, PyHazards writes + TCBench's ``unmatched_tracks`` files byte for byte (so do the official binaries), and matching the + tracks to TCBench's 2023 IBTrACS extract gives exactly TCBench's ``matched_tracks`` rows. +* **Scoring vs TCBench's own code**: on every row TCBench evaluates (10,983 of the 11,031 released + Pangu-Weather rows, 8,335 of the 8,403 FourCastNet v2 rows), ``protocol="tcbench"`` equals TCBench's + ``_DPE`` and ``_AE`` (``dev/metrics_test.py``) to 1e-9. This includes a TCBench quirk: it reads IBTrACS latitudes + and longitudes as ``float16`` and evaluates the haversine formula with the half-precision latitude, + which moves individual errors by up to several km (mean errors by about 0.1 km). +* **Following tracker**: synthetic vortices on known tracks in both hemispheres are followed within half + a grid cell by all presets; lows without cyclonic vorticity, weak lows over land, cold-core lows + poleward of the extratropical latitude and (GraphCast preset) reversals are rejected. +* **Sources**: TCBench field reader on files with TCBench's packed layout; the earth2studio runner with + earth2studio's own ``Persistence`` model; WeatherBench 2 slices of the real Pangu-Weather and GraphCast + stores locate Typhoon Kong-rey's centre within 100 km of IBTrACS. + +Reproduced published numbers +---------------------------- + +TCBench's official notebook prints the errors of sample rows of its 2023 Pangu-Weather evaluation. +``scripts/reproduce_tcbench_tracks.py`` recomputes them end to end: raw Pangu-Weather fields from +TCBench's Hugging Face dataset, PyHazards' TempestExtremes-rule tracker, HuracanPy-rule matching, +``protocol="tcbench"`` scoring against NCEI IBTrACS v04r01. + +.. list-table:: + :widths: 22 22 18 18 20 + :header-rows: 1 + :class: dataset-list + + * - Storm (SID) + - Forecast + - TCBench DPE (km) + - PyHazards DPE (km) + - Wind / pressure error + * - Don (2023193N37305) + - 2023-07-16 12 UTC + 84 h + - 302.565885 + - 302.565885 + - 21.254614 kt / 9.488 hPa (as published) + * - Norma (2023290N12256) + - 2023-10-19 12 UTC + 12 h + - 18.454374 + - 18.454374 + - 62.780767 kt / 39.9856 hPa (as published) + * - Mocha (2023129N08091) + - 2023-05-07 00 UTC + 120 h + - 424.145817 + - 424.145817 + - 25.624799 kt / 9.5378 hPa (as published) + * - Cheneso (2023013S08081) + - 2023-01-15 12 UTC + 60 h + - 216.013123 + - 206.263455 (216.013123 with TCBench's IBTrACS copy) + - 4.770411 kt / 6.561 hPa (as published) + +The Cheneso row differs only because NCEI revised the best track since TCBench's evaluation (longitude +at 2023-01-18 00 UTC 55.8 then, 55.9 now); with the position in TCBench's own IBTrACS extract the +published value is reproduced. Over the whole released 2023 sample, TCBench's protocol gives mean track +errors of 68.8 / 103.5 / 150.7 / 202.6 / 270.8 km at 1-5 days for Pangu-Weather (453-554 rows per lead, +73 storms) and 69.2 / 111.1 / 170.5 / 225.4 / 314.3 km for FourCastNet v2; TCBench itself reports these +only in figures, so they are PyHazards' computation from its released tracks, not published numbers. + +**Not reproduced.** Pangu-Weather's TC2018 numbers (120.29 / 195.65 km) need its deterministic forecasts +for every initial time of 88 cyclones; the only public archive (WeatherBench 2) stores each lead time as a +full global chunk with all 13 pressure levels, about 1.8 GB per forecast for the fields the tracker +needs (41.9 MB per lead time for each of u and v), roughly a terabyte for TC2018, and the paper's +exact sample (cyclones present in both IBTrACS and HRES / TIGGE, initial times) is not published. GraphCast's numbers exist only in figures, its tracker +was never released, and its 2018-2021 forecasts at 06 / 18 UTC are not published (WeatherBench 2 has +00 / 12 UTC forecasts for 2018 and 2020). FourCastNet's paper has no aggregate cyclone numbers. As a +qualitative check on the paper case of Pangu-Weather's Fig. 1 (Typhoon Kong-rey from 2018-09-30 00 UTC), +the Pangu-Weather tracker on WeatherBench 2's Pangu-Weather forecast is 15, 39, 12, 12 and 26 km from +IBTrACS at 1-5 days (the paper describes its track as almost coinciding with the best track); +WeatherBench 2's GraphCast forecast of the same case, tracked with the GraphCast preset, is 15, 12, 33, +88 and 222 km off. + +Usage +----- + +Score TCBench's released tracks with TCBench's protocol: + +.. code-block:: python + + from pyhazards.datasets.tc import download_ibtracs, read_ibtracs + from pyhazards.forecasts import (download_tcbench_file, read_tcbench_matched_tracks, + score_forecast_tracks, tcbench_ibtracs, tcbench_path) + + tracks = read_tcbench_matched_tracks(download_tcbench_file(tcbench_path("pangu", "matched"), "data/tcbench")) + ibtracs = tcbench_ibtracs(read_ibtracs(download_ibtracs("data/ibtracs", subset="ALL")), year=2023) + result = score_forecast_tracks(tracks, ibtracs, lead_hours=[24, 48, 72, 96, 120], protocol="tcbench") + print(result.metrics["track_error_km_72h"], result.metadata["units"]) + +Track a forecast yourself (TCBench rules, or the papers' tracker): + +.. code-block:: python + + from pyhazards.forecasts import (GRAPHCAST_TRACKER, follow_forecast_tracks, read_tcbench_fields, + read_weatherbench2_forecast, required_variables, + tempest_forecast_tracks) + + fields = read_tcbench_fields("pangu", "2023-07-16 12:00") # ~200 MB of range requests + table = tempest_forecast_tracks(fields, ibtracs, "2023-07-16 12:00") # forecast-track table + + gc = read_weatherbench2_forecast("graphcast", "2018-09-30T00", # needs pyhazards[weather] + variables=required_variables(GRAPHCAST_TRACKER), + lat_bounds=(0, 55), lon_bounds=(95, 185)) + table = follow_forecast_tracks(gc, ibtracs, "2018-09-30T00", GRAPHCAST_TRACKER) + +Run a model through earth2studio (install it and the model's extra yourself; weights are downloaded by +earth2studio under their own licences; a 0.25-degree model needs a GPU with about 40 GB): + +.. code-block:: python + + from earth2studio.data import ARCO + from pyhazards.forecasts import load_earth2studio_model, run_earth2studio_forecast + + model = load_earth2studio_model("fourcastnet", device="cuda") + fields = run_earth2studio_forecast(model, ARCO(), "2018-10-07T00", lead_hours=120, device="cuda") + table = tempest_forecast_tracks(fields, ibtracs, "2018-10-07T00") + +API +--- + +See :doc:`api/pyhazards.forecasts`. diff --git a/docs/source/pyhazards_metrics.rst b/docs/source/pyhazards_metrics.rst index 128f5896..329dd4da 100644 --- a/docs/source/pyhazards_metrics.rst +++ b/docs/source/pyhazards_metrics.rst @@ -15,6 +15,45 @@ Core Classes - ``RegressionMetrics``: MAE and RMSE style regression summaries. - ``SegmentationMetrics``: segmentation-oriented aggregation. +Hydrological Metrics +-------------------- + +``pyhazards.metrics.hydrology`` ports NeuralHydrology's evaluation metrics (BSD-3-Clause) for daily +discharge series: ``nse``, ``mse``, ``rmse``, ``kge``, ``alpha_nse``, ``beta_kge``, ``beta_nse``, +``pearson_r``, the flow-duration-curve biases ``fdc_fhv``, ``fdc_fms`` and ``fdc_flv``, and the peak +metrics ``mean_peak_timing``, ``missed_peaks`` and ``mean_absolute_percentage_peak_error``. Missing values +are skipped as in NeuralHydrology. ``calculate_metrics`` scores one basin and ``aggregate_basin_metrics`` +reports the median and mean over basins; the flood benchmark (``flood.streamflow``) uses both. + +.. code-block:: python + + import numpy as np + from pyhazards.metrics.hydrology import calculate_metrics + + obs = np.array([1.0, 3.0, 2.0, 5.0, 4.0]) + sim = np.array([1.2, 2.5, 2.1, 4.0, 4.4]) + print(calculate_metrics(obs, sim, metrics=["nse", "kge"])) + +Inundation Metrics +------------------ + +``pyhazards.metrics.inundation`` scores water-depth predictions for the flood benchmark +(``flood.inundation``): ``pixel_mae`` and ``rmse`` (depth errors over all cells), ``iou`` / ``f1`` of the wet +cells, and, per event as in the UrbanFloodCast evaluation (``DNO/utils25.py``), ``critical_success_index`` +at 1 / 10 / 50 cm, ``relative_l2`` (FNO's relative L2 error per variable, averaged over variables), +``nash_sutcliffe`` and ``pearson_correlation`` over all predicted variables. ``rollout_rmse`` gives the depth +RMSE at every step of an autoregressive mesh rollout (HydroGraphNet's ``inference.py``). The definitions +are checked against the official code (oracle tests). + +.. code-block:: python + + import torch + from pyhazards.metrics.inundation import inundation_metrics + + pred = torch.rand(2, 32, 32, 24, 3) # (events, Sy, Sx, steps, depth / qx / qy) + target = torch.rand(2, 32, 32, 24, 3) + print(inundation_metrics(pred, target, depth_index=0)) + Usage ----- diff --git a/docs/source/pyhazards_models.rst b/docs/source/pyhazards_models.rst index fd46d953..d7b533c3 100644 --- a/docs/source/pyhazards_models.rst +++ b/docs/source/pyhazards_models.rst @@ -6,6 +6,10 @@ Models Browse PyHazards model implementations across hazard families, compare scope and maturity, and navigate to model-specific detail pages. +Prompted multimodal LLMs used as zero-shot wildfire-smoke detectors (SmokeBench: Qwen2.5-VL, +InternVL3, Idefics2, Gemini 2.5 Pro, GPT-4o) are not ``nn.Module`` models; they are documented +separately under :doc:`pyhazards_prompted`. + At a Glance ----------- @@ -29,7 +33,7 @@ At a Glance .. container:: catalog-stat-value - 24 + 46 .. container:: catalog-stat-note @@ -40,7 +44,7 @@ At a Glance .. container:: catalog-stat-value - 3 + 1 .. container:: catalog-stat-note @@ -51,7 +55,7 @@ At a Glance .. container:: catalog-stat-value - 27 + 45 .. container:: catalog-stat-note @@ -89,11 +93,11 @@ pages and compatible benchmark coverage. .. container:: catalog-entry-summary - A temporal convolution baseline for weekly wildfire activity forecasting. + Attention Swin U-Net with Focal Modulation for next-day wildfire spread (fire-mask segmentation of 64x64 Next Day Wildfire Spread tiles). .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row @@ -105,22 +109,22 @@ pages and compatible benchmark coverage. .. container:: catalog-link-row - **Paper:** `Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer `_ | **Repo:** `Repository `__ + **Paper:** `Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer `_ | **Repo:** `Repository `__ - .. grid-item-card:: DNN-LSTM-AutoEncoder + .. grid-item-card:: Attention U-Net :class-card: catalog-entry-card .. container:: catalog-entry-summary - A two-stage wildfire framework with a DNN stage for incident-level cause and size prediction plus an LSTM + autoencoder stage for weekly forecasting. + U-Net with additive attention gates on its skip connections, in MONAI's implementation, configured by default as the TS-SatFire spatio-temporal (3D) baseline. .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`DNN-LSTM-AutoEncoder ` + **Details:** :doc:`Attention U-Net ` .. container:: catalog-meta-row @@ -128,41 +132,37 @@ pages and compatible benchmark coverage. .. container:: catalog-link-row - **Paper:** `Developing risk assessment framework for wildfire in the United States `_ + **Paper:** `Attention U-Net: Learning Where to Look for the Pancreas `_ | **Repo:** `Repository `__ - .. grid-item-card:: FireCastNet + .. grid-item-card:: ConvGRU :class-card: catalog-entry-card .. container:: catalog-entry-summary - A compact encoder-decoder baseline for wildfire spread mask prediction. + Convolutional GRU (Ballas et al., ICLR 2016) with a convolutional head on the last hidden state: the Conv-GRU baseline that FireCastNet trained for seasonal burned-area prediction. .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`FireCastNet ` + **Details:** :doc:`ConvGRU ` .. container:: catalog-meta-row **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row - - **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` - .. container:: catalog-link-row - **Paper:** `FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction `_ | **Repo:** `Repository `__ + **Paper:** `Delving Deeper into Convolutional Networks for Learning Video Representations `_ - .. grid-item-card:: ForeFire Adapter + .. grid-item-card:: ConvLSTM :class-card: catalog-entry-card .. container:: catalog-entry-summary - A lightweight simulator-style wildfire spread adapter inspired by front-propagation systems. + Convolutional LSTM over daily raster sequences with a convolutional head on the final cell state, as used by the WildfireSpreadTS benchmark. .. container:: catalog-chip-row @@ -170,7 +170,7 @@ pages and compatible benchmark coverage. .. container:: catalog-meta-row - **Details:** :doc:`ForeFire Adapter ` + **Details:** :doc:`ConvLSTM ` .. container:: catalog-meta-row @@ -182,22 +182,22 @@ pages and compatible benchmark coverage. .. container:: catalog-link-row - **Paper:** `ForeFire: A Modular, Scriptable C++ Simulation Engine and Library for Wildland-Fire Spread `_ | **Repo:** `Repository `__ + **Paper:** `Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting `_ | **Repo:** `Repository `__ - .. grid-item-card:: Wildfire Forecasting + .. grid-item-card:: Deep Ensemble :class-card: catalog-entry-card .. container:: catalog-entry-summary - A sequence forecasting baseline for next-window wildfire activity across weekly count features. + Deep ensembles (Lakshminarayanan et al., 2017) of any registered PyHazards model, with the uncertainty terms of the ten-LSTM wildfire-danger ensemble of Kondylatos et al. (2025). .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Segmentation` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`Wildfire Forecasting ` + **Details:** :doc:`Deep Ensemble ` .. container:: catalog-meta-row @@ -205,662 +205,1094 @@ pages and compatible benchmark coverage. .. container:: catalog-link-row - **Paper:** `Wildfire Danger Prediction and Understanding with Deep Learning `_ | **Repo:** `Repository `__ + **Paper:** `Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles `_ - .. grid-item-card:: WildfireSpreadTS + .. grid-item-card:: DeepLabV3 :class-card: catalog-entry-card .. container:: catalog-entry-summary - A temporal convolution wildfire spread baseline over short raster history windows. + DeepLabV3 (Chen et al., 2017) as implemented by segmentation_models_pytorch: a dilated ResNet encoder, atrous spatial pyramid pooling with image-level features, and bilinear up-sampling, configured as the DeepLabV3 baseline of Shadrin et al. (2024) for multi-day wildfire spread. .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`WildfireSpreadTS ` + **Details:** :doc:`DeepLabV3 ` .. container:: catalog-meta-row **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row - - **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` - .. container:: catalog-link-row - **Paper:** `WildfireSpreadTS: A Dataset of Multi-Modal Time Series for Wildfire Spread Prediction `_ | **Repo:** `Repository `__ + **Paper:** `Rethinking Atrous Convolution for Semantic Image Segmentation `_ | **Repo:** `Repository `__ - .. grid-item-card:: WRF-SFIRE Adapter + .. grid-item-card:: DNN-LSTM-AutoEncoder :class-card: catalog-entry-card .. container:: catalog-entry-summary - A lightweight raster wildfire spread adapter inspired by WRF-SFIRE style transport. + A two-stage wildfire framework with a DNN stage for incident-level cause and size prediction plus an LSTM + autoencoder stage for weekly forecasting. .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`WRF-SFIRE Adapter ` + **Details:** :doc:`DNN-LSTM-AutoEncoder ` .. container:: catalog-meta-row **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row - - **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` - .. container:: catalog-link-row - **Paper:** `Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011 `_ | **Repo:** `Repository `__ + **Paper:** `Developing risk assessment framework for wildfire in the United States `_ - .. grid-item-card:: CNN-ASPP + .. grid-item-card:: Earthfarseer :class-card: catalog-entry-card .. container:: catalog-entry-summary - An explainable CNN segmentation model with an ASPP mechanism for next-day wildfire spread prediction. + Spatio-temporal forecaster that combines a local CNN branch with a global Fourier transformer (FoTF) and a SimVP-style temporal block with Fourier mixing (TeDev); a Sim2Real-Fire fire-forecasting baseline. .. container:: catalog-chip-row - :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`CNN-ASPP ` + **Details:** :doc:`Earthfarseer ` .. container:: catalog-meta-row **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row + .. container:: catalog-link-row - **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` + **Paper:** `Earthfarseer: Versatile Spatio-Temporal Dynamical Systems Modeling in One Model `_ | **Repo:** `Repository `__ - .. container:: catalog-link-row + .. grid-item-card:: Earthformer + :class-card: catalog-entry-card - **Paper:** `Application of Explainable Artificial Intelligence in Predicting Wildfire Spread `_ + .. container:: catalog-entry-summary + Space-time Transformer built from cuboid attention with global vectors, a hierarchical encoder-decoder for frame sequences; one of the Sim2Real-Fire forecasting baselines. - .. tab-item:: Earthquake + .. container:: catalog-chip-row - .. container:: catalog-section-note + :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` - Earthquake models span phase picking and dense-grid forecasting, with detail pages linked to the shared earthquake benchmark coverage. + .. container:: catalog-meta-row - .. rubric:: Implemented Models + **Details:** :doc:`Earthformer ` - .. container:: catalog-section-note + .. container:: catalog-meta-row - This table includes both core baselines and public variants or additional implementations for the hazard family. + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. grid:: 1 1 2 2 - :gutter: 2 - :class-container: catalog-grid + .. container:: catalog-link-row - .. grid-item-card:: EQNet + **Paper:** `Earthformer: Exploring Space-Time Transformers for Earth System Forecasting `_ | **Repo:** `Repository `__ + + .. grid-item-card:: FireCastNet :class-card: catalog-entry-card .. container:: catalog-entry-summary - A transformer-style earthquake phase-picking baseline for modern sequence modeling comparisons. + GraphCast on an icosahedral multi-mesh for global seasonal burned-area forecasting on the SeasFire datacube, with the official pretrained weights. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`EQNet ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Earthquake Benchmark ` + **Details:** :doc:`FireCastNet ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`SeisBench ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `An End-To-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning `_ | **Repo:** `Repository `__ + **Paper:** `FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction `_ | **Repo:** `Repository `__ - .. grid-item-card:: EQTransformer + .. grid-item-card:: Logistic Regression (pixel) :class-card: catalog-entry-card .. container:: catalog-entry-summary - A bidirectional sequence encoder for joint earthquake phase picking with attention pooling over waveform windows. + Per-pixel logistic regression over a 3x3 neighbourhood, the linear baseline of WildfireSpreadTS and Next Day Wildfire Spread. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`EQTransformer ` + **Details:** :doc:`Logistic Regression (pixel) ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Earthquake Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`pick-benchmark ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `Earthquake Transformer-An attentive deep-learning model for simultaneous earthquake detection and phase picking `_ | **Repo:** `Repository `__ + **Paper:** `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ | **Repo:** `Repository `__ - .. grid-item-card:: GPD + .. grid-item-card:: Prithvi-EO-2.0 BurnScars :class-card: catalog-entry-card .. container:: catalog-entry-summary - A compact CNN baseline for generalized phase detection and historical earthquake picking comparisons. + The IBM/NASA Prithvi-EO-2.0-300M foundation model fine-tuned to segment burn scars in single HLS scenes (post-fire burned-area mapping), with the official weights. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`GPD ` - - .. container:: catalog-meta-row - - **Benchmark Family:** :doc:`Earthquake Benchmark ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`pick-benchmark ` + **Details:** :doc:`Prithvi-EO-2.0 BurnScars ` .. container:: catalog-link-row - **Paper:** `Generalized Seismic Phase Detection with Deep Learning `_ | **Repo:** `Repository `__ + **Paper:** `Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications `_ | **Repo:** `Repository `__ - .. grid-item-card:: PhaseNet + .. grid-item-card:: Prithvi-EO-2.0-TL :class-card: catalog-entry-card .. container:: catalog-entry-summary - A lightweight phase-picking baseline that predicts P- and S-arrival indices from multichannel waveform windows. + Prithvi-EO-2.0 Earth-observation foundation-model encoder with time and location embeddings (300M or 600M, official pretrained weights), wrapped in the official burn-scar segmentation head for fine-tuning. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`PhaseNet ` - - .. container:: catalog-meta-row - - **Benchmark Family:** :doc:`Earthquake Benchmark ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`SeisBench ` + **Details:** :doc:`Prithvi-EO-2.0-TL ` .. container:: catalog-link-row - **Paper:** `PhaseNet: A Deep-Neural-Network-Based Seismic Arrival Time Picking Method `_ | **Repo:** `Repository `__ + **Paper:** `Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications `_ | **Repo:** `Repository `__ - .. grid-item-card:: WaveCastNet + .. grid-item-card:: Rainformer :class-card: catalog-entry-card .. container:: catalog-entry-summary - A ConvLEM-based sequence-to-sequence model for dense-grid earthquake wavefield forecasting and early-warning style rollout experiments. + U-shaped radar-nowcasting network whose stages fuse shifted-window self-attention (global) and CNN + CBAM attention (local) features through a gate; the strongest Sim2Real-Fire baseline, with the official KNMI weights verified. .. container:: catalog-chip-row - :bdg-primary:`Earthquake` :bdg-secondary:`Wavefield Forecasting` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`WaveCastNet ` + **Details:** :doc:`Rainformer ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Earthquake Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row + .. container:: catalog-link-row - **Benchmark Ecosystems:** :doc:`AEFA `, :doc:`pyCSEP ` + **Paper:** `Rainformer: Features Extraction Balanced Network for Radar-Based Precipitation Nowcasting `_ | **Repo:** `Repository `__ - .. container:: catalog-link-row + .. grid-item-card:: Random Forest + :class-card: catalog-entry-card - **Paper:** `Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning `_ + .. container:: catalog-entry-summary + The random-forest baseline of Kondylatos et al. (2022) for next-day wildfire danger: a scikit-learn forest of 100 trees of depth 10 on 35 instance features built from ten days of covariates. - .. tab-item:: Flood + .. container:: catalog-chip-row - .. container:: catalog-section-note + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` - Flood models cover streamflow and inundation forecasting, ranging from sequence baselines to dense-grid flood-mapping architectures. + .. container:: catalog-meta-row - .. rubric:: Implemented Models + **Details:** :doc:`Random Forest ` - .. container:: catalog-section-note + .. container:: catalog-meta-row - This table includes both core baselines and public variants or additional implementations for the hazard family. + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. grid:: 1 1 2 2 - :gutter: 2 - :class-container: catalog-grid + .. container:: catalog-link-row - .. grid-item-card:: EA-LSTM + **Paper:** `Random Forests `_ | **Repo:** `Repository `__ + + .. grid-item-card:: ResNet-18 U-Net :class-card: catalog-entry-card .. container:: catalog-entry-summary - An entity-aware hydrology baseline with static-feature gating over streamflow histories. + U-Net with a ResNet-18 encoder, equivalent to segmentation_models_pytorch's Unet and used as the U-Net baseline of WildfireSpreadTS. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`EA-LSTM ` + **Details:** :doc:`ResNet-18 U-Net ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`WaterBench ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ + **Paper:** `U-Net: Convolutional Networks for Biomedical Image Segmentation `_ | **Repo:** `Repository `__ - .. grid-item-card:: FloodCast + .. grid-item-card:: SegFormer :class-card: catalog-entry-card .. container:: catalog-entry-summary - A compact spatiotemporal flood-inundation baseline for raster forecast experiments. + Hierarchical Mix Transformer encoder with a lightweight all-MLP decoder (SegFormer-B0 to B5), used as a Transformer baseline for next-day wildfire spread on WildfireSpreadTS. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Inundation` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`FloodCast ` + **Details:** :doc:`SegFormer ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`FloodCastBench ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `Large-scale flood modeling and forecasting with FloodCast `_ | **Repo:** `Repository `__ + **Paper:** `SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers `_ | **Repo:** `Repository `__ - .. grid-item-card:: Google Flood Forecasting + .. grid-item-card:: Swin-Unet :class-card: catalog-entry-card .. container:: catalog-entry-summary - A transformer-style sequence baseline for nodewise streamflow forecasting. + U-shaped pure Swin Transformer (Swin-Unet-Tiny), the attention-based spread baseline of the WSTS+ wildfire benchmark. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`Google Flood Forecasting ` + **Details:** :doc:`Swin-Unet ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`Caravan ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `Global Flood Forecasting at a Fine Catchment Resolution using Machine Learning `_ | **Repo:** `Repository `__ + **Paper:** `Swin-Unet: Unet-like Pure Transformer for Medical Image Segmentation `_ | **Repo:** `Repository `__ - .. grid-item-card:: NeuralHydrology LSTM + .. grid-item-card:: SwinLSTM :class-card: catalog-entry-card .. container:: catalog-entry-summary - An adapter-style LSTM baseline for nodewise streamflow forecasting on graph-temporal inputs. + Recurrent cell built from Swin Transformer blocks (Tang et al., ICCV 2023): a frames-to-frames forecaster with the official Moving-MNIST weights, one of the forecasters Sim2Real-Fire compares for fire-area forecasting. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`NeuralHydrology LSTM ` + :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Details:** :doc:`SwinLSTM ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`Caravan ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ + **Paper:** `SwinLSTM: Improving Spatiotemporal Prediction Accuracy using Swin Transformer and LSTM `_ | **Repo:** `Repository `__ - .. grid-item-card:: UrbanFloodCast + .. grid-item-card:: SwinUNETR :class-card: catalog-entry-card .. container:: catalog-entry-summary - A U-Net style urban inundation baseline for dense-grid flood prediction. + Swin-Transformer encoder with a convolutional U-Net decoder (MONAI's SwinUNETR), configured by default as TS-SatFire's spatio-temporal (3D) reference model for next-day fire progression. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Inundation` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`UrbanFloodCast ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Details:** :doc:`SwinUNETR ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`FloodCastBench ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `UrbanFloodCast: WMO Urban Flooding Forecasting Challenge `_ | **Repo:** `Repository `__ + **Paper:** `Swin UNETR: Swin Transformers for Semantic Segmentation of Brain Tumors in MRI Images `_ | **Repo:** `Repository `__ - .. grid-item-card:: HydroGraphNet + .. grid-item-card:: TCN :class-card: catalog-entry-card .. container:: catalog-entry-summary - A physics-informed graph neural network for flood forecasting with interpretable KAN-style components, residual message passing, and delta-state decoding. + Generic temporal convolutional network of Bai et al. (2018): causal dilated residual convolutions with weight normalisation and a linear head, for per-step feature sequences. .. container:: catalog-chip-row - :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`HydroGraphNet ` + **Details:** :doc:`TCN ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Flood Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row + .. container:: catalog-link-row - **Benchmark Ecosystems:** :doc:`HydroBench ` + **Paper:** `An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling `_ | **Repo:** `Repository `__ - .. container:: catalog-link-row + .. grid-item-card:: TrajGRU + :class-card: catalog-entry-card - **Paper:** `Interpretable physics-informed graph neural networks for flood forecasting `_ + .. container:: catalog-entry-summary + Trajectory GRU encoder-forecaster for precipitation nowcasting (Shi et al., NeurIPS 2017): a frames-to-frames forecaster whose recurrent connections follow learned flow fields, ported from the official MXNet code with its HKO-7 and MovingMNIST++ weights. - .. tab-item:: Tropical Cyclone + .. container:: catalog-chip-row - .. container:: catalog-section-note + :bdg-primary:`Wildfire` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` - Storm models are organized under one tropical-cyclone family, including basin-specific hurricane baselines and shared all-basin forecasting models. + .. container:: catalog-meta-row - .. rubric:: Implemented Models + **Details:** :doc:`TrajGRU ` - .. container:: catalog-section-note + .. container:: catalog-meta-row - This table includes both core baselines and public variants or additional implementations for the hazard family. + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. grid:: 1 1 2 2 - :gutter: 2 - :class-container: catalog-grid + .. container:: catalog-link-row - .. grid-item-card:: Hurricast + **Paper:** `Deep Learning for Precipitation Nowcasting: A Benchmark and A New Model `_ | **Repo:** `Repository `__ + + .. grid-item-card:: TS-SatFire Baselines :class-card: catalog-entry-card .. container:: catalog-entry-summary - A compact multimodal storm baseline for hurricane track and intensity forecasting. + The four spatio-temporal TS-SatFire prediction baselines (U-Net-3D, Attention-U-Net-3D, UNETR-3D, SwinUNETR-3D) with the benchmark's own configurations. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`Hurricast ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Details:** :doc:`TS-SatFire Baselines ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`IBTrACS ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `Hurricane Forecasting: A Novel Multimodal Machine Learning Framework `_ | **Repo:** `Repository `__ + **Paper:** `TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction `_ | **Repo:** `Repository `__ - .. grid-item-card:: SAF-Net + .. grid-item-card:: U-Net-3D (MONAI) :class-card: catalog-entry-card .. container:: catalog-entry-summary - A spatiotemporal tropical-cyclone baseline with an intensity-focused head and shared trajectory output. + MONAI's strided-convolution U-Net, configured by default as the TS-SatFire spatio-temporal (3D) baseline for next-day fire progression. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`SAF-Net ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Details:** :doc:`U-Net-3D (MONAI) ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`TCBench Alpha ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction `_ | **Repo:** `Repository `__ + **Paper:** `Left-Ventricle Quantification Using Residual U-Net `_ | **Repo:** `Repository `__ - .. grid-item-card:: TCIF-fusion + .. grid-item-card:: U-TAE :class-card: catalog-entry-card .. container:: catalog-entry-summary - A knowledge-guided fusion baseline for tropical cyclone track and intensity forecasting. + U-Net whose temporal dimension is collapsed by a lightweight temporal attention encoder, the strongest WildfireSpreadTS baseline. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`TCIF-fusion ` + **Details:** :doc:`U-TAE ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`TCBench Alpha ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `Tropical cyclone intensity forecasting using model knowledge guided deep learning model `_ | **Repo:** `Repository `__ + **Paper:** `Panoptic Segmentation of Satellite Image Time Series with Convolutional Temporal Attention Networks `_ | **Repo:** `Repository `__ - .. grid-item-card:: Tropical Cyclone MLP + .. grid-item-card:: UNETR :class-card: catalog-entry-card .. container:: catalog-entry-summary - A compact MLP baseline for hurricane track and intensity forecasting. + Vision-Transformer encoder with a convolutional U-Net decoder (MONAI's UNETR), configured by default as the TS-SatFire spatio-temporal (3D) baseline for next-day fire progression. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`Tropical Cyclone MLP ` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Details:** :doc:`UNETR ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`TCBench Alpha ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ | **Repo:** `Repository `__ + **Paper:** `UNETR: Transformers for 3D Medical Image Segmentation `_ | **Repo:** `Repository `__ - .. grid-item-card:: TropiCycloneNet + .. grid-item-card:: Wildfire Forecasting :class-card: catalog-entry-card .. container:: catalog-entry-summary - A GRU plus attention baseline for all-basin tropical cyclone forecasting. + The LSTM and ConvLSTM of Kondylatos et al. (2022) that classify next-day wildfire danger of a 1 km cell from ten days of weather, vegetation, terrain, human and land-cover covariates. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` - - .. container:: catalog-meta-row - - **Details:** :doc:`TropiCycloneNet ` + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Details:** :doc:`Wildfire Forecasting ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`TropiCycloneNet-Dataset ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-link-row - **Paper:** `Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ | **Repo:** `Repository `__ - - .. rubric:: Experimental Adapters - - .. container:: catalog-section-note - - These entries remain public as lightweight wrapper or prototype integrations and should not be counted as stable implemented methods. - - .. grid:: 1 1 2 2 - :gutter: 2 - :class-container: catalog-grid + **Paper:** `Wildfire Danger Prediction and Understanding With Deep Learning `_ | **Repo:** `Repository `__ - .. grid-item-card:: FourCastNet TC Adapter + .. grid-item-card:: WildfireSpreadTS Baselines :class-card: catalog-entry-card .. container:: catalog-entry-summary - An experimental wrapper-style storm adapter inspired by FourCastNet forecast fields. + The four learned WildfireSpreadTS baselines (logistic regression, ResNet-18 U-Net, ConvLSTM, U-TAE) with the benchmark's own configurations. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-warning:`Experimental Adapter` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`FourCastNet TC Adapter ` + **Details:** :doc:`WildfireSpreadTS Baselines ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`IBTrACS ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `FourCastNet: A Global Data-driven High-resolution Weather Model using Adaptive Fourier Neural Operators `_ | **Repo:** `Repository `__ + **Paper:** `WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction `_ | **Repo:** `Repository `__ - .. grid-item-card:: GraphCast TC Adapter + .. grid-item-card:: CNN-ASPP :class-card: catalog-entry-card .. container:: catalog-entry-summary - An experimental wrapper-style storm adapter inspired by GraphCast/GenCast forecast fields. + A fully convolutional network with an atrous spatial pyramid of four dilation rates for next-day wildfire spread on Next Day Wildfire Spread tiles. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-warning:`Experimental Adapter` + :bdg-primary:`Wildfire` :bdg-secondary:`Spread` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`GraphCast TC Adapter ` + **Details:** :doc:`CNN-ASPP ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` .. container:: catalog-meta-row - **Benchmark Ecosystems:** :doc:`IBTrACS ` + **Benchmark Ecosystems:** :doc:`WildfireSpreadTS ` .. container:: catalog-link-row - **Paper:** `GraphCast: Learning skillful medium-range global weather forecasting `_ | **Repo:** `Repository `__ + **Paper:** `Application of Explainable Artificial Intelligence in Predicting Wildfire Spread: An ASPP-Enabled CNN Approach `_ - .. grid-item-card:: Pangu TC Adapter + .. grid-item-card:: U-Net :class-card: catalog-entry-card .. container:: catalog-entry-summary - An experimental wrapper-style storm adapter inspired by Pangu-Weather forecast fields. + The original U-Net of Ronneberger et al. (MICCAI 2015): a contracting and an expansive path of unpadded 3x3 convolutions joined by centre-cropped skip connections, without batch normalisation. .. container:: catalog-chip-row - :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-warning:`Experimental Adapter` + :bdg-primary:`Wildfire` :bdg-secondary:`Segmentation` :bdg-success:`Implemented` .. container:: catalog-meta-row - **Details:** :doc:`Pangu TC Adapter ` + **Details:** :doc:`U-Net ` .. container:: catalog-meta-row - **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + **Benchmark Family:** :doc:`Wildfire Benchmark ` - .. container:: catalog-meta-row + .. container:: catalog-link-row - **Benchmark Ecosystems:** :doc:`IBTrACS ` + **Paper:** `U-Net: Convolutional Networks for Biomedical Image Segmentation `_ | **Repo:** `Repository `__ + + .. grid-item-card:: XGBoost + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Gradient-boosted trees (XGBoost) on the 35 instance features of Kondylatos et al. (2022) for next-day wildfire danger, with library-default hyperparameters until the paper's are known. + + .. container:: catalog-chip-row + + :bdg-primary:`Wildfire` :bdg-secondary:`Classification` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`XGBoost ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Wildfire Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `XGBoost: A Scalable Tree Boosting System `_ | **Repo:** `Repository `__ + + + .. tab-item:: Earthquake + + .. container:: catalog-section-note + + Earthquake models span phase picking and dense-grid forecasting, with detail pages linked to the shared earthquake benchmark coverage. + + .. rubric:: Implemented Models + + .. container:: catalog-section-note + + This table includes both core baselines and public variants or additional implementations for the hazard family. + + .. grid:: 1 1 2 2 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: EQTransformer + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Earthquake Transformer (Mousavi et al., Nature Communications 2020): a multi-task network that turns a 60-s three-component seismogram into per-sample earthquake-detection, P-arrival and S-arrival probabilities, ported from the official Keras code with its two released models. + + .. container:: catalog-chip-row + + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`EQTransformer ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Earthquake Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` + + .. container:: catalog-link-row + + **Paper:** `Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking `_ | **Repo:** `Repository `__ + + .. grid-item-card:: GPD + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Generalized Phase Detection (Ross et al., BSSA 2018): a convolutional classifier that labels 4-s three-component windows as P, S or noise, and picks continuous data with a sliding window. Ported from the official Keras release, whose weights load and reproduce the official picks. + + .. container:: catalog-chip-row + + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`GPD ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Earthquake Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` + + .. container:: catalog-link-row + + **Paper:** `Generalized Seismic Phase Detection with Deep Learning `_ | **Repo:** `Repository `__ + + .. grid-item-card:: PhaseNet + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + 1-D U-Net that turns three-component waveforms into per-sample probabilities of noise, P and S arrivals (Zhu & Beroza, GJI 2019); picks are the peaks of the P and S traces. + + .. container:: catalog-chip-row + + :bdg-primary:`Earthquake` :bdg-secondary:`Phase Picking` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`PhaseNet ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Earthquake Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`pick-benchmark `, :doc:`SeisBench ` + + .. container:: catalog-link-row + + **Paper:** `PhaseNet: a deep-neural-network-based seismic arrival-time picking method `_ | **Repo:** `Repository `__ + + .. grid-item-card:: WaveCastNet + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + ConvLEM sequence-to-sequence network that forecasts ground-motion wavefields (three velocity components on a regular grid) for earthquake early warning (Lyu et al., Nat. Commun. 2025), with dense-grid and sparse-station inputs. + + .. container:: catalog-chip-row + + :bdg-primary:`Earthquake` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`WaveCastNet ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Earthquake Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning `_ | **Repo:** `Repository `__ + + .. grid-item-card:: EQNet + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + End-to-end multi-station earthquake detector (Zhu et al., JGR Solid Earth 2022): a 1-D ResNet feature extractor, P and S picking heads, and a shift-and-stack module that aligns station features on candidate hypocentres before an event detection network. Rebuilt from the paper. + + .. container:: catalog-chip-row + + :bdg-primary:`Earthquake` :bdg-secondary:`Picking` :bdg-secondary:`Detection` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`EQNet ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Earthquake Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning `_ | **Repo:** `Repository `__ + + + .. tab-item:: Flood + + .. container:: catalog-section-note + + Flood models cover streamflow and inundation forecasting, ranging from sequence baselines to dense-grid flood-mapping architectures. + + .. rubric:: Implemented Models + + .. container:: catalog-section-note + + This table includes both core baselines and public variants or additional implementations for the hazard family. + + .. grid:: 1 1 2 2 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: EA-LSTM + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The Entity-Aware LSTM of Kratzert et al. (HESS 2019): static catchment attributes set the input gate, daily forcings drive the other gates; ported from NeuralHydrology. + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`EA-LSTM ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`CAMELS-US `, :doc:`Caravan ` + + .. container:: catalog-link-row + + **Paper:** `Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets `_ | **Repo:** `Repository `__ + + .. grid-item-card:: Google Flood Forecasting + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Google's operational streamflow model (FloodHub): hindcast and forecast LSTMs over masked-mean embeddings of several weather products, with a probabilistic CMAL head; released weights load. + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`Google Flood Forecasting ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`Caravan ` + + .. container:: catalog-link-row + + **Paper:** `How to deal w___ missing input data `_ | **Repo:** `Repository `__ + + .. grid-item-card:: HydroGraphNet + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The physics-informed graph network of Taghizadeh et al. (CACIE 2025) as released in NVIDIA PhysicsNeMo (MeshGraphKAN): water depth and volume changes on an unstructured flood mesh, rolled out step by step. + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Inundation` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`HydroGraphNet ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`HydroGraphNet White River ` + + .. container:: catalog-link-row + + **Paper:** `Interpretable physics-informed graph neural networks for flood forecasting `_ | **Repo:** `Repository `__ + + .. grid-item-card:: NeuralHydrology LSTM + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The regional rainfall-runoff LSTM of Kratzert et al. (HESS 2019) as NeuralHydrology implements it (CudaLSTM): daily forcings plus static catchment attributes to daily discharge. + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Streamflow` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`NeuralHydrology LSTM ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`CAMELS-US `, :doc:`Caravan ` + + .. container:: catalog-link-row + + **Paper:** `Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks `_ | **Repo:** `Repository `__ + + .. grid-item-card:: UrbanFloodCast + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The deep neural operator (DNO) of UrbanFloodCast (Xu et al., J. Hydrology 2025): a U-shaped Fourier neural operator in space and time that predicts urban water depth and discharge for 24 steps at once. + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`UrbanFloodCast ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `Urban flood modeling and forecasting with deep neural operator and transfer learning `_ | **Repo:** `Repository `__ + + .. rubric:: Experimental Adapters + + .. container:: catalog-section-note + + These entries remain public as lightweight wrapper or prototype integrations and should not be counted as stable implemented methods. + + .. grid:: 1 1 2 2 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: FloodCast + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + A small convolutional inundation baseline under the FloodCast name; not the published model, whose flood-model code was never released and whose network widths the paper does not report (experimental). + + .. container:: catalog-chip-row + + :bdg-primary:`Flood` :bdg-secondary:`Forecasting` :bdg-secondary:`Segmentation` :bdg-warning:`Experimental Adapter` + + .. container:: catalog-meta-row + + **Details:** :doc:`FloodCast ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Flood Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `Large-scale flood modeling and forecasting with FloodCast `_ | **Repo:** `Repository `__ + + + .. tab-item:: Tropical Cyclone + + .. container:: catalog-section-note + + Storm models are organized under one tropical-cyclone family, including basin-specific hurricane baselines and shared all-basin forecasting models. + + .. rubric:: Implemented Models + + .. container:: catalog-section-note + + This table includes both core baselines and public variants or additional implementations for the hazard family. + + .. grid:: 1 1 2 2 + :gutter: 2 + :class-container: catalog-grid + + .. grid-item-card:: Hurricast + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Hurricast (HUML) of Boussioux et al. (2022): ERA5 maps encoded by a CNN and IBTrACS statistics pass a Transformer encoder-decoder, whose embeddings feed XGBoost for the 24-hour intensity or track. + + .. container:: catalog-chip-row + + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-secondary:`Intensity` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`Hurricast ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`IBTrACS ` + + .. container:: catalog-link-row + + **Paper:** `Hurricane Forecasting: A Novel Multimodal Machine Learning Framework `_ | **Repo:** `Repository `__ + + .. grid-item-card:: SAF-Net + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + Wide-and-deep typhoon intensity network of Xu et al. (2022): 96 best-track predictors plus 31x31 ERA-Interim u/v winds at four levels and four times, fused by spatial attention, predict the maximum sustained wind 24 hours ahead. + + .. container:: catalog-chip-row + + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`SAF-Net ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction `_ | **Repo:** `Repository `__ + + .. grid-item-card:: TCIF-fusion + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The model-knowledge-guided intensity network of Wang, Li and Zheng (2024): 3-D CNN branches with a fusion branch over ERA5 winds and SST, a VGG-19 on infrared images and storm history give the 24-hour intensity. + + .. container:: catalog-chip-row + + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Forecasting` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`TCIF-fusion ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-link-row + + **Paper:** `Tropical cyclone intensity forecasting using model knowledge guided deep learning model `_ | **Repo:** `Repository `__ + + .. grid-item-card:: Tropical Cyclone MLP + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The 24-hour intensity-change MLP of Xu et al. (2021): 121 SHIPS predictors -> two hidden layers of 2048 units (sigmoid, ReLU) -> the change of the maximum sustained wind over the next 24 hours. + + .. container:: catalog-chip-row + + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Intensity` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`Tropical Cyclone MLP ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`SHIPS Predictors (Xu et al. 2021) ` + + .. container:: catalog-link-row + + **Paper:** `Deep Learning Experiments for Tropical Cyclone Intensity Forecasts `_ | **Repo:** `Repository `__ + + .. grid-item-card:: TropiCycloneNet + :class-card: catalog-entry-card + + .. container:: catalog-entry-summary + + The TCN_M generator of Huang et al. (2025): a multimodal GAN with six decoders that samples 6- to 24-hour forecasts of position, central pressure and maximum wind from the best track, 500 hPa geopotential and environmental features; the released checkpoint is verified. + + .. container:: catalog-chip-row + + :bdg-primary:`Tropical Cyclone` :bdg-secondary:`Track + Intensity` :bdg-success:`Implemented` + + .. container:: catalog-meta-row + + **Details:** :doc:`TropiCycloneNet ` + + .. container:: catalog-meta-row + + **Benchmark Family:** :doc:`Tropical Cyclone Benchmark ` + + .. container:: catalog-meta-row + + **Benchmark Ecosystems:** :doc:`TropiCycloneNet Dataset ` .. container:: catalog-link-row - **Paper:** `Accurate medium-range global weather forecasting with 3D neural networks `_ | **Repo:** `Repository `__ + **Paper:** `Benchmark dataset and deep learning method for global tropical cyclone forecasting `_ | **Repo:** `Repository `__ @@ -877,9 +1309,9 @@ starting point for each hazard family. .. grid-item-card:: Wildfire :class-card: catalog-detail-card - **Start with:** :doc:`FireCastNet ` + **Start with:** :doc:`WildfireSpreadTS Baselines ` - A compact encoder-decoder baseline for wildfire spread mask prediction. + The four learned WildfireSpreadTS baselines (logistic regression, ResNet-18 U-Net, ConvLSTM, U-TAE) with the benchmark's own configurations. **Benchmark:** :doc:`Wildfire Benchmark ` @@ -888,25 +1320,25 @@ starting point for each hazard family. **Start with:** :doc:`PhaseNet ` - A lightweight phase-picking baseline that predicts P- and S-arrival indices from multichannel waveform windows. + 1-D U-Net that turns three-component waveforms into per-sample probabilities of noise, P and S arrivals (Zhu & Beroza, GJI 2019); picks are the peaks of the P and S traces. **Benchmark:** :doc:`Earthquake Benchmark ` .. grid-item-card:: Flood :class-card: catalog-detail-card - **Start with:** :doc:`FloodCast ` + **Start with:** :doc:`NeuralHydrology LSTM ` - A compact spatiotemporal flood-inundation baseline for raster forecast experiments. + The regional rainfall-runoff LSTM of Kratzert et al. (HESS 2019) as NeuralHydrology implements it (CudaLSTM): daily forcings plus static catchment attributes to daily discharge. **Benchmark:** :doc:`Flood Benchmark ` .. grid-item-card:: Tropical Cyclone :class-card: catalog-detail-card - **Start with:** :doc:`Hurricast ` + **Start with:** :doc:`TropiCycloneNet ` - A compact multimodal storm baseline for hurricane track and intensity forecasting. + The TCN_M generator of Huang et al. (2025): a multimodal GAN with six decoders that samples 6- to 24-hour forecasts of position, central pressure and maximum wind from the best track, 500 hPa geopotential and environmental features; the released checkpoint is verified. **Benchmark:** :doc:`Tropical Cyclone Benchmark ` @@ -924,29 +1356,49 @@ before selecting a model for evaluation. :hidden: modules/models_asufm + modules/models_attention_unet + modules/models_convgru + modules/models_convlstm + modules/models_deep_ensemble + modules/models_deeplabv3 + modules/models_earthfarseer + modules/models_earthformer modules/models_eqnet modules/models_eqtransformer modules/models_firecastnet modules/models_floodcast - modules/models_forefire - modules/models_fourcastnet_tc modules/models_google_flood_forecasting modules/models_gpd - modules/models_graphcast_tc modules/models_hurricast modules/models_hydrographnet + modules/models_logistic_regression modules/models_neuralhydrology_ealstm modules/models_neuralhydrology_lstm - modules/models_pangu_tc modules/models_phasenet + modules/models_prithvi_burnscars + modules/models_prithvi_eo_2_tl + modules/models_rainformer + modules/models_random_forest + modules/models_resnet18_unet modules/models_saf_net + modules/models_segformer + modules/models_swin_unet + modules/models_swin_unetr + modules/models_swinlstm modules/models_tcif_fusion + modules/models_tcn + modules/models_trajgru modules/models_tropicalcyclone_mlp modules/models_tropicyclonenet + modules/models_ts_satfire + modules/models_unet + modules/models_unet3d + modules/models_unetr modules/models_urbanfloodcast + modules/models_utae modules/models_wavecastnet modules/models_wildfire_aspp modules/models_wildfire_forecasting modules/models_wildfire_fpa modules/models_wildfirespreadts - modules/models_wrf_sfire + modules/models_xgboost diff --git a/docs/source/pyhazards_prompted.rst b/docs/source/pyhazards_prompted.rst new file mode 100644 index 00000000..f78d1a44 --- /dev/null +++ b/docs/source/pyhazards_prompted.rst @@ -0,0 +1,661 @@ +.. This file is generated by scripts/render_prompted_docs.py. Do not edit by hand. + +Prompted VLM Baselines +====================== + +Zero-shot multimodal large language models used as wildfire-smoke detectors by prompting them +with an image and a question. They are not trainable ``nn.Module`` models and are therefore not +part of the :doc:`model catalog `; ``pyhazards.prompted`` provides the +SmokeBench protocol (prompts, image partitions, answer parsing, metrics, a resumable runner) and +backends for the models SmokeBench evaluated: open-weight checkpoints through Hugging Face +``transformers`` and closed models through their official Python clients. + +Install the optional dependencies of the backend you use (nothing is added to the core install): + +.. code-block:: bash + + pip install "pyhazards[prompted]" # Pillow + OpenCV: data, grid overlay, metrics + pip install "pyhazards[prompted-hf]" # + transformers, accelerate, torchvision (Qwen2.5-VL, InternVL3, Idefics2) + pip install "pyhazards[prompted-gemini]" # + google-genai (reads GEMINI_API_KEY) + pip install "pyhazards[prompted-openai]" # + openai (reads OPENAI_API_KEY) + +Protocol +-------- + +PyHazards implements the four tasks of `SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection `_ (Qi, Li & Barnes, +WACV 2026) on the SmokeBench images, :doc:`FIgLib frames with the SmokeyNet smoke boxes ` +(5,046 smoke images and 1,000 smoke-free images). A model sees one image (or one tile) and one +prompt and answers in text; decoding temperature 0.5. The prompts are the paper's, verbatim: + +**Smoke classification**: + +.. code-block:: text + + Please look at this image. Detect if the image contains smoke. If you can find any smoke, return True. Otherwise, return False. Do not return any other words. + +**Tile-based localization** -- the classification prompt on each tile of a 3 x 4 grid. + +**Grid-based localization** (on the image with the numbered 5 x 5 grid drawn on it): + +.. code-block:: text + + Please look at this image, which is divided into several numbered regions (from left to right, top to bottom). Please output the numbered regions that contain smoke in JSON format as a list of dicts like [{"region": 1}, {"region": 2}]. If you cannot find any smoke, return an empty list []. without other words + +**Smoke detection**: + +.. code-block:: text + + Detect all smoke and output bounding boxes in the format [[x1, y1, x2, y2], [x1, y1, x2, y2]]. If you cannot find any smoke, return an empty list [] without other words. Do not return dictionaries. + +Metrics and scoring +~~~~~~~~~~~~~~~~~~~ + +- **Classification** -- accuracy, reported separately on the smoke images (paper Tables 1-2, per + smoke-area and Weber-contrast quintile) and on the smoke-free images (Table 3). An answer counts + as "smoke" iff it contains ``True``; every other answer, including unparseable ones, counts as + "no smoke" (the authors' script; the paper does not say). +- **Tile** -- the 3 x 4 tiles are classified independently with the classification prompt (a tile is + positive iff its answer contains ``True`` or ``true``); per-image IoU of the predicted and + ground-truth tile sets, averaged over smoke images (mIoU, Tables 4-5). +- **Grid** -- the image carries a numbered 5 x 5 grid; every integer in the answer is a predicted + cell (an answer without numbers predicts nothing, IoU 0); mIoU of the cell sets (Tables 6-7). +- **Detection** -- the first ``[[...]]`` span is read as JSON boxes; anything unparseable is the box + ``[0, 0, 0, 0]``. Per image, the largest IoU between a predicted and a ground-truth box (pixel + coordinates of the original frame), averaged over smoke images (Table 8). +- A tile or cell is ground-truth positive when it contains a pixel of a box (both box ends inclusive). +- Smoke area is the area of the (single) box; Weber contrast is ``|I_box - I_frame| / I_frame`` on the + OpenCV grey image with a 20-pixel frame around the box. Reports bin results at the quintiles of + the 5,046 boxes: area ``(42, 4356], (4356, 11232], (11232, 28565], (28565, 83157], (83157, 2232020]`` + and contrast ``(0, 0.0246], (0.0246, 0.0549], (0.0549, 0.0878], (0.0878, 0.13], (0.13, 0.728]`` + (Q1 = Very Small / Very Low ... Q5 = Very Large / Very High). PyHazards' area and contrast values + for the 5,046 SmokeBench images give exactly these quintiles (contrast to the 3 printed digits). + +The paper defines the tasks, prompts, temperature, partitions and metrics. Where it is silent +(answer parsing, cell geometry, contrast background, per-model input handling) PyHazards follows +the authors' evaluation script (`SoraLink/MLLM `_ at ``183cdca``; +no licence, so it is used only as a test oracle and nothing is copied). The oracle test +``tests/oracle/test_smokebench_oracle.py`` runs that script's own functions against PyHazards'. + +Differences from the paper and the authors' script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- **Prompts.** The released script words the prompts slightly differently from the paper: the + classification prompt ends "Do MUST not return any other words"; the grid and detection prompts say + "If you cannot find any smoke return empty list []"; the detection prompt asks for "bounding box + in the format[[x1, y1, x2, y2], ...]" and ends "without other wordsDo not return dict!" (string + pieces joined without spaces). PyHazards sends the paper's text. +- **Temperature.** The paper fixes it at 0.5; the released script never sets it, so the authors' runs + used each checkpoint's generation config (greedy for Idefics2 and InternVL3, temperature 1e-6 for + Qwen2.5-VL). PyHazards samples at 0.5; ``do_sample=False`` gives greedy decoding. +- **Tile crops.** The script crops ``image[i*hb:(i+1)*wb, j*wb:(j+1)*hb]`` (height and width blocks + swapped), so on the 3072 x 2048 frames (1,994 of 5,046) tiles overlap or leave gaps, while the + paper describes non-overlapping tiles. ``protocol="paper"`` (default) crops the paper's tiles; + ``protocol="reference_code"`` reproduces the script. +- **Edge cells.** The script maps a box reaching the last ``H % rows`` / ``W % cols`` pixels to a + non-existent row/column, i.e. to a wrong cell id (72 grid and 19 tile cases among the 5,046 boxes). + ``protocol="paper"`` clamps to the last row/column; ``protocol="reference_code"`` keeps the script's ids. +- **Malformed boxes.** The script scores boxes with fewer than four numbers 0 and crashes on other + malformed values; PyHazards scores every malformed prediction (and a zero-union NaN IoU) 0 and + counts them in the report. +- **Smoke-free images.** The authors' 1,000 smoke-free frames were drawn without a seed from all + FIgLib sequences and not released; PyHazards draws a seeded sample from the pre-ignition frames of + the 145 annotated sequences, so smoke-free accuracy is not the same sample as Table 3. +- **Closed models.** No code was released for GPT-4o and Gemini-2.5 Pro (classification only); + the request layout is documented on their cards below. + +Usage +----- + +.. code-block:: python + + from pyhazards.datasets.figlib_smokebench import FIgLibSmokeBench, download_smokebench + from pyhazards.prompted import build_backend, evaluate_smokebench + + download_smokebench("data/figlib") # SmokeyNet boxes + 145 FIgLib sequences (~11.4 GB) + data = FIgLibSmokeBench("data/figlib") # 5,046 smoke + 1,000 sampled smoke-free frames + backend = build_backend("qwen2_5_vl_7b") # temperature 0.5, 448 x 448 input as in SmokeBench + report = evaluate_smokebench(backend, data, "classification", output_dir="runs/qwen7b_cls") + print(report["metrics"]["accuracy_smoke"], report["paper_reported"]) + +or from the command line: + +.. code-block:: bash + + python -m pyhazards.prompted --backend qwen2_5_vl_7b --task classification \ + --root data/figlib --output runs/qwen7b_cls + +Any object with ``generate(image, prompt) -> str`` (a subclass of +``pyhazards.prompted.PromptedBackend``) can be evaluated the same way. + +Models +------ + +.. list-table:: SmokeBench models available as backends + :header-rows: 1 + + * - Backend + - Model + - Access + - Licence + - Extra + - SmokeBench tasks + * - ``idefics2_8b`` + - `Idefics2-8B `__ + - open weights + - Apache-2.0 + - ``prompted-hf`` + - classification, tile, grid, detection + * - ``qwen2_5_vl_7b`` + - `Qwen2.5-VL-7B-Instruct `__ + - open weights + - Apache-2.0 + - ``prompted-hf`` + - classification, tile, grid, detection + * - ``qwen2_5_vl_32b`` + - `Qwen2.5-VL-32B-Instruct `__ + - open weights + - Apache-2.0 + - ``prompted-hf`` + - classification, tile, grid, detection + * - ``internvl3_14b`` + - `InternVL3-14B `__ + - open weights + - MIT per the model card text; the Hugging Face metadata says 'other' and links the Qwen licence (Qwen2.5 component) + - ``prompted-hf`` + - classification, grid, detection + * - ``gemini_2_5_pro`` + - `Gemini 2.5 Pro `__ + - API + - Proprietary (Gemini API terms); no weights + - ``prompted-gemini`` + - classification + * - ``gpt_4o`` + - `GPT-4o `__ + - API + - Proprietary (OpenAI API terms); no weights + - ``prompted-openai`` + - classification + +Unified-IO 2 and Grounding DINO (detection only in SmokeBench) are not included: they are a +referring-expression model and an open-set detector driven without the SmokeBench prompts. Llama 4 +is not part of SmokeBench and has no published wildfire-smoke protocol here, so it is not included. + +Idefics2-8B +~~~~~~~~~~~ + +**Model paper:** `What matters when building vision-language models? (Laurencon et al., NeurIPS 2024, arXiv:2405.02246) `_. + +**Backend:** ``build_backend("idefics2_8b")`` -- ``HuggingFaceM4/idefics2-8b`` (open weights; licence: Apache-2.0). + +.. list-table:: SmokeBench smoke classification (Tables 1-3) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.482 + - 0.596 + - 0.598 + - 0.575 + - 0.709 + - 0.592 + * - Weber contrast + - 0.607 + - 0.589 + - 0.616 + - 0.558 + - 0.589 + - 0.592 + +SmokeBench smoke classification (Tables 1-3): accuracy on smoke-free images 0.498. + +.. list-table:: SmokeBench tile-based localization (Tables 4-5) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.348 + - 0.505 + - 0.487 + - 0.530 + - 0.507 + - 0.475 + * - Weber contrast + - 0.416 + - 0.440 + - 0.480 + - 0.477 + - 0.563 + - 0.475 + +.. list-table:: SmokeBench grid-based localization (Tables 6-7) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.029 + - 0.025 + - 0.033 + - 0.054 + - 0.067 + - 0.042 + * - Weber contrast + - 0.036 + - 0.042 + - 0.040 + - 0.048 + - 0.043 + - 0.042 + +SmokeBench smoke detection (Table 8): mIoU 0.000. + +**Settings of the SmokeBench runs:** + +- bfloat16 weights, ``do_image_splitting=False``. +- Classification, grid and detection: the raw text ``"\n" + prompt`` without the chat template through the ``image-text-to-text`` pipeline (256 new tokens, the checkpoint's greedy generation config). +- Tiles: the 12 tiles of an image as one left-padded batch through the chat template, greedy, 16 new tokens. + +**Deviations:** + +- Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the greedy decoding of the released script. + +**Notes:** + +- ``build_backend`` loads Hugging Face revision ``2c42686c57fe21cf0348c9ce1077d094b72e7698`` (2026-10-07) unless ``revision=`` is given (the base checkpoint, not the instruction-tuned ``idefics2-8b-chatty``; the paper says only "Idefics2" and the script loads ``idefics2-8b``). +- SmokeBench notes that Idefics2 answers close to chance on smoke-free images (0.498), which inflates its accuracy on smoke images. + +Qwen2.5-VL-7B-Instruct +~~~~~~~~~~~~~~~~~~~~~~ + +**Model paper:** `Qwen2.5-VL Technical Report (Bai et al., arXiv:2502.13923, 2025) `_ (`code `__). + +**Backend:** ``build_backend("qwen2_5_vl_7b")`` -- ``Qwen/Qwen2.5-VL-7B-Instruct`` (open weights; licence: Apache-2.0). + +.. list-table:: SmokeBench smoke classification (Tables 1-3) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.098 + - 0.232 + - 0.423 + - 0.463 + - 0.686 + - 0.380 + * - Weber contrast + - 0.289 + - 0.327 + - 0.395 + - 0.417 + - 0.473 + - 0.380 + +SmokeBench smoke classification (Tables 1-3): accuracy on smoke-free images 0.982. + +.. list-table:: SmokeBench tile-based localization (Tables 4-5) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.311 + - 0.479 + - 0.485 + - 0.485 + - 0.520 + - 0.456 + * - Weber contrast + - 0.376 + - 0.458 + - 0.482 + - 0.478 + - 0.485 + - 0.456 + +.. list-table:: SmokeBench grid-based localization (Tables 6-7) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.000 + - 0.000 + - 0.000 + - 0.000 + - 0.000 + - 0.000 + * - Weber contrast + - 0.000 + - 0.000 + - 0.000 + - 0.000 + - 0.000 + - 0.000 + +SmokeBench smoke detection (Table 8): mIoU 0.000. + +**Settings of the SmokeBench runs:** + +- Every image (whole frame, grid overlay or tile) is resized to 448 x 448 with ``PIL.Image.resize`` before the processor, as in the authors' ``QwenVL.predict``; the paper does not mention it. ``image_size=None`` keeps the native resolution. +- Chat template with the image before the text; up to 128 new tokens; a Markdown ``json`` fence is stripped from the answer. +- The authors' script loads the weights with ``torch_dtype="auto"`` (bfloat16) and ``device_map="auto"`` and never sets a temperature, so its runs used the checkpoint's generation config (``do_sample=True``, temperature 1e-6, repetition penalty 1.05: effectively greedy). + +**Deviations:** + +- Samples at temperature 0.5 as the paper states (other sampling parameters from the checkpoint's generation config); ``do_sample=False`` reproduces the effectively greedy decoding of the released script. +- The 12 tiles of an image are generated as one left-padded batch (the authors also batch them; their padding side is the processor default). +- Detection boxes are scored in the pixel frame of the original image, as in the authors' script, although the model answers in the frame of its 448 x 448 input, so a box placed correctly on that input generally misses the ground-truth box of the 2048 x 1536 or 3072 x 2048 frame (Table 8: 0.000). + +**Notes:** + +- PyHazards run (2026-10-07; this revision, transformers 5.19, one RTX 6000 Ada, temperature 0.5, seed 0, ``protocol="paper"``, 22 min): accuracy on the 5,046 smoke images 0.375 (paper 0.380); by smoke area 0.088 / 0.249 / 0.408 / 0.463 / 0.666 (paper 0.098 / 0.232 / 0.423 / 0.463 / 0.686); by contrast 0.294 / 0.329 / 0.392 / 0.412 / 0.446 (paper 0.289 / 0.327 / 0.395 / 0.417 / 0.473); 0.975 on 1,000 seeded smoke-free frames (paper 0.982 on its unreleased sample). On a stratified subset (120 smoke images per area bin + 200 smoke-free) greedy decoding gave 0.382 / 0.985 against 0.363 / 0.975 at temperature 0.5. In the full run every answer was exactly ``True`` or ``False``. +- ``build_backend`` loads Hugging Face revision ``cc594898137f460bfe9f0759e9844b3ce807cfb5`` (2026-10-07) unless ``revision=`` is given. The SmokeBench runs did not pin a revision. +- Section 5.2 of the paper says Qwen2.5-VL-7B underperforms the 32B model on tiles, but Table 4 gives 0.456 (7B) against 0.435 (32B); the numbers above are the tables'. + +Qwen2.5-VL-32B-Instruct +~~~~~~~~~~~~~~~~~~~~~~~ + +**Model paper:** `Qwen2.5-VL Technical Report (Bai et al., arXiv:2502.13923, 2025) `_ (`code `__). + +**Backend:** ``build_backend("qwen2_5_vl_32b")`` -- ``Qwen/Qwen2.5-VL-32B-Instruct`` (open weights; licence: Apache-2.0). + +.. list-table:: SmokeBench smoke classification (Tables 1-3) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.041 + - 0.103 + - 0.222 + - 0.284 + - 0.569 + - 0.244 + * - Weber contrast + - 0.204 + - 0.224 + - 0.251 + - 0.249 + - 0.291 + - 0.244 + +SmokeBench smoke classification (Tables 1-3): accuracy on smoke-free images 0.983. + +.. list-table:: SmokeBench tile-based localization (Tables 4-5) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.348 + - 0.466 + - 0.422 + - 0.456 + - 0.483 + - 0.435 + * - Weber contrast + - 0.380 + - 0.420 + - 0.450 + - 0.440 + - 0.485 + - 0.435 + +.. list-table:: SmokeBench grid-based localization (Tables 6-7) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.057 + - 0.155 + - 0.242 + - 0.226 + - 0.239 + - 0.184 + * - Weber contrast + - 0.155 + - 0.157 + - 0.189 + - 0.202 + - 0.215 + - 0.184 + +SmokeBench smoke detection (Table 8): mIoU 0.000. + +**Settings of the SmokeBench runs:** + +- Same code path as the 7B model (``QwenVL`` in the authors' script, switched to the 32B checkpoint): 448 x 448 input, chat template, 128 new tokens, ``json`` fence stripped, ``torch_dtype="auto"``, ``device_map="auto"``, checkpoint generation config (temperature 1e-6). + +**Deviations:** + +- Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the effectively greedy decoding of the released script. +- Detection boxes are scored in the pixel frame of the original image (as the authors do) although the model answers in its 448 x 448 input frame. + +**Notes:** + +- ``build_backend`` loads Hugging Face revision ``7cfb30d71a1f4f49a57592323337a4a4727301da`` (2026-10-07) unless ``revision=`` is given. The weights are about 68 GB in bfloat16. + +InternVL3-14B +~~~~~~~~~~~~~ + +**Model paper:** `InternVL3: Exploring Advanced Training and Test-Time Recipes for Open-Source Multimodal Models (Zhu et al., arXiv:2504.10479, 2025) `_ (`code `__). + +**Backend:** ``build_backend("internvl3_14b")`` -- ``OpenGVLab/InternVL3-14B-hf`` (open weights; licence: MIT per the model card text; the Hugging Face metadata says 'other' and links the Qwen licence (Qwen2.5 component)). + +.. list-table:: SmokeBench smoke classification (Tables 1-3) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.090 + - 0.262 + - 0.376 + - 0.432 + - 0.636 + - 0.359 + * - Weber contrast + - 0.269 + - 0.304 + - 0.368 + - 0.401 + - 0.453 + - 0.359 + +SmokeBench smoke classification (Tables 1-3): accuracy on smoke-free images 0.985. + +.. list-table:: SmokeBench grid-based localization (Tables 6-7) + :header-rows: 1 + + * - mIoU by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.001 + - 0.017 + - 0.057 + - 0.095 + - 0.114 + - 0.057 + * - Weber contrast + - 0.042 + - 0.041 + - 0.055 + - 0.062 + - 0.084 + - 0.057 + +SmokeBench smoke detection (Table 8): mIoU 0.000. + +**Settings of the SmokeBench runs:** + +- The authors run the transformers-native checkpoint ``OpenGVLab/InternVL3-14B-hf`` through the ``image-text-to-text`` pipeline with float32 weights (``device_map="balanced"``): chat template with the image before the text, the processor's dynamic 448-pixel tiling at native resolution, 256 new tokens (the pipeline default) and the checkpoint's greedy generation config. +- The tile task was not run with InternVL3 (the paper's Tables 4-5 have no InternVL3 row; the script has no batch path for it). + +**Deviations:** + +- Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the greedy decoding of the released script. +- ``device_map="auto"`` by default (pass ``device_map="balanced"`` to match the authors' sharding; it does not change outputs). + +**Notes:** + +- ``build_backend`` loads Hugging Face revision ``e22931943e5336f85e06f4e2b38f3e5e6ee4de3b`` (2026-10-07) unless ``revision=`` is given. About 30 GB in bfloat16; the authors' float32 load needs about 60 GB. +- SmokeBench groups InternVL3 with the grounding-trained models; prompted with the SmokeBench detection prompt it still scores 0.000. + +Gemini 2.5 Pro +~~~~~~~~~~~~~~ + +**Model paper:** `Gemini 2.5: Pushing the Frontier with Advanced Reasoning, Multimodality, Long Context, and Next Generation Agentic Capabilities (Gemini Team, arXiv:2507.06261, 2025) `_. + +**Backend:** ``build_backend("gemini_2_5_pro")`` -- ``gemini-2.5-pro`` (API; licence: Proprietary (Gemini API terms); no weights). + +.. list-table:: SmokeBench smoke classification (Tables 1-2) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.441 + - 0.608 + - 0.713 + - 0.773 + - 0.882 + - 0.683 + * - Weber contrast + - 0.588 + - 0.629 + - 0.717 + - 0.696 + - 0.786 + - 0.683 + +**Settings of the SmokeBench runs:** + +- Classification only ("due to cost and resource constraints", Sec. 4.1), temperature 0.5. SmokeBench released no code for its Gemini runs and does not report smoke-free accuracy for the closed models (Table 3 lists the open models only). + +**Deviations:** + +- Request layout chosen by PyHazards: ``google-genai`` ``generate_content`` with the image as an inline JPEG (quality 95) followed by the prompt, temperature 0.5, no output-token cap (Gemini 2.5 Pro spends output tokens on thinking). The API key is read from ``GEMINI_API_KEY`` or ``GOOGLE_API_KEY``. + +**Notes:** + +- The provider-reported model version of every answer is stored in the run records (``served_model``); the model behind ``gemini-2.5-pro`` can change, so results drift over time. +- Google's model page (checked 2026-10-07) limits 2.5-generation access to projects that used it before; new projects may need another model id (``build_backend("gemini_2_5_pro", model_id=...)``), which is then no longer the SmokeBench model. +- Images are sent to Google; FIgLib frames are public HPWREN data. + +GPT-4o +~~~~~~ + +**Model paper:** `GPT-4o System Card (OpenAI, arXiv:2410.21276, 2024) `_. + +**Backend:** ``build_backend("gpt_4o")`` -- ``gpt-4o`` (API; licence: Proprietary (OpenAI API terms); no weights). + +.. list-table:: SmokeBench smoke classification (Tables 1-2) + :header-rows: 1 + + * - accuracy by quintile + - Q1 (lowest) + - Q2 + - Q3 + - Q4 + - Q5 (highest) + - Overall + * - smoke area + - 0.529 + - 0.727 + - 0.770 + - 0.831 + - 0.931 + - 0.758 + * - Weber contrast + - 0.739 + - 0.703 + - 0.774 + - 0.792 + - 0.781 + - 0.758 + +**Settings of the SmokeBench runs:** + +- Classification only (Sec. 4.1), temperature 0.5. The paper does not give the GPT-4o snapshot, and the release has no code for these runs and no smoke-free accuracy for the closed models. + +**Deviations:** + +- Request layout from the only GPT-4o call in the authors' repository (an early grid script): Chat Completions with ``[text, image]`` content, the image as a base64 JPEG data URL (quality 95, OpenCV's default there) and ``max_tokens=300``; temperature 0.5 as the paper states. The API key is read from ``OPENAI_API_KEY``. + +**Notes:** + +- The snapshot behind the ``gpt-4o`` alias is recorded per answer (``served_model``); pass a dated snapshot as ``model_id`` to pin it. +- Images are sent to OpenAI; FIgLib frames are public HPWREN data. + +References +---------- + +- Qi, T., Li, W., Barnes, N. `SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection `_. WACV 2026. +- Dewangan, A. et al. `FIgLib & SmokeyNet: Dataset and Deep Learning Model for Real-Time Wildland + Fire Smoke Detection `_. Remote Sensing 14(4):1007, 2022. +- HPWREN Fire Ignition images Library (FIgLib), https://www.hpwren.ucsd.edu/FIgLib/ (credit + https://www.hpwren.ucsd.edu/ in derivative work). diff --git a/docs/source/pyhazards_simulators.rst b/docs/source/pyhazards_simulators.rst new file mode 100644 index 00000000..3fad4e17 --- /dev/null +++ b/docs/source/pyhazards_simulators.rst @@ -0,0 +1,105 @@ +Simulators +=================== + +Overview +-------- + +ForeFire and WRF-SFIRE are physics-based wildland-fire simulators, not neural networks. PyHazards +does not reimplement them and does not list them as models. Instead it offers two thin, honest +interfaces to the official software: + +- :class:`~pyhazards.simulators.ForeFireSimulator` runs the official ForeFire engine, which you + install yourself, on PyHazards rasters and returns arrival-time and burned-mask rasters. +- The ``wrf_sfire_spread`` dataset and :func:`~pyhazards.datasets.wrf_sfire.read_wrf_sfire_fire_grid` + read the fire-grid outputs (``wrfout`` files) of WRF-SFIRE runs that you made with the official + model. See :doc:`datasets/wrf_sfire`. + +Both appear as ``External simulator`` entries on :doc:`appendix_a_coverage`. + +ForeFire +-------- + +`ForeFire `_ (Filippi et al., `JOSS 2025 +`_; front-tracking method in Filippi et al., `SIMULATION 86(10) +`_) is a C++ discrete-event front-tracking simulator with +official Python bindings, ``pyforefire``. + +**Installation.** ForeFire is GPL-3.0 and PyHazards is MIT, so ForeFire is not a PyHazards +dependency and no ForeFire code is copied into PyHazards. Install the official wheel yourself +(Linux x86_64/aarch64 and macOS; checked with 2.5.0): + +.. code-block:: bash + + pip install forefire + +``pyforefire`` is imported only when a simulation runs. Whoever redistributes PyHazards together +with ForeFire must follow the GPL. + +**What the adapter does.** It makes the same calls as ForeFire's official Python examples: a +``FireDomain`` covering the fuel raster, the propagation model, the fuel index map +(``addIndexLayer``), optional altitude and wind layers (``addScalarLayer``), ignitions +(``startFire``) and wind changes (``trigger[wind;...]``), then ``step``. It reads back ForeFire's +burning map (``arrival_time``) and reduces it to the output grid by taking, for each output cell, +the earliest arrival time of the burning-map cells inside it. Each run happens in a fresh process by +default, because ForeFire keeps its parameters in a process-wide singleton. + +**What it does not do.** It does not change ForeFire's propagation models, fuel tables or +parameters, calibrate anything, or learn anything. The physical realism of a run depends on the fuel +table, propagation model and parameters you choose. + +.. code-block:: python + + import numpy as np + from pyhazards.simulators import ForeFireSimulator + + table = open("fuels.csv").read() # a ForeFire fuel table (';'-separated, 'Index' column) + fuel = np.full((100, 100), 1, dtype=np.int32) # codes from the table's Index column, north-up + dem = np.zeros((100, 100)) # terrain height in metres + ignition = np.zeros((100, 100), dtype=bool) + ignition[50, 50] = True + + sim = ForeFireSimulator(propagation_model="Rothermel", fuels_table=table) + result = sim.run(fuel, cell_size=30.0, duration=3600.0, ignition_mask=ignition, + wind=(3.0, 0.0), altitude=dem) + result.arrival_time # (100, 100) seconds since ignition, inf if unburned + result.burned_masks([1200, 2400, 3600]) # (3, 100, 100) spread targets + +Conventions: rasters are ``(rows, cols)`` with row 0 at the northern edge (``origin="upper"``) unless +``origin="lower"``; the domain is ``cols * dx`` by ``rows * dy`` metres with its south-west corner +at ``(0, 0)``; ``wind`` is ``(u, v)`` in m/s; times are seconds. + +**Verification** (``tests/oracle/test_forefire_oracle.py``, ForeFire 2.5.0): given the rasters of +ForeFire's own regression case ``tests/runff`` (a 64 km Corsican landscape, Rothermel, three +ignitions and a wind change), the adapter reproduces the reference arrival-time map +``ForeFire.0.nc.ref`` within the tolerance of ForeFire's ``compare_nc.py``, and it reproduces the +official ``tests/python/idealizedwind.py`` run bit for bit. + +WRF-SFIRE +--------- + +`WRF-SFIRE `_ (Mandel, Beezley and Kochanski, `GMD 2011 +`_; Mandel et al., `NHESS 2014 +`_) couples the WRF atmosphere model with the SFIRE +level-set fire-spread model. It is a Fortran/MPI model built per machine and run on clusters, so a +PyHazards object cannot run it. PyHazards reads what it writes: + +.. code-block:: python + + from pyhazards.datasets.wrf_sfire import read_wrf_sfire_fire_grid + + grid = read_wrf_sfire_fire_grid("run/wrfout_d01_*", variables=("TIGN_G", "LFN", "FIRE_AREA")) + grid.arrival_time() # TIGN_G where burned, inf elsewhere (s since simulation start) + grid.burned_masks() # (time, rows, cols), LFN < 0 + +The variable names, the fire-subgrid layout (refinement ``sr_x`` by ``sr_y`` with padding rows and +columns) and the meaning of ``TIGN_G`` and ``LFN`` follow the official ``Registry/registry.fire`` +and SFIRE source of release ``W4.4-S0.1``, and were checked on a real history file of the official +ideal case ``test/em_fire/hill`` (its header is kept in +``tests/fixtures/wrf_sfire_hill_wrfout_header.json``). To produce ``wrfout`` files, build WRF-SFIRE from the +official repository (ideal cases in ``test/em_fire``) or use the official real-data workflow +`wrfxpy `_. + +API +--- + +See :doc:`api/pyhazards.simulators`. diff --git a/docs/source/quick_start.rst b/docs/source/quick_start.rst index c0ed7060..8e0b2c60 100644 --- a/docs/source/quick_start.rst +++ b/docs/source/quick_start.rst @@ -27,48 +27,37 @@ training: Step 3: Build a Model --------------------- -Instantiate ``hydrographnet`` through the unified model registry: +Instantiate ``hydrographnet`` (PhysicsNeMo's MeshGraphKAN, the HydroGraphNet flood model) through the +unified model registry: .. code-block:: python from pyhazards.models import build_model - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, - ) - print(type(model).__name__) + model = build_model(name="hydrographnet", task="regression") + print(type(model).__name__, sum(p.numel() for p in model.parameters())) # HydroGraphNet 2318722 Step 4: Run a Short Train/Evaluate Loop --------------------------------------- -This example pairs the ERA5 subset with ``hydrographnet`` to confirm that the -dataset, model, and training engine work together in one workflow. +This example trains ``hydrographnet`` for one epoch on synthetic mesh hydrographs (the layout of the +HydroGraphNet White River data; use ``hydrographnet_white_river`` with a local copy of the release for +real data) to confirm that the dataset, model, and training engine work together. .. code-block:: python import torch - from pyhazards.data.load_hydrograph_data import load_hydrograph_data - from pyhazards.datasets import graph_collate + from pyhazards.datasets import load_dataset + from pyhazards.datasets.flood import hydrograph_collate from pyhazards.engine import Trainer from pyhazards.metrics import RegressionMetrics from pyhazards.models import build_model - data = load_hydrograph_data("pyhazards/data/era5_subset", max_nodes=50) - - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, - ) + data = load_dataset("flood_mesh_synthetic", micro=True).load() + model = build_model(name="hydrographnet", task="regression") trainer = Trainer(model=model, metrics=[RegressionMetrics()], mixed_precision=False) - optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-4) loss_fn = torch.nn.MSELoss() trainer.fit( @@ -77,17 +66,20 @@ dataset, model, and training engine work together in one workflow. loss_fn=loss_fn, max_epochs=1, batch_size=1, - collate_fn=graph_collate, + collate_fn=hydrograph_collate, ) metrics = trainer.evaluate( data, split="train", batch_size=1, - collate_fn=graph_collate, + collate_fn=hydrograph_collate, ) print(metrics) +The flood benchmark scores the test hydrographs with autoregressive rollouts: +``python scripts/run_benchmark.py --config pyhazards/configs/flood/hydrographnet_smoke.yaml``. + Step 5: Next Steps ------------------ diff --git a/docs/source/references.rst b/docs/source/references.rst index 71a1176b..3b3e9f3b 100644 --- a/docs/source/references.rst +++ b/docs/source/references.rst @@ -24,53 +24,71 @@ Wildfire - *Developing risk assessment framework for wildfire in the United States*. `[paper] `__. - *Application of Explainable Artificial Intelligence in Predicting Wildfire Spread: An ASPP-Enabled CNN Approach*. `[paper] `__. -- *Wildfire Danger Prediction and Understanding with Deep Learning*. `[paper] `__, `[repo] `__. +- Kondylatos, S., Prapas, I., Ronco, M., et al. (2022). *Wildfire Danger Prediction and Understanding With Deep Learning*. Geophysical Research Letters, 49(17), e2022GL099368. `[paper] `__, `[repo] `__. - *WildfireSpreadTS: A Dataset of Multi-Modal Time Series for Wildfire Spread Prediction*. `[paper] `__, `[repo] `__. - *Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer*. `[paper] `__, `[repo] `__. -- *ForeFire: A Modular, Scriptable C++ Simulation Engine and Library for Wildland-Fire Spread*. `[paper] `__, `[repo] `__. -- *Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011*. `[paper] `__, `[repo] `__. +- *ForeFire: A Modular, Scriptable C++ Simulation Engine and Library for Wildland-Fire Spread* (Filippi et al., JOSS 2025). `[paper] `__, `[repo] `__. +- *Discrete Event Front-tracking Simulation of a Physical Fire-spread Model* (Filippi et al., SIMULATION 86(10)). `[paper] `__. +- *Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011* (Mandel, Beezley and Kochanski, GMD 2011). `[paper] `__, `[repo] `__. +- *Recent advances and applications of WRF-SFIRE* (Mandel et al., NHESS 2014). `[paper] `__. - *FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction*. `[paper] `__, `[repo] `__. Earthquake ~~~~~~~~~~ -- *Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning*. `[paper] `__. -- *PhaseNet: A Deep-Neural-Network-Based Seismic Arrival Time Picking Method*. `[paper] `__, `[repo] `__. -- *Earthquake Transformer-An attentive deep-learning model for simultaneous earthquake detection and phase picking*. `[paper] `__, `[repo] `__. -- *Generalized Seismic Phase Detection with Deep Learning*. `[paper] `__, `[repo] `__. -- *An End-To-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning*. `[paper] `__, `[repo] `__. +- Lyu, D., Nakata, R., Ren, P., et al. (2025). *Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning*. Nature Communications, 16, 10622. `[paper] `__, `[arXiv] `__, `[repo] `__. +- Zhu, W., and Beroza, G. C. (2019). *PhaseNet: a deep-neural-network-based seismic arrival-time picking method*. Geophysical Journal International, 216(1), 261-273. `[paper] `__, `[arXiv] `__, `[repo] `__. +- Mousavi, S. M., Ellsworth, W. L., Zhu, W., Chuang, L. Y., and Beroza, G. C. (2020). *Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking*. Nature Communications, 11, 3952. `[paper] `__, `[repo] `__. +- Ross, Z. E., Meier, M.-A., Hauksson, E., and Heaton, T. H. (2018). *Generalized Seismic Phase Detection with Deep Learning*. Bulletin of the Seismological Society of America, 108(5A), 2894-2901. `[paper] `__, `[arXiv] `__, `[repo] `__. +- Zhu, W., Tai, K. S., Mousavi, S. M., Bailis, P., and Beroza, G. C. (2022). *An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning*. Journal of Geophysical Research: Solid Earth, 127(3), e2021JB023283. `[paper] `__, `[arXiv] `__, `[repo (non-commercial licence)] `__. Flood ~~~~~ -- *Interpretable physics-informed graph neural networks for flood forecasting*. `[paper] `__. -- *Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets*. `[paper] `__, `[repo] `__. -- *Large-scale flood modeling and forecasting with FloodCast*. `[paper] `__, `[repo] `__. -- *UrbanFloodCast: WMO Urban Flooding Forecasting Challenge*. `[paper] `__, `[repo] `__. -- *Global Flood Forecasting at a Fine Catchment Resolution using Machine Learning*. `[paper] `__, `[repo] `__. +- Kratzert, F., Klotz, D., Brenner, C., Schulz, K., and Herrnegger, M. (2018). *Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks*. Hydrology and Earth System Sciences, 22, 6005-6022. `[paper] `__. +- Kratzert, F., Klotz, D., Shalev, G., Klambauer, G., Hochreiter, S., and Nearing, G. (2019). *Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets*. Hydrology and Earth System Sciences, 23, 5089-5110. `[paper] `__, `[repo] `__, `[weights] `__. +- Kratzert, F., Gauch, M., Nearing, G., and Klotz, D. (2022). *NeuralHydrology - A Python library for Deep Learning research in hydrology*. Journal of Open Source Software, 7(71), 4050. `[paper] `__, `[repo] `__. +- Nearing, G., Cohen, D., Dube, V., Gauch, M., Gilon, O., Harrigan, S., et al. (2024). *Global prediction of extreme floods in ungauged watersheds*. Nature, 627, 559-563. `[paper] `__, `[repo] `__. +- Gauch, M., Kratzert, F., Klotz, D., Nearing, G., Cohen, D., and Gilon, O. (2025). *How to deal w___ missing input data*. Hydrology and Earth System Sciences, 29, 6221-6235. `[paper] `__, `[repo] `__. +- Taghizadeh, M., Zandsalimi, Z., Nabian, M. A., Shafiee-Jood, M., and Alemazkoor, N. (2025). *Interpretable physics-informed graph neural networks for flood forecasting*. Computer-Aided Civil and Infrastructure Engineering, 40(18), 2629-2649. `[paper] `__, `[repo] `__. +- Xu, Q., Shi, Y., Bamber, J., Ouyang, C., and Zhu, X. X. (2024). *Large-scale flood modeling and forecasting with FloodCast*. Water Research, 264, 122162. `[paper] `__, `[repo] `__. +- Xu, Q., De Vos, L. F., Shi, Y., Rüther, N., Bronstert, A., and Zhu, X. X. (2025). *Urban flood modeling and forecasting with deep neural operator and transfer learning*. Journal of Hydrology, 661, 133705. `[paper] `__, `[repo] `__. Hurricane and Tropical Cyclone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- *Hurricane Forecasting: A Novel Multimodal Machine Learning Framework*. `[paper] `__, `[repo] `__. -- *Deep Learning Experiments for Tropical Cyclone Intensity Forecasts*. `[paper] `__, `[repo] `__. -- *Benchmark dataset and deep learning method for global tropical cyclone forecasting*. `[paper] `__, `[repo] `__. -- *SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction*. `[paper] `__, `[repo] `__. -- *Tropical cyclone intensity forecasting using model knowledge guided deep learning model*. `[paper] `__, `[repo] `__. -- *GraphCast: Learning skillful medium-range global weather forecasting*. `[paper] `__, `[repo] `__. -- *Accurate medium-range global weather forecasting with 3D neural networks*. `[paper] `__, `[repo] `__. +- *Hurricane Forecasting: A Novel Multimodal Machine Learning Framework*. Weather and Forecasting 37(6), 2022. `[paper] `__, `[arXiv] `__, `[repo] `__. +- *Deep Learning Experiments for Tropical Cyclone Intensity Forecasts*. Weather and Forecasting 36(4), 2021. `[paper] `__, `[repo] `__. +- *Benchmark dataset and deep learning method for global tropical cyclone forecasting*. Nature Communications 16, 5923, 2025. `[paper] `__, `[repo] `__, `[code and weights, CC BY 4.0] `__. +- *SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction*. Pattern Recognition Letters 155, 2022. `[paper] `__, `[repo] `__. +- *Tropical cyclone intensity forecasting using model knowledge guided deep learning model*. Environmental Research Letters 19, 024006, 2024. `[paper] `__, `[repo] `__. +- *Learning skillful medium-range global weather forecasting* (GraphCast). Science 382(6677), 2023. `[paper] `__, `[arXiv] `__, `[repo] `__ (formerly google-deepmind/graphcast). +- *Accurate medium-range global weather forecasting with 3D neural networks* (Pangu-Weather). Nature 619, 2023. `[paper] `__, `[technical report] `__, `[repo] `__ (no code licence; weights CC BY-NC-SA 4.0). - *FourCastNet: A Global Data-driven High-resolution Weather Model using Adaptive Fourier Neural Operators*. `[paper] `__, `[repo] `__. +- Gomez, M. et al. (2026). *TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale*. `[arXiv] `__, `[repo] `__, `[data] `__. +- Ullrich, P. A. and Zarzycki, C. M. (2017). *TempestExtremes: a framework for scale-insensitive pointwise feature tracking on unstructured grids*. Geoscientific Model Development, 10, 1069-1090. `[paper] `__, `[repo] `__. +- Ullrich, P. A., Zarzycki, C. M., McClenny, E. E., Pinheiro, M. C., Stansfield, A. M., and Reed, K. A. (2021). *TempestExtremes v2.1: a community framework for feature detection, tracking, and analysis in large datasets*. Geoscientific Model Development, 14, 5023-5048. `[paper] `__. +- Rasp, S. et al. (2024). *WeatherBench 2: A benchmark for the next generation of data-driven global weather models*. Journal of Advances in Modeling Earth Systems, 16, e2023MS004019. `[paper] `__, `[repo] `__. +- van der Grijn, G. (2002). *Tropical cyclone forecasting at ECMWF: new products and validation*. ECMWF Technical Memorandum 386. `[report] `__. Benchmark and Data Resources ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- *SeisBench - A Toolbox for Machine Learning in Seismology*. `[paper] `__, `[repo] `__. -- *pick-benchmark*. `[repo] `__. -- *pyCSEP*. `[repo] `__. -- *AEFA*. `[repo] `__. -- *Caravan - A global community dataset for large-sample hydrology*. `[paper] `__, `[repo] `__. +- Woollam, J., Münchmeyer, J., Tilmann, F., et al. (2022). *SeisBench - A Toolbox for Machine Learning in Seismology*. Seismological Research Letters, 93(3), 1695-1709. `[paper] `__, `[repo] `__. +- Münchmeyer, J., Woollam, J., Rietbrock, A., et al. (2022). *Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers*. Journal of Geophysical Research: Solid Earth, 127(1), e2021JB023499. `[paper] `__, `[repo] `__. +- Mousavi, S. M., Sheng, Y., Zhu, W., and Beroza, G. C. (2019). *STanford EArthquake Dataset (STEAD): A Global Data Set of Seismic Signals for AI*. IEEE Access, 7, 179464-179476. `[paper] `__, `[repo] `__. +- Michelini, A., Cianetti, S., Gaviano, S., et al. (2021). *INSTANCE - the Italian seismic dataset for machine learning*. Earth System Science Data, 13, 5509-5544. `[paper] `__, `[data] `__. +- Savran, W. H., Bayona, J. A., Iturrieta, P., et al. (2022). *pyCSEP: A Python Toolkit for Earthquake Forecast Developers*. Seismological Research Letters, 93(5), 2858-2870. `[paper] `__, `[repo] `__. Not implemented in PyHazards. +- Chen, Y., Savvaidis, A., Chen, Y., et al. (2025). *AEFA: an earthquake forecasting dataset for AI*. Geodata and AI, 3, 100022. `[paper] `__, `[repo] `__. Not implemented in PyHazards. +- Kratzert, F., Nearing, G., Addor, N., et al. (2023). *Caravan - A global community dataset for large-sample hydrology*. Scientific Data, 10, 61. `[paper] `__, `[repo] `__. +- Addor, N., Newman, A. J., Mizukami, N., and Clark, M. P. (2017). *The CAMELS data set: catchment attributes and meteorology for large-sample studies*. Hydrology and Earth System Sciences, 21, 5293-5313. `[paper] `__. - *WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting*. `[paper] `__, `[repo] `__. -- *FloodCastBench*. `[repo] `__. +- Xu, Q., Shi, Y., Zhao, J., and Zhu, X. X. (2025). *FloodCastBench: A Large-Scale Dataset and Foundation Models for Flood Modeling and Forecasting*. Scientific Data, 12, 431. `[paper] `__, `[data] `__, `[repo] `__. No reader in PyHazards. +- Rahman, M. A., Ross, Z. E., and Azizzadenesheli, K. (2022). *U-NO: U-shaped Neural Operators*. arXiv:2204.11127. `[paper] `__, `[repo] `__. Operator blocks of the UrbanFloodCast DNO. +- Taghizadeh, M., et al. (2025). *HydroGraphNet dataset (White River, Indiana, HEC-RAS simulations)*. `[data, CC BY 4.0] `__. +- Xu, Q., et al. (2025). *UrbanFloodCast benchmark dataset (Berlin design storms)*. `[data, CC BY 4.0] `__. No reader in PyHazards. - *HydroBench*. `[repo] `__. - *TCBench Alpha*. `[repo] `__. -- *IBTrACS*. `[product page] `__. +- *The International Best Track Archive for Climate Stewardship (IBTrACS): Unifying tropical cyclone best track data*. Bulletin of the American Meteorological Society 91, 2010. `[paper] `__, `[dataset v04r01] `__, `[product page] `__. +- *TropiCycloneNet Dataset (TCND)*. `[dataset, CC BY 4.0] `__, `[repo] `__. +- *Supporting data for Xu et al. 2021 - Weather and Forecasting* (SHIPS predictors). `[dataset, CC BY 4.0] `__. diff --git a/pyhazards/__init__.py b/pyhazards/__init__.py index 23a9336f..891488fd 100644 --- a/pyhazards/__init__.py +++ b/pyhazards/__init__.py @@ -65,6 +65,8 @@ "configs": "pyhazards.configs", "benchmarks": "pyhazards.benchmarks", "models": "pyhazards.models", + "simulators": "pyhazards.simulators", + "forecasts": "pyhazards.forecasts", "metrics": "pyhazards.metrics", "reports": "pyhazards.reports", "engine": "pyhazards.engine", diff --git a/pyhazards/appendix_a_catalog.py b/pyhazards/appendix_a_catalog.py index fa92c3ae..7c1efd66 100644 --- a/pyhazards/appendix_a_catalog.py +++ b/pyhazards/appendix_a_catalog.py @@ -2,7 +2,7 @@ from dataclasses import dataclass from pathlib import Path -from typing import Dict, List, Sequence +from typing import Dict, List, Sequence, Tuple from .model_catalog import ModelCard, group_cards_by_hazard, load_model_cards, public_catalog_cards @@ -19,9 +19,16 @@ "core": "Implemented", "variant": "Variant only", "experimental": "Experimental", + "external": "External simulator", + "pipeline": "Foundation model pipeline", "missing": "Missing", } +SUMMARY_STATUSES = ("core", "variant", "experimental", "external", "pipeline", "missing") + +# Statuses for resources that are not PyHazards models: they must link documentation, not model cards. +NON_MODEL_STATUSES = {"external": "an external simulator", "pipeline": "a foundation model pipeline"} + @dataclass(frozen=True) class AppendixAEntry: @@ -32,49 +39,128 @@ class AppendixAEntry: status: str mapped_models: Sequence[str] = () notes: str = "" + # (label, Sphinx docname) links for entries that are not models, e.g. an external simulator or a + # foundation-model pipeline. + mapped_docs: Sequence[Tuple[str, str]] = () +FOREFIRE_NOTE = ( + "ForeFireSimulator runs the official ForeFire engine (GPL-3.0; installed separately with " + "``pip install forefire``, never vendored) on PyHazards rasters and returns arrival-time and " + "burned-mask rasters. It reproduces ForeFire's own regression reference (tests/runff) and the " + "official idealized-wind example. It is a physics simulator, not a trainable model." +) +WRF_SFIRE_NOTE = ( + "PyHazards does not run WRF-SFIRE (an MPI Fortran model). The ``wrf_sfire_spread`` dataset reads " + "the fire grid (TIGN_G, LFN, FIRE_AREA, FGRNHFX, ROS, ...) of wrfout files written by the official " + "model into spread rasters. Variable names and layout follow the official Registry and were " + "checked on a real output of the official hill ideal case." +) + +FOUNDATION_PIPELINE_DOCS = (("Foundation Weather Models", "pyhazards_forecasts"),) +GRAPHCAST_NOTE = ( + "Not reimplemented: GraphCast (36.3M parameters, JAX) is a global weather model whose cyclone tracks come " + "from a tracker run on its forecasts. PyHazards reads WeatherBench 2's GraphCast forecasts (2018 from the " + "1979-2017 model, 2020), can run it through earth2studio (user-installed; weights CC BY 4.0 per the README " + "since 2026-08-06), tracks with a re-implementation of the paper's modified ECMWF tracker (the tracker was " + "never released) and scores against IBTrACS. The paper's Fig. 3 numbers are not reproduced. GenCast is a " + "different model and is not covered." +) +PANGU_NOTE = ( + "Not reimplemented: PyHazards reads TCBench's released 2023 Pangu-Weather tracks and fields and WeatherBench " + "2's 2018-2022 forecasts, can run the official ONNX graphs through earth2studio, and tracks with the paper's " + "ECMWF-style rules or TCBench's TempestExtremes rules. TCBench's released tracks are reproduced byte for byte " + "from the raw fields, and its published DPE values exactly. The TC2018 numbers (120.29 / 195.65 km) are not " + "reproduced. Weights CC BY-NC-SA 4.0 (non-commercial); the official repository has no code licence." +) +FOURCASTNET_NOTE = ( + "Not reimplemented: FourCastNet (74.7M-parameter AFNO) can be run through earth2studio (FCN, a 26-variable " + "retrain) and its fields tracked and scored. The paper has only a qualitative cyclone case. TCBench's " + "'FourCastNet v2' tracks and fields (SFNO small, a different model) can be read and scored." +) + APPENDIX_A_ENTRIES: List[AppendixAEntry] = [ - AppendixAEntry("Earthquake", "PhaseNet", "Baseline", "https://github.com/AI4EPS/PhaseNet", "core", ("phasenet",), "Model adapter is implemented, but the SeisBench / pick-benchmark data path is still missing."), - AppendixAEntry("Earthquake", "EQTransformer", "Baseline", "https://github.com/smousavi05/EQTransformer", "core", ("eqtransformer",), "Model adapter is implemented, but the benchmark stack remains lighter than the PDF target."), - AppendixAEntry("Earthquake", "GPD", "Baseline", "https://github.com/interseismic/generalized-phase-detection", "core", ("gpd",), "Model adapter is implemented behind the shared picking interface."), - AppendixAEntry("Earthquake", "EQNet", "Baseline", "https://github.com/AI4EPS/EQNet", "core", ("eqnet",), "Model adapter is implemented behind the shared picking interface."), - AppendixAEntry("Earthquake", "SeisBench", "Benchmark / Data Ecosystem", "https://github.com/seisbench/seisbench", "core", notes="A synthetic-backed SeisBench-compatible waveform adapter is registered for smoke benchmarking."), - AppendixAEntry("Earthquake", "pick-benchmark", "Benchmark", "https://github.com/seisbench/pick-benchmark", "core", notes="A synthetic-backed pick-benchmark-compatible waveform adapter is registered for smoke benchmarking."), - AppendixAEntry("Earthquake", "pyCSEP", "Benchmark / Reports", "https://github.com/SCECCode/pycsep", "core", notes="The forecasting smoke benchmark exports a pyCSEP-style JSON artifact."), - AppendixAEntry("Earthquake", "AEFA", "Dataset / Forecast Benchmark", "https://github.com/chenyk1990/aefa", "core", notes="A synthetic-backed AEFA-style forecasting dataset adapter is registered."), - AppendixAEntry("Wildfire", "wildfire_forecasting", "Baseline", "https://github.com/Orion-AI-Lab/wildfire_forecasting", "core", ("wildfire_forecasting",)), + AppendixAEntry("Earthquake", "PhaseNet", "Baseline", "https://github.com/AI4EPS/PhaseNet", "core", ("phasenet",), "Port of the official TensorFlow U-Net (268,443 parameters); the released checkpoint 190703-214543 loads without TensorFlow and matches the official graph and SeisBench's port. Scored with the PhaseNet and EQTransformer pick metrics on real SeisBench-format / STEAD data."), + AppendixAEntry("Earthquake", "EQTransformer", "Baseline", "https://github.com/smousavi05/EQTransformer", "core", ("eqtransformer",), "Port of the released Keras models (paper model 371,639 parameters, conservative 376,423) with detection, P and S outputs; both official .h5 files load and match Keras and SeisBench."), + AppendixAEntry("Earthquake", "GPD", "Baseline", "https://github.com/interseismic/generalized-phase-detection", "core", ("gpd",), "Port of the released Keras P/S/noise window classifier (1,741,003 parameters) and its sliding-window picker; the official weights match Keras and SeisBench and reproduce the shipped Anza picks."), + AppendixAEntry("Earthquake", "EQNet", "Baseline", "https://github.com/AI4EPS/EQNet", "variant", ("eqnet",), "Rebuilt from the paper (Zhu et al. 2022, doi:10.1029/2021JB023283; 1,043,619 parameters): 1-D ResNet-18 feature extractor, P and S picking heads, shift-and-stack over candidate hypocentres and event detection, with a multi-station input (station gathers plus travel times). The official repository (non-commercial licence, no shift-and-stack, no weights) is only a test oracle: the feature extractor and both heads match the author's code; the shift-and-stack module and the end-to-end model are unverified. Its picking heads are scored on the earthquake.picking task."), + AppendixAEntry("Earthquake", "SeisBench", "Benchmark / Data Ecosystem", "https://github.com/seisbench/seisbench", "core", notes="seisbench_waveforms reads SeisBench-format datasets (and STEAD's own files) with PyHazards' own reader, checked against SeisBench's writer and reader; SeisBench itself (GPL-3.0) is only a test oracle. Datasets are downloaded by the user."), + AppendixAEntry("Earthquake", "pick-benchmark", "Benchmark", "https://github.com/seisbench/pick-benchmark", "missing", notes="Its SeisBench-format datasets can be read with seisbench_waveforms, but its three evaluation tasks (event detection AUC, phase identification MCC, onset regression on sampled windows) are not implemented; PyHazards scores pickers with the PhaseNet / EQTransformer pick metrics instead. The former synthetic pick_benchmark_waveforms adapter was removed."), + AppendixAEntry("Earthquake", "pyCSEP", "Benchmark / Reports", "https://github.com/SCECCode/pycsep", "missing", notes="pyCSEP tests earthquake-rate forecasts (Savran et al. 2022, doi:10.1785/0220220033); PyHazards has no rate-forecasting task. The former 'pyCSEP-style' JSON export of the wavefield-forecasting benchmark was only a metrics dump and was removed."), + AppendixAEntry("Earthquake", "AEFA", "Dataset / Forecast Benchmark", "https://github.com/chenyk1990/aefa", "missing", notes="AEFA is a weekly earthquake-occurrence forecasting dataset with electromagnetic / geoacoustic features (Chen et al. 2025, doi:10.1016/j.geoai.2025.100022; README states GPL-3.0). No loader exists; the former aefa_forecast adapter generated synthetic wavefields (now earthquake_wavefield_synthetic, used by WaveCastNet's wavefield-forecasting task) and was removed."), + AppendixAEntry("Wildfire", "wildfire_forecasting", "Baseline", "https://github.com/Orion-AI-Lab/wildfire_forecasting", "core", ("wildfire_forecasting",), "The paper's LSTM (default) and ConvLSTM are ported and checked against the official code; the Greek datacube is not loaded yet (synthetic smoke data). The paper's random forest (random_forest, checked against the official notebook) and XGBoost (xgboost, hyperparameters pending the paper's Supporting Information) are separate entries."), AppendixAEntry("Wildfire", "WildfireSpreadTS", "Baseline / Benchmark", "https://github.com/SebastianGer/WildfireSpreadTS", "core", ("wildfirespreadts",)), - AppendixAEntry("Wildfire", "ASUFM", "Baseline", "https://github.com/bronteee/fire-asufm", "core", ("asufm",)), - AppendixAEntry("Wildfire", "WRF-SFIRE", "Simulator Adapter", "https://github.com/openwfm/WRF-SFIRE", "core", ("wrf_sfire",), "The current adapter is lightweight and synthetic-backed rather than a full external simulator binding."), - AppendixAEntry("Wildfire", "ForeFire", "Simulator Adapter", "https://github.com/forefireAPI/forefire", "core", ("forefire",), "The current adapter is lightweight and synthetic-backed rather than a full external simulator binding."), - AppendixAEntry("Wildfire", "FireCastNet", "Optional Baseline", "https://github.com/SeasFire/firecastnet", "core", ("firecastnet",)), - AppendixAEntry("Flood", "NeuralHydrology", "Baseline Family", "https://github.com/neuralhydrology/neuralhydrology", "core", ("neuralhydrology_lstm", "neuralhydrology_ealstm"), "The LSTM and EA-LSTM adapters are implemented, but Caravan / WaterBench benchmark backing is still missing."), - AppendixAEntry("Flood", "Caravan", "Dataset", "https://github.com/kratzert/Caravan", "core", notes="A synthetic-backed Caravan adapter is registered for streamflow smoke benchmarking."), - AppendixAEntry("Flood", "WaterBench", "Dataset", "https://github.com/uihilab/WaterBench", "core", notes="A synthetic-backed WaterBench adapter is registered for streamflow smoke benchmarking."), - AppendixAEntry("Flood", "FloodCast", "Baseline", "https://github.com/HydroPML/FloodCast", "core", ("floodcast",), "The model adapter is implemented, but FloodCastBench-backed evaluation is not wired yet."), - AppendixAEntry("Flood", "FloodCastBench", "Benchmark", "https://github.com/HydroPML/FloodCastBench", "core", notes="A synthetic-backed FloodCastBench-style inundation adapter is registered."), - AppendixAEntry("Flood", "UrbanFloodCast", "Baseline", "https://github.com/HydroPML/UrbanFloodCast", "core", ("urbanfloodcast",), "The model adapter is implemented on synthetic inundation fixtures today."), - AppendixAEntry("Flood", "HydroBench", "Benchmark / Diagnostics", "https://github.com/EMscience/HydroBench", "core", notes="A synthetic-backed HydroBench adapter is registered for streamflow smoke benchmarking."), - AppendixAEntry("Flood", "google-research/flood-forecasting", "Reference Baseline", "https://github.com/google-research/flood-forecasting", "core", ("google_flood_forecasting",)), - AppendixAEntry("Hurricane / Tropical Cyclone", "Hurricast", "Baseline", "https://github.com/leobix/hurricast", "core", ("hurricast",), "The model adapter is implemented, but the real TCBench / IBTrACS data path is still missing."), - AppendixAEntry("Hurricane / Tropical Cyclone", "tropicalcyclone_MLP", "Baseline", "https://github.com/wenweixu/tropicalcyclone_MLP", "core", ("tropicalcyclone_mlp",), "The model adapter is implemented as a basin-filtered storm baseline."), - AppendixAEntry("Hurricane / Tropical Cyclone", "TCIF-fusion", "Baseline", "https://github.com/wangchong96/TCIF-fusion", "core", ("tcif_fusion",), "The model adapter is implemented behind the shared storm evaluator."), - AppendixAEntry("Hurricane / Tropical Cyclone", "SAF-Net", "Baseline", "https://github.com/xuguangning1218/TI_Prediction", "core", ("saf_net",), "The model adapter is implemented behind the shared storm evaluator."), - AppendixAEntry("Hurricane / Tropical Cyclone", "TropiCycloneNet", "Baseline", "https://github.com/xiaochengfuhuo/TropiCycloneNet", "core", ("tropicyclonenet",), "The model adapter is implemented, but the public benchmark/data track remains synthetic-first."), - AppendixAEntry("Hurricane / Tropical Cyclone", "TropiCycloneNet-Dataset", "Dataset", "https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset", "core", notes="A synthetic-backed TropiCycloneNet-Dataset adapter is registered."), - AppendixAEntry("Hurricane / Tropical Cyclone", "TCBench Alpha", "Benchmark", "https://github.com/msgomez06/TCBench_Alpha", "core", notes="A synthetic-backed TCBench Alpha adapter is registered."), - AppendixAEntry("Hurricane / Tropical Cyclone", "IBTrACS", "Dataset", "https://www.ncei.noaa.gov/products/international-best-track-archive", "core", notes="A synthetic-backed IBTrACS adapter is registered."), - AppendixAEntry("Hurricane / Tropical Cyclone", "GraphCast / GenCast", "Foundation Adapter", "https://github.com/google-deepmind/graphcast", "experimental", ("graphcast_tc",), "The current wrapper is intentionally lightweight and should not be counted as stable core coverage."), - AppendixAEntry("Hurricane / Tropical Cyclone", "Pangu-Weather", "Foundation Adapter", "https://github.com/198808xc/Pangu-Weather", "experimental", ("pangu_tc",), "The current wrapper is intentionally lightweight and should not be counted as stable core coverage."), - AppendixAEntry("Hurricane / Tropical Cyclone", "FourCastNet", "Foundation Adapter", "https://github.com/NVlabs/FourCastNet", "experimental", ("fourcastnet_tc",), "The current wrapper is intentionally lightweight and should not be counted as stable core coverage."), + AppendixAEntry("Wildfire", "ASUFM", "Baseline", "https://github.com/bronteee/fire-asufm", "core", ("asufm",), "Next-day fire-mask segmentation on 64x64 NDWS tiles, verified against the official code; the smoke benchmark runs it on synthetic 64x64 spread rasters because no NDWS loader exists yet."), + AppendixAEntry("Wildfire", "WRF-SFIRE", "Simulator Output Reader", "https://github.com/openwfm/WRF-SFIRE", "external", notes=WRF_SFIRE_NOTE, mapped_docs=(("WRF-SFIRE Outputs", "datasets/wrf_sfire"), ("Simulators", "pyhazards_simulators"))), + AppendixAEntry("Wildfire", "ForeFire", "Simulator Adapter", "https://github.com/forefireAPI/forefire", "external", notes=FOREFIRE_NOTE, mapped_docs=(("Simulators", "pyhazards_simulators"),)), + AppendixAEntry("Wildfire", "FireCastNet", "Optional Baseline", "https://github.com/SeasFire/firecastnet", "core", ("firecastnet",), "Pure PyTorch port of the official model; the released SeasFire checkpoints load and match the official DGL implementation. SeasFire datacube backing is still missing."), + AppendixAEntry("Flood", "NeuralHydrology", "Baseline Family", "https://github.com/neuralhydrology/neuralhydrology", "core", ("neuralhydrology_lstm", "neuralhydrology_ealstm"), "Ports of NeuralHydrology's CudaLSTM and EA-LSTM at the Kratzert et al. (2019) configuration, checked against NeuralHydrology and the official 2019 checkpoints; CAMELS-US and Caravan readers and the per-basin NSE / KGE evaluation are checked against NeuralHydrology's datasets and Tester."), + AppendixAEntry("Flood", "Caravan", "Dataset", "https://github.com/kratzert/Caravan", "core", notes="``caravan_streamflow`` reads a local copy of the official release (netCDF or CSV) into NeuralHydrology-style samples; checked against NeuralHydrology's reader on real Caravan files.", mapped_docs=(("Caravan", "datasets/caravan_streamflow"),)), + AppendixAEntry("Flood", "WaterBench", "Dataset", "https://github.com/uihilab/WaterBench", "missing", notes="No reader. The former ``waterbench_streamflow`` adapter generated random numbers and was removed."), + AppendixAEntry("Flood", "FloodCast", "Baseline", "https://github.com/HydroPML/FloodCast", "experimental", ("floodcast",), "The model under this name is a small CNN, not FloodCast (Xu et al. 2024, doi:10.1016/j.watres.2024.122162). The flood model (sequence-to-sequence GeoPINS, a physics-informed space-time Fourier operator) was never released, and the paper does not report its channel widths, so it cannot be rebuilt faithfully; the repository has no licence."), + AppendixAEntry("Flood", "FloodCastBench", "Benchmark", "https://github.com/HydroPML/FloodCastBench", "missing", notes="No reader for the 21.6 GB release (Zenodo 10.5281/zenodo.14017092); the former ``floodcastbench_inundation`` adapter generated random numbers and was removed. Its FNO / FNO+ baselines (4 layers, 12 modes, width 20) are not provided: only the data-generation code was released (no licence), so there is no model code to check a port against. The ``flood.inundation`` metrics (RMSE, NSE, Pearson r, CSI) cover its scores."), + AppendixAEntry("Flood", "UrbanFloodCast", "Baseline", "https://github.com/HydroPML/UrbanFloodCast", "core", ("urbanfloodcast",), "The deep neural operator (DNO-3, 4,470,437 parameters, 24 steps at once) written from the paper with U-NO (BSD-2) and FNO (MIT) blocks, since the official code has no licence; parameters, seeded initialisation, outputs, the one-shot input pipeline and the evaluation metrics match the official code. The Berlin GeoTIFFs (Zenodo 10.5281/zenodo.15700880) have no reader yet (urbanfloodcast_synthetic in their layout)."), + AppendixAEntry("Flood", "HydroBench", "Benchmark / Diagnostics", "https://github.com/EMscience/HydroBench", "missing", notes="No integration. The former ``hydrobench_streamflow`` adapter generated random numbers and was removed; the flood benchmark computes NeuralHydrology's hydrograph metrics instead."), + AppendixAEntry("Flood", "google-research/flood-forecasting", "Reference Baseline", "https://github.com/google-research/flood-forecasting", "core", ("google_flood_forecasting",), "Port of the released FloodHub model (MeanEmbeddingForecastLSTM, Gauch et al. 2025); the released weights load and match googlehydrology. Caravan MultiMet forecast inputs are not read yet."), + AppendixAEntry("Hurricane / Tropical Cyclone", "Hurricast", "Baseline", "https://github.com/leobix/hurricast", "core", ("hurricast",), "Written from the paper (the official code has no licence): the CNN + Transformer encoder-decoder matches the official network for every released preset (seeded weights, outputs, gradients) and XGBoost runs on its embeddings with the official defaults; hurricast_ibtracs_era5 reads IBTrACS and ERA5. The paper's GRU decoder is not in the released code; no weights were released."), + AppendixAEntry("Hurricane / Tropical Cyclone", "tropicalcyclone_MLP", "Baseline", "https://github.com/wenweixu/tropicalcyclone_MLP", "core", ("tropicalcyclone_mlp",), "The official 24-hour intensity-change MLP (121 SHIPS predictors, BSD-2) is ported and matches the official Keras model; ships_xu2021 reads the authors' predictor table (Zenodo 4784610) with the official leave-one-year-out folds. No trained weights were released."), + AppendixAEntry("Hurricane / Tropical Cyclone", "TCIF-fusion", "Baseline", "https://github.com/wangchong96/TCIF-fusion", "core", ("tcif_fusion",), "Written from the paper and the notebook (no licence); the notebook graph rebuilt in Keras 3 gives the same outputs with copied weights and the authors' printed layer counts (299.6 M parameters). The ALL input has the paper's 65 channels (notebook: 85). The CMA / ERA5 / GridSat-B1 inputs have no reader yet (synthetic layout only)."), + AppendixAEntry("Hurricane / Tropical Cyclone", "SAF-Net", "Baseline", "https://github.com/xuguangning1218/TI_Prediction", "core", ("saf_net",), "Written from the paper (the official code has no licence); the released checkpoint loads strictly and matches the official notebook network. The CMA / ERA-Interim inputs have no PyHazards reader yet (synthetic layout only)."), + AppendixAEntry("Hurricane / Tropical Cyclone", "TropiCycloneNet", "Baseline", "https://github.com/xiaochengfuhuo/TropiCycloneNet", "core", ("tropicyclonenet",), "The six-generator GAN (CC BY 4.0 release) is ported; the released checkpoint loads strictly and matches the official code. The benchmark reports the paper's best-of-6 errors next to sample-mean errors."), + AppendixAEntry("Hurricane / Tropical Cyclone", "TropiCycloneNet-Dataset", "Dataset", "https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset", "core", notes="tropicyclonenet_dataset reads TCND Data1d, Env-Data and 500 hPa GPH files (Zenodo, CC BY 4.0) exactly like the official TropiCycloneNet loader; tropicyclonenet_dataset_synthetic is a random stand-in for smoke tests.", mapped_docs=(("TropiCycloneNet Dataset", "datasets/tropicyclonenet_dataset"),)), + AppendixAEntry("Hurricane / Tropical Cyclone", "TCBench Alpha", "Benchmark", "https://github.com/msgomez06/TCBench_Alpha", "core", notes="pyhazards.forecasts reads TCBench's released tracks and raw forecast fields (Hugging Face, pinned revision), re-implements its TempestExtremes tracking (identical tracks) and HuracanPy matching, and scores direct position error and intensity errors exactly as its evaluation does (the DPE values printed in its notebook are reproduced; one only with the IBTrACS position TCBench used, since revised by NCEI). CRPS, along/cross-track errors, rapid-intensification scores and its post-processing models are not implemented.", mapped_docs=(("TCBench Alpha", "datasets/tcbench_alpha"), ("Foundation Weather Models", "pyhazards_forecasts"))), + AppendixAEntry("Hurricane / Tropical Cyclone", "IBTrACS", "Dataset", "https://www.ncei.noaa.gov/products/international-best-track-archive", "core", notes="ibtracs_tracks reads NOAA NCEI IBTrACS v04 CSV or netCDF files (best-track positions, intensities, agency columns) into forecast windows; the cyclone benchmark scores great-circle track error in km and intensity errors per lead time.", mapped_docs=(("IBTrACS", "datasets/ibtracs_tracks"),)), + AppendixAEntry("Hurricane / Tropical Cyclone", "GraphCast", "Foundation Model Pipeline", "https://github.com/google-deepmind/weathernext", "pipeline", notes=GRAPHCAST_NOTE, mapped_docs=FOUNDATION_PIPELINE_DOCS), + AppendixAEntry("Hurricane / Tropical Cyclone", "Pangu-Weather", "Foundation Model Pipeline", "https://github.com/198808xc/Pangu-Weather", "pipeline", notes=PANGU_NOTE, mapped_docs=FOUNDATION_PIPELINE_DOCS), + AppendixAEntry("Hurricane / Tropical Cyclone", "FourCastNet", "Foundation Model Pipeline", "https://github.com/NVlabs/FourCastNet", "pipeline", notes=FOURCASTNET_NOTE, mapped_docs=FOUNDATION_PIPELINE_DOCS), ] -def appendix_a_alignment_issues(cards: Sequence[ModelCard]) -> List[str]: +def _doc_exists(docname: str) -> bool: + if docname.startswith("datasets/"): + from .dataset_catalog import load_dataset_cards + + return docname.split("/", 1)[1] in {card.slug for card in load_dataset_cards()} + return (DOCS_SOURCE_DIR / f"{docname}.rst").exists() + + +def appendix_a_alignment_issues( + cards: Sequence[ModelCard], + entries: Sequence[AppendixAEntry] | None = None, +) -> List[str]: issues: List[str] = [] mapping = {card.model_name: card for card in cards} - for entry in APPENDIX_A_ENTRIES: + for entry in APPENDIX_A_ENTRIES if entries is None else entries: + if entry.status not in STATUS_LABELS: + issues.append( + "Coverage entry '{name}' has unknown status '{status}'.".format( + name=entry.source_name, + status=entry.status, + ) + ) + kind = NON_MODEL_STATUSES.get(entry.status) + if kind and entry.mapped_models: + issues.append( + "Coverage entry '{name}' is {kind} and must not map to model cards.".format( + name=entry.source_name, + kind=kind, + ) + ) + if kind and not entry.mapped_docs: + issues.append( + "Coverage entry '{name}' is {kind} but links no documentation.".format( + name=entry.source_name, + kind=kind, + ) + ) + for _, docname in entry.mapped_docs: + if not _doc_exists(docname): + issues.append( + "Coverage entry '{name}' links missing doc '{doc}'.".format( + name=entry.source_name, + doc=docname, + ) + ) for model_name in entry.mapped_models: card = mapping.get(model_name) if card is None: @@ -109,7 +195,7 @@ def _summary_rows() -> Dict[str, Dict[str, int]]: for entry in APPENDIX_A_ENTRIES: bucket = summary.setdefault( entry.hazard_family, - {"core": 0, "experimental": 0, "missing": 0}, + {status: 0 for status in SUMMARY_STATUSES}, ) if entry.status in bucket: bucket[entry.status] += 1 @@ -135,6 +221,12 @@ def _grouped_non_core_cards(cards: Sequence[ModelCard]) -> Dict[str, List[List[M return grouped +def _mapping_cell(entry: AppendixAEntry, cards: Sequence[ModelCard]) -> str: + links = [_linked_models(cards)] if cards else [] + links.extend(":doc:`{label} <{doc}>`".format(label=label, doc=doc) for label, doc in entry.mapped_docs) + return ", ".join(links) if links else "None" + + def _linked_models(cards: Sequence[ModelCard]) -> str: if not cards: return "None" @@ -153,6 +245,7 @@ def render_appendix_a_page(cards: Sequence[ModelCard] | None = None) -> str: card_map = {card.model_name: card for card in cards} summary = _summary_rows() non_core = _grouped_non_core_cards(cards) + planned_models = {name for entry in APPENDIX_A_ENTRIES for name in entry.mapped_models} lines: List[str] = [ GENERATED_MARKER, @@ -166,25 +259,34 @@ def render_appendix_a_page(cards: Sequence[ModelCard] | None = None) -> str: "This page audits the current PyHazards implementation against the", "planned methods, benchmarks, and datasets listed in ``pyhazard_plan.pdf``.", "It separates implemented public entries from variant-only entries,", - "experimental wrappers, and items that are still missing.", + "experimental wrappers, external simulators, foundation-model pipelines, and items that are still missing.", "", "Status meanings:", "", "- ``Implemented``: a public PyHazards adapter exists for the named method or resource.", "- ``Experimental``: a lightweight wrapper exists, but it should not be counted as stable core coverage.", + "- ``External simulator``: PyHazards drives the official simulator, installed separately, or reads", + " its outputs. Nothing of the simulator is reimplemented, and it is not counted as a model.", + "- ``Foundation model pipeline``: a global weather model whose hazard results come from tracking its", + " forecast fields. PyHazards reads published forecasts or tracks, can run the official model through a", + " separately installed runner, and provides the tracker and the scoring; the model itself is not", + " reimplemented and is not counted as a model.", "- ``Missing``: no aligned adapter or benchmark integration is present yet.", "", "Hazard Summary", "--------------", "", ".. list-table::", - " :widths: 26 18 18 18", + " :widths: 22 13 13 13 13 13 13", " :header-rows: 1", " :class: dataset-list", "", " * - Hazard Family", " - Implemented", + " - Variant only", " - Experimental", + " - External", + " - Pipeline", " - Missing", ] @@ -193,7 +295,10 @@ def render_appendix_a_page(cards: Sequence[ModelCard] | None = None) -> str: [ " * - {hazard}".format(hazard=hazard_family), " - {count}".format(count=counts["core"]), + " - {count}".format(count=counts["variant"]), " - {count}".format(count=counts["experimental"]), + " - {count}".format(count=counts["external"]), + " - {count}".format(count=counts["pipeline"]), " - {count}".format(count=counts["missing"]), ] ) @@ -226,7 +331,7 @@ def render_appendix_a_page(cards: Sequence[ModelCard] | None = None) -> str: " - `{name} <{url}>`_".format(name=entry.source_name, url=entry.source_url), " - {item_type}".format(item_type=entry.item_type), " - ``{status}``".format(status=STATUS_LABELS[entry.status]), - " - {mapping}".format(mapping=_linked_models(mapped_cards)), + " - {mapping}".format(mapping=_mapping_cell(entry, mapped_cards)), " - {notes}".format(notes=entry.notes or " "), ] ) @@ -279,7 +384,13 @@ def render_appendix_a_page(cards: Sequence[ModelCard] | None = None) -> str: name=first.display_name, slug=first.module_doc_name, ) - reason = "Implemented outside the current core method set and kept public as an additional model." + if first.model_name in planned_models: + reason = ( + "Planned method rebuilt from its paper; only the parts covered by a reference implementation " + "are verified against code (see its Reproduction section)." + ) + else: + reason = "Implemented outside the current core method set and kept public as an additional model." lines.extend( [ @@ -319,6 +430,9 @@ def sync_generated_appendix_a_docs(check: bool = False) -> List[Path]: __all__ = [ "APPENDIX_A_ENTRIES", "APPENDIX_A_PAGE_PATH", + "AppendixAEntry", + "NON_MODEL_STATUSES", + "STATUS_LABELS", "appendix_a_alignment_issues", "render_appendix_a_page", "sync_generated_appendix_a_docs", diff --git a/pyhazards/benchmark_cards/aefa.yaml b/pyhazards/benchmark_cards/aefa.yaml deleted file mode 100644 index 3137452f..00000000 --- a/pyhazards/benchmark_cards/aefa.yaml +++ /dev/null @@ -1,26 +0,0 @@ -slug: aefa -display_name: AEFA -kind: ecosystem -hazard_family: Earthquake -benchmark_key: earthquake -support_status: synthetic-backed -summary: > - AEFA-style forecasting dataset support for the shared earthquake forecasting path. -description: - - > - The AEFA alignment is implemented as a synthetic-backed dense-grid forecasting adapter - used by the WaveCastNet benchmark config. - - > - It keeps the forecasting task and metric shape aligned without claiming a full AEFA data pipeline. -source: - title: AEFA - url: https://github.com/chenyk1990/aefa -tasks: - - earthquake.forecasting -metrics: - - mae - - mse -smoke_configs: - - pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml -linked_models: - - wavecastnet diff --git a/pyhazards/benchmark_cards/camels_us.yaml b/pyhazards/benchmark_cards/camels_us.yaml new file mode 100644 index 00000000..f7fd3036 --- /dev/null +++ b/pyhazards/benchmark_cards/camels_us.yaml @@ -0,0 +1,44 @@ +slug: camels_us +display_name: CAMELS-US +kind: ecosystem +hazard_family: Flood +benchmark_key: flood +support_status: real-backed +summary: > + The CAMELS-US benchmark of Kratzert et al. (2019): 531 basins, extended Maurer forcings, 27 attributes, + test 1989-1999, scored per basin with NSE and the FDC metrics. +description: + - > + ``camels_us_streamflow`` reads a local CAMELS-US copy with the paper's defaults (forcings, the 27 + attributes, 270-day windows, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30). The + ``flood.streamflow`` evaluator reports the median and mean NSE over basins and the number of basins + with NSE <= 0, as in Table 2 of the paper, plus KGE, alpha-NSE, beta-NSE, FHV, FMS and FLV. + - > + Applied to the official stored simulations of the 2019 runs, the PyHazards metrics give the paper's + Table 2 values (e.g. EA-LSTM NSE* median 0.71 single / 0.74 ensemble; LSTM with static inputs 0.73 / + 0.76). The smoke configs exercise the contract on synthetic basins. +source: + title: "Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets" + url: https://doi.org/10.5194/hess-23-5089-2019 + repo_url: https://github.com/kratzert/ealstm_regional_modeling +tasks: + - flood.streamflow +metrics: + - nse + - nse_mean + - n_basins_nse_le_0 + - alpha_nse + - beta_nse + - fhv + - fms + - flv +smoke_configs: + - pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml + - pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml +linked_models: + - neuralhydrology_lstm + - neuralhydrology_ealstm +notes: + - > + Dataset: Addor et al. (HESS 2017), CC BY 4.0; extended Maurer forcings on HydroShare + (doi 10.4211/hs.17c896843cf940339c3c3496d0c1c077). PyHazards downloads nothing. diff --git a/pyhazards/benchmark_cards/caravan.yaml b/pyhazards/benchmark_cards/caravan.yaml index cf2388e5..44468925 100644 --- a/pyhazards/benchmark_cards/caravan.yaml +++ b/pyhazards/benchmark_cards/caravan.yaml @@ -3,29 +3,35 @@ display_name: Caravan kind: ecosystem hazard_family: Flood benchmark_key: flood -support_status: synthetic-backed +support_status: real-backed summary: > - Caravan-style streamflow benchmark coverage for the shared flood streamflow evaluator. + Caravan, the global large-sample hydrology dataset, read from a local copy and scored with the + per-basin streamflow metrics. description: - > - The current Caravan alignment is a metadata-backed streamflow adapter layered on top - of the shared synthetic graph-temporal flood dataset. + ``caravan_streamflow`` reads the official Caravan layout (per-basin netCDF or CSV time series and + attribute CSVs) into NeuralHydrology-style samples; the ``flood.streamflow`` evaluator then reports + per-basin NSE, KGE and the other NeuralHydrology metrics, summarised by the median and mean over basins. - > - It currently drives the public smoke runs for NeuralHydrology LSTM and Google Flood Forecasting. + Caravan has no fixed benchmark split: choose inputs, basins and periods for the experiment. Google's + FloodHub model was trained on Caravan with the MultiMet forecast products (not read by PyHazards). + The smoke configs exercise the same contract on synthetic basins. source: - title: Caravan - A global community dataset for large-sample hydrology - url: https://www.nature.com/articles/s41597-023-01975-w + title: "Caravan - A global community dataset for large-sample hydrology" + url: https://doi.org/10.1038/s41597-023-01975-w repo_url: https://github.com/kratzert/Caravan tasks: - flood.streamflow metrics: - - mae - - rmse - nse - kge + - nse_mean smoke_configs: - pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml - pyhazards/configs/flood/google_flood_forecasting_smoke.yaml linked_models: - neuralhydrology_lstm + - neuralhydrology_ealstm - google_flood_forecasting +notes: + - The reader is checked against NeuralHydrology's Caravan dataset on real Caravan basin files. diff --git a/pyhazards/benchmark_cards/earthquake_benchmark.yaml b/pyhazards/benchmark_cards/earthquake_benchmark.yaml index 467da8e4..f9f89d27 100644 --- a/pyhazards/benchmark_cards/earthquake_benchmark.yaml +++ b/pyhazards/benchmark_cards/earthquake_benchmark.yaml @@ -3,25 +3,64 @@ display_name: Earthquake Benchmark kind: family hazard_family: Earthquake benchmark_key: earthquake -support_status: synthetic-backed +support_status: real-backed summary: > - Shared PyHazards evaluator family for earthquake phase-picking and wavefield-forecasting runs. + Shared PyHazards evaluator for seismic phase picking (pick metrics of the PhaseNet and + EQTransformer papers) and ground-motion wavefield forecasting (ACC / RFNE of WaveCastNet). description: - > - The earthquake benchmark family groups the picking and forecasting paths under one - registered evaluator and benchmark runner entrypoint. + ``earthquake.picking`` takes three-component windows ``(n, 3, samples)`` and arrival targets + ``(n, 2)`` (P, S samples; NaN = none). Each model's own pipeline turns waveforms into picks + (``annotate`` = official normalisation + forward; ``extract_picks`` = official post-processing: + PhaseNet peaks above 0.5, EQTransformer's detection-and-picking rule, GPD's sliding-window + triggers). Picks are matched to the manual arrivals per phase: precision, recall and F1 within a + tolerance window and residual mean, standard deviation and MAE in seconds, with + ``protocol=phasenet`` (Zhu & Beroza 2019: TP if |dt| < 0.1 s, residual statistics over |dt| < 0.5 s) + or ``protocol=eqtransformer`` (Mousavi et al. 2020: TP if |dt| < 0.5 s). Models with a detection + output also get trace-level detection precision, recall and F1. - > - Current public coverage is synthetic-backed but already exposes the same task and - report shape used across the earthquake smoke configs. + Real data comes from ``seisbench_waveforms`` (SeisBench-format datasets and STEAD's own files); + the smoke configs run on ``earthquake_waveforms_synthetic``. EQNet is scored here through its + single-station picking heads (the paper's STEAD evaluation); its multi-station event detection has no + benchmark task yet. + - > + ``earthquake.forecasting`` takes velocity wavefields ``(n, 3, T_in, H, W)`` and future frames + ``(n, 3, T_out, H, W)``. Models with ``rollout`` (WaveCastNet) forecast ``T_out`` frames by repeated + calls on their own output, as the official validation does, in evaluation mode with a seeded + generator for the decoder noise (param ``seed``). Metrics follow WaveCastNet's + ``Validation_pixel.py`` (equations 17-18 of Lyu et al. 2025): ACC, RFNE and RMSE per (sequence, + channel) over time and space, averaged over all pairs (``acc``, ``rfne``, ``rmse``) and per channel + (``acc_x`` ... ``rfne_z``), plus MAE and MSE. It runs on ``earthquake_wavefield_synthetic`` only + (synthetic point sources): the paper's SW4 simulations (tens of GB) have no reader yet. This task is + not earthquake-occurrence forecasting (AEFA, pyCSEP are not implemented). tasks: - earthquake.picking - earthquake.forecasting metrics: + - p_precision + - p_recall + - p_f1 + - p_residual_mean + - p_residual_std - p_pick_mae + - s_precision + - s_recall + - s_f1 + - s_residual_mean + - s_residual_std - s_pick_mae - - precision - - recall - - f1 + - detection_precision + - detection_recall + - detection_f1 + - acc + - rfne + - rmse + - acc_x + - acc_y + - acc_z + - rfne_x + - rfne_y + - rfne_z - mae - mse smoke_configs: @@ -37,4 +76,7 @@ linked_models: - eqnet - wavecastnet notes: - - "Forecasting runs export a pyCSEP-style report artifact through the shared earthquake benchmark." + - "Before this release the picking evaluator reported one hit rate (both regressed picks within 8 samples) as precision, recall and F1 alike; those numbers are not comparable with the new ones." + - "EQTransformer's MAPE is not computed: the paper does not define its denominator." + - "Smoke configs use randomly initialised models on synthetic data; pass ``pretrained`` in the model params and a real dataset for meaningful numbers." + - "Before this release ``earthquake.forecasting`` reported only MAE / MSE of a single forward pass on moving Gaussian blobs (``earthquake_forecast_synthetic``); the ACC / RFNE numbers are new." diff --git a/pyhazards/benchmark_cards/flood_benchmark.yaml b/pyhazards/benchmark_cards/flood_benchmark.yaml index 028de0fa..230e315e 100644 --- a/pyhazards/benchmark_cards/flood_benchmark.yaml +++ b/pyhazards/benchmark_cards/flood_benchmark.yaml @@ -3,38 +3,79 @@ display_name: Flood Benchmark kind: family hazard_family: Flood benchmark_key: flood -support_status: synthetic-backed +support_status: real-backed summary: > - Shared PyHazards evaluator family for streamflow forecasting and inundation prediction. + Shared PyHazards evaluator for daily streamflow (per-basin NSE, KGE and the other NeuralHydrology + metrics) and for inundation depth on rasters and flood meshes (depth errors, CSI, relative L2, NSE, + autoregressive mesh rollouts). description: - > - The flood benchmark family keeps streamflow and inundation scoring under one shared - evaluator contract while preserving hazard-task-specific metrics. + ``flood.streamflow`` follows Kratzert et al. (HESS 2019) and NeuralHydrology: each model predicts the + discharge of every day of the evaluation period from the preceding window of daily forcings and the + basin's static attributes; predictions go back to mm/day with the training scaler, negative values + are set to zero, and NeuralHydrology's metrics (NSE, MSE, RMSE, KGE, alpha-NSE, beta-KGE, beta-NSE, + Pearson r, FHV, FMS, FLV, peak timing, missed peaks, peak MAPE) are computed per basin over the period. + Reported values are the median over basins (``nse``, ``kge``, ...), the mean over basins + (``nse_mean``, ...), ``n_basins`` and ``n_basins_nse_le_0``; per-basin values are in the report + metadata. Probabilistic models are scored by their mixture mean. - > - Current public coverage is synthetic-backed, but the same family already drives the - streamflow and inundation smoke configs used across the flood models. + Real streamflow data come from ``camels_us_streamflow`` and ``caravan_streamflow`` (local copies of the + official releases); the smoke configs run the same contract on ``flood_streamflow_synthetic``. + - > + ``flood.inundation`` scores water depth. Rasters: the model maps the split inputs to depth + ``(batch, 1, H, W)`` or to several variables channels-last (UrbanFloodCast: depth and x / y unit + discharge for 24 steps, with a NaN mask). Meshes: each test hydrograph of ``hydrographnet_white_river`` + is rolled out with the model's ``rollout`` method as in the HydroGraphNet example, and depths are + scored in metres (``rollout_rmse``: depth RMSE per step averaged over steps and hydrographs). + Reported: ``pixel_mae`` / ``rmse`` (depth errors over all cells), ``iou`` / ``f1`` (prediction >= 0.5 m + against depth > 0), and, averaged over events / hydrographs as the UrbanFloodCast test loop does, + depth CSI at 1 / 10 / 50 cm (``csi_1cm``, ``csi_10cm``, ``csi_50cm``) and the relative L2 error, NSE + and Pearson r over all predicted variables. Real mesh data: ``hydrographnet_white_river``; the + UrbanFloodCast and FloodCastBench rasters have no reader yet. tasks: - flood.streamflow - flood.inundation metrics: - - mae - - rmse - nse - kge + - alpha_nse + - beta_nse + - fhv + - fms + - flv + - nse_mean + - n_basins_nse_le_0 - pixel_mae + - rmse - iou - f1 + - csi_10cm + - relative_l2 + - rollout_rmse smoke_configs: - - pyhazards/configs/flood/hydrographnet_smoke.yaml - pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml - pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml - pyhazards/configs/flood/google_flood_forecasting_smoke.yaml + - pyhazards/configs/flood/hydrographnet_smoke.yaml - pyhazards/configs/flood/floodcast_smoke.yaml - pyhazards/configs/flood/urbanfloodcast_smoke.yaml linked_models: - - hydrographnet - neuralhydrology_lstm - neuralhydrology_ealstm - google_flood_forecasting + - hydrographnet - floodcast - urbanfloodcast +notes: + - > + The streamflow evaluation (reader, normalisation, rescaling, clipping and per-basin metrics) is + checked against NeuralHydrology's Tester on real CAMELS-US basins, and the metric code reproduces + Table 2 of Kratzert et al. (2019) from the official stored simulations. + - > + hydrographnet (PhysicsNeMo's MeshGraphKAN) and urbanfloodcast (the UrbanFloodCast DNO) match their + official code; the inundation metrics, the HydroGraphNet rollout and both input pipelines are checked + against the official evaluation code (oracle tests). floodcast is still an experimental stand-in: the + published flood model was never released and the paper does not give its widths. + - > + WaterBench, HydroBench and FloodCastBench have no PyHazards reader; the former adapters with these + names generated random numbers and were removed. diff --git a/pyhazards/benchmark_cards/floodcastbench.yaml b/pyhazards/benchmark_cards/floodcastbench.yaml deleted file mode 100644 index b82e6757..00000000 --- a/pyhazards/benchmark_cards/floodcastbench.yaml +++ /dev/null @@ -1,29 +0,0 @@ -slug: floodcastbench -display_name: FloodCastBench -kind: ecosystem -hazard_family: Flood -benchmark_key: flood -support_status: synthetic-backed -summary: > - FloodCastBench-style inundation benchmark coverage for the shared flood inundation evaluator. -description: - - > - The current FloodCastBench alignment is implemented as a synthetic raster inundation - adapter used by the public inundation smoke configs. - - > - It documents the benchmark/data protocol behind the FloodCast and UrbanFloodCast smoke paths. -source: - title: FloodCastBench - url: https://github.com/HydroPML/FloodCastBench -tasks: - - flood.inundation -metrics: - - pixel_mae - - iou - - f1 -smoke_configs: - - pyhazards/configs/flood/floodcast_smoke.yaml - - pyhazards/configs/flood/urbanfloodcast_smoke.yaml -linked_models: - - floodcast - - urbanfloodcast diff --git a/pyhazards/benchmark_cards/hydrobench.yaml b/pyhazards/benchmark_cards/hydrobench.yaml deleted file mode 100644 index d9d8de8b..00000000 --- a/pyhazards/benchmark_cards/hydrobench.yaml +++ /dev/null @@ -1,28 +0,0 @@ -slug: hydrobench -display_name: HydroBench -kind: ecosystem -hazard_family: Flood -benchmark_key: flood -support_status: synthetic-backed -summary: > - HydroBench-style streamflow diagnostics coverage for the shared flood streamflow evaluator. -description: - - > - The current HydroBench alignment uses a metadata-backed streamflow adapter over the - shared synthetic flood streamflow dataset. - - > - It is currently exercised through the HydroGraphNet smoke benchmark path. -source: - title: HydroBench - url: https://github.com/EMscience/HydroBench -tasks: - - flood.streamflow -metrics: - - mae - - rmse - - nse - - kge -smoke_configs: - - pyhazards/configs/flood/hydrographnet_smoke.yaml -linked_models: - - hydrographnet diff --git a/pyhazards/benchmark_cards/hydrographnet_white_river.yaml b/pyhazards/benchmark_cards/hydrographnet_white_river.yaml new file mode 100644 index 00000000..ab4189d8 --- /dev/null +++ b/pyhazards/benchmark_cards/hydrographnet_white_river.yaml @@ -0,0 +1,38 @@ +slug: hydrographnet_white_river +display_name: HydroGraphNet White River +kind: ecosystem +hazard_family: Flood +benchmark_key: flood +support_status: real-backed +summary: > + HEC-RAS flood simulations on the 4,787-cell White River mesh (HydroGraphNet, Taghizadeh et al. 2025), + rolled out autoregressively and scored as water depth in metres. +description: + - > + ``hydrographnet_white_river`` reads a local copy of the release exactly like PhysicsNeMo's + ``HydroGraphDataset``. The ``flood.inundation`` evaluator rolls every test hydrograph out for 30 steps + (10 hours) with the model's ``rollout`` method, as the HydroGraphNet example's inference script does, + and reports ``rollout_rmse`` (depth RMSE per step, averaged over steps and hydrographs, in metres; the + per-step curve is in the report metadata), depth MAE / RMSE, CSI and NSE. + - > + The release has no official test split, and the paper's numbers could not be accessed, so no paper + result is reproduced. The smoke config runs the contract on ``flood_mesh_synthetic``. +source: + title: "Interpretable physics-informed graph neural networks for flood forecasting" + url: https://doi.org/10.1111/mice.13484 + repo_url: https://github.com/NVIDIA/physicsnemo/tree/main/examples/weather/flood_modeling/hydrographnet +tasks: + - flood.inundation +metrics: + - rollout_rmse + - pixel_mae + - rmse + - csi_10cm + - nse +smoke_configs: + - pyhazards/configs/flood/hydrographnet_smoke.yaml +linked_models: + - hydrographnet +notes: + - > + Dataset: Zenodo 14969507 (HydroGraphNet.zip, 8.3 GB, CC BY 4.0). PyHazards downloads nothing. diff --git a/pyhazards/benchmark_cards/ibtracs.yaml b/pyhazards/benchmark_cards/ibtracs.yaml index 0623b545..a05a7d62 100644 --- a/pyhazards/benchmark_cards/ibtracs.yaml +++ b/pyhazards/benchmark_cards/ibtracs.yaml @@ -3,31 +3,34 @@ display_name: IBTrACS kind: ecosystem hazard_family: Tropical Cyclone benchmark_key: tc -support_status: synthetic-backed +support_status: real-backed summary: > - IBTrACS-backed storm benchmark coverage for the shared tropical cyclone evaluator. + Best-track ground truth from NOAA NCEI's IBTrACS v04 for track and intensity forecasts scored by + the shared tropical cyclone evaluator. description: - > - The current IBTrACS alignment uses a metadata-backed storm-history adapter over the - shared synthetic tropical-cyclone dataset. + ``ibtracs_tracks`` reads IBTrACS v04 CSV or netCDF files with PyHazards' reader and builds + forecasting windows (history of six-hourly observations, targets at the requested lead times) for any + agency's winds and pressures. - > - It is the benchmark ecosystem currently used by Hurricast and the experimental - weather-model adapter smoke configs. + ``hurricast_ibtracs_era5`` builds Hurricast's inputs from IBTrACS (30 statistical features per 3-hour + step) and ERA5 maps, with the IBTrACS wind 24 h ahead or position 24 h ahead as targets. The + weather-model cyclone pipelines (forecast fields, tracker, scoring against IBTrACS) are pending. + IBTrACS is also the reference of the weather-model cyclone pipelines in ``pyhazards.forecasts``: + forecast tracks of FourCastNet, GraphCast and Pangu-Weather (tracked in their forecast fields) are + matched to IBTrACS storms and scored by great-circle track error and intensity errors per lead time. + No ported neural network consumes IBTrACS directly yet (Hurricast, which uses IBTrACS with ERA5, is + pending). source: title: IBTrACS url: https://www.ncei.noaa.gov/products/international-best-track-archive tasks: - tc.track_intensity + - tc.intensity metrics: - - track_error + - track_error_km - intensity_mae -smoke_configs: - - pyhazards/configs/tc/hurricast_smoke.yaml - - pyhazards/configs/tc/graphcast_tc_smoke.yaml - - pyhazards/configs/tc/pangu_tc_smoke.yaml - - pyhazards/configs/tc/fourcastnet_tc_smoke.yaml + - pressure_mae +smoke_configs: [] linked_models: - hurricast - - graphcast_tc - - pangu_tc - - fourcastnet_tc diff --git a/pyhazards/benchmark_cards/pick_benchmark.yaml b/pyhazards/benchmark_cards/pick_benchmark.yaml index ff09850a..4a7c7fc1 100644 --- a/pyhazards/benchmark_cards/pick_benchmark.yaml +++ b/pyhazards/benchmark_cards/pick_benchmark.yaml @@ -3,29 +3,35 @@ display_name: pick-benchmark kind: ecosystem hazard_family: Earthquake benchmark_key: earthquake -support_status: synthetic-backed +support_status: experimental summary: > - pick-benchmark-compatible waveform picking support routed through the shared earthquake evaluator. + The SeisBench picking benchmark of Münchmeyer et al. (2022). Its datasets can be read with + ``seisbench_waveforms``; its own three evaluation tasks are not implemented in PyHazards. description: - > - The current pick-benchmark path reuses the synthetic waveform picking bundle and tags - it as a pick-benchmark-style benchmark adapter. + pick-benchmark compares deep-learning pickers on eight SeisBench datasets with three tasks: event + detection (ROC-AUC), phase identification (Matthews correlation) and onset-time regression + (residual distributions), on windows cut around the picks. PyHazards scores pickers with the pick + metrics of the PhaseNet and EQTransformer papers instead; pick-benchmark's tasks, window sampling + and MCC / AUC metrics are not reproduced. - > - It supports the earthquake picking smoke path for the transformer and CNN picking baselines. + Its numbers for PhaseNet were obtained with SeisBench's pre-0.3 PhaseNet (23,305 parameters), not + the original architecture that PyHazards ports. source: - title: pick-benchmark - url: https://github.com/seisbench/pick-benchmark + title: "Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers (Münchmeyer et al., J. Geophys. Res. Solid Earth 127, e2021JB023499, 2022)" + url: https://doi.org/10.1029/2021JB023499 + repo_url: https://github.com/seisbench/pick-benchmark tasks: - earthquake.picking metrics: - - p_pick_mae - - s_pick_mae - - precision - - recall - - f1 + - p_f1 + - s_f1 smoke_configs: - pyhazards/configs/earthquake/eqtransformer_smoke.yaml - pyhazards/configs/earthquake/gpd_smoke.yaml linked_models: + - phasenet - eqtransformer - gpd +notes: + - "pick-benchmark is GPL-3.0; it is not vendored or imported." diff --git a/pyhazards/benchmark_cards/pycsep.yaml b/pyhazards/benchmark_cards/pycsep.yaml deleted file mode 100644 index 7354e89e..00000000 --- a/pyhazards/benchmark_cards/pycsep.yaml +++ /dev/null @@ -1,28 +0,0 @@ -slug: pycsep -display_name: pyCSEP -kind: ecosystem -hazard_family: Earthquake -benchmark_key: earthquake -support_status: synthetic-backed -summary: > - pyCSEP-style forecasting report export for the earthquake forecasting smoke path. -description: - - > - The current pyCSEP alignment is implemented as a report export contract inside the - shared earthquake benchmark rather than as a standalone benchmark family. - - > - It documents the forecasting artifact shape used by the WaveCastNet smoke config. -source: - title: pyCSEP - url: https://github.com/SCECCode/pycsep -tasks: - - earthquake.forecasting -metrics: - - mae - - mse -smoke_configs: - - pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml -linked_models: - - wavecastnet -notes: - - "Current repo support is report-export alignment, not a separate pyCSEP benchmark runner." diff --git a/pyhazards/benchmark_cards/seisbench.yaml b/pyhazards/benchmark_cards/seisbench.yaml index 69262490..f805a330 100644 --- a/pyhazards/benchmark_cards/seisbench.yaml +++ b/pyhazards/benchmark_cards/seisbench.yaml @@ -3,31 +3,39 @@ display_name: SeisBench kind: ecosystem hazard_family: Earthquake benchmark_key: earthquake -support_status: synthetic-backed +support_status: real-backed summary: > - SeisBench-shaped waveform picking support for the shared earthquake benchmark family. + SeisBench-format waveform datasets (STEAD, INSTANCE, ETHZ, ...) read by PyHazards' own + ``seisbench_waveforms`` reader and scored by the earthquake picking evaluator. description: - > - The current SeisBench path uses a synthetic waveform adapter that preserves the same - picking task shape expected by the shared earthquake benchmark. + SeisBench (Woollam et al. 2022) distributes seismic machine-learning benchmark datasets in a + common format (metadata CSV + waveform HDF5). PyHazards reads that format without importing + SeisBench, whose GPL-3.0 code is used only as a test oracle (the reader, and the PhaseNet, + EQTransformer and GPD ports, are compared with SeisBench in ``tests/oracle``). - > - It exists today as a benchmark-compatible smoke path rather than a full external - SeisBench ingestion pipeline. + The datasets are not redistributed; download them with SeisBench or from their providers. source: - title: SeisBench - A Toolbox for Machine Learning in Seismology - url: https://joss.theoj.org/papers/10.21105/joss.04418 + title: "SeisBench - A Toolbox for Machine Learning in Seismology (Woollam et al., Seismological Research Letters 93(3):1695-1709, 2022)" + url: https://doi.org/10.1785/0220210324 repo_url: https://github.com/seisbench/seisbench tasks: - earthquake.picking metrics: + - p_precision + - p_recall + - p_f1 - p_pick_mae + - s_precision + - s_recall + - s_f1 - s_pick_mae - - precision - - recall - - f1 smoke_configs: - pyhazards/configs/earthquake/phasenet_smoke.yaml - - pyhazards/configs/earthquake/eqnet_smoke.yaml linked_models: - phasenet - - eqnet + - eqtransformer + - gpd +notes: + - "SeisBench is GPL-3.0; PyHazards (MIT) neither vendors nor imports it." + - "The smoke config runs on synthetic windows; point ``seisbench_waveforms`` at a downloaded dataset for real numbers." diff --git a/pyhazards/benchmark_cards/ships_xu2021.yaml b/pyhazards/benchmark_cards/ships_xu2021.yaml new file mode 100644 index 00000000..114fdea1 --- /dev/null +++ b/pyhazards/benchmark_cards/ships_xu2021.yaml @@ -0,0 +1,30 @@ +slug: ships_xu2021 +display_name: SHIPS Predictors (Xu et al. 2021) +kind: ecosystem +hazard_family: Tropical Cyclone +benchmark_key: tc +support_status: real-backed +summary: > + The standardised SHIPS predictor table of Xu et al. (2021) with 24-hour intensity-change targets and + the official leave-one-year-out folds, scored with the intensity task. +description: + - > + ``ships_xu2021`` reads the authors' table (Zenodo 4784610, CC BY 4.0): 121 SHIPS predictors per + storm and forecast time and the 24-hour change of the maximum wind in knots. Test rows are a year's + Atlantic operational cases; the paper averages the folds 2010-2018. +source: + title: Deep Learning Experiments for Tropical Cyclone Intensity Forecasts + url: https://doi.org/10.1175/WAF-D-20-0104.1 + repo_url: https://github.com/wenweixu/tropicalcyclone_MLP +tasks: + - tc.intensity +metrics: + - intensity_mae + - intensity_rmse + - intensity_mae_group_mean +smoke_configs: + - pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml +linked_models: + - tropicalcyclone_mlp +notes: + - "The smoke config uses ships_xu2021_synthetic (random data in the same layout)." diff --git a/pyhazards/benchmark_cards/tcbench_alpha.yaml b/pyhazards/benchmark_cards/tcbench_alpha.yaml index 5bd16526..fc131205 100644 --- a/pyhazards/benchmark_cards/tcbench_alpha.yaml +++ b/pyhazards/benchmark_cards/tcbench_alpha.yaml @@ -3,28 +3,36 @@ display_name: TCBench Alpha kind: ecosystem hazard_family: Tropical Cyclone benchmark_key: tc -support_status: synthetic-backed +support_status: real-backed summary: > - TCBench Alpha-style storm benchmark coverage for the shared tropical cyclone evaluator. + TCBench (Gomez et al. 2026): 2023 cyclone tracks of Pangu-Weather, FourCastNet v2 and AIFS extracted + with TempestExtremes, matched to IBTrACS and scored by direct position error and intensity errors. description: - > - The current TCBench Alpha alignment uses a metadata-backed storm-history adapter over - the shared synthetic tropical-cyclone dataset. + ``pyhazards.forecasts`` reads TCBench's released tracks and raw forecast fields from the Hugging Face + dataset (pinned revision), re-implements its TempestExtremes tracking and HuracanPy matching, and + scores tracks with ``score_forecast_tracks(..., protocol="tcbench")``, which reproduces TCBench's + ``evaluate_tracks.py`` exactly (including its float16 reading of IBTrACS positions). - > - It currently drives the tropicalcyclone_MLP, SAF-Net, and TCIF-fusion smoke configs. + Verified: on TCBench's raw Pangu-Weather fields the tracker writes TCBench's released track files + byte for byte (and the official TempestExtremes binaries agree), every row of the released Pangu-Weather + and FourCastNet v2 matched tracks scores exactly as TCBench's own metric code, and the DPE / AE values + printed in TCBench's notebook are reproduced. + - > + Not implemented: CRPS, along/cross-track errors, rapid-intensification scores and TCBench's + post-processing models. TCBench's "FourCastNet v2" is SFNO-small, not the FourCastNet of Pathak et al. source: - title: TCBench Alpha - url: https://github.com/msgomez06/TCBench_Alpha + title: "TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale" + url: https://arxiv.org/abs/2601.23268 + repo_url: https://github.com/msgomez06/TCBench_Alpha tasks: - tc.track_intensity metrics: - - track_error + - track_error_km - intensity_mae -smoke_configs: - - pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml - - pyhazards/configs/tc/saf_net_smoke.yaml - - pyhazards/configs/tc/tcif_fusion_smoke.yaml -linked_models: - - tropicalcyclone_mlp - - saf_net - - tcif_fusion + - pressure_mae +smoke_configs: [] +linked_models: [] +notes: + - "TCBench code and data are MIT-licensed; the Pangu-Weather forecasts derive from CC BY-NC-SA 4.0 weights (non-commercial)." + - "Weather models are pipelines, not PyHazards models, so no model is linked here; see the Foundation Weather Models page." diff --git a/pyhazards/benchmark_cards/tropical_cyclone_benchmark.yaml b/pyhazards/benchmark_cards/tropical_cyclone_benchmark.yaml index 225629e0..d7c874ad 100644 --- a/pyhazards/benchmark_cards/tropical_cyclone_benchmark.yaml +++ b/pyhazards/benchmark_cards/tropical_cyclone_benchmark.yaml @@ -3,38 +3,62 @@ display_name: Tropical Cyclone Benchmark kind: family hazard_family: Tropical Cyclone benchmark_key: tc -support_status: synthetic-backed +support_status: real-backed summary: > - Shared PyHazards evaluator family for tropical cyclone and hurricane track-intensity forecasting. + Shared PyHazards evaluator for tropical cyclone forecasts: great-circle track error in km and + intensity errors in the dataset's units, per lead time, plus single-lead intensity regression. description: - > - The tropical cyclone benchmark family is the single storm evaluator used by the - hurricane-specific and all-basin tropical-cyclone smoke configs. + ``tc.track_intensity`` scores forecasts of position, maximum wind and central pressure at the + dataset's lead times: great-circle track error (km; ``track_distance: tcn_equirectangular`` gives + TropiCycloneNet's 111 km-per-degree formula), wind MAE in the dataset's unit (knots for IBTrACS, m/s + for TCND) and pressure MAE (hPa), each per lead time and averaged. Models with several samples per + storm are scored on the sample mean and with the best-of-k errors of the TropiCycloneNet paper (per + lead time and per variable, the smallest error among the samples). - > - Current coverage is synthetic-backed, but the same evaluator contract already scores - core storm baselines and experimental weather-model adapters. + ``tc.intensity`` scores one intensity (or 24-hour intensity change) per storm and time: MAE and RMSE + in the dataset's unit, per test year when the split names years, and their unweighted mean, the way + Xu et al. (2021) and SAF-Net report results. + - > + Real data: ``ibtracs_tracks`` (IBTrACS best tracks), ``tropicyclonenet_dataset`` (TCND), + ``ships_xu2021`` (SHIPS predictors) and ``hurricast_ibtracs_era5`` (IBTrACS statistics and ERA5 maps; + Hurricast's 24-hour intensity with ``tc.intensity`` and track with ``tc.track_intensity`` at lead 24 h). + The smoke configs run on synthetic data with the same layouts. + Real data: ``ibtracs_tracks`` (IBTrACS best tracks), ``tropicyclonenet_dataset`` (TCND) and + ``ships_xu2021`` (SHIPS predictors). The smoke configs run on synthetic data with the same layouts. + - > + Global weather models (FourCastNet, GraphCast, Pangu-Weather) are not models of this benchmark: their + cyclone tracks come from a tracker run on their forecast fields. ``pyhazards.forecasts`` builds those + tracks (TCBench's TempestExtremes rules or the papers' ECMWF-style tracker) and + ``pyhazards.forecasts.score_forecast_tracks`` scores them against IBTrACS with this evaluator's + ``track_intensity_metrics`` (same metric names, ``tc`` / ``tc.track_intensity`` results). tasks: - tc.track_intensity + - tc.intensity metrics: - - track_error + - track_error_km - intensity_mae + - pressure_mae + - best_of_k_track_error_km + - best_of_k_intensity_mae + - best_of_k_pressure_mae + - intensity_rmse + - intensity_mae_group_mean smoke_configs: - - pyhazards/configs/tc/hurricast_smoke.yaml - pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml - - pyhazards/configs/tc/tropicyclonenet_smoke.yaml - pyhazards/configs/tc/saf_net_smoke.yaml + - pyhazards/configs/tc/tropicyclonenet_smoke.yaml + - pyhazards/configs/tc/hurricast_smoke.yaml - pyhazards/configs/tc/tcif_fusion_smoke.yaml - - pyhazards/configs/tc/graphcast_tc_smoke.yaml - - pyhazards/configs/tc/pangu_tc_smoke.yaml - - pyhazards/configs/tc/fourcastnet_tc_smoke.yaml linked_models: - - hurricast - tropicalcyclone_mlp - - tropicyclonenet - saf_net + - tropicyclonenet + - hurricast - tcif_fusion - - graphcast_tc - - pangu_tc - - fourcastnet_tc notes: - - "IBTrACS, TCBench Alpha, and TropiCycloneNet-Dataset are surfaced as the public storm benchmark ecosystems." + - "Smoke configs use synthetic datasets (tc_tracks_synthetic, ships_xu2021_synthetic, safnet_cma_era_interim_synthetic, tropicyclonenet_dataset_synthetic, hurricast_synthetic, tcif_fusion_synthetic); their scores mean nothing. Benchmark results carry synthetic=True for them. The hurricast smoke config runs the network head (the XGBoost stage needs fitting) and the tcif_fusion one a reduced copy of the network." + - "The GraphCast / Pangu-Weather / FourCastNet adapters are experimental generic stand-ins, not the published models." + - "Smoke configs use synthetic datasets (tc_tracks_synthetic, ships_xu2021_synthetic, safnet_cma_era_interim_synthetic, tropicyclonenet_dataset_synthetic); their scores mean nothing. Benchmark results carry synthetic=True for them." + - "hurricast and tcif_fusion are experimental generic stand-ins, not the published models." + - "The former graphcast_tc, pangu_tc and fourcastnet_tc entries (small networks without forecast fields, weights or tracker) were removed; see the Foundation Weather Models page (pyhazards.forecasts)." diff --git a/pyhazards/benchmark_cards/tropicyclonenet_dataset.yaml b/pyhazards/benchmark_cards/tropicyclonenet_dataset.yaml index d0407f05..1aaf34b8 100644 --- a/pyhazards/benchmark_cards/tropicyclonenet_dataset.yaml +++ b/pyhazards/benchmark_cards/tropicyclonenet_dataset.yaml @@ -1,26 +1,35 @@ slug: tropicyclonenet_dataset -display_name: TropiCycloneNet-Dataset +display_name: TropiCycloneNet Dataset kind: ecosystem hazard_family: Tropical Cyclone benchmark_key: tc -support_status: synthetic-backed +support_status: real-backed summary: > - TropiCycloneNet-Dataset-backed storm benchmark coverage for the shared tropical cyclone evaluator. + TCND (Huang et al. 2025): six-basin best tracks, Env-Data and ERA5 geopotential, read exactly like + the official TropiCycloneNet loader and scored with the paper's best-of-6 errors. description: - > - The current TropiCycloneNet-Dataset alignment uses a metadata-backed storm-history adapter - over the shared synthetic tropical-cyclone dataset. + ``tropicyclonenet_dataset`` reads the TCND files (Zenodo, CC BY 4.0) into TropiCycloneNet's input + layout; targets are position, central pressure (hPa) and maximum wind (m/s) at 6, 12, 18 and 24 h. - > - It exists today to support the public TropiCycloneNet smoke benchmark path. + The paper reports best-of-6 errors (per lead time and variable, the smallest error among six sampled + forecasts); the evaluator reports those and the errors of the sample mean. source: - title: TropiCycloneNet-Dataset - url: https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset + title: Benchmark dataset and deep learning method for global tropical cyclone forecasting + url: https://doi.org/10.1038/s41467-025-61087-4 + repo_url: https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset tasks: - tc.track_intensity metrics: - - track_error + - track_error_km - intensity_mae + - pressure_mae + - best_of_k_track_error_km + - best_of_k_intensity_mae + - best_of_k_pressure_mae smoke_configs: - pyhazards/configs/tc/tropicyclonenet_smoke.yaml linked_models: - tropicyclonenet +notes: + - "The smoke config uses tropicyclonenet_dataset_synthetic (random data in the TCND layout)." diff --git a/pyhazards/benchmark_cards/waterbench.yaml b/pyhazards/benchmark_cards/waterbench.yaml deleted file mode 100644 index fb28e812..00000000 --- a/pyhazards/benchmark_cards/waterbench.yaml +++ /dev/null @@ -1,29 +0,0 @@ -slug: waterbench -display_name: WaterBench -kind: ecosystem -hazard_family: Flood -benchmark_key: flood -support_status: synthetic-backed -summary: > - WaterBench-style streamflow benchmark coverage for the shared flood evaluator. -description: - - > - The current WaterBench alignment uses a metadata-only adapter over the shared - synthetic streamflow bundle and preserves the streamflow task contract. - - > - It is currently exercised by the EA-LSTM smoke benchmark path. -source: - title: "WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting" - url: https://neurips.cc/virtual/2023/80632 - repo_url: https://github.com/uihilab/WaterBench -tasks: - - flood.streamflow -metrics: - - mae - - rmse - - nse - - kge -smoke_configs: - - pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml -linked_models: - - neuralhydrology_ealstm diff --git a/pyhazards/benchmark_cards/wildfire_benchmark.yaml b/pyhazards/benchmark_cards/wildfire_benchmark.yaml index e905aaf2..e1a082b4 100644 --- a/pyhazards/benchmark_cards/wildfire_benchmark.yaml +++ b/pyhazards/benchmark_cards/wildfire_benchmark.yaml @@ -8,8 +8,8 @@ summary: > Shared PyHazards evaluator family for wildfire danger and wildfire spread experiments. description: - > - The wildfire benchmark family is the single scoring layer for tabular danger tasks, - weekly forecasting tasks, and raster spread tasks. + The wildfire benchmark family is the single scoring layer for tabular, daily-sequence and + gridded (per-cell) danger tasks, weekly forecasting tasks, and raster spread tasks. - > Current coverage is synthetic-backed, but it already exposes a single hazard-level evaluator contract across wildfire danger and wildfire spread smoke configs. @@ -23,6 +23,7 @@ metrics: - pr_auc - mae - rmse + - average_precision - iou - f1 - burned_area_mae @@ -32,17 +33,70 @@ smoke_configs: - pyhazards/configs/wildfire/asufm_smoke.yaml - pyhazards/configs/wildfire/wildfire_spread_smoke.yaml - pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml - - pyhazards/configs/wildfire/forefire_smoke.yaml - - pyhazards/configs/wildfire/wrf_sfire_smoke.yaml - pyhazards/configs/wildfire/firecastnet_smoke.yaml + - pyhazards/configs/wildfire/track_o_convlstm_smoke.yaml linked_models: - wildfire_fpa - wildfire_forecasting + - random_forest + - xgboost + - deep_ensemble - asufm - wildfire_aspp - wildfirespreadts - - forefire - - wrf_sfire + - logistic_regression + - resnet18_unet + - convlstm + - convgru + - utae + - segformer + - swin_unet + - swinlstm + - trajgru + - attention_unet + - ts_satfire + - unet3d + - unetr + - swin_unetr + - tcn + - earthformer + - unet + - deeplabv3 + - earthfarseer + - rainformer - firecastnet notes: - "WildfireSpreadTS is the public Appendix-A benchmark ecosystem surfaced on this page." + - > + Track-O (from PR #33 by runyangxu) scores ``wildfire.danger`` as daily fire occurrence on a + latitude-longitude grid: whether a cell has a NASA FIRMS detection on a day, from that day's + weather (MERRA-2 surface variables or any NetCDF files on a regular grid) and LANDFIRE fuels. + Build the cache with ``scripts/build_wildfire_track_o_cache.py``, load it with the + ``wildfire_track_o_raster`` / ``_temporal`` / ``_tabular`` datasets, and train and score + registry models with ``scripts/run_wildfire_track_o_baselines.py``. Raster and temporal + layouts are scored per cell (one logit per cell; accuracy and macro F1 at probability 0.5, + ROC AUC, PR AUC). The smoke config ``track_o_convlstm_smoke.yaml`` runs on the synthetic + ``micro`` cache; no real-data Track-O results are published with PyHazards. + - > + The Kondylatos et al. (2022) tree baselines ``random_forest`` and ``xgboost`` read the same + daily danger tensors as ``wildfire_forecasting`` but must be fitted (``model.fit``) before + they are scored, so they have no smoke config; pass the fitted model to + ``BenchmarkRunner.run(model=...)``. ``deep_ensemble`` wraps any of the linked models (the + ten-LSTM danger ensemble of Kondylatos et al. 2025, or U-TAE members for spread). + - > + FireCastNet forecasts seasonal burned-area presence on the SeasFire datacube (AUPRC in its + paper); without a SeasFire adapter its smoke config runs on synthetic rasters and is scored + with the spread-mask metrics. + - > + Earthfarseer and Rainformer are frame-sequence forecasters (Sim2Real-Fire baselines); their + task="segmentation" adaptation maps the first predicted frame to fire-mask logits, which is a + PyHazards convention, not a published Sim2Real-Fire configuration. + - >- + Prithvi-EO-2.0 BurnScars and Prithvi-EO-2.0-TL segment burn scars after a fire (post-fire + burned-area mapping). They are wildfire models but are not linked here, because this family + scores danger and spread prediction, not post-fire mapping. + - >- + ForeFire and WRF-SFIRE are physics simulators, not trainable models, so they are not linked + models. ``pyhazards.simulators.ForeFireSimulator`` runs the official ForeFire (installed + separately) on spread rasters, and the ``wrf_sfire_spread`` dataset turns WRF-SFIRE ``wrfout`` + files into spread samples for this family's ``wildfire.spread`` task. diff --git a/pyhazards/benchmark_cards/wildfirespreadts_ecosystem.yaml b/pyhazards/benchmark_cards/wildfirespreadts_ecosystem.yaml index 85771ead..e02eb363 100644 --- a/pyhazards/benchmark_cards/wildfirespreadts_ecosystem.yaml +++ b/pyhazards/benchmark_cards/wildfirespreadts_ecosystem.yaml @@ -19,18 +19,19 @@ source: tasks: - wildfire.spread metrics: + - average_precision - iou - f1 - burned_area_mae smoke_configs: - pyhazards/configs/wildfire/wildfire_spread_smoke.yaml - pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml - - pyhazards/configs/wildfire/forefire_smoke.yaml - - pyhazards/configs/wildfire/wrf_sfire_smoke.yaml - - pyhazards/configs/wildfire/firecastnet_smoke.yaml linked_models: - wildfire_aspp - wildfirespreadts - - forefire - - wrf_sfire - - firecastnet + - logistic_regression + - resnet18_unet + - convlstm + - utae + - segformer + - swin_unet diff --git a/pyhazards/benchmark_catalog.py b/pyhazards/benchmark_catalog.py index 1e3e4c28..b2de73aa 100644 --- a/pyhazards/benchmark_catalog.py +++ b/pyhazards/benchmark_catalog.py @@ -44,6 +44,7 @@ "flood.streamflow": "Streamflow", "flood.inundation": "Inundation", "tc.track_intensity": "Track + Intensity", + "tc.intensity": "Intensity", } SUPPORT_STATUS_BADGE_ROLES = { @@ -66,12 +67,40 @@ "recall": "Recall", "nse": "NSE", "kge": "KGE", + "nse_mean": "Mean NSE", + "alpha_nse": "Alpha-NSE", + "beta_nse": "Beta-NSE", + "fhv": "FHV", + "fms": "FMS", + "flv": "FLV", + "n_basins_nse_le_0": "Basins with NSE <= 0", "p_pick_mae": "P-pick MAE", "s_pick_mae": "S-pick MAE", + "p_precision": "P Precision", + "p_recall": "P Recall", + "p_f1": "P F1", + "p_residual_mean": "P Residual Mean", + "p_residual_std": "P Residual Std", + "s_precision": "S Precision", + "s_recall": "S Recall", + "s_f1": "S F1", + "s_residual_mean": "S Residual Mean", + "s_residual_std": "S Residual Std", + "detection_precision": "Detection Precision", + "detection_recall": "Detection Recall", + "detection_f1": "Detection F1", "pixel_mae": "Pixel MAE", "burned_area_mae": "Burned-area MAE", + "average_precision": "Average Precision", "track_error": "Track Error", + "track_error_km": "Track Error (km)", "intensity_mae": "Intensity MAE", + "intensity_rmse": "Intensity RMSE", + "intensity_mae_group_mean": "Mean Yearly Intensity MAE", + "pressure_mae": "Pressure MAE", + "best_of_k_track_error_km": "Best-of-k Track Error (km)", + "best_of_k_intensity_mae": "Best-of-k Intensity MAE", + "best_of_k_pressure_mae": "Best-of-k Pressure MAE", } diff --git a/pyhazards/benchmarks/earthquake.py b/pyhazards/benchmarks/earthquake.py index 8c638e59..2f0f3fc0 100644 --- a/pyhazards/benchmarks/earthquake.py +++ b/pyhazards/benchmarks/earthquake.py @@ -1,61 +1,253 @@ +"""Earthquake benchmark: seismic phase picking and ground-motion wavefield forecasting. + +``earthquake.picking`` scores phase pickers the way the original papers do (see +:mod:`pyhazards.metrics.picking`): + +1. waveforms ``(n, 3, samples)`` are reordered from the dataset's component order to the model's + ``component_order`` (the model's ``sampling_rate`` must match the dataset's); +2. ``model.annotate(waveforms)`` (official per-window normalisation + forward) gives probabilities, + ``model.extract_picks(probabilities)`` the official picks of each model (PhaseNet: peaks above 0.5, + EQTransformer: its detection/picking post-processing, GPD: sliding-window triggers). Models without + ``annotate`` are called directly: a ``(n, C, samples)`` output is read as per-sample probabilities + with P in channel 1 and S in channel 2 (or ``model.phase_channels``) and picked with peaks above + ``threshold`` at least ``min_distance_s`` apart; a ``(n, 2)`` output is read as one regressed + (P, S) arrival sample per trace; +3. picks are matched to the dataset's arrivals (targets ``(n, 2)``, NaN = none) per phase: + precision, recall and F1 with a tolerance window, and residual mean / standard deviation / MAE in + seconds, under ``protocol="phasenet"`` (Zhu & Beroza 2019: TP if ``|dt| < 0.1 s``, residual + statistics over ``|dt| < 0.5 s``) or ``protocol="eqtransformer"`` (Mousavi et al. 2020: TP if + ``|dt| < 0.5 s``). ``tolerance_s`` / ``residual_window_s`` override the protocol; +4. models with ``extract_detections`` (EQTransformer) also get trace-level detection precision, + recall and F1 (a trace is an event when it has a P or S arrival). + +Benchmark ``params``: ``protocol``, ``tolerance_s``, ``residual_window_s``, ``batch_size`` (default +32), ``pick_params`` (passed to ``extract_picks``), ``detection_params`` (passed to +``extract_detections``), and ``threshold`` / ``min_distance_s`` for models without ``extract_picks``. + +``earthquake.forecasting`` scores ground-motion wavefield forecasts the way WaveCastNet (Lyu et al., +Nat. Commun. 2025) does (see :mod:`pyhazards.metrics.wavefield`): inputs ``(n, channels, T_in, H, W)`` +and targets ``(n, channels, T_out, H, W)`` of velocity wavefields; models with ``rollout`` (WaveCastNet) +forecast the ``T_out`` frames by repeated calls on their own output, as the official validation does +(params ``rollout_step``, default the model's ``future_seq``), other models are called once and must +return the target shape. The model runs in evaluation mode without gradients; ``seed`` (default 0) seeds +a ``torch.Generator`` passed to models whose forecast is random (WaveCastNet's decoder starts from +uniform noise). Metrics: ACC, RFNE and RMSE per (sample, channel) over time and space, averaged over all +pairs (``acc``, ``rfne``, ``rmse``, the official validation numbers) and per channel (``acc_``, +``rfne_`` with the dataset's ``channel_names``, default ``x``, ``y``, ``z``), plus MAE and MSE. +This task is not earthquake-occurrence forecasting (AEFA, pyCSEP). +""" + from __future__ import annotations import json +import math from pathlib import Path -from typing import Dict +from typing import Any, Dict, List import torch import torch.nn as nn from ..configs import ExperimentConfig from ..datasets.base import DataBundle +from ..metrics.picking import PICKING_PROTOCOLS, detection_scores, peak_picks, score_picks +from ..metrics.wavefield import wavefield_metrics from .base import Benchmark from .registry import register_benchmark from .schemas import BenchmarkResult +PICKING_METRICS = [ + "p_precision", + "p_recall", + "p_f1", + "p_residual_mean", + "p_residual_std", + "p_pick_mae", + "s_precision", + "s_recall", + "s_f1", + "s_residual_mean", + "s_residual_std", + "s_pick_mae", + "detection_precision", + "detection_recall", + "detection_f1", +] + +DEFAULT_CHANNEL_NAMES = ("x", "y", "z") +FORECASTING_METRICS = [ + "acc", + "rfne", + "rmse", + *(f"acc_{name}" for name in DEFAULT_CHANNEL_NAMES), + *(f"rfne_{name}" for name in DEFAULT_CHANNEL_NAMES), + "mae", + "mse", +] + + +def _reorder(waveforms: torch.Tensor, source: Any, target: Any) -> torch.Tensor: + if not source or not target or str(source).upper() == str(target).upper(): + return waveforms + from ..models._seismic import reorder_components + + return reorder_components(waveforms, str(source), str(target)) + + +def _generic_picks(output: torch.Tensor, model: nn.Module, params: Dict[str, Any], sampling_rate: float): + if output.ndim == 2 and output.shape[1] == 2: + # Regressed (P, S) arrival samples: one pick of each phase per trace. + return [{"P": [(float(p), math.nan)], "S": [(float(s), math.nan)]} for p, s in output.tolist()] + if output.ndim != 3: + raise ValueError( + "earthquake.picking expects models to return per-sample probabilities (batch, classes, samples) " + f"or regressed arrival samples (batch, 2); got shape {tuple(output.shape)}." + ) + channels = getattr(model, "phase_channels", {"P": 1, "S": 2}) + threshold = float(params.get("threshold", 0.5)) + distance = int(round(float(params.get("min_distance_s", 0.5)) * sampling_rate)) + values = output.detach().cpu().double().numpy() + return [ + {phase: peak_picks(trace[channel], threshold, distance) for phase, channel in channels.items()} + for trace in values + ] + class EarthquakeBenchmark(Benchmark): name = "earthquake" hazard_task = "earthquake.picking" metric_names_by_task = { - "earthquake.picking": ["p_pick_mae", "s_pick_mae", "precision", "recall", "f1"], - "earthquake.forecasting": ["mae", "mse"], + "earthquake.picking": PICKING_METRICS, + "earthquake.forecasting": FORECASTING_METRICS, } def evaluate(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: + if config.benchmark.hazard_task == "earthquake.picking": + return self._evaluate_picking(model, data, config) + if config.benchmark.hazard_task == "earthquake.forecasting": + return self._evaluate_forecasting(model, data, config) + raise ValueError(f"Unknown earthquake task {config.benchmark.hazard_task!r}.") + + def _evaluate_forecasting(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: + params = dict(config.benchmark.params) + batch_size = int(params.get("batch_size", 8)) + seed = int(params.get("seed", 0)) + rollout_step = params.get("rollout_step") split = data.get_split(config.benchmark.eval_split) - x = split.inputs - y = split.targets - preds = model(x) + inputs, targets = split.inputs, split.targets + if inputs.ndim != 5 or targets.ndim != 5 or len(inputs) != len(targets) or inputs.shape[1] != targets.shape[1]: + raise ValueError( + "earthquake.forecasting needs inputs shaped (n, channels, T_in, H, W) and targets shaped " + f"(n, channels, T_out, H, W); got {tuple(inputs.shape)} and {tuple(targets.shape)}." + ) + steps = int(targets.shape[2]) + generator = torch.Generator().manual_seed(seed) + was_training = model.training + model.eval() + predictions = [] + try: + with torch.no_grad(): + for start in range(0, len(inputs), batch_size): + batch = inputs[start : start + batch_size] + if hasattr(model, "rollout"): + step = None if rollout_step is None else int(rollout_step) + predictions.append(model.rollout(batch, steps, step=step, generator=generator)) + else: + predictions.append(model(batch)) + finally: + model.train(was_training) + preds = torch.cat(predictions).to(targets.dtype) + if preds.shape != targets.shape: + raise ValueError(f"The model forecast has shape {tuple(preds.shape)}, the targets {tuple(targets.shape)}.") + names = data.metadata.get("channel_names") or data.feature_spec.extra.get("channel_names") + if not names: + names = DEFAULT_CHANNEL_NAMES if targets.shape[1] == len(DEFAULT_CHANNEL_NAMES) else None + metrics = wavefield_metrics(preds, targets, names) + metrics["mae"] = float(torch.mean(torch.abs(preds - targets))) + metrics["mse"] = float(torch.mean((preds - targets) ** 2)) + return BenchmarkResult( + benchmark_name=self.name, + hazard_task=config.benchmark.hazard_task, + metrics=metrics, + metadata={ + "split": config.benchmark.eval_split, + "n_sequences": len(inputs), + "input_steps": int(inputs.shape[2]), + "forecast_steps": steps, + "seed": seed, + "dataset_name": data.metadata.get("dataset"), + "source_dataset": data.metadata.get("source_dataset", data.metadata.get("dataset")), + "synthetic_data": bool(data.metadata.get("synthetic", False)), + }, + ) - if config.benchmark.hazard_task == "earthquake.picking": - mae = (preds - y).abs() - tolerances = config.benchmark.params.get("detection_tolerances", [4.0, 8.0, 12.0]) - threshold_curve: Dict[str, float] = {} - detection_rate = 0.0 - for tolerance in tolerances: - hits = ((preds - y).abs() <= float(tolerance)).all(dim=1).float() - hit_rate = float(hits.mean().detach().cpu()) - threshold_curve[str(tolerance)] = hit_rate - if float(tolerance) == 8.0: - detection_rate = hit_rate - - metrics = { - "p_pick_mae": float(mae[:, 0].mean().detach().cpu()), - "s_pick_mae": float(mae[:, 1].mean().detach().cpu()), - "mean_pick_mae": float(mae.mean().detach().cpu()), - "precision": detection_rate, - "recall": detection_rate, - "f1": detection_rate, - } - else: - mse = torch.mean((preds - y) ** 2) - mae = torch.mean(torch.abs(preds - y)) - threshold_curve = {} - metrics = { - "mae": float(mae.detach().cpu()), - "mse": float(mse.detach().cpu()), - } + def _evaluate_picking(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: + params = dict(config.benchmark.params) + protocol = str(params.get("protocol", "phasenet")).lower() + if protocol not in PICKING_PROTOCOLS: + raise ValueError(f"Unknown picking protocol {protocol!r}; expected one of {sorted(PICKING_PROTOCOLS)}.") + tolerance_s = float(params.get("tolerance_s", PICKING_PROTOCOLS[protocol]["tolerance_s"])) + residual_window_s = float(params.get("residual_window_s", PICKING_PROTOCOLS[protocol]["residual_window_s"])) + batch_size = int(params.get("batch_size", 32)) + pick_params = dict(params.get("pick_params", {})) + detection_params = dict(params.get("detection_params", {})) + + split = data.get_split(config.benchmark.eval_split) + waveforms, targets = split.inputs, split.targets + if waveforms.ndim != 3 or targets.ndim != 2 or targets.shape[1] != 2 or len(waveforms) != len(targets): + raise ValueError( + "earthquake.picking needs inputs shaped (n, channels, samples) and targets shaped (n, 2) " + f"[P, S arrival samples, NaN = none]; got {tuple(waveforms.shape)} and {tuple(targets.shape)}." + ) + data_rate = data.metadata.get("sampling_rate") or data.feature_spec.extra.get("sampling_rate") + model_rate = getattr(model, "sampling_rate", None) + if data_rate and model_rate and not math.isclose(float(data_rate), float(model_rate)): + raise ValueError( + f"The model expects {model_rate} Hz waveforms but the dataset is sampled at {data_rate} Hz." + ) + sampling_rate = float(data_rate or model_rate or 100.0) + source_order = data.metadata.get("component_order") or data.feature_spec.extra.get("component_order") + waveforms = _reorder(waveforms, source_order, getattr(model, "component_order", None)) + + picks: List[Dict[str, list]] = [] + detections: List[list] = [] + has_detections = hasattr(model, "extract_detections") + for start in range(0, len(waveforms), batch_size): + batch = waveforms[start : start + batch_size] + if hasattr(model, "annotate"): + output = model.annotate(batch) + else: + output = model(batch) + if hasattr(model, "extract_picks"): + picks.extend(model.extract_picks(output, **pick_params)) + else: + picks.extend(_generic_picks(output, model, params, sampling_rate)) + if has_detections: + detections.extend(model.extract_detections(output, **detection_params)) + + tolerance, window = tolerance_s * sampling_rate, residual_window_s * sampling_rate + metrics: Dict[str, float] = {} + counts: Dict[str, Dict[str, int]] = {} + manual = targets.detach().cpu().double().tolist() + for column, phase in enumerate(("P", "S")): + predicted = [[sample for sample, _ in trace_picks.get(phase, [])] for trace_picks in picks] + score = score_picks(predicted, [[row[column]] for row in manual], tolerance, window) + values = score.metrics(sampling_rate) + prefix = phase.lower() + metrics.update( + { + f"{prefix}_precision": values["precision"], + f"{prefix}_recall": values["recall"], + f"{prefix}_f1": values["f1"], + f"{prefix}_residual_mean": values["residual_mean"], + f"{prefix}_residual_std": values["residual_std"], + f"{prefix}_pick_mae": values["mae"], + } + ) + counts[phase] = {"manual": score.n_true, "predicted": score.n_pred, "true_positive": score.n_tp} + if has_detections: + is_event = [not (math.isnan(p) and math.isnan(s)) for p, s in manual] + scores = detection_scores([len(windows) > 0 for windows in detections], is_event) + metrics.update({f"detection_{key}": value for key, value in scores.items()}) return BenchmarkResult( benchmark_name=self.name, @@ -63,35 +255,29 @@ def evaluate(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) metrics=metrics, metadata={ "split": config.benchmark.eval_split, - "threshold_curve": threshold_curve, + "protocol": protocol, + "tolerance_s": tolerance_s, + "residual_window_s": residual_window_s, + "sampling_rate": sampling_rate, + "pick_counts": counts, + "n_traces": len(waveforms), "dataset_name": data.metadata.get("dataset"), "source_dataset": data.metadata.get("source_dataset", data.metadata.get("dataset")), + "synthetic_data": bool(data.metadata.get("synthetic", False)), }, ) - def export_report( - self, - result: BenchmarkResult, - output_dir: str, - formats, - ) -> Dict[str, str]: + def export_report(self, result: BenchmarkResult, output_dir: str, formats) -> Dict[str, str]: paths = super().export_report(result, output_dir=output_dir, formats=formats) - if result.hazard_task == "earthquake.forecasting": + if result.hazard_task == "earthquake.picking": target = Path(output_dir) target.mkdir(parents=True, exist_ok=True) - pycsep_path = target / "earthquake_pycsep.json" - payload = { - "adapter": "pyCSEP-style", - "benchmark_name": result.benchmark_name, - "hazard_task": result.hazard_task, - "metrics": result.metrics, - "metadata": result.metadata, - } - pycsep_path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8") - paths["pycsep"] = str(pycsep_path) + path = target / "earthquake_pick_counts.json" + path.write_text(json.dumps(result.metadata.get("pick_counts", {}), indent=2, sort_keys=True), encoding="utf-8") + paths["pick_counts"] = str(path) return paths register_benchmark(EarthquakeBenchmark.name, EarthquakeBenchmark) -__all__ = ["EarthquakeBenchmark"] +__all__ = ["EarthquakeBenchmark", "FORECASTING_METRICS", "PICKING_METRICS"] diff --git a/pyhazards/benchmarks/flood.py b/pyhazards/benchmarks/flood.py index 5c0509d9..f8045883 100644 --- a/pyhazards/benchmarks/flood.py +++ b/pyhazards/benchmarks/flood.py @@ -1,95 +1,289 @@ +"""Flood benchmark: per-basin streamflow metrics and inundation depth / extent metrics. + +``flood.streamflow`` follows Kratzert et al. (HESS 2019) and the NeuralHydrology tester: every model +predicts the discharge of each day of the evaluation period from the ``seq_length`` days before it (the +last step of its output sequence); predictions and observations are put back into physical units with +the training scaler, negative predictions are set to zero (``clip_negative``, as in the 2019 code and +NeuralHydrology's CAMELS configurations), and NeuralHydrology's metrics are computed per basin over the +period (:mod:`pyhazards.metrics.hydrology`). Reported values are the median over basins (``nse``, +``kge``, ...), the mean over basins (``nse_mean``, ...), ``n_basins`` and ``n_basins_nse_le_0``; the +per-basin values are in ``metadata["per_basin"]``. + +``flood.inundation`` compares predicted and simulated water depth (:mod:`pyhazards.metrics.inundation`) +on three kinds of data: + +- rasters (``(batch, 1, H, W)`` depth, or channels-last multi-variable outputs such as UrbanFloodCast's + ``(batch, Sy, Sx, T, 3)`` depth and discharges with ``metadata["depth_channel"]`` and a NaN mask in the + split metadata): the model maps the split inputs to the targets in batches; +- mesh hydrographs (``hydrographnet_white_river``, ``flood_mesh_synthetic``): every test hydrograph is + rolled out autoregressively with the model's ``rollout`` method (HydroGraphNet's ``inference.py``) + and the predicted depths are denormalised to metres; ``rollout_rmse`` is the depth RMSE per step + averaged over steps and hydrographs (the per-step curve is in the report metadata); +- graph-temporal node series (``GraphTemporalDataset``), scored per node. + +Reported: ``pixel_mae`` and ``rmse`` (depth errors over all cells), ``iou`` / ``f1`` (wet cells: prediction +>= 0.5 m, target > 0), the depth CSI at 1 / 10 / 50 cm and the per-sample relative L2, NSE and Pearson r +of the UrbanFloodCast evaluation, averaged over samples (events or hydrographs). +""" + from __future__ import annotations -from typing import Dict +from typing import Any, Dict, List, Tuple +import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from ..configs import ExperimentConfig from ..datasets.base import DataBundle -from ..datasets.graph import graph_collate +from ..datasets.flood.hydrograph import HydrographRollouts +from ..datasets.flood.streamflow import StreamflowWindows, scaler_from_metadata +from ..datasets.graph import GraphTemporalDataset, graph_collate +from ..metrics.hydrology import STREAMFLOW_METRICS, aggregate_basin_metrics, calculate_metrics, streamflow_metric_names +from ..metrics.inundation import INUNDATION_METRICS, inundation_metrics, rollout_rmse from .base import Benchmark from .registry import register_benchmark from .schemas import BenchmarkResult +def _model_device(model: nn.Module): + parameter = next(model.parameters(), None) + return parameter.device if parameter is not None else None + + +def _to_device(obj: Any, device) -> Any: + if device is None: + return obj + if isinstance(obj, torch.Tensor): + return obj.to(device) + if isinstance(obj, dict): + return {key: _to_device(value, device) for key, value in obj.items()} + return obj + + +def point_prediction(model: nn.Module, outputs: Any) -> torch.Tensor: + """Deterministic prediction ``(batch, time, n_targets)`` from a streamflow model's output. + + NeuralHydrology-style models return a dict: regression heads give ``y_hat``; probabilistic heads + (e.g. CMAL) are reduced with the model's ``point_prediction`` (the mixture mean). Plain tensors are + used as they are. + """ + if isinstance(outputs, torch.Tensor): + return outputs + if isinstance(outputs, dict): + if "y_hat" in outputs: + return outputs["y_hat"] + if hasattr(model, "point_prediction"): + return model.point_prediction(outputs) + raise ValueError( + "Streamflow models must return a tensor of shape (batch, time, n_targets) or a dict with 'y_hat' " + f"(or a model with point_prediction); got {type(outputs).__name__}." + ) + + +def _last_step(prediction: torch.Tensor, n_targets: int) -> torch.Tensor: + if prediction.ndim == 3: + return prediction[:, -1, :] + if prediction.ndim == 2 and prediction.shape[-1] == n_targets: + return prediction + raise ValueError( + "Streamflow predictions must have shape (batch, time, n_targets) or (batch, n_targets); " + f"got {tuple(prediction.shape)} for {n_targets} target(s)." + ) + + +def streamflow_predictions( + model: nn.Module, windows: StreamflowWindows, n_targets: int, batch_size: int = 256 +) -> Tuple[np.ndarray, np.ndarray]: + """Normalised (simulation, observation) arrays ``(n_samples, n_targets)`` at the last window step.""" + loader = DataLoader(windows, batch_size=batch_size, shuffle=False) + device = _model_device(model) + sims: List[np.ndarray] = [] + obs: List[np.ndarray] = [] + with torch.no_grad(): + for inputs, target in loader: + outputs = model(_to_device(inputs, device)) + prediction = _last_step(point_prediction(model, outputs), n_targets) + sims.append(prediction.detach().float().cpu().numpy()) + obs.append(target[:, -1, :].numpy()) + if not sims: + return np.zeros((0, n_targets)), np.zeros((0, n_targets)) + return np.concatenate(sims), np.concatenate(obs) + + +def evaluate_streamflow( + model: nn.Module, + data: DataBundle, + split_name: str = "test", + batch_size: int = 256, + clip_negative: bool = True, + metrics: Any = None, +) -> Tuple[Dict[str, float], Dict[str, Dict[str, float]]]: + """Summary metrics and per-basin metrics of ``model`` on a streamflow split.""" + split = data.get_split(split_name) + windows = split.inputs + if not isinstance(windows, StreamflowWindows): + raise ValueError( + "flood.streamflow needs a streamflow dataset (StreamflowWindows splits, e.g. camels_us_streamflow, " + f"caravan_streamflow or flood_streamflow_synthetic); got {type(windows).__name__}." + ) + targets = list(data.metadata.get("target_variables", ["discharge"])) + scaler = scaler_from_metadata(data.metadata) + sim, obs = streamflow_predictions(model, windows, len(targets), batch_size=batch_size) + sim = scaler.rescale_target(sim) + obs = scaler.rescale_target(obs) + if clip_negative: + sim = np.where(sim < 0, 0.0, sim) + + names = list(STREAMFLOW_METRICS if metrics is None else metrics) + per_basin: Dict[str, Dict[str, float]] = {} + for basin_index, basin in enumerate(windows.basins): + rows = np.flatnonzero(windows.sample_basin == basin_index) + if rows.size == 0: + continue + rows = rows[np.argsort(windows.sample_date[rows], kind="stable")] + dates = windows.sample_date[rows] + values: Dict[str, float] = {} + for t, target in enumerate(targets): + basin_obs = obs[rows, t] + if np.isnan(basin_obs).all(): + continue + result = calculate_metrics(basin_obs, sim[rows, t], dates=dates, metrics=names) + if len(targets) > 1: + result = {f"{target}_{key}": value for key, value in result.items()} + values.update(result) + if values: + per_basin[basin] = values + return aggregate_basin_metrics(per_basin), per_basin + + +def _batched_predictions(model: nn.Module, inputs: torch.Tensor, batch_size: int) -> torch.Tensor: + device = _model_device(model) + preds = [] + with torch.no_grad(): + for start in range(0, inputs.shape[0], batch_size): + batch = inputs[start : start + batch_size] + preds.append(model(batch if device is None else batch.to(device)).detach().cpu()) + return torch.cat(preds, dim=0) + + +def evaluate_mesh_rollouts(model: nn.Module, rollouts: HydrographRollouts) -> Tuple[Dict[str, float], Dict[str, Any]]: + """Roll out every test hydrograph with ``model.rollout`` and score the depths in metres.""" + if not hasattr(model, "rollout"): + raise ValueError( + "flood.inundation on mesh hydrographs rolls models out autoregressively; " + f"{type(model).__name__} has no rollout(...) method (see HydroGraphNet)." + ) + device = _model_device(model) + stats = rollouts.depth_stats + scale = stats["std"] + 1e-8 + preds, targets, curves = [], [], [] + with torch.no_grad(): + for idx in range(len(rollouts)): + inputs, target = rollouts[idx] + inputs = _to_device(inputs, device) + out = model.rollout( + inputs["node_features"], + inputs["edge_features"], + inputs["edge_index"], + inputs["inflow"], + inputs["precipitation"], + n_time_steps=rollouts.n_time_steps, + ) + pred = out["water_depth"].detach().cpu().float() + truth = target["water_depth"].float() + curves.append(rollout_rmse(pred, truth)) + preds.append(pred * scale + stats["mean"]) + targets.append(truth * scale + stats["mean"]) + metrics = inundation_metrics(torch.stack(preds), torch.stack(targets)) + curve = torch.stack(curves).mean(dim=0) if curves else torch.zeros(0) + metrics["rollout_rmse"] = float(curve.mean() * scale) if curves else float("nan") + metadata = { + "rollout_rmse_per_step_m": [float(v) * scale for v in curve], + "rollout_rmse_per_step_normalized": [float(v) for v in curve], + "hydrographs": list(rollouts.hydrograph_ids), + "rollout_length": rollouts.rollout_length, + } + return metrics, metadata + + +def evaluate_inundation( + model: nn.Module, data: DataBundle, split_name: str = "test", batch_size: int = 1 +) -> Tuple[Dict[str, float], Dict[str, Any]]: + """Inundation metrics of ``model`` on a raster, mesh-rollout or graph-temporal split.""" + split = data.get_split(split_name) + if isinstance(split.inputs, HydrographRollouts): + return evaluate_mesh_rollouts(model, split.inputs) + if isinstance(split.inputs, GraphTemporalDataset): + loader = DataLoader(split.inputs, batch_size=4, shuffle=False, collate_fn=graph_collate) + preds, targets = [], [] + with torch.no_grad(): + for batch, target in loader: + preds.append(model(batch)) + targets.append(target) + return inundation_metrics(torch.cat(preds, dim=0), torch.cat(targets, dim=0)), {} + if not isinstance(split.inputs, torch.Tensor) or not isinstance(split.targets, torch.Tensor): + raise ValueError( + "flood.inundation needs tensor splits (rasters), mesh hydrographs (HydrographRollouts) or a " + f"GraphTemporalDataset; got inputs of type {type(split.inputs).__name__}." + ) + preds = _batched_predictions(model, split.inputs, max(1, int(batch_size))) + metrics = inundation_metrics( + preds, + split.targets, + mask=split.metadata.get("mask"), + depth_index=data.metadata.get("depth_channel"), + ) + return metrics, {} + + class FloodBenchmark(Benchmark): name = "flood" hazard_task = "flood.streamflow" metric_names_by_task = { - "flood.streamflow": ["mae", "rmse", "nse", "kge"], - "flood.inundation": ["pixel_mae", "iou", "f1"], + "flood.streamflow": streamflow_metric_names(), + "flood.inundation": list(INUNDATION_METRICS) + ["rollout_rmse"], } def evaluate(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: - split = data.get_split(config.benchmark.eval_split) - if ( - config.benchmark.hazard_task == "flood.streamflow" - and hasattr(split.inputs, "__len__") - and not isinstance(split.inputs, torch.Tensor) - ): - loader = DataLoader(split.inputs, batch_size=4, shuffle=False, collate_fn=graph_collate) - preds_all = [] - target_all = [] - with torch.no_grad(): - for batch, target in loader: - preds_all.append(model(batch)) - target_all.append(target) - preds = torch.cat(preds_all, dim=0) - targets = torch.cat(target_all, dim=0) - else: - preds = model(split.inputs) - targets = split.targets - + params = config.benchmark.params + metadata: Dict[str, Any] = { + "split": config.benchmark.eval_split, + "dataset_name": data.metadata.get("dataset"), + "source_dataset": data.metadata.get("source_dataset", data.metadata.get("dataset")), + } if config.benchmark.hazard_task == "flood.inundation": - pred_depth = preds.float() - target_depth = targets.float() - pred_mask = (pred_depth >= 0.5).float() - target_mask = (target_depth > 0).float() - intersection = (pred_mask * target_mask).sum() - union = pred_mask.sum() + target_mask.sum() - intersection - metrics: Dict[str, float] = { - "pixel_mae": float(torch.mean(torch.abs(pred_depth - target_depth)).detach().cpu()), - "iou": float((intersection / union.clamp(min=1.0)).detach().cpu()), - "f1": float( - ( - 2 * intersection - / (pred_mask.sum() + target_mask.sum()).clamp(min=1.0) - ).detach().cpu() - ), - } + metrics, extra = evaluate_inundation( + model, data, split_name=config.benchmark.eval_split, batch_size=int(params.get("batch_size", 1)) + ) + metadata.update(extra) else: - mae = torch.mean(torch.abs(preds - targets)) - rmse = torch.sqrt(torch.mean((preds - targets) ** 2)) - target_mean = torch.mean(targets) - denominator = torch.sum((targets - target_mean) ** 2).clamp(min=1e-6) - nse = 1.0 - torch.sum((preds - targets) ** 2) / denominator - pred_std = torch.std(preds).clamp(min=1e-6) - target_std = torch.std(targets).clamp(min=1e-6) - covariance = torch.mean((preds - torch.mean(preds)) * (targets - target_mean)) - correlation = covariance / (pred_std * target_std) - alpha = pred_std / target_std - beta = torch.mean(preds) / target_mean.clamp(min=1e-6) - kge = 1.0 - torch.sqrt((correlation - 1.0) ** 2 + (alpha - 1.0) ** 2 + (beta - 1.0) ** 2) - metrics = { - "mae": float(mae.detach().cpu()), - "rmse": float(rmse.detach().cpu()), - "nse": float(nse.detach().cpu()), - "kge": float(kge.detach().cpu()), - } + metrics, per_basin = evaluate_streamflow( + model, + data, + split_name=config.benchmark.eval_split, + batch_size=int(params.get("batch_size", 256)), + clip_negative=bool(params.get("clip_negative", True)), + ) + metadata["per_basin"] = per_basin + metadata["aggregation"] = "median over basins (), mean over basins (_mean)" return BenchmarkResult( benchmark_name=self.name, hazard_task=config.benchmark.hazard_task, metrics=metrics, - metadata={ - "split": config.benchmark.eval_split, - "dataset_name": data.metadata.get("dataset"), - "source_dataset": data.metadata.get("source_dataset", data.metadata.get("dataset")), - }, + metadata=metadata, ) register_benchmark(FloodBenchmark.name, FloodBenchmark) -__all__ = ["FloodBenchmark"] +__all__ = [ + "FloodBenchmark", + "evaluate_inundation", + "evaluate_mesh_rollouts", + "evaluate_streamflow", + "inundation_metrics", + "point_prediction", + "streamflow_predictions", +] diff --git a/pyhazards/benchmarks/runner.py b/pyhazards/benchmarks/runner.py index 65e1655e..2a2ec88e 100644 --- a/pyhazards/benchmarks/runner.py +++ b/pyhazards/benchmarks/runner.py @@ -2,6 +2,7 @@ from typing import Union +import torch import torch.nn as nn from ..configs import ExperimentConfig @@ -25,7 +26,14 @@ def run_benchmark( output_dir: str | None = None, ) -> BenchmarkRunSummary: benchmark_obj = resolve_benchmark(benchmark) - result = benchmark_obj.evaluate(model=model, data=data, config=config) + # Score in inference mode (dropout off, BatchNorm running statistics) and restore the mode after. + was_training = model.training + model.eval() + try: + with torch.no_grad(): + result = benchmark_obj.evaluate(model=model, data=data, config=config) + finally: + model.train(was_training) metrics = benchmark_obj.aggregate_metrics([result]) result.metrics = metrics report_dir = output_dir or config.report.output_dir diff --git a/pyhazards/benchmarks/tc.py b/pyhazards/benchmarks/tc.py index f555b88d..92327dd2 100644 --- a/pyhazards/benchmarks/tc.py +++ b/pyhazards/benchmarks/tc.py @@ -1,5 +1,51 @@ +"""Tropical cyclone evaluator: track error in km and intensity errors per lead time. + +Two hazard tasks are scored: + +``tc.track_intensity`` + Forecast positions (and intensity) at several lead times. The data bundle's metadata gives + ``lead_hours`` (one per forecast step), ``target_variables`` (the order of the last axis of + tensor targets, from ``lat``, ``lon``, ``wind``, ``pres``) and ``units`` (e.g. + ``{"wind": "kt", "pres": "hPa"}``). Models either define ``forecast(inputs)`` returning a dict + of ``lat``, ``lon`` (degrees), ``wind`` and/or ``pres`` arrays shaped ``(storms, lead)`` or + ``(storms, samples, lead)``, or return a tensor ``(storms, lead, variables)`` / + ``(storms, samples, lead, variables)`` in the order of ``target_variables``. + + Metrics (NaN targets are skipped): + + * ``track_error_km`` and ``track_error_km_h``: great-circle distance (haversine on a sphere + of radius 6371.0 km) between forecast and observed centres, averaged over storms (and over + lead times for the aggregate). ``params: {track_distance: tcn_equirectangular}`` switches to + the TropiCycloneNet evaluation formula instead (111 km per degree, longitude difference + scaled by the cosine of the observed latitude). + * ``intensity_mae`` / ``intensity_mae_h``: mean absolute error of the maximum sustained wind + in the dataset's wind unit (``units["wind"]``, knots for IBTrACS, m/s for TCND / CMA); + ``pressure_mae`` / ``pressure_mae_h`` likewise for central pressure (hPa). + * With several samples per storm, the deterministic metrics above score the sample mean (mean + position computed on the unit sphere), and ``best_of_k_*`` metrics follow the + TropiCycloneNet paper (Huang et al. 2025, evaluate_model_Me.py): for every storm, lead time + and variable separately, the smallest error over the ``k`` samples, averaged over storms. + Track, wind and pressure minima may come from different samples; these are oracle + (best-case) errors and are not comparable with single-forecast errors. + + Benchmark ``params``: ``track_distance`` (above), ``batch_size`` (score in chunks) and ``seed`` + (default: the experiment seed; sampling models draw their noise from it). + +``tc.intensity`` + One intensity value per storm and time (e.g. the 24-hour intensity or 24-hour intensity + change). Targets are in physical units; ``metadata["prediction_transform"]`` (``{"kind": + "minmax", "min": a, "max": b}``) maps model outputs back to them when the model predicts a + scaled target. Metrics: ``intensity_mae``, ``intensity_rmse`` and ``intensity_mae_h`` for the + single lead time; when the split metadata has ``groups`` (e.g. the test year of each sample), + also ``intensity_mae_`` per group and their unweighted mean ``intensity_mae_group_mean`` + (the way Xu et al. 2021 and SAF-Net report yearly test MAE). +""" + from __future__ import annotations +import math +from typing import Any, Dict, Mapping, Optional, Sequence + import torch import torch.nn as nn @@ -9,39 +55,274 @@ from .registry import register_benchmark from .schemas import BenchmarkResult +EARTH_RADIUS_KM = 6371.0 +TCN_KM_PER_DEGREE = 111.0 +TRACK_VARIABLES = ("lat", "lon", "wind", "pres") + + +def great_circle_distance_km(lat1, lon1, lat2, lon2, radius_km: float = EARTH_RADIUS_KM) -> torch.Tensor: + """Haversine distance in km between points given in degrees (broadcasting tensors).""" + lat1, lon1, lat2, lon2 = (torch.deg2rad(torch.as_tensor(v, dtype=torch.float64)) for v in (lat1, lon1, lat2, lon2)) + dlat = lat2 - lat1 + dlon = lon2 - lon1 + h = torch.sin(dlat / 2) ** 2 + torch.cos(lat1) * torch.cos(lat2) * torch.sin(dlon / 2) ** 2 + return 2 * radius_km * torch.asin(torch.sqrt(h.clamp(0.0, 1.0))) + + +def tcn_equirectangular_distance_km(lat_pred, lon_pred, lat_true, lon_true) -> torch.Tensor: + """Track error of the official TropiCycloneNet evaluation (``trajectory_displacement_error``). + + 111 km per degree, with the longitude difference scaled by the cosine of the observed latitude. + """ + lat_pred, lon_pred, lat_true, lon_true = (torch.as_tensor(v, dtype=torch.float64) for v in (lat_pred, lon_pred, lat_true, lon_true)) + dx = (lon_true - lon_pred) * TCN_KM_PER_DEGREE * torch.cos(torch.deg2rad(lat_true)) + dy = (lat_true - lat_pred) * TCN_KM_PER_DEGREE + return torch.sqrt(dx**2 + dy**2) + + +def _distance_fn(name: str): + if name == "great_circle": + return great_circle_distance_km + if name == "tcn_equirectangular": + return lambda lat_p, lon_p, lat_t, lon_t: tcn_equirectangular_distance_km(lat_p, lon_p, lat_t, lon_t) + raise ValueError(f"unknown track_distance {name!r}; use 'great_circle' or 'tcn_equirectangular'") + + +def _spherical_mean(lat: torch.Tensor, lon: torch.Tensor, dim: int): + """Mean position over ``dim`` computed from unit vectors (safe across the dateline).""" + lat_r, lon_r = torch.deg2rad(lat), torch.deg2rad(lon) + x = (torch.cos(lat_r) * torch.cos(lon_r)).mean(dim) + y = (torch.cos(lat_r) * torch.sin(lon_r)).mean(dim) + z = torch.sin(lat_r).mean(dim) + mean_lat = torch.rad2deg(torch.atan2(z, torch.sqrt(x**2 + y**2))) + mean_lon = torch.rad2deg(torch.atan2(y, x)) + return mean_lat, mean_lon + + +def _lead_label(hours: float) -> str: + return f"{int(hours)}h" if float(hours).is_integer() else f"{hours:g}h".replace(".", "p") + + +def _nanmean(values: torch.Tensor) -> float: + valid = ~torch.isnan(values) + if not bool(valid.any()): + return float("nan") + return float(values[valid].mean()) + + +def _as_dict(values: Any, variables: Sequence[str]) -> Dict[str, torch.Tensor]: + if isinstance(values, Mapping): + return {name: torch.as_tensor(values[name]).detach().cpu().double() for name in TRACK_VARIABLES if name in values} + tensor = torch.as_tensor(values).detach().cpu().double() + if tensor.size(-1) != len(variables): + raise ValueError( + f"tensor forecasts must end with one entry per target variable {list(variables)}, got shape {tuple(tensor.shape)}" + ) + return {name: tensor[..., i] for i, name in enumerate(variables)} + + +def _call_model(model: nn.Module, inputs: Any) -> Any: + forecast = getattr(model, "forecast", None) + if callable(forecast): + return forecast(inputs) + return model(inputs) + + +def _batch_slice(inputs: Any, start: int, end: int, batch_dims: Mapping[str, int], key: Optional[str] = None) -> Any: + if isinstance(inputs, Mapping): + return {name: _batch_slice(value, start, end, batch_dims, name) for name, value in inputs.items()} + if isinstance(inputs, torch.Tensor): + return inputs.narrow(int(batch_dims.get(key, 0)), start, end - start) + return inputs + + +def _concat_outputs(chunks: Sequence[Any]) -> Any: + first = chunks[0] + if isinstance(first, Mapping): + return {name: _concat_outputs([chunk[name] for chunk in chunks]) for name in first} + if isinstance(first, (tuple, list)): + return type(first)(_concat_outputs([chunk[i] for chunk in chunks]) for i in range(len(first))) + return torch.cat([torch.as_tensor(chunk).detach().cpu() for chunk in chunks], dim=0) + + +def _batched_model_outputs(model: nn.Module, inputs: Any, count: int, batch_size: Optional[int], batch_dims: Mapping[str, int]) -> Any: + """Run the model on chunks of ``batch_size`` samples (all at once when ``batch_size`` is None). + + Mapping inputs are sliced along each entry's batch axis (``batch_dims``, default 0; e.g. + TropiCycloneNet's ``obs_traj`` is time-first). Forecast dicts must be batch-first. + """ + if not batch_size or batch_size >= count: + return _call_model(model, inputs) + chunks = [ + _call_model(model, _batch_slice(inputs, start, min(count, start + int(batch_size)), batch_dims)) + for start in range(0, count, int(batch_size)) + ] + return _concat_outputs(chunks) + + +def track_intensity_metrics( + forecast: Mapping[str, torch.Tensor], + target: Mapping[str, torch.Tensor], + lead_hours: Sequence[float], + track_distance: str = "great_circle", +) -> Dict[str, float]: + """Per-lead and aggregate track / intensity errors; see the module docstring.""" + distance = _distance_fn(track_distance) + lead_hours = list(lead_hours) + sample = forecast["lat"].ndim == 3 + if not sample and forecast["lat"].ndim != 2: + raise ValueError(f"forecasts must be (storms, lead) or (storms, samples, lead), got {tuple(forecast['lat'].shape)}") + if target["lat"].ndim != 2 or target["lat"].size(1) != len(lead_hours): + raise ValueError(f"targets must be (storms, {len(lead_hours)} lead times), got {tuple(target['lat'].shape)}") + metrics: Dict[str, float] = {} + + if sample: + mean_lat, mean_lon = _spherical_mean(forecast["lat"], forecast["lon"], dim=1) + point = {"lat": mean_lat, "lon": mean_lon} + for name in ("wind", "pres"): + if name in forecast: + point[name] = forecast[name].mean(dim=1) + else: + point = dict(forecast) + + errors = {"track_error_km": distance(point["lat"], point["lon"], target["lat"], target["lon"])} + for name, metric in (("wind", "intensity_mae"), ("pres", "pressure_mae")): + if name in point and name in target: + errors[metric] = (point[name] - target[name]).abs() + if sample: + lat_t, lon_t = target["lat"].unsqueeze(1), target["lon"].unsqueeze(1) + per_sample = {"best_of_k_track_error_km": distance(forecast["lat"], forecast["lon"], lat_t, lon_t)} + for name, metric in (("wind", "best_of_k_intensity_mae"), ("pres", "best_of_k_pressure_mae")): + if name in forecast and name in target: + per_sample[metric] = (forecast[name] - target[name].unsqueeze(1)).abs() + for metric, values in per_sample.items(): + errors[metric] = values.min(dim=1).values + + for metric, values in errors.items(): + metrics[metric] = _nanmean(values) + for step, hours in enumerate(lead_hours): + metrics[f"{metric}_{_lead_label(hours)}"] = _nanmean(values[:, step]) + if sample: + metrics["num_samples"] = float(forecast["lat"].size(1)) + return metrics + + +def intensity_metrics( + predictions: torch.Tensor, + targets: torch.Tensor, + lead_hours: Optional[Sequence[float]] = None, + groups: Optional[Sequence[Any]] = None, +) -> Dict[str, float]: + preds = torch.as_tensor(predictions).detach().cpu().double().reshape(-1) + truth = torch.as_tensor(targets).detach().cpu().double().reshape(-1) + if preds.shape != truth.shape: + raise ValueError(f"expected one prediction per target, got {tuple(preds.shape)} and {tuple(truth.shape)}") + valid = ~torch.isnan(truth) + error = preds[valid] - truth[valid] + metrics = { + "intensity_mae": float(error.abs().mean()), + "intensity_rmse": float(torch.sqrt((error**2).mean())), + } + if lead_hours and len(lead_hours) == 1: + metrics[f"intensity_mae_{_lead_label(lead_hours[0])}"] = metrics["intensity_mae"] + if groups is not None: + labels = list(groups) + if len(labels) != preds.numel(): + raise ValueError("split metadata 'groups' needs one label per sample") + group_maes = [] + for label in sorted(set(labels), key=str): + mask = torch.tensor([item == label for item in labels]) & valid + if bool(mask.any()): + mae = float((preds[mask] - truth[mask]).abs().mean()) + metrics[f"intensity_mae_{label}"] = mae + group_maes.append(mae) + if group_maes: + metrics["intensity_mae_group_mean"] = sum(group_maes) / len(group_maes) + return metrics + + +def _apply_transform(values: torch.Tensor, transform: Optional[Mapping[str, Any]]) -> torch.Tensor: + if not transform: + return values + kind = transform.get("kind") + if kind == "minmax": + return values * (float(transform["max"]) - float(transform["min"])) + float(transform["min"]) + if kind == "affine": + return values * float(transform["scale"]) + float(transform["offset"]) + raise ValueError(f"unknown prediction_transform kind {kind!r}") + class TropicalCycloneBenchmark(Benchmark): name = "tc" hazard_task = "tc.track_intensity" metric_names_by_task = { - "tc.track_intensity": ["track_error", "intensity_mae"], + "tc.track_intensity": [ + "track_error_km", + "intensity_mae", + "pressure_mae", + "best_of_k_track_error_km", + "best_of_k_intensity_mae", + "best_of_k_pressure_mae", + ], + "tc.intensity": ["intensity_mae", "intensity_rmse", "intensity_mae_group_mean"], } def evaluate(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: split = data.get_split(config.benchmark.eval_split) - preds = model(split.inputs) - targets = split.targets - - track_error = torch.norm(preds[..., :2] - targets[..., :2], dim=-1).mean() - intensity_mae = torch.mean(torch.abs(preds[..., 2] - targets[..., 2])) - metrics = { - "track_error": float(track_error.detach().cpu()), - "intensity_mae": float(intensity_mae.detach().cpu()), - } + task = config.benchmark.hazard_task + meta = data.metadata + lead_hours = list(meta.get("lead_hours") or []) + params = config.benchmark.params or {} + count = len(split.targets) + # Sampling models (TropiCycloneNet) draw noise: score with a fixed seed without touching the + # caller's random state. + with torch.random.fork_rng(devices=[]): + torch.manual_seed(int(params.get("seed", config.seed))) + outputs = _batched_model_outputs(model, split.inputs, count, params.get("batch_size"), meta.get("batch_dims") or {}) + + if task == "tc.intensity": + if isinstance(outputs, Mapping): + outputs = outputs["intensity"] + predictions = _apply_transform(torch.as_tensor(outputs).detach().cpu().double(), meta.get("prediction_transform")) + metrics = intensity_metrics(predictions, split.targets, lead_hours, (split.metadata or {}).get("groups")) + elif task == "tc.track_intensity": + variables = list(meta.get("target_variables") or ("lat", "lon", "wind")) + if not lead_hours: + raise ValueError("tc.track_intensity data needs metadata['lead_hours']") + target = _as_dict(split.targets, variables) + forecast = _as_dict(outputs, variables) + metrics = track_intensity_metrics(forecast, target, lead_hours, params.get("track_distance", "great_circle")) + else: + raise ValueError(f"TropicalCycloneBenchmark does not score hazard task {task!r}") + + data_units = meta.get("units") or {} + units = {"intensity_mae": data_units.get("wind"), "intensity_rmse": data_units.get("wind")} + if task == "tc.track_intensity": + units.update({"track_error_km": "km", "pressure_mae": data_units.get("pres")}) + units = {name: unit for name, unit in units.items() if unit} return BenchmarkResult( benchmark_name=self.name, - hazard_task=config.benchmark.hazard_task, - metrics=metrics, + hazard_task=task, + metrics={key: value for key, value in metrics.items() if not math.isnan(value)}, metadata={ "split": config.benchmark.eval_split, - "dataset_name": data.metadata.get("dataset"), - "source_dataset": data.metadata.get("source_dataset", data.metadata.get("dataset")), - "history": data.metadata.get("history"), - "horizon": data.feature_spec.extra.get("horizon") if data.feature_spec.extra else None, + "dataset_name": meta.get("dataset"), + "source_dataset": meta.get("source_dataset", meta.get("dataset")), + "lead_hours": lead_hours, + "units": units, + "track_distance": params.get("track_distance", "great_circle") if task == "tc.track_intensity" else None, + "synthetic": bool(meta.get("synthetic", False)), }, ) register_benchmark(TropicalCycloneBenchmark.name, TropicalCycloneBenchmark) -__all__ = ["TropicalCycloneBenchmark"] +__all__ = [ + "EARTH_RADIUS_KM", + "TropicalCycloneBenchmark", + "great_circle_distance_km", + "intensity_metrics", + "tcn_equirectangular_distance_km", + "track_intensity_metrics", +] diff --git a/pyhazards/benchmarks/wildfire.py b/pyhazards/benchmarks/wildfire.py index d487918b..9bb05d24 100644 --- a/pyhazards/benchmarks/wildfire.py +++ b/pyhazards/benchmarks/wildfire.py @@ -16,6 +16,10 @@ def _spread_metrics(logits: torch.Tensor, targets: torch.Tensor) -> Dict[str, float]: probs = torch.sigmoid(logits) + # Pixel-level average precision is the primary WildfireSpreadTS metric. + flat_targets = targets.detach().flatten().cpu().numpy() > 0.5 + flat_probs = probs.detach().flatten().cpu().numpy() + average_precision = float(average_precision_score(flat_targets, flat_probs)) if flat_targets.any() else 0.0 preds = (probs >= 0.5).float() targets = targets.float() intersection = (preds * targets).sum() @@ -25,7 +29,46 @@ def _spread_metrics(logits: torch.Tensor, targets: torch.Tensor) -> Dict[str, fl burned_area_mae = float( torch.mean(torch.abs(preds.flatten(1).sum(dim=1) - targets.flatten(1).sum(dim=1))).detach().cpu() ) - return {"iou": iou, "f1": f1, "burned_area_mae": burned_area_mae} + return { + "average_precision": average_precision, + "iou": iou, + "f1": f1, + "burned_area_mae": burned_area_mae, + } + + +def _binary_map_metrics(logits: torch.Tensor, targets: torch.Tensor) -> Dict[str, float]: + """Danger metrics for per-cell binary maps: one logit per cell, 0/1 targets of the same shape.""" + probs = torch.sigmoid(logits.detach().float()).flatten().cpu().numpy() + y_true = targets.detach().float().flatten().cpu().numpy() > 0.5 + y_pred = probs >= 0.5 + try: + auc = float(roc_auc_score(y_true, probs)) + except ValueError: + auc = 0.0 + pr_auc = float(average_precision_score(y_true, probs)) if y_true.any() else 0.0 + return { + "accuracy": float(accuracy_score(y_true, y_pred)), + "macro_f1": float(f1_score(y_true, y_pred, average="macro", labels=[False, True], zero_division=0)), + "auc": auc, + "pr_auc": pr_auc, + } + + +def _batched_forward(model: nn.Module, inputs: torch.Tensor, batch_size: int | None) -> torch.Tensor: + """Run ``model`` over ``inputs`` in chunks on the model's device and return CPU outputs.""" + parameter = next(model.parameters(), None) + device = parameter.device if parameter is not None else None + if not batch_size or batch_size >= len(inputs): + chunks = [inputs] + else: + chunks = list(torch.split(inputs, int(batch_size))) + outputs = [] + for chunk in chunks: + if device is not None and isinstance(chunk, torch.Tensor): + chunk = chunk.to(device) + outputs.append(model(chunk).detach().cpu()) + return outputs[0] if len(outputs) == 1 else torch.cat(outputs) def _danger_metrics(logits: torch.Tensor, targets: torch.Tensor) -> Dict[str, float]: @@ -66,17 +109,26 @@ class WildfireBenchmark(Benchmark): hazard_task = "wildfire.danger" metric_names_by_task = { "wildfire.danger": ["accuracy", "macro_f1", "auc", "pr_auc", "mae", "rmse"], - "wildfire.spread": ["iou", "f1", "burned_area_mae"], + "wildfire.spread": ["average_precision", "iou", "f1", "burned_area_mae"], } def evaluate(self, model: nn.Module, data: DataBundle, config: ExperimentConfig) -> BenchmarkResult: split = data.get_split(config.benchmark.eval_split) x = split.inputs y = split.targets - logits = model(x) + logits = _batched_forward(model, x, config.benchmark.params.get("batch_size")) if config.benchmark.hazard_task == "wildfire.danger": - metrics = _danger_metrics(logits, y) + if data.label_spec.task_type == "segmentation": + # Danger maps (e.g. the Track-O raster and temporal layouts): one logit per cell. + if tuple(logits.shape) != tuple(y.shape): + raise ValueError( + "wildfire.danger maps need logits with the target shape (one logit per cell): " + f"got logits of shape {tuple(logits.shape)} for targets of shape {tuple(y.shape)}." + ) + metrics = _binary_map_metrics(logits, y) + else: + metrics = _danger_metrics(logits, y) else: metrics = _spread_metrics(logits, y) diff --git a/pyhazards/configs/earthquake/eqnet_smoke.yaml b/pyhazards/configs/earthquake/eqnet_smoke.yaml index 7c23b438..00d0e95c 100644 --- a/pyhazards/configs/earthquake/eqnet_smoke.yaml +++ b/pyhazards/configs/earthquake/eqnet_smoke.yaml @@ -1,21 +1,28 @@ +# EQNet (randomly initialised) used as a single-station picker: backbone + P / S picking heads on synthetic +# windows (not real data), scored like the paper's STEAD benchmark (Table 1: a pick is a true positive within +# 0.5 s of the manual pick, the "eqtransformer" protocol). The multi-station shift-and-stack / event detection +# path takes station gathers and travel times (see the model card) and has no benchmark task yet. benchmark: name: earthquake hazard_task: earthquake.picking metrics: + - p_f1 + - s_f1 - p_pick_mae - s_pick_mae - - f1 eval_split: test + params: + protocol: eqtransformer dataset: - name: seisbench_waveforms + name: earthquake_waveforms_synthetic params: micro: true + length: 3072 model: name: eqnet - task: regression + task: picking params: in_channels: 3 - hidden_dim: 48 report: output_dir: reports/earthquake_eqnet formats: diff --git a/pyhazards/configs/earthquake/eqtransformer_smoke.yaml b/pyhazards/configs/earthquake/eqtransformer_smoke.yaml index 3e6e5ace..959de8fc 100644 --- a/pyhazards/configs/earthquake/eqtransformer_smoke.yaml +++ b/pyhazards/configs/earthquake/eqtransformer_smoke.yaml @@ -1,21 +1,26 @@ +# EQTransformer (paper model, randomly initialised) on synthetic 60-s windows, scored with the +# EQTransformer protocol (Mousavi et al. 2020: TP if |dt| < 0.5 s) plus detection metrics. benchmark: name: earthquake hazard_task: earthquake.picking metrics: + - p_f1 + - s_f1 - p_pick_mae - s_pick_mae - - f1 + - detection_f1 eval_split: test + params: + protocol: eqtransformer dataset: - name: pick_benchmark_waveforms + name: earthquake_waveforms_synthetic params: micro: true model: name: eqtransformer - task: regression + task: picking params: in_channels: 3 - hidden_dim: 48 report: output_dir: reports/earthquake_eqtransformer formats: diff --git a/pyhazards/configs/earthquake/gpd_smoke.yaml b/pyhazards/configs/earthquake/gpd_smoke.yaml index e164ccd0..fc519438 100644 --- a/pyhazards/configs/earthquake/gpd_smoke.yaml +++ b/pyhazards/configs/earthquake/gpd_smoke.yaml @@ -1,21 +1,25 @@ +# GPD (randomly initialised) slid over synthetic windows (stride 10 samples), scored with the +# EQTransformer protocol (TP if |dt| < 0.5 s), under which Mousavi et al. (2020) compared GPD. benchmark: name: earthquake hazard_task: earthquake.picking metrics: + - p_f1 + - s_f1 - p_pick_mae - s_pick_mae - - f1 eval_split: test + params: + protocol: eqtransformer dataset: - name: pick_benchmark_waveforms + name: earthquake_waveforms_synthetic params: micro: true model: name: gpd - task: regression + task: picking params: in_channels: 3 - hidden_dim: 32 report: output_dir: reports/earthquake_gpd formats: diff --git a/pyhazards/configs/earthquake/phasenet_smoke.yaml b/pyhazards/configs/earthquake/phasenet_smoke.yaml index 8f0033fd..1a345c78 100644 --- a/pyhazards/configs/earthquake/phasenet_smoke.yaml +++ b/pyhazards/configs/earthquake/phasenet_smoke.yaml @@ -1,20 +1,28 @@ +# PhaseNet (randomly initialised) on synthetic windows, scored with the PhaseNet protocol +# (Zhu & Beroza 2019: TP if |dt| < 0.1 s). Add `pretrained: original` under model.params for the +# official weights, and a real dataset (seisbench_waveforms) for meaningful numbers. benchmark: name: earthquake hazard_task: earthquake.picking metrics: + - p_precision + - p_recall + - p_f1 + - s_f1 - p_pick_mae - s_pick_mae eval_split: test + params: + protocol: phasenet dataset: - name: seisbench_waveforms + name: earthquake_waveforms_synthetic params: micro: true model: name: phasenet - task: regression + task: picking params: in_channels: 3 - hidden_dim: 32 report: output_dir: reports/earthquake formats: diff --git a/pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml b/pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml index d451ba59..a1be1904 100644 --- a/pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml +++ b/pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml @@ -1,26 +1,30 @@ +# WaveCastNet (dense, randomly initialised) on synthetic point-source wavefields (not real data): a 32 x 24 +# grid, 6 input frames and 6 forecast frames, produced by two rolling calls of 3 frames like the official +# validation forecast. Scored with the official ACC / RFNE / RMSE per (sequence, channel). benchmark: name: earthquake hazard_task: earthquake.forecasting metrics: - - mae - - mse + - acc + - rfne + - rmse eval_split: test + params: + seed: 0 + rollout_step: 3 dataset: - name: aefa_forecast + name: earthquake_wavefield_synthetic params: micro: true model: name: wavecastnet - task: regression + task: forecasting params: + variant: dense in_channels: 3 - height: 12 - width: 10 - temporal_in: 5 - temporal_out: 4 - hidden_dim: 16 - num_layers: 1 - dropout: 0.0 + height: 32 + width: 24 + future_seq: 3 report: output_dir: reports/earthquake_forecasting formats: diff --git a/pyhazards/configs/flood/floodcast_smoke.yaml b/pyhazards/configs/flood/floodcast_smoke.yaml index 3808baa3..df3d6324 100644 --- a/pyhazards/configs/flood/floodcast_smoke.yaml +++ b/pyhazards/configs/flood/floodcast_smoke.yaml @@ -7,7 +7,7 @@ benchmark: - f1 eval_split: test dataset: - name: floodcastbench_inundation + name: flood_inundation_synthetic params: micro: true model: diff --git a/pyhazards/configs/flood/google_flood_forecasting_smoke.yaml b/pyhazards/configs/flood/google_flood_forecasting_smoke.yaml index 6382f25e..0a24e2a2 100644 --- a/pyhazards/configs/flood/google_flood_forecasting_smoke.yaml +++ b/pyhazards/configs/flood/google_flood_forecasting_smoke.yaml @@ -1,25 +1,25 @@ +# Google's MeanEmbeddingForecastLSTM in the PyHazards streamflow layout (config "streamflow": one shared +# input group, lead_time 0, smaller hidden size) on synthetic basins, scored by the CMAL mixture mean. benchmark: name: flood hazard_task: flood.streamflow metrics: - - mae - - rmse - nse - kge eval_split: test dataset: - name: caravan_streamflow + name: flood_streamflow_synthetic params: micro: true model: name: google_flood_forecasting task: regression params: - input_dim: 2 - hidden_dim: 32 - out_dim: 1 - history: 4 - dropout: 0.0 + config: streamflow + n_dynamic: 5 + n_static: 27 + seq_length: 30 + hidden_size: 64 report: output_dir: reports/google_flood_forecasting formats: diff --git a/pyhazards/configs/flood/hydrographnet_smoke.yaml b/pyhazards/configs/flood/hydrographnet_smoke.yaml index 7c09e9bd..bd5ebfbe 100644 --- a/pyhazards/configs/flood/hydrographnet_smoke.yaml +++ b/pyhazards/configs/flood/hydrographnet_smoke.yaml @@ -1,25 +1,26 @@ +# HydroGraphNet (PhysicsNeMo MeshGraphKAN, 2,318,722 parameters) rolled out autoregressively over synthetic +# mesh hydrographs in the White River layout and scored in metres. Real data: dataset hydrographnet_white_river +# with params {data_dir, test_ids} (rollout_length 30, as in the HydroGraphNet example). benchmark: name: flood - hazard_task: flood.streamflow + hazard_task: flood.inundation metrics: - - mae + - rollout_rmse + - pixel_mae - rmse + - csi_10cm - nse - - kge eval_split: test dataset: - name: hydrobench_streamflow + name: flood_mesh_synthetic params: micro: true model: name: hydrographnet task: regression - params: - node_in_dim: 2 - edge_in_dim: 3 - out_dim: 1 + params: {} report: - output_dir: reports/flood + output_dir: reports/flood_hydrographnet formats: - json seed: 7 diff --git a/pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml b/pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml index 92f4d589..6de21477 100644 --- a/pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml +++ b/pyhazards/configs/flood/neuralhydrology_ealstm_smoke.yaml @@ -1,23 +1,28 @@ +# Kratzert et al. (2019) EA-LSTM (5 forcings, 27 attributes in the input gate, hidden 256) on synthetic basins. +# Real data: dataset camels_us_streamflow with params {data_dir, basins} (paper periods and 270-day windows). benchmark: name: flood hazard_task: flood.streamflow metrics: - - mae - - rmse - nse - kge + - alpha_nse + - beta_nse + - fhv + - fms + - flv eval_split: test dataset: - name: waterbench_streamflow + name: flood_streamflow_synthetic params: micro: true model: name: neuralhydrology_ealstm task: regression params: - input_dim: 2 - hidden_dim: 64 - out_dim: 1 + n_dynamic: 5 + n_static: 27 + hidden_size: 256 report: output_dir: reports/flood_neuralhydrology_ealstm formats: diff --git a/pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml b/pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml index 50085133..ba741201 100644 --- a/pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml +++ b/pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml @@ -1,23 +1,28 @@ +# Kratzert et al. (2019) LSTM with static inputs (5 forcings + 27 attributes, hidden 256) on synthetic basins. +# Real data: dataset camels_us_streamflow with params {data_dir, basins} (paper periods and 270-day windows). benchmark: name: flood hazard_task: flood.streamflow metrics: - - mae - - rmse - nse - kge + - alpha_nse + - beta_nse + - fhv + - fms + - flv eval_split: test dataset: - name: caravan_streamflow + name: flood_streamflow_synthetic params: micro: true model: name: neuralhydrology_lstm task: regression params: - input_dim: 2 - hidden_dim: 64 - out_dim: 1 + n_dynamic: 5 + n_static: 27 + hidden_size: 256 report: output_dir: reports/flood_neuralhydrology_lstm formats: diff --git a/pyhazards/configs/flood/urbanfloodcast_smoke.yaml b/pyhazards/configs/flood/urbanfloodcast_smoke.yaml index 48bfe4f6..63f059dc 100644 --- a/pyhazards/configs/flood/urbanfloodcast_smoke.yaml +++ b/pyhazards/configs/flood/urbanfloodcast_smoke.yaml @@ -1,22 +1,28 @@ +# UrbanFloodCast deep neural operator (DNO-3, 4,470,437 parameters): 24 future steps of depth and unit +# discharge at once on synthetic events in the UrbanFloodCast one-shot layout, scored with relative L2, +# NSE, Pearson r and depth CSI as in the official evaluation. benchmark: name: flood hazard_task: flood.inundation metrics: + - relative_l2 + - nse + - pearson_r + - csi_1cm + - csi_10cm + - csi_50cm - pixel_mae - - iou - - f1 eval_split: test + params: + batch_size: 1 dataset: - name: floodcastbench_inundation + name: urbanfloodcast_synthetic params: micro: true model: name: urbanfloodcast task: regression - params: - in_channels: 3 - history: 4 - base_channels: 32 + params: {} report: output_dir: reports/flood_urbanfloodcast formats: diff --git a/pyhazards/configs/tc/fourcastnet_tc_smoke.yaml b/pyhazards/configs/tc/fourcastnet_tc_smoke.yaml deleted file mode 100644 index 8f9967cb..00000000 --- a/pyhazards/configs/tc/fourcastnet_tc_smoke.yaml +++ /dev/null @@ -1,25 +0,0 @@ -benchmark: - name: tc - hazard_task: tc.track_intensity - metrics: - - track_error - - intensity_mae - eval_split: test -dataset: - name: ibtracs_tracks - params: - micro: true -model: - name: fourcastnet_tc - task: regression - params: - input_dim: 8 - history: 6 - hidden_dim: 96 - horizon: 5 - output_dim: 3 -report: - output_dir: reports/fourcastnet_tc - formats: - - json -seed: 7 diff --git a/pyhazards/configs/tc/graphcast_tc_smoke.yaml b/pyhazards/configs/tc/graphcast_tc_smoke.yaml deleted file mode 100644 index 764379c4..00000000 --- a/pyhazards/configs/tc/graphcast_tc_smoke.yaml +++ /dev/null @@ -1,24 +0,0 @@ -benchmark: - name: tc - hazard_task: tc.track_intensity - metrics: - - track_error - - intensity_mae - eval_split: test -dataset: - name: ibtracs_tracks - params: - micro: true -model: - name: graphcast_tc - task: regression - params: - input_dim: 8 - hidden_dim: 96 - horizon: 5 - output_dim: 3 -report: - output_dir: reports/graphcast_tc - formats: - - json -seed: 7 diff --git a/pyhazards/configs/tc/hurricast_smoke.yaml b/pyhazards/configs/tc/hurricast_smoke.yaml index 326b6dec..d0750ad8 100644 --- a/pyhazards/configs/tc/hurricast_smoke.yaml +++ b/pyhazards/configs/tc/hurricast_smoke.yaml @@ -1,25 +1,25 @@ +# Smoke run of Hurricast's encoder-decoder head on random inputs in the hurricast_ibtracs_era5 layout. The full +# model (XGBoost on the embeddings) must be fitted first (Hurricast.fit); scores on synthetic data mean nothing. benchmark: name: tc - hazard_task: tc.track_intensity + hazard_task: tc.intensity metrics: - - track_error - intensity_mae + - intensity_rmse + - intensity_mae_group_mean eval_split: test dataset: - name: ibtracs_tracks + name: hurricast_synthetic params: micro: true model: name: hurricast task: regression params: - input_dim: 8 - hidden_dim: 64 - num_layers: 2 - horizon: 5 - output_dim: 3 + target: intensity + predictor: network report: - output_dir: reports/tc + output_dir: reports/hurricast formats: - json seed: 7 diff --git a/pyhazards/configs/tc/pangu_tc_smoke.yaml b/pyhazards/configs/tc/pangu_tc_smoke.yaml deleted file mode 100644 index 43c1309b..00000000 --- a/pyhazards/configs/tc/pangu_tc_smoke.yaml +++ /dev/null @@ -1,24 +0,0 @@ -benchmark: - name: tc - hazard_task: tc.track_intensity - metrics: - - track_error - - intensity_mae - eval_split: test -dataset: - name: ibtracs_tracks - params: - micro: true -model: - name: pangu_tc - task: regression - params: - input_dim: 8 - hidden_dim: 96 - horizon: 5 - output_dim: 3 -report: - output_dir: reports/pangu_tc - formats: - - json -seed: 7 diff --git a/pyhazards/configs/tc/saf_net_smoke.yaml b/pyhazards/configs/tc/saf_net_smoke.yaml index 5ccc8cca..a7725e15 100644 --- a/pyhazards/configs/tc/saf_net_smoke.yaml +++ b/pyhazards/configs/tc/saf_net_smoke.yaml @@ -1,21 +1,18 @@ benchmark: name: tc - hazard_task: tc.track_intensity + hazard_task: tc.intensity metrics: - - track_error - intensity_mae + - intensity_rmse + - intensity_mae_group_mean eval_split: test dataset: - name: tcbench_alpha + name: safnet_cma_era_interim_synthetic params: micro: true model: name: saf_net task: regression - params: - input_dim: 8 - hidden_dim: 64 - horizon: 5 report: output_dir: reports/saf_net formats: diff --git a/pyhazards/configs/tc/tcif_fusion_smoke.yaml b/pyhazards/configs/tc/tcif_fusion_smoke.yaml index fd220a20..720b3916 100644 --- a/pyhazards/configs/tc/tcif_fusion_smoke.yaml +++ b/pyhazards/configs/tc/tcif_fusion_smoke.yaml @@ -1,22 +1,28 @@ +# Smoke run of a reduced TCIF-fusion (same graph, small grids and widths) on random inputs in its layout; the +# paper's model has 25 x 25 ERA5 grids, 224 x 224 IR images and about 300 M parameters. benchmark: name: tc - hazard_task: tc.track_intensity + hazard_task: tc.intensity metrics: - - track_error - intensity_mae + - intensity_rmse + - intensity_mae_group_mean eval_split: test dataset: - name: tcbench_alpha + name: tcif_fusion_synthetic params: micro: true + grid_size: 9 + ir_size: 32 model: name: tcif_fusion task: regression params: - input_dim: 8 - hidden_dim: 64 - horizon: 5 - output_dim: 3 + grid_size: 9 + ir_size: 32 + widths: [4, 8, 8] + vgg_filters: [4, 4, 8, 8, 8] + vgg_fc: 16 report: output_dir: reports/tcif_fusion formats: diff --git a/pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml b/pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml index 1f9e3bdc..953da2e3 100644 --- a/pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml +++ b/pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml @@ -1,24 +1,22 @@ benchmark: name: tc - hazard_task: tc.track_intensity + hazard_task: tc.intensity metrics: - - track_error - intensity_mae + - intensity_rmse + - intensity_mae_group_mean eval_split: test dataset: - name: tcbench_alpha + name: ships_xu2021_synthetic params: micro: true model: name: tropicalcyclone_mlp task: regression params: - input_dim: 8 - history: 6 - horizon: 5 - output_dim: 3 + input_dim: 121 report: - output_dir: reports/tc_mlp + output_dir: reports/tropicalcyclone_mlp formats: - json seed: 7 diff --git a/pyhazards/configs/tc/tropicyclonenet_smoke.yaml b/pyhazards/configs/tc/tropicyclonenet_smoke.yaml index f42d2155..dc493b1b 100644 --- a/pyhazards/configs/tc/tropicyclonenet_smoke.yaml +++ b/pyhazards/configs/tc/tropicyclonenet_smoke.yaml @@ -2,21 +2,20 @@ benchmark: name: tc hazard_task: tc.track_intensity metrics: - - track_error + - track_error_km - intensity_mae + - pressure_mae + - best_of_k_track_error_km + - best_of_k_intensity_mae + - best_of_k_pressure_mae eval_split: test dataset: - name: tropicyclonenet_dataset + name: tropicyclonenet_dataset_synthetic params: micro: true model: name: tropicyclonenet task: regression - params: - input_dim: 8 - hidden_dim: 64 - horizon: 5 - output_dim: 3 report: output_dir: reports/tropicyclonenet formats: diff --git a/pyhazards/configs/wildfire/asufm_smoke.yaml b/pyhazards/configs/wildfire/asufm_smoke.yaml index 9493c2ff..5907459b 100644 --- a/pyhazards/configs/wildfire/asufm_smoke.yaml +++ b/pyhazards/configs/wildfire/asufm_smoke.yaml @@ -1,25 +1,23 @@ benchmark: name: wildfire - hazard_task: wildfire.danger + hazard_task: wildfire.spread metrics: - - mae - - rmse + - iou + - f1 + - burned_area_mae eval_split: test dataset: - name: fpa_fod_weekly + name: wildfire_spread_synthetic params: micro: true - lookback_weeks: 12 - features: counts+time + channels: 6 + height: 64 + width: 64 model: name: asufm - task: forecasting + task: segmentation params: - input_dim: 7 - hidden_dim: 32 - output_dim: 5 - lookback: 12 - dropout: 0.0 + in_channels: 6 report: output_dir: reports/asufm formats: diff --git a/pyhazards/configs/wildfire/firecastnet_smoke.yaml b/pyhazards/configs/wildfire/firecastnet_smoke.yaml index 6e91d22f..c303c932 100644 --- a/pyhazards/configs/wildfire/firecastnet_smoke.yaml +++ b/pyhazards/configs/wildfire/firecastnet_smoke.yaml @@ -1,3 +1,6 @@ +# FireCastNet smoke run on synthetic rasters. The real model forecasts burned-area presence on the +# global 0.25-degree SeasFire grid (24 x 11 x 720 x 1440 inputs); here a tiny global grid +# (2.5 degree, 72 x 144) with icosphere levels 0-2 stands in, scored with the spread-mask metrics. benchmark: name: wildfire hazard_task: wildfire.spread @@ -7,15 +10,28 @@ benchmark: - burned_area_mae eval_split: test dataset: - name: wildfire_spread_synthetic + name: wildfire_spread_temporal_synthetic params: micro: true + history: 4 + channels: 6 + height: 72 + width: 144 model: name: firecastnet task: segmentation params: - in_channels: 12 - hidden_dim: 24 + in_channels: 6 + timeseries_len: 4 + mesh_levels: [0, 1, 2] + sp_res: 2.5 + max_lat: 88.75 + min_lat: -88.75 + max_lon: 178.75 + min_lon: -178.75 + hidden_dim: 32 + embed_cube_dim: 32 + processor_layers: 4 report: output_dir: reports/firecastnet formats: diff --git a/pyhazards/configs/wildfire/forefire_smoke.yaml b/pyhazards/configs/wildfire/forefire_smoke.yaml deleted file mode 100644 index e821e666..00000000 --- a/pyhazards/configs/wildfire/forefire_smoke.yaml +++ /dev/null @@ -1,23 +0,0 @@ -benchmark: - name: wildfire - hazard_task: wildfire.spread - metrics: - - iou - - f1 - - burned_area_mae - eval_split: test -dataset: - name: wildfire_spread_synthetic - params: - micro: true -model: - name: forefire - task: segmentation - params: - in_channels: 12 - diffusion_steps: 2 -report: - output_dir: reports/forefire - formats: - - json -seed: 7 diff --git a/pyhazards/configs/wildfire/track_o_convlstm_smoke.yaml b/pyhazards/configs/wildfire/track_o_convlstm_smoke.yaml new file mode 100644 index 00000000..f0635a8a --- /dev/null +++ b/pyhazards/configs/wildfire/track_o_convlstm_smoke.yaml @@ -0,0 +1,25 @@ +benchmark: + name: wildfire + hazard_task: wildfire.danger + metrics: + - accuracy + - macro_f1 + - auc + - pr_auc + eval_split: test +dataset: + name: wildfire_track_o_temporal + params: + micro: true + history: 6 +model: + name: convlstm + task: segmentation + params: + in_channels: 5 + hidden_dim: 16 +report: + output_dir: reports/track_o_convlstm + formats: + - json +seed: 7 diff --git a/pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml b/pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml index cf05783d..8556b14d 100644 --- a/pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml +++ b/pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml @@ -2,25 +2,24 @@ benchmark: name: wildfire hazard_task: wildfire.danger metrics: - - mae - - rmse + - accuracy + - macro_f1 + - auc + - pr_auc eval_split: test dataset: - name: fpa_fod_weekly + name: wildfire_danger_synthetic params: micro: true - lookback_weeks: 12 - features: counts+time + access_mode: temporal + history: 10 + channels: 25 model: name: wildfire_forecasting - task: forecasting + task: classification params: - input_dim: 7 - hidden_dim: 32 - output_dim: 5 - lookback: 12 - num_layers: 2 - dropout: 0.0 + variant: lstm + input_dim: 25 report: output_dir: reports/wildfire_forecasting formats: diff --git a/pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml b/pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml index df156b66..09159847 100644 --- a/pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml +++ b/pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml @@ -2,6 +2,7 @@ benchmark: name: wildfire hazard_task: wildfire.spread metrics: + - average_precision - iou - f1 - burned_area_mae @@ -14,9 +15,9 @@ model: name: wildfirespreadts task: segmentation params: + baseline: utae history: 4 in_channels: 6 - hidden_dim: 24 report: output_dir: reports/wildfirespreadts formats: diff --git a/pyhazards/configs/wildfire/wrf_sfire_smoke.yaml b/pyhazards/configs/wildfire/wrf_sfire_smoke.yaml deleted file mode 100644 index cd33e5c6..00000000 --- a/pyhazards/configs/wildfire/wrf_sfire_smoke.yaml +++ /dev/null @@ -1,23 +0,0 @@ -benchmark: - name: wildfire - hazard_task: wildfire.spread - metrics: - - iou - - f1 - - burned_area_mae - eval_split: test -dataset: - name: wildfire_spread_synthetic - params: - micro: true -model: - name: wrf_sfire - task: segmentation - params: - in_channels: 12 - diffusion_steps: 3 -report: - output_dir: reports/wrf_sfire - formats: - - json -seed: 7 diff --git a/pyhazards/dataset_cards/aefa_forecast.yaml b/pyhazards/dataset_cards/aefa_forecast.yaml deleted file mode 100644 index 66b0fd7e..00000000 --- a/pyhazards/dataset_cards/aefa_forecast.yaml +++ /dev/null @@ -1,56 +0,0 @@ -slug: aefa_forecast -display_name: AEFA Forecast -hazard_family: Earthquake -source_role: Forecast Benchmark -summary: Synthetic-backed dense-grid forecasting adapter aligned to the AEFA earthquake forecasting workflow. -provider: AEFA forecasting ecosystem surfaced through a PyHazards adapter -geometry: Dense-grid wavefield tensors -spatial_resolution: Benchmark-defined dense sensor grid -temporal_resolution: Short history and forecast windows -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned earthquake forecasting samples -formats: PyTorch tensors via the dataset registry -overview: - - AEFA Forecast is the public forecasting adapter used by the earthquake benchmark when exercising dense-grid wavefield forecasting models. - - The current implementation is synthetic-backed, but it preserves the task shape, tensor layout, and reporting surface used by the shared earthquake evaluator. -data_characteristics: - - Multichannel dense-grid history tensors paired with future dense-grid targets. - - Registry-backed benchmark adapter rather than a raw external archive loader. - - Intended for forecasting-path validation and report generation. -typical_use_cases: - - Smoke tests for WaveCastNet-style earthquake forecasting. - - Shared forecasting benchmark runs under the earthquake evaluator. - - Validation of report exports aligned to the forecasting path. -access_links: - - label: AEFA repository - url: https://github.com/chenyk1990/aefa -inspection: null -registry: - name: aefa_forecast - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "aefa_forecast", - micro=True, - temporal_in=5, - temporal_out=4, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) - notes: - - micro=True keeps the synthetic-backed forecasting path lightweight for validation. -primary_references: - - citation: AEFA - url: https://github.com/chenyk1990/aefa -pyhazards_usage: - - Use this adapter when you want the public earthquake forecasting benchmark surface rather than the private synthetic dataset name. -related_models: - - wavecastnet -related_benchmarks: - - earthquake_benchmark - - aefa -notes: - - This is a benchmark adapter, not a full external AEFA ingestion pipeline. diff --git a/pyhazards/dataset_cards/camels_us_streamflow.yaml b/pyhazards/dataset_cards/camels_us_streamflow.yaml new file mode 100644 index 00000000..4db90e9f --- /dev/null +++ b/pyhazards/dataset_cards/camels_us_streamflow.yaml @@ -0,0 +1,70 @@ +slug: camels_us_streamflow +display_name: CAMELS-US +hazard_family: Flood +source_role: Streamflow Benchmark +summary: Reader for a local copy of CAMELS-US (671 US catchments, daily forcings, USGS streamflow and catchment attributes) in the setup of Kratzert et al. (2019), as NeuralHydrology reads it. +provider: NCAR / USGS CAMELS data set (Newman et al. 2015; Addor et al. 2017), read by PyHazards from a local copy +geometry: Daily basin time series with static attributes +spatial_resolution: Catchment averages (one series per gauge) +temporal_resolution: Daily +update_cadence: Static research dataset (extended Maurer forcings released separately in 2019) +period_of_record: 1980-2014 +coverage: 671 catchments in the contiguous United States (531 in the Kratzert et al. 2019 benchmark) +formats: Whitespace-separated forcing and streamflow text files; ';'-separated attribute tables +overview: + - > + CAMELS-US provides basin-averaged daily meteorological forcings (Daymet, Maurer, NLDAS), USGS + streamflow and catchment attributes (Newman et al., HESS 2015; Addor et al., HESS 2017; CC BY 4.0, Zenodo 15529996). Kratzert et al. + (HESS 2019) used 531 of its basins with the extended Maurer forcings (daily minimum and maximum + temperature added; HydroShare, doi 10.4211/hs.17c896843cf940339c3c3496d0c1c077) and 27 attributes, + the standard benchmark for the NeuralHydrology models. + - > + ``camels_us_streamflow`` reads that layout like NeuralHydrology's ``CamelsUS`` dataset (discharge from + cubic feet per second to mm/day with the area of the forcing-file header, negative values to NaN) and + builds streamflow samples. Defaults are the paper's: forcings ``maurer_extended``, inputs prcp, srad, + tmax, tmin, vp, the 27 attributes, 270-day windows, train 1999-10-01 to 2008-09-30 and test + 1989-10-01 to 1999-09-30 (validation 1980-10-01 to 1989-09-30, from NeuralHydrology's example + configuration). PyHazards downloads nothing. +data_characteristics: + - "Layout: ``basin_mean_forcing//[/]_*_forcing_leap.txt``, ``usgs_streamflow/[/]_streamflow_qc.txt``, ``camels_attributes_v2.0/camels_*.txt``." + - Target ``QObs(mm/d)``; with several forcing products the input columns get a ``_`` suffix. + - Normalisation and sample selection as for Caravan (training statistics; training samples with missing inputs or targets dropped; every evaluation day kept). +typical_use_cases: + - Reproducing the Kratzert et al. (2019) LSTM and EA-LSTM benchmark. + - Per-basin NSE / KGE / FHV / FMS / FLV evaluation with the flood benchmark (``flood.streamflow``). +access_links: + - label: CAMELS (NCAR RAL) + url: https://ral.ucar.edu/solutions/products/camels + - label: CAMELS time series and attributes (Zenodo) + url: https://zenodo.org/records/15529996 + - label: Extended Maurer forcings (HydroShare) + url: https://www.hydroshare.org/resource/17c896843cf940339c3c3496d0c1c077 + - label: NeuralHydrology data prerequisites + url: https://neuralhydrology.readthedocs.io/en/latest/tutorials/data-prerequisites.html +inspection: null +registry: + name: camels_us_streamflow + example: | + from pyhazards.datasets import load_dataset + + # The 531 basins of Kratzert et al. (2019), e.g. NeuralHydrology's 531_basin_list.txt. + data = load_dataset("camels_us_streamflow", data_dir="/data/CAMELS_US", basins="531_basin_list.txt").load() + inputs, y = data.get_split("test").inputs[0] + print(inputs["x_d"].shape, inputs["x_s"].shape, y.shape) # (270, 5) (27,) (270, 1) +primary_references: + - citation: "Addor, Newman, Mizukami and Clark (2017). The CAMELS data set: catchment attributes and meteorology for large-sample studies. HESS 21:5293-5313." + url: https://doi.org/10.5194/hess-21-5293-2017 + - citation: "Kratzert et al. (2019). Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets. HESS 23:5089-5110." + url: https://doi.org/10.5194/hess-23-5089-2019 + repo_url: https://github.com/kratzert/ealstm_regional_modeling +pyhazards_usage: + - Point ``data_dir`` at the CAMELS-US root (with ``basin_mean_forcing/maurer_extended`` added) and pass the basin list. + - Score models with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.streamflow``). +related_models: + - neuralhydrology_lstm + - neuralhydrology_ealstm +related_benchmarks: + - flood_benchmark + - camels_us +notes: + - The reader, scaler and samples are checked against NeuralHydrology's CamelsUS dataset on the real CAMELS-US test basins shipped with NeuralHydrology (oracle test), and the whole evaluation against NeuralHydrology's Tester. diff --git a/pyhazards/dataset_cards/caravan_streamflow.yaml b/pyhazards/dataset_cards/caravan_streamflow.yaml index 39709664..ab122552 100644 --- a/pyhazards/dataset_cards/caravan_streamflow.yaml +++ b/pyhazards/dataset_cards/caravan_streamflow.yaml @@ -2,31 +2,42 @@ slug: caravan_streamflow display_name: Caravan hazard_family: Flood source_role: Streamflow Benchmark -summary: Synthetic-backed streamflow benchmark adapter aligned to the Caravan large-sample hydrology ecosystem. -provider: Caravan community dataset surfaced through a PyHazards adapter -geometry: Graph-temporal basin or node sequences -spatial_resolution: Basin or gauge nodes represented as graph elements -temporal_resolution: Rolling history windows for streamflow prediction -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned streamflow forecasting samples -formats: PyTorch graph-temporal dataset objects via the dataset registry +summary: Reader for a local copy of Caravan, the global large-sample hydrology dataset (daily ERA5-Land forcings, catchment attributes and observed streamflow), in NeuralHydrology's sample layout. +provider: Caravan community dataset (Kratzert et al. 2023), read by PyHazards from a local copy +geometry: Daily basin time series with static attributes +spatial_resolution: Catchment averages (one series per gauge) +temporal_resolution: Daily +update_cadence: Versioned Zenodo releases (netCDF and CSV editions) plus community extensions +period_of_record: 1981-2020 in the original release (later versions extend it) +coverage: 6,830 catchments in the original release (Australia, Brazil, Canada, Chile, Great Britain, Central Europe, United States) plus extensions +formats: Per-basin netCDF or CSV time series; per-source attribute CSV files overview: - - Caravan is the public flood streamflow adapter used to align PyHazards with a large-sample hydrology benchmark surface. - - The current implementation is synthetic-backed, but it preserves the streamflow forecasting contract used by the shared flood benchmark. + - > + Caravan (Kratzert et al., Scientific Data 10:61, 2023) harmonises the CAMELS-style datasets of several + countries: every basin has daily ERA5-Land forcings and states (precipitation, temperature, radiation, + pressure, wind, soil water, evaporation, ...) aggregated over the catchment in local time, observed + streamflow in mm/day, and HydroATLAS / ERA5-Land climate attributes. The Zenodo records are licensed + CC BY 4.0, with per-source licence notes in the dataset's ``licenses/`` folder. + - > + ``caravan_streamflow`` reads that layout (as NeuralHydrology's ``Caravan`` dataset does) and builds + streamflow samples: ``seq_length``-day windows of the chosen dynamic inputs ``x_d``, the basin's static + attributes ``x_s`` and the discharge series ``y``, normalised with training-period statistics, split + into the train / val / test periods you pass. PyHazards downloads nothing. data_characteristics: - - Graph-temporal sequences with node-level targets for next-step streamflow prediction. - - Registry-backed benchmark adapter instead of a raw Caravan ingestion pipeline. - - Supports the public streamflow smoke path for NeuralHydrology LSTM and Google Flood Forecasting. + - "Layout: ``attributes//attributes_{caravan,hydroatlas,other}_.csv`` (column ``gauge_id``) and ``timeseries/{netcdf,csv}//_.{nc,csv}``; basin ids are ``_``." + - Inputs and target are standardised with the mean and population standard deviation over all training basins and days; static attributes with their mean and standard deviation over the training basins, sorted alphabetically (NeuralHydrology's order). + - Training samples with a missing input in the window or a missing target on the last day are dropped; validation and test keep one sample per basin and day so that metrics cover the whole period. + - Caravan publishes no single input set or split, so ``dynamic_inputs`` and ``periods`` are required. typical_use_cases: - - Streamflow smoke tests for benchmark-linked flood models. - - Shared flood benchmark runs with streamflow metrics such as NSE and KGE. - - Regression checks for graph-temporal basin workflows. + - Regional or global LSTM streamflow models (``neuralhydrology_lstm``, ``neuralhydrology_ealstm``, ``google_flood_forecasting``). + - Per-basin NSE / KGE evaluation with the flood benchmark (``flood.streamflow``). access_links: - - label: Caravan paper - url: https://www.nature.com/articles/s41597-023-01975-w + - label: Caravan paper (Scientific Data 2023) + url: https://doi.org/10.1038/s41597-023-01975-w - label: Caravan repository url: https://github.com/kratzert/Caravan + - label: Caravan netCDF release (Zenodo) + url: https://doi.org/10.5281/zenodo.6522634 inspection: null registry: name: caravan_streamflow @@ -35,24 +46,29 @@ registry: data = load_dataset( "caravan_streamflow", - micro=True, - history=4, - nodes=6, + data_dir="/data/Caravan", + basins=["camelsgb_28015", "lamah_215"], + dynamic_inputs=["total_precipitation_sum", "temperature_2m_mean", "potential_evaporation_sum"], + static_attributes=["p_mean", "aridity", "area"], + periods={"train": ("1981-10-01", "1990-09-30"), "test": ("2000-10-01", "2010-09-30")}, # your split + seq_length=365, ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) + inputs, y = data.get_split("test").inputs[0] + print(inputs["x_d"].shape, inputs["x_s"].shape, y.shape) primary_references: - - citation: Caravan - A global community dataset for large-sample hydrology - url: https://www.nature.com/articles/s41597-023-01975-w + - citation: "Kratzert et al. (2023). Caravan - A global community dataset for large-sample hydrology. Scientific Data 10:61." + url: https://doi.org/10.1038/s41597-023-01975-w repo_url: https://github.com/kratzert/Caravan pyhazards_usage: - - Use this adapter when you want the public Caravan-aligned streamflow surface exposed by the flood benchmark. + - Point ``data_dir`` at an extracted Caravan release and pass basin ids (or a basin file), dynamic inputs and periods. + - Score models with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.streamflow``). related_models: - neuralhydrology_lstm + - neuralhydrology_ealstm - google_flood_forecasting related_benchmarks: - flood_benchmark - caravan notes: - - This is a synthetic-backed benchmark adapter rather than a full Caravan downloader. + - The reader is checked against NeuralHydrology's Caravan dataset on real Caravan basin files (oracle test). + - Until 2026-10 this registry name generated random numbers; it now reads only real Caravan files (synthetic data is ``flood_streamflow_synthetic``). diff --git a/pyhazards/dataset_cards/earthquake_wavefield_synthetic.yaml b/pyhazards/dataset_cards/earthquake_wavefield_synthetic.yaml new file mode 100644 index 00000000..75692b19 --- /dev/null +++ b/pyhazards/dataset_cards/earthquake_wavefield_synthetic.yaml @@ -0,0 +1,53 @@ +slug: earthquake_wavefield_synthetic +display_name: Synthetic Wavefield Sequences +hazard_family: Earthquake +source_role: Synthetic Smoke Data +summary: Synthetic X / Y / Z ground-velocity wavefields of point sources for wavefield-forecasting smoke runs. Not real data. +provider: Generated locally by PyHazards (pyhazards/datasets/earthquake/synthetic.py) +geometry: Regular grid of three-component velocity frames +spatial_resolution: Not applicable (synthetic grid, default 32 x 24 cells) +temporal_resolution: Frames (default 6 input and 6 target frames) +update_cadence: Generated on load +period_of_record: Not applicable (synthetic) +coverage: Not applicable (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + This dataset is synthetic. Each sequence is a point source at a random grid position and onset + radiating a P and an S wavefront (Ricker pulses at two speeds, amplitudes decaying with distance): + P moves particles radially and vertically, S transversally, giving X, Y and Z velocity channels. It + mimics only the layout of WaveCastNet's data (three velocity components on a regular grid); it is not + an elastic simulation and says nothing about forecasting skill on real or SW4-simulated wavefields. + - > + It exercises the ``earthquake.forecasting`` task (ACC / RFNE / RMSE of WaveCastNet) in CI. Formerly + ``earthquake_forecast_synthetic`` (moving Gaussian blobs; that name is kept as a deprecated alias) + and, before that, ``aefa_forecast``: AEFA is an unrelated earthquake-occurrence forecasting dataset. + - > + WaveCastNet's own data (SW4 simulations of the San Francisco Bay Area, arrays ``(events, 3, 376, 256, + 461)``, 16-24 GB per file) are on the authors' Google Drive; PyHazards has no reader for them yet. +data_characteristics: + - "Inputs ``(n, 3, temporal_in, height, width)``, targets ``(n, 3, temporal_out, height, width)``; channels X, Y, Z (``channel_names`` metadata)." + - "Seeded generator (``seed``); ``vp`` and ``vs`` are wave speeds in grid cells per frame; height and width default to multiples of 8, as WaveCastNet needs." +typical_use_cases: + - WaveCastNet smoke tests of the wavefield-forecasting benchmark. +access_links: + - label: Generator source + url: https://github.com/LabRAI/PyHazards/blob/main/pyhazards/datasets/earthquake/synthetic.py +inspection: null +registry: + name: earthquake_wavefield_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("earthquake_wavefield_synthetic", micro=True, temporal_in=6, temporal_out=6).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (4, 3, 6, 32, 24) (4, 3, 6, 32, 24) +references: + - citation: "PyHazards synthetic wavefield generator (no external source)." + url: https://github.com/LabRAI/PyHazards/blob/main/pyhazards/datasets/earthquake/synthetic.py +pyhazards_usage: + - Used by ``wavecastnet_benchmark_smoke.yaml``. +related_models: + - wavecastnet +related_benchmarks: + - earthquake_benchmark diff --git a/pyhazards/dataset_cards/earthquake_waveforms_synthetic.yaml b/pyhazards/dataset_cards/earthquake_waveforms_synthetic.yaml new file mode 100644 index 00000000..cb1a2917 --- /dev/null +++ b/pyhazards/dataset_cards/earthquake_waveforms_synthetic.yaml @@ -0,0 +1,52 @@ +slug: earthquake_waveforms_synthetic +display_name: Synthetic Phase-Picking Waveforms +hazard_family: Earthquake +source_role: Synthetic Smoke Data +summary: Synthetic three-component windows with P and S wavelets for picking smoke runs. Not real data. +provider: Generated locally by PyHazards (pyhazards/datasets/earthquake/synthetic.py) +geometry: Three-component waveform windows +spatial_resolution: Not applicable (synthetic) +temporal_resolution: 100 Hz by default +update_cadence: Generated on load from a fixed seed +period_of_record: Not applicable (synthetic) +coverage: Not applicable (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + This dataset is synthetic. Each event window is Gaussian background noise plus two damped + sinusoids that start at the P arrival (about 8 Hz, strongest on Z) and at the S arrival (about + 4 Hz, strongest on N and E); about a quarter of the windows are noise only. It exists to exercise + the picking models and the ``earthquake.picking`` benchmark in CI; numbers obtained on it say + nothing about real seismic data. +data_characteristics: + - "Inputs ``(n, 3, length)`` in Z, N, E order, 100 Hz, ``length`` 6000 by default (60 s, EQTransformer's window)." + - "Targets ``(n, 2)``: P and S arrival samples, NaN for noise windows." + - "Deterministic: the same ``seed`` and sizes give the same data; ``micro=True`` makes 24 windows." +typical_use_cases: + - Smoke tests of PhaseNet, EQTransformer, GPD and the picking evaluator. +access_links: + - label: Generator source + url: https://github.com/LabRAI/PyHazards/blob/main/pyhazards/datasets/earthquake/synthetic.py +inspection: null +registry: + name: earthquake_waveforms_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("earthquake_waveforms_synthetic", micro=True).load() + test = data.get_split("test") + print(test.inputs.shape, test.targets.shape) # (4, 3, 6000), (4, 2) +references: + - citation: "PyHazards synthetic phase-picking generator (no external source)." + url: https://github.com/LabRAI/PyHazards/blob/main/pyhazards/datasets/earthquake/synthetic.py +pyhazards_usage: + - Used by the earthquake picking smoke configs; use ``seisbench_waveforms`` for real data. +related_models: + - phasenet + - eqtransformer + - gpd + - eqnet +related_benchmarks: + - earthquake_benchmark +notes: + - "Renamed from ``earthquake_waveforms``; it also replaces the synthetic data that used to be served as ``seisbench_waveforms`` and ``pick_benchmark_waveforms``." diff --git a/pyhazards/dataset_cards/era5.yaml b/pyhazards/dataset_cards/era5.yaml index 46d91ce5..148e677b 100644 --- a/pyhazards/dataset_cards/era5.yaml +++ b/pyhazards/dataset_cards/era5.yaml @@ -13,7 +13,7 @@ coverage: Global formats: GRIB and NetCDF overview: - ERA5 is ECMWF's fifth-generation global reanalysis, combining historical observations with a modern data assimilation system to produce temporally consistent atmospheric fields. - - PyHazards uses ERA5 as a shared meteorological baseline for flood, wildfire, and weather-aware graph workflows, including the HydroGraphNet example path. + - PyHazards uses ERA5 as a shared meteorological baseline for flood, wildfire, and weather-aware graph workflows. data_characteristics: - Global hourly fields on a regular latitude-longitude grid. - Single-level products with optional pressure-level and model-level variables. @@ -34,9 +34,8 @@ primary_references: - citation: Hersbach et al. (2020). The ERA5 global reanalysis. url: https://rmets.onlinelibrary.wiley.com/doi/10.1002/qj.3803 pyhazards_usage: - - Use the inspection command for direct file validation, then feed local ERA5 files into HydroGraphNet-style helper loaders when you need graph-temporal training inputs. + - Use the inspection command for direct file validation, then feed local ERA5 files into the graph helper ``pyhazards.data.load_hydrograph_data`` (grid cells as nodes) when you need generic graph-temporal inputs. notes: - - ERA5 is inspection-first in the public catalog; the downstream HydroGraphNet helper is documented here for convenience but is not a ``load_dataset(...)`` registry entry. -related_models: - - hydrographnet + - ERA5 is inspection-first in the public catalog; the graph helper is documented here for convenience but is not a ``load_dataset(...)`` registry entry. It is not HydroGraphNet's data (HydroGraphNet runs on HEC-RAS mesh hydrographs, see ``hydrographnet_white_river``). +related_models: [] related_benchmarks: [] diff --git a/pyhazards/dataset_cards/figlib_smokebench.yaml b/pyhazards/dataset_cards/figlib_smokebench.yaml new file mode 100644 index 00000000..0a2e59ec --- /dev/null +++ b/pyhazards/dataset_cards/figlib_smokebench.yaml @@ -0,0 +1,50 @@ +slug: figlib_smokebench +display_name: FIgLib SmokeBench +hazard_family: Wildfire +source_role: Smoke Detection Benchmark +summary: The SmokeBench evaluation images -- HPWREN FIgLib camera frames with the SmokeyNet smoke boxes -- for prompting multimodal LLMs to classify and localize early wildfire smoke. +provider: HPWREN (UC San Diego) FIgLib images; SmokeyNet (Dewangan et al. 2022) boxes; SmokeBench (Qi, Li & Barnes, WACV 2026) protocol +geometry: Fixed-camera RGB photographs with smoke bounding boxes +spatial_resolution: 1600 x 1200 to 3072 x 2048 pixel frames from mountain-top cameras +temporal_resolution: Sequences of up to 81 frames, usually one minute apart, from 40 minutes before to 40 minutes after the first visible plume +update_cadence: Static evaluation set (FIgLib itself keeps adding sequences) +period_of_record: Fires of 2016-2020 (the 145 annotated sequences) +coverage: Southern California (HPWREN camera network) +formats: JPEG frames in per-sequence tgz archives; boxes in a Python pickle (SmokeyNet metadata.pkl) +overview: + - "SmokeBench (Qi, Li & Barnes, WACV 2026) evaluates multimodal LLMs on 5,046 smoke images with ground-truth boxes and 1,000 smoke-free images from FIgLib, the HPWREN Fire Ignition images Library of fixed-view camera sequences around wildfire ignitions." + - "SmokeBench released no data or image lists. The 5,046 boxes are the bbox_labels of SmokeyNet's metadata.pkl (Apache-2.0 repository, pinned and checksummed): one box per frame on 145 sequences, whose area quintiles are exactly the SmokeBench area bins (42, 4356, 11232, 28565, 83157, 2232020 pixels)." + - "The frames are downloaded from the official HPWREN CDN on demand; PyHazards redistributes no images." +data_characteristics: + - "Smoke images are frames at or after the first visible plume (file names _+.jpg) that SmokeyNet's annotators boxed; smoke-free images are frames before it (_-.jpg)." + - "Frame sizes: 2,846 at 2048 x 1536, 1,994 at 3072 x 2048, 172 at 1600 x 1200 and 34 at 2560 x 1920 among the smoke images." + - "Boxes are [x1, y1, x2, y2] integer pixel coordinates of the original frame (extremes of the annotated polygon); smoke areas range from 42 to 2,232,020 pixels." + - "SmokeBench's 1,000 smoke-free frames were an unseeded random draw over all FIgLib sequences and were not released; the adapter draws a seeded sample from the pre-ignition frames of the 145 annotated sequences (5,666 candidates)." +typical_use_cases: + - Zero-shot evaluation of multimodal LLMs on smoke classification, tile and grid localization and box detection (SmokeBench). + - Studying how smoke size and contrast limit early wildfire smoke detection. +access_links: + - label: HPWREN FIgLib + url: https://www.hpwren.ucsd.edu/FIgLib/ + - label: FIgLib sequence archives (HPWREN CDN) + url: https://cdn.hpwren.ucsd.edu/HPWREN-FIgLib-Data/Tar/index.html + - label: SmokeyNet repository (boxes in data/metadata.pkl) + url: https://gitlab.nrp-nautilus.io/anshumand/pytorch-lightning-smoke-detection +inspection: + command: python -m pyhazards.datasets.figlib_smokebench.inspection --root /path/to/figlib --download + notes: + - "--download fetches the pinned SmokeyNet metadata.pkl (sha256-checked) and streams the 145 FIgLib archives (about 11.4 GB), keeping only the JPEG frames." +primary_references: + - citation: "Qi, T., Li, W., Barnes, N. (2026). SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection. WACV 2026." + url: https://arxiv.org/abs/2512.11215 + - citation: "Dewangan, A. et al. (2022). FIgLib & SmokeyNet: Dataset and Deep Learning Model for Real-Time Wildland Fire Smoke Detection. Remote Sensing 14(4):1007." + url: https://doi.org/10.3390/rs14041007 + repo_url: https://gitlab.nrp-nautilus.io/anshumand/pytorch-lightning-smoke-detection +pyhazards_usage: + - "pyhazards.datasets.figlib_smokebench.FIgLibSmokeBench(root) yields SmokeSample(image_id, path, label, boxes) and decodes frames to RGB arrays; download_smokebench(root) fetches the boxes and frames." + - "pyhazards.prompted.evaluate_smokebench runs the SmokeBench tasks on it with a prompted multimodal-LLM backend (see the Prompted VLM Baselines page)." +related_models: [] +related_benchmarks: [] +notes: + - "Licence: HPWREN publishes FIgLib as public data and asks that derivative work credit https://www.hpwren.ucsd.edu/; no licence file accompanies the images. The SmokeyNet repository (boxes) is Apache-2.0." + - "Smoke-free accuracy on the seeded sample is not the same sample as SmokeBench Table 3." diff --git a/pyhazards/dataset_cards/firms.yaml b/pyhazards/dataset_cards/firms.yaml index 24d5ef33..7875aa22 100644 --- a/pyhazards/dataset_cards/firms.yaml +++ b/pyhazards/dataset_cards/firms.yaml @@ -34,7 +34,7 @@ inspection: - Some archive and bulk-download routes require Earthdata login credentials. primary_references: - citation: Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product. - url: https://doi.org/10.1016/j.rse.2013.08.008 + url: https://doi.org/10.1016/j.rse.2013.12.008 related_models: [] related_benchmarks: - wildfire_benchmark diff --git a/pyhazards/dataset_cards/flood_mesh_synthetic.yaml b/pyhazards/dataset_cards/flood_mesh_synthetic.yaml new file mode 100644 index 00000000..a6ed389e --- /dev/null +++ b/pyhazards/dataset_cards/flood_mesh_synthetic.yaml @@ -0,0 +1,44 @@ +slug: flood_mesh_synthetic +display_name: Synthetic Mesh Hydrographs +hazard_family: Flood +source_role: Synthetic Smoke Data +summary: "Random mesh fields and toy hydrographs in the HydroGraphNet (White River) layout, for smoke tests of hydrographnet and of mesh inundation rollouts." +provider: PyHazards (generated in memory; no real flood) +geometry: Graph-temporal basin or node sequences +spatial_resolution: Not applicable (random points) +temporal_resolution: Not applicable (synthetic steps) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Static fields are random and the depth series is a toy function of a random inflow + curve and the terrain; scores on it mean nothing. It runs the same pipeline as + ``hydrographnet_white_river`` (normalisation, 4-nearest-neighbour graph, 16 node features, training + windows with physics data, rollout test split), so models and the flood benchmark can be exercised + without the 8.3 GB release. ``write_hydrograph_files`` writes such data in the release's file layout. +data_characteristics: + - "Default: 64 nodes, 4 training and 2 test hydrographs of 48 steps, rollouts of 30 steps; ``micro=True``: 24 nodes, 2 + 1 hydrographs of 16 steps, rollouts of 6 steps." +typical_use_cases: + - Smoke tests and CI runs of hydrographnet and of the ``flood.inundation`` mesh rollouts. +access_links: [] +inspection: null +registry: + name: flood_mesh_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("flood_mesh_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/flood/hydrograph.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; the real data are ``hydrographnet_white_river``. +related_models: + - hydrographnet +related_benchmarks: + - flood_benchmark +notes: + - Bundle metadata carries synthetic=True. Until this release the name held random node series on a line graph. diff --git a/pyhazards/dataset_cards/floodcastbench_inundation.yaml b/pyhazards/dataset_cards/floodcastbench_inundation.yaml deleted file mode 100644 index f7fdf47b..00000000 --- a/pyhazards/dataset_cards/floodcastbench_inundation.yaml +++ /dev/null @@ -1,55 +0,0 @@ -slug: floodcastbench_inundation -display_name: FloodCastBench -hazard_family: Flood -source_role: Inundation Benchmark -summary: Synthetic-backed inundation benchmark adapter aligned to the FloodCastBench evaluation ecosystem. -provider: FloodCastBench ecosystem surfaced through a PyHazards adapter -geometry: Raster inundation sequences -spatial_resolution: Benchmark-defined raster tiles -temporal_resolution: Short history windows with next-horizon inundation targets -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned flood inundation samples -formats: PyTorch tensors via the dataset registry -overview: - - FloodCastBench is the public inundation adapter used by PyHazards for raster flood prediction benchmarks. - - The current implementation is synthetic-backed, but it preserves the raster task and metric surface used by the shared flood evaluator. -data_characteristics: - - Multi-step raster inputs paired with next-horizon inundation targets. - - Registry-backed benchmark adapter rather than a raw external dataset ingestion path. - - Intended for pixel-level evaluation such as IoU and pixel MAE. -typical_use_cases: - - Smoke tests for FloodCast and UrbanFloodCast. - - Shared flood benchmark runs on inundation tasks. - - Regression checks for raster flood prediction outputs. -access_links: - - label: FloodCastBench repository - url: https://github.com/HydroPML/FloodCastBench -inspection: null -registry: - name: floodcastbench_inundation - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "floodcastbench_inundation", - micro=True, - history=4, - channels=3, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) -primary_references: - - citation: FloodCastBench - url: https://github.com/HydroPML/FloodCastBench -pyhazards_usage: - - Use this adapter when you want the public FloodCastBench-aligned inundation surface exposed by the flood benchmark. -related_models: - - floodcast - - urbanfloodcast -related_benchmarks: - - flood_benchmark - - floodcastbench -notes: - - This is a synthetic-backed benchmark adapter rather than a full FloodCastBench ingestion pipeline. diff --git a/pyhazards/dataset_cards/fpa_fod_weekly.yaml b/pyhazards/dataset_cards/fpa_fod_weekly.yaml index a7599be7..2d18ef20 100644 --- a/pyhazards/dataset_cards/fpa_fod_weekly.yaml +++ b/pyhazards/dataset_cards/fpa_fod_weekly.yaml @@ -50,7 +50,5 @@ primary_references: url: https://github.com/LabRAI/PyHazards related_models: - wildfire_fpa - - wildfire_forecasting - - asufm related_benchmarks: - wildfire_benchmark diff --git a/pyhazards/dataset_cards/frap_fire_perimeters.yaml b/pyhazards/dataset_cards/frap_fire_perimeters.yaml new file mode 100644 index 00000000..308d8a4c --- /dev/null +++ b/pyhazards/dataset_cards/frap_fire_perimeters.yaml @@ -0,0 +1,55 @@ +slug: frap_fire_perimeters +display_name: CAL FIRE FRAP Fire Perimeters +hazard_family: Wildfire +source_role: Historical Perimeters +summary: California's historical wildfire perimeter archive, maintained by CAL FIRE's Fire and Resource Assessment Program, with fires back to 1878. +provider: CAL FIRE Fire and Resource Assessment Program (FRAP), with USFS Region 5, BLM, NPS, USFWS, California State Parks and contract counties +geometry: Fire perimeter polygons +spatial_resolution: Vector polygons (native coordinate system California Teale Albers, EPSG:3310) +temporal_resolution: One record per fire, with alarm and containment dates +update_cadence: Annual, each spring, adding the previous fire season (release firep25_1, April 2026) +period_of_record: 1878 to 2025 in release firep25_1 +coverage: California +formats: File geodatabase; shapefile, GeoJSON, CSV, KML and GeoPackage exports from the California open-data hub +overview: + - > + The FRAP fire perimeter layer is CAL FIRE's statewide archive of mapped wildfire perimeters on + public and private land in California, compiled with federal and local agencies and updated each + spring with the previous fire season. Prescribed burns are kept in a separate layer. + - > + It is a long, regional perimeter record that complements the national incident feeds (WFIGS) + and satellite detections (FIRMS) for California. +data_characteristics: + - > + Minimum mapped size for CAL FIRE and contract counties: at least 10 acres of timber, 50 acres of + brush or 300 acres of grass, or at least 3 damaged or destroyed structures, or a fatality; other + agencies submit perimeters of at least 10 acres. The criteria changed around 1991 and 2010. + - > + The archive is incomplete: some historical records were lost or too small for the cutoffs, + some fires are duplicated or over-generalised, and unburned islands inside perimeters are + mapped as burned. Perimeters may differ from those published by NIFC. + - > + Attributes include YEAR_, AGENCY, UNIT_ID, FIRE_NAME, INC_NUM, IRWINID, ALARM_DATE, CONT_DATE, + CAUSE, C_METHOD, OBJECTIVE, GIS_ACRES and COMPLEX_NAME. +typical_use_cases: + - Historical burned-area footprints for California wildfire studies. + - Validating perimeters from national feeds or satellite products in California. +access_links: + - label: California Fire Perimeters (all) on data.ca.gov + url: https://data.ca.gov/dataset/california-fire-perimeters-all + - label: California Natural Resources Agency open-data hub (downloads and services) + url: https://gis.data.cnra.ca.gov/datasets/CALFIRE-Forestry::california-fire-perimeters-all +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for California + perimeter data. +primary_references: + - citation: CAL FIRE FRAP (2026). Fire Perimeters, release firep25_1 (metadata). + url: https://www.arcgis.com/sharing/rest/content/items/a31aa1efe1d6466f8530b501c30ab00a/data +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: data.ca.gov lists the dataset under CC BY; the metadata asks users to cite the + California Department of Forestry and Fire Protection as the source, states "There are no + restrictions on distribution of the data by users", and gives no warranty. diff --git a/pyhazards/dataset_cards/geomac_historical.yaml b/pyhazards/dataset_cards/geomac_historical.yaml new file mode 100644 index 00000000..6cd43e15 --- /dev/null +++ b/pyhazards/dataset_cards/geomac_historical.yaml @@ -0,0 +1,53 @@ +slug: geomac_historical +display_name: GeoMAC Historical Perimeters +hazard_family: Wildfire +source_role: Historical Perimeters +summary: Wildfire perimeters processed by the USGS GeoMAC service from 2000 to 2019, now distributed by the National Interagency Fire Center. +provider: USGS Geospatial Multi-Agency Coordination (GeoMAC; shut down on 30 April 2020), archive distributed by NIFC Open Data +geometry: Fire perimeter polygons +spatial_resolution: Vector polygons (geographic coordinates, NAD83) +temporal_resolution: The latest perimeter processed for each fire, with its perimeter date and time +update_cadence: Static archive (GeoMAC was retired on 30 April 2020) +period_of_record: 2000 to 2019 (a combined 2000-2018 layer and a separate 2019 layer) +coverage: United States (the 2019 layer covers the conterminous 48 states and Alaska) +formats: File geodatabase downloads and ArcGIS feature services +overview: + - > + GeoMAC was the USGS-operated wildfire mapping website (2000-2020) that published fire + perimeters for incident support. After it was shut down on 30 April 2020, its historical + perimeters moved to the National Interagency Fire Center (NIFC) open-data site. + - > + It is the main national perimeter archive for 2000-2019. For 2021 onwards the interagency WFIGS + perimeters are the successor; the NIFC Interagency Fire Perimeter History layer also covers + perimeters through 2019. +data_characteristics: + - The combined 2000-2018 layer holds 23,776 perimeters; 2019 is a separate layer. + - > + Attributes include incidentname, fireyear, perimeterdatetime, gisacres, agency, mapmethod, + uniquefireidentifier, irwinid, state and complexname. + - > + The perimeters are the last ones processed by the GeoMAC team for each fire; NIFC notes that + they are not necessarily the final or official perimeter. +typical_use_cases: + - National wildfire burned-area footprints for 2000-2019. + - Extending perimeter records before the WFIGS era. +access_links: + - label: NIFC Open Data, Historic Perimeters Combined 2000-2018 GeoMAC + url: https://data-nifc.opendata.arcgis.com/datasets/nifc::historic-perimeters-combined-2000-2018-geomac/about + - label: NIFC Open Data, Historic GeoMAC Perimeters 2019 + url: https://data-nifc.opendata.arcgis.com/datasets/nifc::historic-geomac-perimeters-2019/about +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for historical + U.S. wildfire perimeters. +primary_references: + - citation: National Interagency Fire Center. Historic Perimeters Combined 2000-2018 GeoMAC (NIFC Open Data). + url: https://data-nifc.opendata.arcgis.com/datasets/nifc::historic-perimeters-combined-2000-2018-geomac/about + - citation: Walters, Schneider and Guthrie (2011). Geospatial Multi-Agency Coordination (GeoMAC) wildland fire perimeters, 2008. USGS Data Series 612 (documents the 2008 season only). + url: https://doi.org/10.3133/ds612 +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: the NIFC items state no licence and carry no-warranty disclaimers. USGS-produced data + are in the U.S. public domain under USGS policy, but the items do not say so explicitly. diff --git a/pyhazards/dataset_cards/goesr_fdcf.yaml b/pyhazards/dataset_cards/goesr_fdcf.yaml new file mode 100644 index 00000000..17cece7b --- /dev/null +++ b/pyhazards/dataset_cards/goesr_fdcf.yaml @@ -0,0 +1,61 @@ +slug: goesr_fdcf +display_name: GOES-R ABI Fire/Hot Spot Characterization (FDCF) +hazard_family: Wildfire +source_role: Active Fire Detections +summary: NOAA's GOES-R ABI Level-2 fire detection and characterization product on the full-disk scan, every 10 minutes since April 2019, openly distributed on AWS. +provider: NOAA NESDIS GOES-R Series; Fire Detection and Characterization Algorithm (FDCA) from UW-Madison CIMSS +geometry: Raster imagery time series on the ABI fixed grid +spatial_resolution: 2 km at nadir (5424 x 5424 full-disk fixed grid) +temporal_resolution: A full-disk product every 10 minutes since 2 April 2019 (scan mode 6); every 15 minutes before (mode 3) +update_cadence: Continuous operational production +period_of_record: From 24 May 2017 (GOES-16); see the notes for the per-satellite archives +coverage: The full disk of each GOES satellite (GOES-East and GOES-West positions over the Americas) +formats: NetCDF-4 (CF-1.7) in the geostationary projection +overview: + - > + ABI-L2-FDCF is the full-disk version of the GOES-R Fire/Hot Spot Characterization product. The + FDCA algorithm (the operational version of WFABBA) flags fire pixels in Advanced Baseline Imager + data and estimates their fire radiative power, temperature and area. + - > + It gives geostationary fire activity every 10 minutes, much more often than the polar-orbiting + MODIS and VIIRS detections distributed by FIRMS, at a coarser 2 km pixel. +data_characteristics: + - > + Variables: Mask (fire category codes, e.g. 10 good-quality fire, 11 saturated, 12 cloud + contaminated, 13-15 high / medium / low probability, 30-35 their temporally filtered + versions), Power (MW), Temp (K), Area (m2) and DQF, plus viewing angles and summaries. + - Pixels are on the ABI fixed grid (geostationary projection) and need reprojection for latitude-longitude work. + - > + AWS buckets per satellite: noaa-goes16 (2017-05-24 to 2025-04-07), noaa-goes17 (2018-08-27 to + January 2023), noaa-goes18 (from 2022-05-11) and noaa-goes19 (from 2024-10-17); GOES-East data + after April 2025 are in noaa-goes19. Keys look like ABI-L2-FDCF/YYYY/DDD/HH/OR_ABI-L2-FDCF-M6_G16_s....nc. +typical_use_cases: + - High-frequency fire activity time series over the Americas. + - Fire radiative power for growth and intensity analyses. + - Timing ignitions more precisely than polar-orbiting detections allow. +access_links: + - label: NOAA NESDIS GOES-R series data products + url: https://www.nesdis.noaa.gov/our-satellites/currently-flying/goes-east-west/goes-r-series-data-products + - label: NOAA GOES on the AWS Registry of Open Data + url: https://registry.opendata.aws/noaa-goes/ + - label: NOAA STAR GOES-R fire product page + url: https://www.star.nesdis.noaa.gov/goesr/product_land_fire.php +pyhazards_usage: + - > + PyHazards does not load this product; it is listed as an external reference. The ``goesr`` + entry covers ABI imagery in general. +primary_references: + - citation: Schmidt (2020). Monitoring Fires with the GOES-R Series. In The GOES-R Series, Elsevier, 145-163. + url: https://doi.org/10.1016/B978-0-12-814327-8.00013-5 + - citation: GOES-R Algorithm Working Group (2018). NOAA GOES-R Series ABI Level 2 Fire/Hot Spot Characterization (FDC). NOAA NCEI. + url: https://doi.org/10.7289/V5X065CR + - citation: Schmidt, Hoffman, Prins and Lindstrom (2020). GOES-R ABI Algorithm Theoretical Basis Document for Fire / Hot Spot Characterization, version 2.7. NOAA NESDIS STAR. + url: https://www.star.nesdis.noaa.gov/atmospheric-composition-training/documents/ABI_FDC_ATBD.pdf +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: NOAA Open Data Dissemination states that the data "are open to the public and can be + used as desired", requests attribution and forbids implying NOAA endorsement. The "license" + attribute inside the NetCDF files ("Access is restricted to approved users only") is + boilerplate that does not apply to the open distribution. diff --git a/pyhazards/dataset_cards/hms_smoke.yaml b/pyhazards/dataset_cards/hms_smoke.yaml new file mode 100644 index 00000000..488fc01a --- /dev/null +++ b/pyhazards/dataset_cards/hms_smoke.yaml @@ -0,0 +1,51 @@ +slug: hms_smoke +display_name: NOAA HMS Smoke Polygons +hazard_family: Wildfire +source_role: Smoke Plumes +summary: Analyst-drawn smoke plume outlines from NOAA's Hazard Mapping System, produced daily since August 2005. +provider: NOAA NESDIS Office of Satellite and Product Operations (OSPO), Satellite Analysis Branch +geometry: Analyst-drawn smoke polygons +spatial_resolution: Vector polygons (WGS84); annual smoke-day rasters at 0.05 deg +temporal_resolution: Daily analyses, the first around 11:00-12:00 US Eastern time and usually a second around 19:00-20:00; each polygon has start and end times +update_cadence: Daily +period_of_record: 5 August 2005 to the present +coverage: North America, Hawaii and the Caribbean +formats: Zipped shapefiles (daily files and annual bundles), KML, annual GeoTIFF smoke-day rasters +overview: + - > + The Hazard Mapping System (HMS), first implemented in 2002, is NOAA's analyst-driven fire and + smoke product: satellite analysts outline the smoke plumes visible in satellite imagery and + record the satellite and the time window of each outline. + - > + The smoke polygons describe where smoke was visible, which fire detections and perimeters do + not; they are commonly used to flag smoke-affected days and to link plumes to fires. +data_characteristics: + - Attributes are Satellite, Start, End and Density (Light, Medium, Heavy or NA). + - > + The density attribute is consistently filled only from 1 June 2010; most earlier files have + "NA" (apart from April-December 2008), so density-based analyses should start in mid-2010. + - > + File names and columns changed on 19 July 2022, when NOAA regenerated the historical archive; + daily shapefiles are named hms_smokeYYYYMMDD.zip. +typical_use_cases: + - Flagging smoke-affected days and regions in air-quality or wildfire impact studies. + - Linking smoke plumes to fire detections and perimeters. +access_links: + - label: NOAA OSPO Hazard Mapping System + url: https://www.ospo.noaa.gov/products/land/hms.html + - label: HMS smoke polygon archive (shapefile, KML, GeoTIFF) + url: https://satepsanone.nesdis.noaa.gov/pub/FIRE/web/HMS/Smoke_Polygons/ +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for wildfire + smoke extent. +primary_references: + - citation: Ruminski and Kondragunta (2006). Monitoring fire and smoke emissions with the hazard mapping system. Proc. SPIE 6412. + url: https://doi.org/10.1117/12.694183 + - citation: Brey et al. (2018). Connecting smoke plumes to sources using Hazard Mapping System (HMS) smoke and fire location data over North America. Atmospheric Chemistry and Physics 18, 1745-1761. + url: https://doi.org/10.5194/acp-18-1745-2018 +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: the OSPO pages state no licence; the data.gov catalogue record lists CC0. diff --git a/pyhazards/dataset_cards/hrrr.yaml b/pyhazards/dataset_cards/hrrr.yaml new file mode 100644 index 00000000..3490a829 --- /dev/null +++ b/pyhazards/dataset_cards/hrrr.yaml @@ -0,0 +1,49 @@ +slug: hrrr +display_name: HRRR +hazard_family: Shared Forcing +source_role: Weather Forecast +summary: NOAA's 3 km, hourly updated, convection-allowing forecast model for the United States, archived on AWS since July 2014. +provider: NOAA (run operationally by NCEP; developed by the NOAA Global Systems Laboratory) +geometry: Gridded forecast fields +spatial_resolution: 3 km +temporal_resolution: Hourly forecast output; with HRRRv4 (since 2 December 2020) 18-hour forecasts every hour and 48-hour forecasts at 00, 06, 12 and 18 UTC +update_cadence: Every hour for CONUS; every 3 hours for Alaska +period_of_record: AWS archive from 30 July 2014; operational since 30 September 2014 +coverage: Conterminous United States; an Alaska domain from July 2018 +formats: GRIB2 with .idx index files +overview: + - > + The High-Resolution Rapid Refresh is NOAA's operational convection-allowing model. It is run + every hour and produces short-range forecasts of near-surface and upper-air weather at 3 km. + - > + Its near-surface temperature, humidity, wind and precipitation forecasts are a common source of + short-range fire-weather inputs; since HRRRv4 it also predicts wildfire smoke inline. +data_characteristics: + - > + Forecast length changed with the model version: 15 hours until 2016, 18 hours from about + September 2016, 36 hours at the synoptic cycles from mid-2018 and 48 hours from December 2020. + - > + Files are grouped into surface (wrfsfc), pressure-level (wrfprs), native-level (wrfnat) and + sub-hourly (wrfsubh) products; AWS keys look like hrrr.YYYYMMDD/conus/hrrr.tHHz.wrfsfcfFF.grib2. + - The first two months on AWS predate operations and some early surface files are missing. +typical_use_cases: + - Short-range fire-weather covariates (wind, humidity, temperature) for wildfire models. + - Smoke forecast fields from HRRRv4 onwards. +access_links: + - label: NOAA HRRR on the AWS Registry of Open Data + url: https://registry.opendata.aws/noaa-hrrr-pds/ + - label: NOAA Rapid Refresh / HRRR information page + url: https://rapidrefresh.noaa.gov/hrrr/ +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for short-range + weather forecasts. +primary_references: + - citation: "Dowell et al. (2022). The High-Resolution Rapid Refresh (HRRR): An Hourly Updating Convection-Allowing Forecast Model. Part I: Motivation and System Description. Weather and Forecasting 37(8), 1371-1395." + url: https://doi.org/10.1175/WAF-D-21-0151.1 +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: NOAA Open Data Dissemination states that the data "are open to the public and can be + used as desired", requests attribution and forbids implying NOAA endorsement. diff --git a/pyhazards/dataset_cards/hurricast_ibtracs_era5.yaml b/pyhazards/dataset_cards/hurricast_ibtracs_era5.yaml new file mode 100644 index 00000000..b1d758e2 --- /dev/null +++ b/pyhazards/dataset_cards/hurricast_ibtracs_era5.yaml @@ -0,0 +1,104 @@ +slug: hurricast_ibtracs_era5 +display_name: Hurricast IBTrACS + ERA5 Inputs +hazard_family: Tropical Cyclone +source_role: Model Inputs (best track + reanalysis) +summary: "The inputs of Hurricast (Boussioux et al. 2022): 30 IBTrACS statistical features and nine storm-centred ERA5 maps per 3-hour step, 8 steps per sample, with the 24-hour intensity or position as target." +provider: NOAA NCEI (IBTrACS v04) and ECMWF / Copernicus Climate Change Service (ERA5), read from files the user provides +geometry: Storm-centred sequences of feature vectors and 25 x 25 one-degree maps +spatial_resolution: Storm-centre positions; maps 25 x 25 at 1 degree around the storm +temporal_resolution: Three-hourly steps (t-21 h ... t), 24-hour lead time +update_cadence: Follows the user's IBTrACS and ERA5 files +period_of_record: "Paper: 1980-2019 (train 1980-2011, validation 2012-2015, test 2016-2019)" +coverage: All IBTrACS basins (the paper reports test scores for the North Atlantic and Eastern Pacific) +formats: IBTrACS v04 CSV or netCDF; ERA5 pressure-level netCDF / zarr (or an xarray Dataset) with u, v, z at 225, 500, 700 hPa +overview: + - > + ``hurricast_ibtracs_era5`` builds Hurricast's samples. From IBTrACS (``read_ibtracs``) it keeps the rows + on the 3-hour grid, interpolates the WMO wind and pressure linearly within each storm, and computes per + step the 30 features of the official feature tables: latitude, longitude, WMO wind and pressure, distance + to land, translation speed, cosine / sine of the day of year, direction, latitude and longitude, the + Saffir-Simpson category value, one-hot basin and storm nature, and the latitude / longitude change since + the previous step. + - > + Storms are selected like the official ``sort_storm``: kept when more than ``min_steps`` (20, i.e. 60 h) + of their steps reach ``min_wind`` (34 kt), cut to start at the first such step and to at most + ``max_steps`` (120) steps. Each window of 8 steps followed by 8 more gives a sample (windows whose target + period has a step without any movement are dropped, as the official ``remove_zeros``). Winds of samples + outside the North Atlantic and Eastern Pacific are converted from 10-minute to 1-minute values (/ 0.93). + - > + With ``era5=`` (a netCDF / zarr path or an ``xarray.Dataset`` with u, v and z, e.g. a Copernicus Climate + Data Store download or the NCAR RDA copy) each step gets the nine maps u, v, z at 225, 500 and 700 hPa on + the 25 x 25 one-degree grid centred on the grid point nearest to the storm (a 0.25-degree source is + sampled at whole degrees). Maps are read only for samples of a split. +data_characteristics: + - > + Inputs per split: ``x_stat`` ``(N, 8, 30)``, ``x_viz`` ``(N, 8, 9, 25, 25)`` (channels u225, u500, u700, + v..., z...; rows north to south) and ``position`` ``(N, 2)`` (latitude, longitude at the forecast time). + Targets: ``target="intensity"`` the WMO wind 24 h ahead (1-minute kt, ``tc.intensity``); + ``target="displacement"`` the position 24 h ahead ``(N, 1, 2)`` (``tc.track_intensity``). + - > + ``standardize=True`` standardises latitude, longitude, wind, pressure, distance to land, speed and the + displacements (paper Table 2) and every map channel with the training split's statistics (recorded in + the metadata); cyclic encodings and categories are left as they are. + - > + Splits by season (paper defaults: 1980-2011 / 2012-2015 / 2016-2019); the test split keeps only + ``test_basins`` (NA, EP). The paper further restricts its test cases to those with ATCF operational + forecasts (837 EP / 899 NA track cases), which needs the ATCF data and is not done here. +typical_use_cases: + - Training and evaluating Hurricast (encoder-decoder embeddings and XGBoost) on real storms. + - Multimodal (tabular + reanalysis map) 24-hour track and intensity forecasting experiments. +access_links: + - label: IBTrACS v04r01 files (NOAA NCEI) + url: https://www.ncei.noaa.gov/data/international-best-track-archive-for-climate-stewardship-ibtracs/v04r01/access/ + - label: ERA5 hourly data on pressure levels (Copernicus Climate Data Store) + url: https://cds.climate.copernicus.eu/datasets/reanalysis-era5-pressure-levels + - label: ERA5 on NCAR RDA (ds633.0) + url: https://rda.ucar.edu/datasets/ds633.0/ +inspection: null +registry: + name: hurricast_ibtracs_era5 + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset( + "hurricast_ibtracs_era5", + path="ibtracs.since1980.list.v04r01.csv", + era5="era5_u_v_z_225_500_700.nc", # covering the storms' 25 x 25 degree neighbourhoods + target="intensity", + ).load() + train = data.get_split("train") + print(train.inputs["x_stat"].shape, train.inputs["x_viz"].shape, train.targets.shape) + notes: + - "path= is an IBTrACS v04 CSV or netCDF file; era5= is optional (without it only the statistical inputs are built, enough for HUML-(stat, xgb))." + - "min_wind, min_steps, max_steps, window_size, predict_at, the split seasons, test_basins and basins can be changed; the defaults are the paper's." + - "The official per-step CDS requests (area latitude +-12.008, longitude +-12, 1-degree grid) are not reproduced; the maps are cut from the data the user provides." +references: + - citation: "Boussioux, L., C. Zeng, T. Guenais and D. Bertsimas (2022). Hurricane Forecasting: A Novel Multimodal Machine Learning Framework. Weather and Forecasting 37(6), 817-831." + url: https://doi.org/10.1175/WAF-D-21-0091.1 + - citation: "Knapp, K. R. et al. (2010). The International Best Track Archive for Climate Stewardship (IBTrACS). BAMS 91, 363-376; Gahtan, J. et al. (2024), IBTrACS v04r01, NOAA NCEI." + url: https://doi.org/10.25921/82ty-9e16 + - citation: "Hersbach, H. et al. (2023). ERA5 hourly data on pressure levels from 1940 to present. Copernicus Climate Change Service (C3S) Climate Data Store." + url: https://doi.org/10.24381/cds.bd0915c6 +pyhazards_usage: + - > + Fit ``hurricast`` with ``model.fit(train.inputs, train.targets, val.inputs, val.targets)`` and score it + with the ``tc`` benchmark: ``tc.intensity`` (MAE in kt) or ``tc.track_intensity`` with lead 24 h + (great-circle error in km, the paper's haversine metric). +related_models: + - hurricast +related_benchmarks: + - tropical_cyclone_benchmark + - ibtracs +notes: + - > + The official repository (no licence) did not release the code that built the paper's 30-feature tables, + only their column names; the features are computed from the paper (Table 2, footnote 2) and those names, + and the storm selection, interpolation, category and displacement columns are checked against the + released src/utils/data_processing.py. Differences from that code: rows off the 3-hour grid (e.g. + landfall records at 10:15) are dropped, WMO values are interpolated within each storm (the official + numeric_data interpolates across the whole table, so a storm's first gaps take values from the previous + storm), and spur tracks are skipped. + - > + Neither file is redistributed: IBTrACS follows the WDC-Meteorology open-access policy, ERA5 is CC BY 4.0 + (Copernicus). The tests use the 4-storm IBTrACS cut of tests/fixtures/ibtracs and a 9-time ERA5 cut around + Hurricane Ophelia (tests/fixtures/era5). diff --git a/pyhazards/dataset_cards/hurricast_synthetic.yaml b/pyhazards/dataset_cards/hurricast_synthetic.yaml new file mode 100644 index 00000000..8eedd318 --- /dev/null +++ b/pyhazards/dataset_cards/hurricast_synthetic.yaml @@ -0,0 +1,42 @@ +slug: hurricast_synthetic +display_name: Synthetic Hurricast Inputs +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random inputs in the hurricast_ibtracs_era5 layout (8 steps of 30 statistical features and 9 maps of 25 x 25) for smoke tests of hurricast." +provider: PyHazards (generated in memory; no real storms) +geometry: Feature sequences and image sequences +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run hurricast and the cyclone + benchmark without IBTrACS or ERA5 files. +data_characteristics: + - "x_stat (N, 8, 30) with standard-normal numerical features, cyclic encodings in [-1, 1] and valid one-hot basin / nature columns; x_viz (N, 8, 9, 25, 25) standard normal; position (N, 2); targets random winds (kt) or positions (target='displacement')." +typical_use_cases: + - Smoke tests and CI runs of hurricast and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: hurricast_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("hurricast_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; real data come from hurricast_ibtracs_era5. +related_models: + - hurricast +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/hydrobench_streamflow.yaml b/pyhazards/dataset_cards/hydrobench_streamflow.yaml deleted file mode 100644 index 5cddb831..00000000 --- a/pyhazards/dataset_cards/hydrobench_streamflow.yaml +++ /dev/null @@ -1,54 +0,0 @@ -slug: hydrobench_streamflow -display_name: HydroBench -hazard_family: Flood -source_role: Streamflow Benchmark -summary: Synthetic-backed streamflow diagnostics adapter aligned to the HydroBench ecosystem. -provider: HydroBench ecosystem surfaced through a PyHazards adapter -geometry: Graph-temporal basin or node sequences -spatial_resolution: Basin or gauge nodes represented as graph elements -temporal_resolution: Rolling history windows for streamflow prediction -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned streamflow forecasting samples -formats: PyTorch graph-temporal dataset objects via the dataset registry -overview: - - HydroBench is the public flood adapter used for streamflow diagnostics and HydroGraphNet-aligned benchmark runs. - - The current implementation is synthetic-backed, but it preserves the streamflow task and metric contract exposed by the shared flood benchmark. -data_characteristics: - - Graph-temporal sequences with node-level targets for next-step streamflow prediction. - - Registry-backed benchmark adapter rather than a raw HydroBench dataset ingestion path. - - Intended for HydroGraphNet smoke runs and flood benchmark diagnostics. -typical_use_cases: - - HydroGraphNet smoke tests. - - Shared flood benchmark runs with HydroBench-aligned metrics. - - Diagnostics for graph-based flood forecasting experiments. -access_links: - - label: HydroBench repository - url: https://github.com/EMscience/HydroBench -inspection: null -registry: - name: hydrobench_streamflow - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "hydrobench_streamflow", - micro=True, - history=4, - nodes=6, - ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) -primary_references: - - citation: HydroBench - url: https://github.com/EMscience/HydroBench -pyhazards_usage: - - Use this adapter when you want the public HydroBench-aligned streamflow surface exposed by the flood benchmark. -related_models: - - hydrographnet -related_benchmarks: - - flood_benchmark - - hydrobench -notes: - - This is a synthetic-backed benchmark adapter rather than a full HydroBench downloader. diff --git a/pyhazards/dataset_cards/hydrographnet_white_river.yaml b/pyhazards/dataset_cards/hydrographnet_white_river.yaml new file mode 100644 index 00000000..78705056 --- /dev/null +++ b/pyhazards/dataset_cards/hydrographnet_white_river.yaml @@ -0,0 +1,69 @@ +slug: hydrographnet_white_river +display_name: HydroGraphNet White River +hazard_family: Flood +source_role: Inundation Benchmark +summary: Reader for a local copy of the HydroGraphNet dataset (HEC-RAS flood simulations on a 4,787-cell mesh of the White River near Muncie, Indiana), read as PhysicsNeMo's HydroGraphDataset reads it. +provider: Taghizadeh et al. (University of Virginia), Zenodo record 14969507; read by PyHazards from a local copy +geometry: Unstructured 2-D mesh cells with a k-nearest-neighbour graph +spatial_resolution: Mesh cells of about 80 m (4,787 cells) +temporal_resolution: 20-minute steps +update_cadence: Static research dataset (released 2025-03-05) +period_of_record: 500 simulated inflow / rainfall events (hydrographs) +coverage: White River near Muncie, Indiana, USA +formats: Tab-separated text files (HydroGraphNet.zip, 8.3 GB) +overview: + - > + The dataset of HydroGraphNet (Taghizadeh et al., Computer-Aided Civil and Infrastructure Engineering + 2025): HEC-RAS 2-D simulations of 500 boundary-inflow hydrographs with rainfall on the White River + mesh, with per-cell terrain attributes (area, elevation, slope, aspect, curvature, Manning's n, flow + accumulation, infiltration) and per-step water depth and volume. CC BY 4.0, Zenodo 14969507. + - > + ``hydrographnet_white_river`` reproduces PhysicsNeMo's ``HydroGraphDataset``: it drops the first 72 + steps of every hydrograph and cuts it 25 steps after the inflow peak, converts precipitation, builds + the 4-nearest-neighbour graph with standardised (dx, dy, distance) edge features, standardises + static features per column and the dynamic series with statistics of the training hydrographs, and + yields the 16 node features, the next depth / volume change and the physics data of the continuity + loss for every two-step window; test hydrographs are whole rollouts. PyHazards downloads nothing. +data_characteristics: + - "Layout: ``M80_XY.txt``, ``M80_{CA,CE,CS,A,CU,N,FA,IP}.txt`` (static), ``M80_{WD,V,US_InF,Pr}_.txt`` per hydrograph ``H1`` ... ``H500``, ``train.txt``, ``static_norm_stats.json``, ``dynamic_norm_stats.json``." + - "Training split: sliding windows (``n_time_steps=2``) with ``(node_features (N, 16), edge_features (E, 3), edge_index (2, E), physics)`` and the target (N, 2); batch them with ``hydrograph_collate``." + - "Test split: one item per hydrograph with the first window, the normalised inflow / precipitation and the true depth / volume of the next ``rollout_length`` (30) steps." + - "The release ships no test list: ``train.txt`` names all 500 hydrographs and the example's ``Test/test.txt`` is not published, so ``test_ids`` must be given (they are removed from the training list)." +typical_use_cases: + - Training and evaluating HydroGraphNet as in the PhysicsNeMo example. + - Mesh inundation rollouts scored in metres with the flood benchmark (``flood.inundation``). +access_links: + - label: HydroGraphNet dataset (Zenodo 14969507) + url: https://zenodo.org/records/14969507 + - label: PhysicsNeMo HydroGraphNet example + url: https://github.com/NVIDIA/physicsnemo/tree/main/examples/weather/flood_modeling/hydrographnet +inspection: null +registry: + name: hydrographnet_white_river + example: | + from pyhazards.datasets import load_dataset + + # Unzipped HydroGraphNet.zip; hold out e.g. the last 50 hydrographs for rollouts. + data = load_dataset( + "hydrographnet_white_river", + data_dir="/data/HydroGraphNet", + test_ids=[f"H{i}" for i in range(451, 501)], + ).load() + inputs, target = data.get_split("train").inputs[0] + print(inputs["node_features"].shape, target.shape) # (4787, 16) (4787, 2) + notes: + - "``norm_stats='files'`` uses the released normalisation statistics instead of recomputing them." +primary_references: + - citation: "Taghizadeh, Zandsalimi, Nabian, Shafiee-Jood and Alemazkoor (2025). Interpretable physics-informed graph neural networks for flood forecasting. Computer-Aided Civil and Infrastructure Engineering 40(18):2629-2649." + url: https://doi.org/10.1111/mice.13484 + repo_url: https://github.com/NVIDIA/physicsnemo/tree/main/examples/weather/flood_modeling/hydrographnet +pyhazards_usage: + - Point ``data_dir`` at the unzipped release and pass the test hydrographs as ``test_ids``. + - Score models that provide ``rollout(...)`` (HydroGraphNet) with ``BenchmarkRunner`` on the ``flood`` benchmark (task ``flood.inundation``). +related_models: + - hydrographnet +related_benchmarks: + - flood_benchmark + - hydrographnet_white_river +notes: + - "Every training window, physics value and rollout target equals PhysicsNeMo's HydroGraphDataset on fixtures in the release layout (oracle test); a local check on real hydrographs of the release (H1, H2) matched as well." diff --git a/pyhazards/dataset_cards/ibtracs_tracks.yaml b/pyhazards/dataset_cards/ibtracs_tracks.yaml index 6794e9c4..19e5e3ab 100644 --- a/pyhazards/dataset_cards/ibtracs_tracks.yaml +++ b/pyhazards/dataset_cards/ibtracs_tracks.yaml @@ -2,56 +2,94 @@ slug: ibtracs_tracks display_name: IBTrACS hazard_family: Tropical Cyclone source_role: Track Archive -summary: Synthetic-backed storm-track adapter aligned to the IBTrACS tropical cyclone archive. -provider: NOAA NCEI International Best Track Archive for Climate Stewardship surfaced through a PyHazards adapter +summary: NOAA NCEI's International Best Track Archive for Climate Stewardship (v04r01), read from its CSV or netCDF files into best-track forecasting windows. +provider: NOAA National Centers for Environmental Information (NCEI), merging the WMO Regional Specialized Meteorological Centres and other agencies geometry: Storm-track history sequences -spatial_resolution: Storm-centered best-track sequences -temporal_resolution: Historical track windows with forecast horizons -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned tropical cyclone track and intensity samples -formats: PyTorch tensors via the dataset registry +spatial_resolution: Storm-centre positions (0.1 degree precision) +temporal_resolution: Three-hourly track points (six-hourly synoptic times are used for samples) +update_cadence: Updated by NCEI several times a week; PyHazards reads the file the user downloads +period_of_record: 1842 to present (agency coverage varies by basin and era) +coverage: All tropical cyclone basins (NA, SA, EP, WP, NI, SI, SP) +formats: CSV (ibtracs..list.v04r01.csv) or netCDF (IBTrACS..v04r01.nc) overview: - - IBTrACS is the public storm-track adapter used by PyHazards for shared tropical cyclone benchmark runs. - - The current implementation is synthetic-backed, but it preserves the track-intensity forecasting surface used by the shared tropical cyclone evaluator. + - > + IBTrACS merges the best tracks of the WMO Regional Specialized Meteorological Centres and other + agencies into one archive with a merged position (``LAT`` / ``LON``) and each agency's own positions, + maximum sustained winds and central pressures (``USA_WIND``, ``TOKYO_WIND``, ``CMA_PRES``, ...). + - > + ``ibtracs_tracks`` reads an IBTrACS v04 CSV or netCDF file with PyHazards' own reader + (``pyhazards.datasets.tc.read_ibtracs``) and turns each storm into forecasting windows: ``history`` + six-hourly observations of the chosen variables before a forecast time and the same variables at + ``lead_hours`` after it. data_characteristics: - - Storm-history sequences with future latitude, longitude, and intensity targets. - - Registry-backed benchmark adapter rather than a raw IBTrACS archive loader. - - Supports both basin-specific hurricane models and broader tropical cyclone adapters. + - > + Inputs ``(samples, history, V)`` and targets ``(samples, len(lead_hours), V)`` hold the ``variables`` + in physical units (default latitude, longitude, maximum sustained wind in knots, central pressure in + hPa) from one ``agency`` (default ``usa``; ``wmo`` gives the WMO_WIND / WMO_PRES columns of the + responsible RSMC). Windows need every value present; spur tracks are skipped unless ``include_spur``. + - > + Winds are as reported by each agency, which use different averaging periods (1-minute for the US + agencies, 2-minute for CMA, 10-minute for most RSMCs); IBTrACS does not convert them. + - > + The merged ``LON`` stays continuous across the dateline (values above 180 occur); agency longitudes + are wrapped to [-180, 180) and are unwrapped inside each window. The track error of the benchmark is a + great-circle distance, which does not depend on the convention. + - > + CSV details handled by the reader: the second line holds units, missing values are a single space, + and ``NA`` (North Atlantic) is a basin code, not a missing value. The netCDF file (storm x date_time + arrays) gives the same table. typical_use_cases: - - Hurricast smoke tests. - - Shared tropical cyclone benchmark runs for track and intensity prediction. - - Benchmark-aligned validation for weather-model storm adapters. + - Ground truth for track and intensity forecasts scored by the PyHazards cyclone benchmark. + - Training and evaluating best-track (persistence, CLIPER-style or learned) track and intensity models. access_links: - - label: IBTrACS product page + - label: IBTrACS product page (NOAA NCEI) url: https://www.ncei.noaa.gov/products/international-best-track-archive + - label: v04r01 CSV files + url: https://www.ncei.noaa.gov/data/international-best-track-archive-for-climate-stewardship-ibtracs/v04r01/access/csv/ + - label: v04r01 netCDF files + url: https://www.ncei.noaa.gov/data/international-best-track-archive-for-climate-stewardship-ibtracs/v04r01/access/netcdf/ inspection: null registry: name: ibtracs_tracks example: | from pyhazards.datasets import load_dataset + from pyhazards.datasets.tc import download_ibtracs + path = download_ibtracs("data/ibtracs", subset="NA") # 58 MB; ALL is 333 MB data = load_dataset( "ibtracs_tracks", - micro=True, - history=6, - horizon=5, + path=str(path), + variables=["lat", "lon", "wind", "pres"], + history=4, + lead_hours=[24, 48, 72], + test_seasons=[2023, 2024], ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) + test = data.get_split("test") + print(test.inputs.shape, test.targets.shape, data.metadata["units"]) + notes: + - "path= is an IBTrACS v04 CSV or netCDF file; alternatively cache_dir= with download=True fetches ibtracs..list.v04r01.csv from NCEI." + - "Splits are by season: test_seasons / val_seasons (other seasons train); by default the last season is the test split and the one before validation." + - "Split metadata lists each sample's SID, name, basin, season and forecast time (iso_time)." primary_references: - - citation: IBTrACS - url: https://www.ncei.noaa.gov/products/international-best-track-archive + - citation: "Knapp, K. R., M. C. Kruk, D. H. Levinson, H. J. Diamond and C. J. Neumann (2010). The International Best Track Archive for Climate Stewardship (IBTrACS): Unifying tropical cyclone best track data. Bulletin of the American Meteorological Society 91, 363-376." + url: https://doi.org/10.1175/2009BAMS2755.1 + - citation: "Gahtan, J., K. R. Knapp, C. J. Schreck, H. J. Diamond, J. P. Kossin and M. C. Kruk (2024). International Best Track Archive for Climate Stewardship (IBTrACS) Project, Version 4r01. NOAA National Centers for Environmental Information." + url: https://doi.org/10.25921/82ty-9e16 pyhazards_usage: - - Use this adapter when you want the public IBTrACS-aligned storm-track surface exposed by the tropical cyclone benchmark. -related_models: - - hurricast - - graphcast_tc - - pangu_tc - - fourcastnet_tc + - > + Score forecasts of any model that returns latitude, longitude and intensity at the dataset's lead times + with the ``tc`` benchmark (``tc.track_intensity``): great-circle track error in km and wind / pressure + MAE in knots / hPa, per lead time. +related_models: [] related_benchmarks: - tropical_cyclone_benchmark - ibtracs notes: - - This is a synthetic-backed benchmark adapter rather than a full IBTrACS ingestion pipeline. + - > + Terms of use (NCEI): IBTrACS follows the World Data Center for Meteorology policy of full and open + access, with WMO Resolution 40 as the guide for commercial use; it is not stated to be public domain. + PyHazards downloads it from NCEI on request and never redistributes it; tests use a 4-storm cut of the + official files (tests/fixtures/ibtracs). + - > + The files change several times a week, so they cannot be pinned by checksum; the dataset records the + sha256 of the file it read (metadata source_sha256). diff --git a/pyhazards/dataset_cards/landscan_population.yaml b/pyhazards/dataset_cards/landscan_population.yaml new file mode 100644 index 00000000..b35ccc30 --- /dev/null +++ b/pyhazards/dataset_cards/landscan_population.yaml @@ -0,0 +1,51 @@ +slug: landscan_population +display_name: LandScan Global +hazard_family: Shared Forcing +source_role: Population Exposure +summary: ORNL's annual 30 arc-second global grid of ambient (24-hour average) population, an exposure layer for hazard impact studies. +provider: Oak Ridge National Laboratory (ORNL) +geometry: Gridded population rasters (WGS84 geographic) +spatial_resolution: 30 arc-seconds (about 1 km at the equator); 21,600 x 43,200 cells +temporal_resolution: Annual +update_cadence: Annual releases (LandScan Global 2024 was published in August 2025) +period_of_record: 2000 to 2024 +coverage: Global +formats: GeoTIFF +overview: + - > + LandScan Global estimates the ambient (24-hour average) population of every 30 arc-second cell + of the world, as one grid per year from 2000. + - > + For hazards it is a population-exposure layer: how many people live or spend time where a fire, + flood or storm occurs. +data_characteristics: + - One band of population counts per cell, one file per year. + - Ambient (24-hour average) population rather than night-time residence counts. + - > + Downloads from the ORNL portal require a short registration form; the 2000-2022 releases are + also mirrored on figshare. +typical_use_cases: + - Population exposure to wildfire, flood or tropical-cyclone footprints. + - Weighting hazard maps by the people affected. +access_links: + - label: LandScan portal (ORNL) + url: https://landscan.ornl.gov/ + - label: LandScan Global 2024 record (OSTI) + url: https://www.osti.gov/biblio/2587445 +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for population + exposure. +primary_references: + - citation: Lebakula et al. (2025). LandScan Global 2024. Oak Ridge National Laboratory. + url: https://doi.org/10.48690/1532445 + - citation: Lebakula et al. (2025). LandScan Global 30 Arcsecond Annual Global Gridded Population Datasets from 2000 to 2022. Scientific Data 12, 495. + url: https://doi.org/10.1038/s41597-025-04817-z +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: since May 2022 LandScan Global is released under the Creative Commons Attribution 4.0 + International licence ("free to use, copy, distribute, transmit, and adapt the data for + commercial and non-commercial purposes ... as long as clear attribution of the source is + provided"). The figshare mirror is labelled CC0; the ORNL licence is the authoritative one. diff --git a/pyhazards/dataset_cards/ndfd.yaml b/pyhazards/dataset_cards/ndfd.yaml new file mode 100644 index 00000000..e1fc0e30 --- /dev/null +++ b/pyhazards/dataset_cards/ndfd.yaml @@ -0,0 +1,57 @@ +slug: ndfd +display_name: NDFD +hazard_family: Shared Forcing +source_role: Weather Forecast +summary: The National Weather Service's gridded official forecasts, including relative humidity, wind, Red Flag Warnings and SPC fire-weather outlook grids, archived since 2004. +provider: NOAA National Weather Service (forecast offices and NCEP; the Storm Prediction Center supplies the fire-weather outlooks) +geometry: Gridded forecast fields +spatial_resolution: 2.5 km for CONUS (2145 x 1377 Lambert conformal grid); separate Alaska, Hawaii, Puerto Rico, Guam and oceanic grids +temporal_resolution: Element-dependent forecast steps over days 1-7 +update_cadence: As often as every 30 minutes, depending on the element +period_of_record: 6 June 2004 to the present at NCEI; AWS archive from 16 April 2020 +coverage: United States and territories +formats: GRIB2 +overview: + - > + The National Digital Forecast Database holds the official National Weather Service forecasts + as grids: temperature, humidity, wind, precipitation, sky cover, weather type and hazard + (watch / warning / advisory) elements, written by the forecast offices and national centres. + - > + For wildfire work it carries the fire-weather ingredients forecasters use (minimum relative + humidity, wind and gusts) and the SPC fire-weather outlook grids. +data_characteristics: + - > + Fire-relevant elements: SPC fire-weather outlooks (critfireo, critical and extremely critical + areas, days 1-7; dryfireo, dry thunderstorm areas), minrh / maxrh / rhm, wspd / wdir / wgust, and + the wwa hazard grid, whose codes include Red Flag Warning (FW.W) and Fire Weather Watch (FW.A). + The SPC outlook grids became operational on 14 July 2011 and cover CONUS only. + - > + Archive access depends on the period: NCEI holds data from 6 June 2004 (older years in bulk + archives, recent years online) and AWS from 16 April 2020. + - Some GRIB2 decoders misread the grid scanning order; NOAA recommends degrib, wgrib2 or grib2io. +typical_use_cases: + - Operational fire-weather forecast covariates and Red Flag Warning history. + - Comparing machine-learning forecasts with the official forecast. +access_links: + - label: NDFD at NOAA NCEI (archive) + url: https://www.ncei.noaa.gov/products/weather-climate-models/national-digital-forecast-database + - label: NOAA NDFD on the AWS Registry of Open Data + url: https://registry.opendata.aws/noaa-ndfd/ + - label: Current NDFD GRIB2 files (NWS) + url: https://tgftp.nws.noaa.gov/SL.us008001/ST.opnl/DF.gr2/DC.ndfd/ + - label: NDFD documentation (NOAA MDL) + url: https://vlab.noaa.gov/web/mdl/ndfd +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for official + fire-weather forecasts. +primary_references: + - citation: Glahn and Ruth (2003). The New Digital Forecast Database of the National Weather Service. Bulletin of the American Meteorological Society 84(2), 195-202. + url: https://doi.org/10.1175/BAMS-84-2-195 +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: NWS information is in the public domain unless noted otherwise and may be used for any + lawful purpose as long as users do not claim it as their own, imply NWS endorsement, or present + modified content as official (https://www.weather.gov/disclaimer). diff --git a/pyhazards/dataset_cards/nohrsc_snodas.yaml b/pyhazards/dataset_cards/nohrsc_snodas.yaml new file mode 100644 index 00000000..5857de55 --- /dev/null +++ b/pyhazards/dataset_cards/nohrsc_snodas.yaml @@ -0,0 +1,53 @@ +slug: nohrsc_snodas +display_name: SNODAS +hazard_family: Shared Forcing +source_role: Snow Analysis +summary: NOAA NOHRSC's daily 1 km snow analysis (snow water equivalent, depth, melt, sublimation) for the conterminous United States, distributed by NSIDC since 2003. +provider: NOAA NWS National Operational Hydrologic Remote Sensing Center (NOHRSC); distributed by NOAA@NSIDC as data set G02158 +geometry: Regular latitude-longitude grid +spatial_resolution: 30 arc-seconds (nominally 1 km) +temporal_resolution: Daily; states are snapshots at 06 UTC, fluxes are 24-hour totals from 06 to 06 UTC +update_cadence: Daily +period_of_record: Masked files from 30 September 2003, unmasked files from 9 December 2009; NSIDC discourages use before October 2004 +coverage: Masked version, conterminous United States and some Canadian basins (24.95-52.875 N, 124.733-66.942 W); unmasked version extends into Canada and Mexico +formats: Daily .tar files of gzipped flat binary 16-bit big-endian grids with text headers (NoData -9999) +overview: + - > + SNODAS is a modelling and data-assimilation system developed by NOHRSC to provide the best + possible daily estimates of snow cover and related variables on a 1 km grid, in support of + hydrologic modelling and analysis. + - > + For hazard work it describes snowpack and melt timing, which shape spring flood risk and the + length of the fire season in snow-dominated mountains. +data_characteristics: + - > + Eight variables: snow water equivalent, snow depth, snowmelt runoff, snowpack sublimation, + blowing-snow sublimation, solid and liquid precipitation, and snowpack average temperature. + - > + Known defects documented by NSIDC: snow water equivalent and depth wrongly zero in 126,950 cells + from 9 October 2014 to 10 October 2019 (a repair mask is provided), values saturating at + 32.767 m, snowpack temperature missing before 21 February 2004 and a 5% cell shift on + 1 October 2013. + - The unmasked version's coverage is not consistent until 2013. +typical_use_cases: + - Snowmelt inputs for spring flood and streamflow models. + - Snow-cover duration and melt timing as covariates of mountain fire seasons. +access_links: + - label: NSIDC data set G02158 + url: https://nsidc.org/data/g02158/versions/1 + - label: NSIDC SNODAS file archive + url: https://noaadata.apps.nsidc.org/NOAA/G02158/ +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for snow state. +primary_references: + - citation: National Operational Hydrologic Remote Sensing Center (2004). Snow Data Assimilation System (SNODAS) Data Products at NSIDC, Version 1. NSIDC. + url: https://doi.org/10.7265/N5TB14TC + - citation: Barrett (2003). National Operational Hydrologic Remote Sensing Center Snow Data Assimilation System (SNODAS) Products at NSIDC. NSIDC Special Report 11. + url: https://nsidc.org/sites/default/files/nsidc_special_report_11.pdf +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: NSIDC states "As a condition of using these data, you must cite the use of this data + set" with the citation above. diff --git a/pyhazards/dataset_cards/pick_benchmark_waveforms.yaml b/pyhazards/dataset_cards/pick_benchmark_waveforms.yaml deleted file mode 100644 index 3d945ec2..00000000 --- a/pyhazards/dataset_cards/pick_benchmark_waveforms.yaml +++ /dev/null @@ -1,55 +0,0 @@ -slug: pick_benchmark_waveforms -display_name: pick-benchmark -hazard_family: Earthquake -source_role: Waveform Benchmark -summary: Synthetic-backed waveform picking adapter aligned to the pick-benchmark evaluation ecosystem. -provider: pick-benchmark ecosystem surfaced through a PyHazards adapter -geometry: Multichannel waveform windows -spatial_resolution: Benchmark-defined waveform channels and sample windows -temporal_resolution: Short waveform windows with phase-pick targets -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned earthquake phase-picking samples -formats: PyTorch tensors via the dataset registry -overview: - - pick-benchmark is the public waveform adapter used by the earthquake benchmark for transformer and CNN picking baselines. - - The current implementation is synthetic-backed, but it preserves the phase-picking task shape, labels, and metrics expected by the shared earthquake evaluator. -data_characteristics: - - Multichannel waveform windows paired with P- and S-arrival sample targets. - - Registry-backed benchmark adapter rather than a raw external waveform ingestion path. - - Intended for phase-picking validation and smoke tests. -typical_use_cases: - - EQTransformer and GPD smoke tests. - - Shared earthquake picking benchmark runs. - - Regression checks for waveform-based picking models. -access_links: - - label: pick-benchmark repository - url: https://github.com/seisbench/pick-benchmark -inspection: null -registry: - name: pick_benchmark_waveforms - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "pick_benchmark_waveforms", - micro=True, - channels=3, - length=256, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) -primary_references: - - citation: pick-benchmark - url: https://github.com/seisbench/pick-benchmark -pyhazards_usage: - - Use this adapter when you want the public pick-benchmark-aligned waveform surface exposed by the earthquake benchmark. -related_models: - - eqtransformer - - gpd -related_benchmarks: - - earthquake_benchmark - - pick_benchmark -notes: - - This is a synthetic-backed benchmark adapter rather than a full pick-benchmark downloader. diff --git a/pyhazards/dataset_cards/safnet_cma_era_interim_synthetic.yaml b/pyhazards/dataset_cards/safnet_cma_era_interim_synthetic.yaml new file mode 100644 index 00000000..6e8b3fac --- /dev/null +++ b/pyhazards/dataset_cards/safnet_cma_era_interim_synthetic.yaml @@ -0,0 +1,42 @@ +slug: safnet_cma_era_interim_synthetic +display_name: Synthetic SAF-Net Inputs +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random inputs in the SAF-Net layout (96 wide predictors and (2, 4, 31, 31, 4) u/v wind cubes) for smoke tests of saf_net." +provider: PyHazards (generated in memory; no real storms) +geometry: Tabular feature vectors +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone + benchmark without downloading data. +data_characteristics: + - "Inputs uniform in [0, 1] like the MinMax-scaled official inputs; targets uniform in 10-70 m/s with a prediction_transform that maps the model's scaled output to m/s." +typical_use_cases: + - Smoke tests and CI runs of the linked models and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: safnet_cma_era_interim_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("safnet_cma_era_interim_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. +related_models: + - saf_net +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/seisbench_waveforms.yaml b/pyhazards/dataset_cards/seisbench_waveforms.yaml index 6ec0ef47..294b6cb2 100644 --- a/pyhazards/dataset_cards/seisbench_waveforms.yaml +++ b/pyhazards/dataset_cards/seisbench_waveforms.yaml @@ -1,31 +1,58 @@ slug: seisbench_waveforms -display_name: SeisBench +display_name: SeisBench-format Waveforms hazard_family: Earthquake source_role: Waveform Benchmark -summary: Synthetic-backed waveform picking adapter aligned to the SeisBench ecosystem. -provider: SeisBench ecosystem surfaced through a PyHazards adapter -geometry: Multichannel waveform windows -spatial_resolution: Benchmark-defined waveform channels and sample windows -temporal_resolution: Short waveform windows with phase-pick targets -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned earthquake phase-picking samples -formats: PyTorch tensors via the dataset registry +summary: Reader for labelled three-component waveform datasets in the SeisBench format (STEAD, INSTANCE, ETHZ, ... as distributed for SeisBench) and in STEAD's own CSV + HDF5 layout. +provider: Dataset authors (STEAD - Stanford; INSTANCE - INGV; others via SeisBench); read by PyHazards +geometry: Three-component station waveform windows +spatial_resolution: Single seismic stations +temporal_resolution: Dataset sampling rate (100 Hz for STEAD and INSTANCE) +update_cadence: Static benchmark releases downloaded by the user +period_of_record: Dataset dependent (see the dataset papers) +coverage: Dataset dependent (STEAD global; INSTANCE Italy) +formats: metadata CSV + waveform HDF5 overview: - - SeisBench is the public waveform adapter used by PyHazards for the earthquake picking path. - - The current implementation is synthetic-backed, but it preserves the picking task shape, labels, and metrics expected by the shared earthquake evaluator. + - > + ``seisbench_waveforms`` reads real phase-picking datasets from disk: the SeisBench format + (``metadata.csv`` + ``waveforms.hdf5``, optionally in chunks, with trace blocks + ``$``) and the layout in which the STEAD authors distribute STEAD + (``.csv`` + ``.hdf5``, one ``(6000, 3)`` E/N/Z array per trace). PyHazards implements + the reader itself with ``h5py`` and ``csv``; SeisBench (GPL-3.0) is not imported. Its output equals + SeisBench's ``WaveformDataset`` on a dataset written by SeisBench's ``WaveformDataWriter`` + (``tests/oracle/test_seisbench_reader_oracle.py``). + - > + Nothing is downloaded or redistributed: STEAD is about 85 GB and INSTANCE's event waveforms about + 160 GB. Download them from their providers (or with SeisBench, which converts them to its format) + and pass the directory as ``path``. data_characteristics: - - Multichannel waveform windows paired with P- and S-arrival sample targets. - - Registry-backed benchmark adapter rather than a raw external waveform ingestion path. - - Intended for phase-picking validation and smoke tests. + - > + Inputs ``(n, 3, window)`` float32 in the dataset's component order (``metadata["component_order"]``, + e.g. ``ZNE`` for SeisBench files, ``ENZ`` for STEAD's own files); the earthquake benchmark reorders + channels to each model's order. Targets ``(n, 2)``: P and S arrival samples relative to the window + start, NaN when a trace has no such arrival (noise traces) or it falls outside the window. + - > + Splits follow the dataset's ``split`` column (``train`` / ``dev`` -> ``val`` / ``test``). STEAD's own + files have no split: ``test_trace_names`` (e.g. EQTransformer's ``ModelsAndSampleData/test.npy``) + selects the test traces and the rest are ``train``; without it all traces are ``test``. + - > + Arrival columns are read in order of preference (``trace_p_arrival_sample``, + ``trace_P_arrival_sample``, ``trace_P1_arrival_sample``, ``trace_Pg_arrival_sample``, ... and the S + equivalents; ``p_arrival_sample`` / ``s_arrival_sample`` for STEAD files); ``phase_columns`` + overrides the list. + - > + Licences: STEAD and INSTANCE are CC BY 4.0 (STEAD repository LICENSE; INGV INSTANCE page and + repository). Cite the dataset papers below when publishing results. typical_use_cases: - - PhaseNet and EQNet smoke tests. - - Shared earthquake benchmark runs on picking tasks. - - Regression checks for waveform-based seismic models. + - Scoring PhaseNet, EQTransformer and GPD (official weights) with the ``earthquake.picking`` benchmark. + - Training phase pickers on real labelled waveforms. access_links: - - label: SeisBench paper - url: https://joss.theoj.org/papers/10.21105/joss.04418 - - label: SeisBench repository + - label: STEAD (download links and licence) + url: https://github.com/smousavi05/STEAD + - label: INSTANCE (INGV) + url: https://www.pi.ingv.it/instance/ + - label: SeisBench data format + url: https://seisbench.readthedocs.io/en/stable/pages/data_format.html + - label: SeisBench repository (GPL-3.0) url: https://github.com/seisbench/seisbench inspection: null registry: @@ -33,26 +60,41 @@ registry: example: | from pyhazards.datasets import load_dataset - data = load_dataset( + # A SeisBench-format directory (metadata.csv + waveforms.hdf5), e.g. SeisBench's copy of STEAD. + data = load_dataset("seisbench_waveforms", path="~/.seisbench/datasets/stead", max_traces=1000).load() + + # STEAD as distributed by its authors (merged.csv + merged.hdf5) with EQTransformer's test split. + stead = load_dataset( "seisbench_waveforms", - micro=True, - channels=3, - length=256, + path="/data/STEAD", + preset="stead", + test_trace_names="/data/STEAD/test.npy", ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) -primary_references: - - citation: SeisBench - A Toolbox for Machine Learning in Seismology - url: https://joss.theoj.org/papers/10.21105/joss.04418 + test = stead.get_split("test") + print(test.inputs.shape, test.targets.shape) # (n, 3, 6000), (n, 2) + notes: + - "``window_samples`` / ``window_start`` cut a fixed window (zero-padded when a trace is shorter); traces of different lengths need it." + - "``max_traces`` keeps the first rows of each split (``micro=True`` keeps 8); ``trace_category`` filters STEAD's ``earthquake_local`` / ``noise`` rows." + - "``preset='instance'`` supplies INSTANCE's component order (E, N, Z) and 100 Hz when the files lack a ``data_format`` group." +references: + - citation: "Woollam, J., Münchmeyer, J., Tilmann, F., et al. (2022). SeisBench - A Toolbox for Machine Learning in Seismology. Seismological Research Letters 93(3):1695-1709." + url: https://doi.org/10.1785/0220210324 repo_url: https://github.com/seisbench/seisbench + - citation: "Mousavi, S. M., Sheng, Y., Zhu, W., Beroza, G. C. (2019). STanford EArthquake Dataset (STEAD): A Global Data Set of Seismic Signals for AI. IEEE Access 7:179464-179476." + url: https://doi.org/10.1109/ACCESS.2019.2947848 + repo_url: https://github.com/smousavi05/STEAD + - citation: "Michelini, A., Cianetti, S., Gaviano, S., Giunchi, C., Jozinović, D., Lauciani, V. (2021). INSTANCE - the Italian seismic dataset for machine learning. Earth System Science Data 13:5509-5544." + url: https://doi.org/10.5194/essd-13-5509-2021 + repo_url: https://github.com/INGV/instance pyhazards_usage: - - Use this adapter when you want the public SeisBench-aligned waveform surface exposed by the earthquake benchmark. + - Pair it with ``phasenet``, ``eqtransformer`` (60-s windows, ``window_samples=6000``) or ``gpd`` and the ``earthquake`` benchmark (``hazard_task=earthquake.picking``). related_models: - phasenet - - eqnet + - eqtransformer + - gpd related_benchmarks: - earthquake_benchmark - seisbench + - pick_benchmark notes: - - This is a synthetic-backed benchmark adapter rather than a full SeisBench ingestion pipeline. + - "Until this release ``seisbench_waveforms`` and ``pick_benchmark_waveforms`` generated synthetic Gaussian pulses; the synthetic data is now ``earthquake_waveforms_synthetic``." diff --git a/pyhazards/dataset_cards/ships_xu2021.yaml b/pyhazards/dataset_cards/ships_xu2021.yaml new file mode 100644 index 00000000..42e67362 --- /dev/null +++ b/pyhazards/dataset_cards/ships_xu2021.yaml @@ -0,0 +1,63 @@ +slug: ships_xu2021 +display_name: SHIPS Predictors (Xu et al. 2021) +hazard_family: Tropical Cyclone +source_role: Intensity Benchmark +summary: The standardised SHIPS predictor table of Xu et al. (2021) with 24-hour intensity-change targets, read into the official leave-one-year-out folds. +provider: Xu et al. (PNNL), "Supporting data for Xu et al. 2021 - Weather and Forecasting" (Zenodo 4784610, CC BY 4.0), built from the SHIPS developmental data (NHC / CIRA) +geometry: Tabular feature vectors +spatial_resolution: One row per storm and forecast time +temporal_resolution: Six-hourly forecast times +update_cadence: Static release (2021) +period_of_record: Reanalysis predictors 1982-2017 (global basins); operational predictors 2010-2018 (Atlantic) +coverage: Atlantic test basin; global training basins (AL, EP, WP, SH, ...) +formats: CSV (train_global_fill_REA_na_wo_img_scaled.csv, 392 MB) +overview: + - > + Each row holds the SHIPS predictors of one storm at one forecast time, standardised by the reanalysis + standard deviation, with ``name``, ``year``, ``basin``, ``type`` (``rea`` reanalysis predictors or + ``opr`` operational predictors) and the target ``dvs24``, the 24-hour change of the maximum sustained + wind in knots. + - > + ``ships_xu2021`` selects the 121 predictors of the paper's 24-hour model (``SHIPS_PREDICTORS``) and builds + the fold of ``leave_out_year`` as the official ``load_loyo_data`` does for the MLP: training rows are + reanalysis rows except Atlantic rows of that year, test rows are that year's operational rows, and a + random 10 % of the training rows (seeded) is the validation split. +data_characteristics: + - Inputs (samples, 121) float32 standardised predictors in the official order; targets (samples,) dvs24 in knots. + - Split metadata gives each row's year (``groups``), storm name and basin; the benchmark reports MAE per test year. + - Rows with a missing predictor or target are dropped (``drop_missing``). +typical_use_cases: + - Training and evaluating the ``tropicalcyclone_mlp`` 24-hour intensity-change model (``tc.intensity`` task). +access_links: + - label: Zenodo record 4784610 (CC BY 4.0) + url: https://doi.org/10.5281/zenodo.4784610 + - label: tropicalcyclone_MLP repository + url: https://github.com/wenweixu/tropicalcyclone_MLP +inspection: null +registry: + name: ships_xu2021 + example: | + from pyhazards.datasets import load_dataset + + fold = load_dataset("ships_xu2021", path="train_global_fill_REA_na_wo_img_scaled.csv", leave_out_year=2018).load() + test = fold.get_split("test") + print(test.inputs.shape, test.targets.shape) # (cases, 121), (cases,) + notes: + - "The paper's leave-one-year-out test averages the folds 2010-2018 (2,464 Atlantic cases)." +primary_references: + - citation: "Xu, W., K. Balaguru, A. August, N. Lalo, N. Hodas, M. DeMaria and D. Judi (2021). Deep Learning Experiments for Tropical Cyclone Intensity Forecasts. Weather and Forecasting 36(4), 1453-1470." + url: https://doi.org/10.1175/WAF-D-20-0104.1 + - citation: "Xu, W., et al. (2021). Supporting data for Xu et al. 2021 - Weather and Forecasting (Version 1). Zenodo." + url: https://doi.org/10.5281/zenodo.4784610 +pyhazards_usage: + - "Score with the ``tc`` benchmark and ``hazard_task: tc.intensity`` (MAE / RMSE in knots, per test year)." +related_models: + - tropicalcyclone_mlp +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - > + The official loyo_testing.py reads a ``..._w2020.csv`` variant that is not in the Zenodo record. The + independent 2019 / 2020 operational files of the record are not standardised and are not read. + - > + PyHazards never redistributes the table; tests use ten real rows cut from it (tests/fixtures/ships_xu2021). diff --git a/pyhazards/dataset_cards/ships_xu2021_synthetic.yaml b/pyhazards/dataset_cards/ships_xu2021_synthetic.yaml new file mode 100644 index 00000000..8e27c882 --- /dev/null +++ b/pyhazards/dataset_cards/ships_xu2021_synthetic.yaml @@ -0,0 +1,42 @@ +slug: ships_xu2021_synthetic +display_name: Synthetic SHIPS Predictors +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random inputs in the layout of ships_xu2021 (121 predictors, 24-hour intensity change in knots) for smoke tests of tropicalcyclone_mlp." +provider: PyHazards (generated in memory; no real storms) +geometry: Tabular feature vectors +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone + benchmark without downloading data. +data_characteristics: + - "(samples, 121) standard-normal inputs; targets are a fixed random linear function of two inputs plus noise, rounded, labelled knots; test years 2017 / 2018 alternate." +typical_use_cases: + - Smoke tests and CI runs of the linked models and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: ships_xu2021_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("ships_xu2021_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. +related_models: + - tropicalcyclone_mlp +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/tc_tracks_synthetic.yaml b/pyhazards/dataset_cards/tc_tracks_synthetic.yaml new file mode 100644 index 00000000..c010f0a8 --- /dev/null +++ b/pyhazards/dataset_cards/tc_tracks_synthetic.yaml @@ -0,0 +1,43 @@ +slug: tc_tracks_synthetic +display_name: Synthetic Storm Histories +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random storm-history features and lat / lon / intensity targets for smoke tests of the generic experimental storm adapters (hurricast, tcif_fusion)." +provider: PyHazards (generated in memory; no real storms) +geometry: Storm-track history sequences +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone + benchmark without downloading data. +data_characteristics: + - "(samples, history=6, features=8) standard-normal inputs; targets (samples, horizon=5, 3) are the last step's first three features plus a fixed drift, labelled lat, lon and wind with lead times 6-30 h." +typical_use_cases: + - Smoke tests and CI runs of the linked models and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: tc_tracks_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("tc_tracks_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. +related_models: + - hurricast + - tcif_fusion +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/tcbench_alpha.yaml b/pyhazards/dataset_cards/tcbench_alpha.yaml index 2e7a379f..b1fb7f9e 100644 --- a/pyhazards/dataset_cards/tcbench_alpha.yaml +++ b/pyhazards/dataset_cards/tcbench_alpha.yaml @@ -2,55 +2,55 @@ slug: tcbench_alpha display_name: TCBench Alpha hazard_family: Tropical Cyclone source_role: Track Benchmark -summary: Synthetic-backed storm-track benchmark adapter aligned to the TCBench Alpha ecosystem. -provider: TCBench Alpha ecosystem surfaced through a PyHazards adapter -geometry: Storm-track history sequences -spatial_resolution: Storm-centered best-track sequences -temporal_resolution: Historical track windows with forecast horizons -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned tropical cyclone track and intensity samples -formats: PyTorch tensors via the dataset registry +summary: Weather-model cyclone tracks (Pangu-Weather, FourCastNet v2, AIFS; 2023) matched to IBTrACS, with the raw forecast fields they were tracked in; read by pyhazards.forecasts at a pinned revision. +provider: TCBench project (Gomez et al.), MIT-licensed code and data on the Hugging Face Hub (TCBench/TCBench) +geometry: Storm-track tables and global gridded forecast fields +spatial_resolution: 0.25-degree global fields; track points on that grid +temporal_resolution: Six-hourly forecast steps to 120 h, initialised at 00 and 12 UTC +update_cadence: Static release (PyHazards pins revision 0124d14d) +period_of_record: 2023 forecasts (TCBench's test year) +coverage: Global tropical cyclones present in IBTrACS +formats: CSV track tables (matched_tracks, unmatched_tracks) and netCDF4 forecast fields (about 3 GB per forecast) overview: - - TCBench Alpha is the public storm adapter used by several tropical cyclone baselines on the shared track-intensity evaluator. - - The current implementation is synthetic-backed, but it preserves the task, metric, and reporting surface used by the shared tropical cyclone benchmark. + - > + TCBench provides data-processing tools, evaluation protocols and baselines to compare tropical cyclone + forecasts: tracks extracted from numerical and data-driven weather models with TempestExtremes are + matched with IBTrACS best tracks and scored by lead time. + - > + ``pyhazards.forecasts.tcbench`` reads the released ``matched_tracks`` and ``unmatched_tracks`` files + and, with HTTP range requests, only the variables a tracker needs from the raw forecast files. + ``pyhazards.forecasts.tempest`` reproduces TCBench's TempestExtremes tracks from those fields byte for + byte, and ``score_forecast_tracks(..., protocol="tcbench")`` its evaluation. data_characteristics: - - Storm-history sequences with future latitude, longitude, and intensity targets. - - Registry-backed benchmark adapter rather than a raw external benchmark ingestion path. - - Intended for benchmark-linked track-intensity forecasting runs. + - "matched_tracks/2023_.csv: SID, Initial Time, Valid Time, wind max (m/s in the released files), pressure min (Pa), lat, lon." + - "unmatched_tracks: TempestExtremes StitchNodes CSV per forecast (track_id, time, grid indices, lon, lat, slp, wind10)." + - "neural_weather_models: int16-packed netCDF4 fields (msl, u10, v10, t2m and u, v, z, t, q on 13 levels for Pangu-Weather) for lead times 6-120 h." + - "TCBench's evaluation reads IBTrACS LAT / LON as float16, which shifts its position errors by up to several km; the tcbench protocol reproduces this." typical_use_cases: - - Tropical Cyclone MLP, SAF-Net, and TCIF-fusion smoke tests. - - Shared tropical cyclone benchmark runs. - - Regression checks for storm-track baselines. + - Scoring weather-model cyclone tracks against IBTrACS with TCBench's protocol. + - Re-tracking published weather-model forecasts with other trackers (e.g. the ECMWF-style tracker of the Pangu-Weather and GraphCast papers). access_links: - label: TCBench Alpha repository url: https://github.com/msgomez06/TCBench_Alpha + - label: TCBench data on the Hugging Face Hub + url: https://huggingface.co/datasets/TCBench/TCBench inspection: null -registry: - name: tcbench_alpha - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "tcbench_alpha", - micro=True, - history=6, - horizon=5, - ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) +registry: null primary_references: - - citation: TCBench Alpha + - citation: "Gomez, M. et al. (2026). TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at the Global Scale. arXiv:2601.23268." + url: https://arxiv.org/abs/2601.23268 + - citation: TCBench Alpha (repository and documentation) url: https://github.com/msgomez06/TCBench_Alpha pyhazards_usage: - - Use this adapter when you want the public TCBench Alpha-aligned storm surface exposed by the tropical cyclone benchmark. -related_models: - - tropicalcyclone_mlp - - saf_net - - tcif_fusion + - > + Not a registered dataset: the tracks are forecasts, not training data. Use + ``pyhazards.forecasts.read_tcbench_matched_tracks`` / ``read_tcbench_fields`` and score with + ``pyhazards.forecasts.score_forecast_tracks`` against IBTrACS (see the Foundation Weather Models page). +related_models: [] related_benchmarks: - tropical_cyclone_benchmark - tcbench_alpha notes: - - This is a synthetic-backed benchmark adapter rather than a full TCBench Alpha ingestion pipeline. + - The repository and the Hugging Face dataset are MIT-licensed (Copyright (c) 2023 Milton Gomez). + - The Pangu-Weather forecasts derive from weights licensed CC BY-NC-SA 4.0 (non-commercial use only). + - TCBench's "FourCastNet v2" is NVIDIA's SFNO-small, not the FourCastNet (AFNO) of Pathak et al. 2022. diff --git a/pyhazards/dataset_cards/tcif_fusion_synthetic.yaml b/pyhazards/dataset_cards/tcif_fusion_synthetic.yaml new file mode 100644 index 00000000..330ac2b4 --- /dev/null +++ b/pyhazards/dataset_cards/tcif_fusion_synthetic.yaml @@ -0,0 +1,42 @@ +slug: tcif_fusion_synthetic +display_name: Synthetic TCIF-fusion Inputs +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random inputs in the TCIF-fusion layout (ERA5 U, V, W, SST, ALL, 30 history features, infrared images; channels last) for smoke tests of tcif_fusion." +provider: PyHazards (generated in memory; no real storms) +geometry: Gridded fields, images and feature vectors +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run tcif_fusion and the cyclone + benchmark; the paper's inputs (CMA best track, ERA5, GridSat-B1) have no PyHazards reader yet. +data_characteristics: + - "u, v, w (N, grid, grid, 5, 4), sst (N, grid, grid, 5, 1), all (their concatenation, 65 channels), his (N, 30), ir (N, ir_size, ir_size, 5); targets uniform 10-70 m/s. The defaults are the paper's sizes (grid 25, IR 224); the smoke config uses grid 9 and IR 32 with a small model." +typical_use_cases: + - Smoke tests and CI runs of tcif_fusion and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: tcif_fusion_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("tcif_fusion_synthetic", micro=True, grid_size=9, ir_size=32).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests. +related_models: + - tcif_fusion +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/tropicyclonenet_dataset.yaml b/pyhazards/dataset_cards/tropicyclonenet_dataset.yaml index 7e07af51..9be28922 100644 --- a/pyhazards/dataset_cards/tropicyclonenet_dataset.yaml +++ b/pyhazards/dataset_cards/tropicyclonenet_dataset.yaml @@ -1,28 +1,54 @@ slug: tropicyclonenet_dataset -display_name: TropiCycloneNet-Dataset +display_name: TropiCycloneNet Dataset hazard_family: Tropical Cyclone source_role: Track Benchmark -summary: Synthetic-backed storm-track benchmark adapter aligned to the TropiCycloneNet-Dataset ecosystem. -provider: TropiCycloneNet-Dataset ecosystem surfaced through a PyHazards adapter +summary: The TropiCycloneNet Dataset (TCND) of Huang et al. (2025) - best tracks, environmental features and ERA5 500 hPa geopotential for 3,630 storms in six basins - read in the layout of the official TropiCycloneNet loader. +provider: Huang et al. (authors of the TropiCycloneNet paper), Zenodo releases under CC BY 4.0 geometry: Storm-track history sequences -spatial_resolution: Storm-centered best-track sequences -temporal_resolution: Historical track windows with forecast horizons -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned tropical cyclone track and intensity samples -formats: PyTorch tensors via the dataset registry +spatial_resolution: Storm-centre positions (0.1 degree); 20 x 20 degree ERA5 crops at 0.25 degree +temporal_resolution: Six-hourly +update_cadence: Static releases (Zenodo 15009527 dataset, 17104690 training data) +period_of_record: 1950-2023 (paper experiments 1950-2016 train / validation, 2017-2021 test) +coverage: Six basins (EP, NA, NI, SI, SP, WP) +formats: Tab-separated Data1d text files, pickled Env-Data .npy dicts, GPH .npy crops (and Data3d netCDF) overview: - - TropiCycloneNet-Dataset is the public storm adapter used by the TropiCycloneNet model path on the shared track-intensity evaluator. - - The current implementation is synthetic-backed, but it preserves the task, metric, and reporting surface used by the shared tropical cyclone benchmark. + - > + TCND combines Data1d (best-track position, central pressure and 2-minute maximum wind, normalised), + Data3d (ERA5 geopotential, wind and SST around the storm) and Env-Data (intensity class, motion, + month, location bins, 12/24-hour motion direction, 24-hour intensity change). It is the training and + test data of the TropiCycloneNet model. + - > + ``tropicyclonenet_dataset`` builds samples exactly like the official ``TrajectoryDataset`` and + ``seq_collate`` (checked by an oracle test): windows of 8 observed and 4 future six-hourly steps, the + observed track and its steps, Env-Data per observed step and 64 x 64 scaled 500 hPa geopotential + frames; targets are the future latitude, longitude, pressure (hPa) and wind (m/s). data_characteristics: - - Storm-history sequences with future latitude, longitude, and intensity targets. - - Registry-backed benchmark adapter rather than a raw external dataset ingestion path. - - Intended for benchmark-linked storm forecasting smoke runs. + - > + Expected layout (the official loader's names under ``root``): ``BST_data///BST.txt``, + ``Env_data////.npy`` and ``ERA5_gph500////.npy``; + the Zenodo training-data archives extract to ``bst_divi10_train_val_test_inlcude15_2023``, + ``all_area_correct_location_includeunder15_2023`` and ``all_ocean_gph500_2023`` (pass them as + ``data1d_dir``, ``env_dir`` and ``gph_dir``). + - > + Normalisation of Data1d: longitude = 5 x + 180 degrees east, latitude = 5 y, pressure = 50 p + 960 hPa, + wind = 25 w + 40 m/s. GPH crops (100 x 100) are resized to 64 x 64 bilinearly and scaled with the + range (44490.578125, 58768.4486860389), clipped to [0, 1]. + - > + Env-Data features that are not yet defined (value -1, e.g. the 24-hour history at a track's start) + are replaced by the first defined value in the window, as the official loader does. The Env-Data files + also contain future-looking keys (future_direction24, future_inte_change24), which are not read. + - > + The whole requested split is loaded into memory (about 0.13 MB per sample); restrict ``areas``, + ``splits`` or ``max_samples`` for large runs. Env-Data files are pickled numpy objects (loaded with + allow_pickle); only read files from the official release. typical_use_cases: - - TropiCycloneNet smoke tests. - - Shared tropical cyclone benchmark runs. - - Regression checks for track-intensity prediction models. + - Training and evaluating TropiCycloneNet (``tropicyclonenet``) with its official inputs. + - Multi-basin track and intensity forecasting at 6-24 h scored with the cyclone benchmark. access_links: + - label: TCND on Zenodo (10.5281/zenodo.15009527) + url: https://doi.org/10.5281/zenodo.15009527 + - label: TCN_M training data on Zenodo (record 17104690) + url: https://zenodo.org/records/17104690 - label: TropiCycloneNet-Dataset repository url: https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset inspection: null @@ -33,22 +59,31 @@ registry: data = load_dataset( "tropicyclonenet_dataset", - micro=True, - history=6, - horizon=5, + data1d_dir="TCND/bst_divi10_train_val_test_inlcude15_2023", + env_dir="TCND/all_area_correct_location_includeunder15_2023", + gph_dir="TCND/all_ocean_gph500_2023", + areas=["WP"], + splits=["test"], ).load() - - train = data.get_split("train") - print(train.inputs.shape, train.targets.shape) + test = data.get_split("test") + print(test.inputs["obs_traj"].shape, test.inputs["image_obs"].shape, test.targets.shape) + notes: + - "Inputs are a dict: obs_traj / obs_traj_rel (8, N, 4), image_obs (N, 1, 8, 64, 64), env_data (nine arrays (N, 8, width)); targets (N, 4, 4) = lat, lon, pres, wind at 6-24 h." + - "root= is accepted when the three folders are named BST_data, Env_data and ERA5_gph500." primary_references: - - citation: TropiCycloneNet-Dataset - url: https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset + - citation: "Huang, C., P. Mu, J. Zhang, S. Chan, S. Zhang, H. Yan, S. Chen and C. Bai (2025). Benchmark dataset and deep learning method for global tropical cyclone forecasting. Nature Communications 16, 5923." + url: https://doi.org/10.1038/s41467-025-61087-4 pyhazards_usage: - - Use this adapter when you want the public TropiCycloneNet-Dataset-aligned storm surface exposed by the tropical cyclone benchmark. + - > + Score ``tropicyclonenet`` (or any model with a ``forecast`` method returning lat / lon / pres / wind) + with the ``tc`` benchmark; sampled forecasts get the paper's best-of-k errors and sample-mean errors. related_models: - tropicyclonenet related_benchmarks: - tropical_cyclone_benchmark - tropicyclonenet_dataset notes: - - This is a synthetic-backed benchmark adapter rather than a full TropiCycloneNet-Dataset downloader. + - > + Licence: the Zenodo releases are CC BY 4.0 (the GitHub dataset repository has no LICENSE file although + its README mentions MIT). PyHazards never redistributes the data; tests use one storm's real Data1d and + Env-Data files (EP 2018 Carlotta, tests/fixtures/tcnd) and generated geopotential crops of the real shape. diff --git a/pyhazards/dataset_cards/tropicyclonenet_dataset_synthetic.yaml b/pyhazards/dataset_cards/tropicyclonenet_dataset_synthetic.yaml new file mode 100644 index 00000000..998d4c75 --- /dev/null +++ b/pyhazards/dataset_cards/tropicyclonenet_dataset_synthetic.yaml @@ -0,0 +1,42 @@ +slug: tropicyclonenet_dataset_synthetic +display_name: Synthetic TCND Samples +hazard_family: Tropical Cyclone +source_role: Synthetic Smoke Data +summary: "Random inputs in the TropiCycloneNet (TCND) layout with random-walk targets for smoke tests of tropicyclonenet." +provider: PyHazards (generated in memory; no real storms) +geometry: Storm-track history sequences +spatial_resolution: Not applicable (random numbers) +temporal_resolution: Not applicable (random numbers) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Every value is a random number; nothing in it describes real tropical cyclones and + scores on it mean nothing. It exists so that smoke tests and CI can run the models and the cyclone + benchmark without downloading data. +data_characteristics: + - "obs_traj / obs_traj_rel (8, N, 4) normalised random walks, image_obs (N, 1, 8, 64, 64) uniform, env_data random one-hot features; targets (N, 4, 4) lat, lon, pressure (hPa) and wind (m/s) continuing the walk." +typical_use_cases: + - Smoke tests and CI runs of the linked models and of the cyclone benchmark. +access_links: [] +inspection: null +registry: + name: tropicyclonenet_dataset_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("tropicyclonenet_dataset_synthetic", micro=True).load() + print(data.metadata["synthetic"]) # True +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/tc/synthetic.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests; real data are ibtracs_tracks, ships_xu2021 and tropicyclonenet_dataset. +related_models: + - tropicyclonenet +related_benchmarks: + - tropical_cyclone_benchmark +notes: + - Bundle metadata carries synthetic=True, and benchmark results report it. diff --git a/pyhazards/dataset_cards/urbanfloodcast_synthetic.yaml b/pyhazards/dataset_cards/urbanfloodcast_synthetic.yaml new file mode 100644 index 00000000..60f8966d --- /dev/null +++ b/pyhazards/dataset_cards/urbanfloodcast_synthetic.yaml @@ -0,0 +1,46 @@ +slug: urbanfloodcast_synthetic +display_name: Synthetic Urban Flood Events +hazard_family: Flood +source_role: Synthetic Smoke Data +summary: "Random urban flood events in the UrbanFloodCast one-shot layout (current state, rainfall and terrain in; depth and discharges of 24 steps out), for smoke tests of urbanfloodcast." +provider: PyHazards (generated in memory; no real flood) +geometry: Raster inundation sequences +spatial_resolution: Not applicable (32 x 32 synthetic cells) +temporal_resolution: Not applicable (24 synthetic output steps) +update_cadence: Generated on every load +period_of_record: None (synthetic) +coverage: None (synthetic) +formats: PyTorch tensors via the dataset registry +overview: + - > + Synthetic data. Each event is a random rain pulse on a tilted random terrain with NaN "buildings"; + scores on it mean nothing. The events go through ``prepare_urbanfloodcast_event``, the official + UrbanFloodCast one-shot preparation (checked against the official ``flood_data``), so the inputs + ``(n, Sy, Sx, 24, 1, 5)``, targets ``(n, Sy, Sx, 24, 3)`` and NaN mask have the layout of the real + benchmark. PyHazards has no reader for the Berlin GeoTIFFs yet (Zenodo 10.5281/zenodo.15700880). +data_characteristics: + - "Inputs per cell and step: depth, x / y unit discharge at the start (repeated), log(1 + rain / 0.01) / 10, terrain L2-normalised along x; targets: depth, x / y unit discharge; the mask is in ``split.metadata['mask']``." +typical_use_cases: + - Smoke tests and CI runs of urbanfloodcast and of the ``flood.inundation`` raster evaluation. +access_links: + - label: UrbanFloodCast benchmark dataset (Zenodo, real data, not read by PyHazards) + url: https://doi.org/10.5281/zenodo.15700880 +inspection: null +registry: + name: urbanfloodcast_synthetic + example: | + from pyhazards.datasets import load_dataset + + data = load_dataset("urbanfloodcast_synthetic", micro=True).load() + print(data.get_split("train").inputs.shape) # (2, 32, 32, 24, 1, 5) +primary_references: + - citation: PyHazards synthetic smoke data (pyhazards/datasets/flood/urbanfloodcast.py) + url: https://github.com/LabRAI/PyHazards +pyhazards_usage: + - Use only for smoke tests. +related_models: + - urbanfloodcast +related_benchmarks: + - flood_benchmark +notes: + - Bundle metadata carries synthetic=True. diff --git a/pyhazards/dataset_cards/waterbench_streamflow.yaml b/pyhazards/dataset_cards/waterbench_streamflow.yaml deleted file mode 100644 index f22206ce..00000000 --- a/pyhazards/dataset_cards/waterbench_streamflow.yaml +++ /dev/null @@ -1,57 +0,0 @@ -slug: waterbench_streamflow -display_name: WaterBench -hazard_family: Flood -source_role: Streamflow Benchmark -summary: Synthetic-backed streamflow benchmark adapter aligned to the WaterBench ecosystem. -provider: WaterBench ecosystem surfaced through a PyHazards adapter -geometry: Graph-temporal basin or node sequences -spatial_resolution: Basin or gauge nodes represented as graph elements -temporal_resolution: Rolling history windows for streamflow prediction -update_cadence: Generated locally for smoke and benchmark-alignment runs -period_of_record: Synthetic-backed benchmark adapter -coverage: Benchmark-aligned streamflow forecasting samples -formats: PyTorch graph-temporal dataset objects via the dataset registry -overview: - - WaterBench is the public flood streamflow adapter used by the EA-LSTM path on the shared flood benchmark. - - The current implementation is synthetic-backed, but it preserves the streamflow forecasting contract expected by the shared evaluator. -data_characteristics: - - Graph-temporal sequences with node-level targets for next-step streamflow prediction. - - Registry-backed benchmark adapter rather than a raw WaterBench ingestion pipeline. - - Intended for benchmark-linked streamflow smoke runs. -typical_use_cases: - - EA-LSTM smoke tests. - - Shared flood benchmark runs with streamflow metrics. - - Regression checks for basin-scale forecasting experiments. -access_links: - - label: WaterBench abstract - url: https://neurips.cc/virtual/2023/80632 - - label: WaterBench repository - url: https://github.com/uihilab/WaterBench -inspection: null -registry: - name: waterbench_streamflow - example: | - from pyhazards.datasets import load_dataset - - data = load_dataset( - "waterbench_streamflow", - micro=True, - history=4, - nodes=6, - ).load() - - train = data.get_split("train") - print(len(train.inputs), train.inputs[0].x.shape) -primary_references: - - citation: "WaterBench: A Large-scale Benchmark Dataset for Data-driven Streamflow Forecasting" - url: https://neurips.cc/virtual/2023/80632 - repo_url: https://github.com/uihilab/WaterBench -pyhazards_usage: - - Use this adapter when you want the public WaterBench-aligned streamflow surface exposed by the flood benchmark. -related_models: - - neuralhydrology_ealstm -related_benchmarks: - - flood_benchmark - - waterbench -notes: - - This is a synthetic-backed benchmark adapter rather than a full WaterBench downloader. diff --git a/pyhazards/dataset_cards/wildfire_track_o.yaml b/pyhazards/dataset_cards/wildfire_track_o.yaml new file mode 100644 index 00000000..e7e32846 --- /dev/null +++ b/pyhazards/dataset_cards/wildfire_track_o.yaml @@ -0,0 +1,118 @@ +slug: wildfire_track_o +display_name: Track-O Wildfire Occurrence +hazard_family: Wildfire +source_role: Occurrence Benchmark +summary: Daily fire / no-fire grids from NASA FIRMS detections with gridded weather and LANDFIRE fuel covariates, built locally for gridded wildfire-danger experiments. +provider: "PyHazards cache builder (PR #33, runyangxu) over NASA FIRMS, MERRA-2 or other gridded weather, and LANDFIRE" +geometry: Daily latitude-longitude grids +spatial_resolution: That of the weather grid (0.5 deg x 0.625 deg for MERRA-2), optionally subsampled +temporal_resolution: Daily (UTC days) +update_cadence: Built by the user from downloaded source files; PyHazards downloads nothing for it +period_of_record: Any period covered by the user's weather and FIRMS files; the default split is calendar year 2024 +coverage: The weather grid's extent (global for MERRA-2); the LANDFIRE fuel layer covers the conterminous United States only +formats: NetCDF weather, FIRMS CSV and LANDFIRE GeoTIFF inputs; NumPy .npy cache +overview: + - > + Track-O ("occurrence") is the real-data wildfire setting contributed in PyHazards PR #33: on a daily + latitude-longitude grid, predict whether a cell has at least one satellite fire detection on a day + from that day's weather (and, in the temporal layout, the preceding days) and a static fuel layer. + - > + ``scripts/build_wildfire_track_o_cache.py`` turns NASA FIRMS active-fire CSVs, daily weather + NetCDF files and an optional LANDFIRE fuel-model GeoTIFF into a cache of per-day NumPy arrays; the + three registered datasets read that cache as raster, temporal or tabular samples. +data_characteristics: + - > + Label: 1 where at least one FIRMS detection falls nearest to the cell centre on that UTC day + (``acq_date``). By default only FIRMS ``type`` 0 (presumed vegetation fire) is kept, which drops + volcanoes, other static land sources and offshore detections. ``type`` exists only in the + standard-quality (archive) files, so near-real-time files are used unfiltered; detections + outside the grid are ignored. + - > + Weather: daily means of the requested variables, by default the 14 MERRA-2 surface variables + T2M, QV2M, TQV, U10M, V10M, GWETROOT, TS, LAI, EFLUX, HFLUX, SWGNT, SWTNT, LWGAB and LWGEM, + standardised with training-split statistics; missing values (MERRA-2 land variables over the + ocean) become 0 after standardisation. + - > + Fuel: the most frequent LANDFIRE fuel-model code (FBFM13 or FBFM40) within each cell divided by + 100, plus a validity mask; both are 0 outside the raster. LANDFIRE's -9999 fill is excluded and + the non-burnable codes (91, 92, 93, 98 and 99) are kept as codes. The code is categorical, so the scaled value + is only a crude numeric encoding (kept from PR #33). + - > + Same-day setting: the label of day t is paired with the weather of day t. With reanalysis + weather such as MERRA-2 this is not a forecast, because that weather is only known afterwards. + - > + Default split (PR #33): train 2024-01-01 to 2024-09-30, validation October 2024, test + November-December 2024. The test months have a different fire regime from the training months. +typical_use_cases: + - Gridded wildfire danger baselines scored by the PyHazards wildfire benchmark (``wildfire.danger``). + - Comparing tabular (tree), raster and temporal models on the same daily fire labels. +access_links: + - label: NASA FIRMS archive download + url: https://firms.modaps.eosdis.nasa.gov/download/ + - label: MERRA-2 at NASA GES DISC + url: https://disc.gsfc.nasa.gov/datasets?project=MERRA-2 + - label: LANDFIRE + url: https://landfire.gov/ + - label: "PyHazards PR #33 (original Track-O pipeline)" + url: https://github.com/LabRAI/PyHazards/pull/33 +pyhazards_usage: + - > + Build a cache with ``python scripts/build_wildfire_track_o_cache.py --cache-dir DIR --weather-dir + WEATHER --firms-dir FIRMS [--fuel-raster LANDFIRE.tif]``. The default variables are in the + MERRA-2 hourly collections M2T1NXSLV (T2M, QV2M, TQV, U10M, V10M, TS), M2T1NXLND (GWETROOT, LAI), + M2T1NXFLX (EFLUX, HFLUX) and M2T1NXRAD (SWGNT, SWTNT, LWGAB, LWGEM), which can be passed as they + are (an Earthdata login is needed to download them); the ``MERRA2_sfc_YYYYMMDD.nc`` files written + by ``python -m pyhazards.datasets.merra2.inspection YYYYMMDD`` also hold them. Any NetCDF files + with the variables on a regular latitude-longitude grid and the date in the file name work. + Aligning the fuel raster needs ``pip install 'pyhazards[geo]'``. + - > + Train and score registry models with ``python scripts/run_wildfire_track_o_baselines.py + --cache-dir DIR --output-dir RUNS``; it writes per-seed histories, metrics and settings. +registry: + name: wildfire_track_o_raster + example: | + from pyhazards.datasets import load_dataset + + # micro=True is a small synthetic cache for smoke tests; pass cache_dir="..." for real data. + data = load_dataset("wildfire_track_o_raster", micro=True).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (days, channels, height, width), (days, 1, height, width) + notes: + - > + ``wildfire_track_o_temporal`` gives windows of ``history`` consecutive days (default 6) + ``(samples, history, channels, height, width)``; windows that would cross a missing day are + skipped. ``wildfire_track_o_tabular`` gives one row per cell and day with the weather, + normalised latitude / longitude, day-of-year sine and cosine and the fuel columns, and int64 labels. + - > + ``downsample_factor`` keeps every f-th grid row and column (defaults: 4 raster, 8 temporal and + tabular) and ``spatial_multiple`` crops the grid to a multiple of it (4 by default; 16 for the + U-Net). + - > + ``micro=True`` replaces the cache with random fields on a 64 x 96 grid; its numbers mean nothing. +primary_references: + - citation: "Schroeder et al. (2014). The New VIIRS 375 m active fire detection data product: Algorithm description and initial assessment." + url: https://doi.org/10.1016/j.rse.2013.12.008 + - citation: Giglio, Schroeder and Justice (2016). The collection 6 MODIS active fire detection algorithm and fire products. + url: https://doi.org/10.1016/j.rse.2016.02.054 + - citation: Gelaro et al. (2017). The Modern-Era Retrospective Analysis for Research and Applications, Version 2 (MERRA-2). + url: https://doi.org/10.1175/JCLI-D-16-0758.1 + - citation: "Rollins (2009). LANDFIRE: A nationally consistent vegetation, wildland fire, and fuel assessment." + url: https://doi.org/10.1071/WF08088 +related_models: + - logistic_regression + - unet + - convlstm + - random_forest + - xgboost +related_benchmarks: + - wildfire_benchmark +notes: + - > + PR #33 took its weather from its own Prithvi-WxC forecast files, which were not published; the + builder reads MERRA-2 (or any gridded NetCDF) instead. PR #33's fuel alignment wrote the + LANDFIRE layer north-up onto a grid whose latitude runs south to north (as MERRA-2's and + Prithvi-WxC's files do), which puts CONUS fuels at 22-52 degrees south, and shifted it by half + a cell; the builder here aligns it to the cell edges and the cache's row order. + - > + PyHazards publishes no real-data Track-O results. ``scripts/run_wildfire_track_o_baselines.py`` + has only been run on the synthetic micro cache and on small synthetic fixtures. diff --git a/pyhazards/dataset_cards/wrc_housing_density.yaml b/pyhazards/dataset_cards/wrc_housing_density.yaml new file mode 100644 index 00000000..4078c8ce --- /dev/null +++ b/pyhazards/dataset_cards/wrc_housing_density.yaml @@ -0,0 +1,46 @@ +slug: wrc_housing_density +display_name: "Wildfire Risk to Communities: Housing Density" +hazard_family: Wildfire +source_role: Exposure and Risk +summary: USDA Forest Service 30 m rasters of housing-unit density, exposure and wildfire risk for populated areas of the United States (2nd edition, 2024). +provider: USDA Forest Service, Rocky Mountain Research Station (Forest Service Research Data Archive) +geometry: Gridded raster layers +spatial_resolution: 30 m +temporal_resolution: Static snapshot +update_cadence: Edition-based (2nd edition published June 2024, metadata corrected September 2024) +period_of_record: Housing from 2020 Census estimates, building footprints reflecting 2022, wildfire hazard from LANDFIRE 2020 (v2.2.0) +coverage: Conterminous United States, Alaska and Hawaii (per-state files and CONUS mosaics) +formats: LZW-compressed GeoTIFF +overview: + - > + The Wildfire Risk to Communities populated-areas data set (RDS-2020-0060-2) maps where people + and homes are and how exposed they are to wildfire, combining census housing and population + estimates with building footprints and the Forest Service wildfire hazard layers. + - > + Its housing-unit density layer (HUDen) gives housing units per square kilometre at 30 m, an + exposure covariate for wildfire-risk and wildland-urban-interface studies. +data_characteristics: + - > + Ten layers: BuildingCount, BuildingDensity, BuildingCover, PopCount, PopDen, HUCount, HUDen + (housing units per square kilometre), HUExposure, HUImpact and HURisk. + - HUExposure, HUImpact and HURisk are NoData outside populated areas. + - The 1st edition (RDS-2020-0060) used 2018 Census estimates; the 2nd edition uses 2020 housing estimates. +typical_use_cases: + - Housing exposure and wildland-urban-interface covariates for wildfire models. + - Weighting wildfire hazard maps by the homes at risk. +access_links: + - label: Forest Service Research Data Archive, RDS-2020-0060-2 + url: https://www.fs.usda.gov/rds/archive/catalog/RDS-2020-0060-2 +pyhazards_usage: + - > + PyHazards does not load this source; it is listed as an external reference for wildfire + exposure. +primary_references: + - citation: "Jaffe, Scott, Callahan, Dillon, Karau and Lazarz (2024). Wildfire Risk to Communities: Spatial datasets of wildfire risk for populated areas in the United States. 2nd Edition. Forest Service Research Data Archive." + url: https://doi.org/10.2737/RDS-2020-0060-2 +related_models: [] +related_benchmarks: [] +notes: + - > + Terms: the data "can be used without additional permissions or fees"; the archive asks that + publications cite the data set as above, and gives no warranty. diff --git a/pyhazards/dataset_cards/wrf_sfire.yaml b/pyhazards/dataset_cards/wrf_sfire.yaml new file mode 100644 index 00000000..beeba445 --- /dev/null +++ b/pyhazards/dataset_cards/wrf_sfire.yaml @@ -0,0 +1,69 @@ +slug: wrf_sfire +display_name: WRF-SFIRE Outputs +hazard_family: Wildfire +source_role: Simulator Outputs +summary: Fire-grid outputs of the coupled WRF-SFIRE atmosphere-fire model, read from wrfout files into spread rasters. +provider: OpenWFM WRF-SFIRE (University of Colorado Denver and collaborators); runs made by the user +geometry: Fire-grid raster time series +spatial_resolution: Fire mesh of DX/sr_x by DY/sr_y (typically a few to tens of metres) +temporal_resolution: WRF history interval of the run +update_cadence: Generated by the user's own WRF-SFIRE runs +period_of_record: Whatever the user simulates +coverage: Any WRF domain the user configures +formats: NetCDF WRF history files (wrfout) +overview: + - WRF-SFIRE couples the WRF atmosphere model with SFIRE, a level-set fire-spread model with Rothermel rate of spread and two-way heat and moisture flux coupling (Mandel, Beezley and Kochanski, GMD 2011). + - PyHazards does not run WRF-SFIRE, which is an MPI Fortran model built per machine, and reimplements none of it. It reads the fire-grid fields that a WRF-SFIRE run writes to its wrfout history files and turns them into wildfire.spread rasters and samples. +data_characteristics: + - Fire-grid variables have dimensions (Time, south_north_subgrid, west_east_subgrid); the fire mesh is sr_x by sr_y times finer than the atmospheric grid, and the last sr_y rows and sr_x columns are padding, which the reader removes. + - TIGN_G is the fire arrival time in seconds since the simulation start where a cell has burned; unburned cells hold a time one fire step in the future. + - LFN is the level-set function; the fire region is LFN < 0, which the reader uses as the burned mask. + - FIRE_AREA (fraction of the cell on fire), FUEL_FRAC, FGRNHFX (ground heat flux, W/m^2), ROS and F_ROS (rate of spread, m/s), FLINEINT, NFUEL_CAT, ZSF, UF/VF and FXLONG/FXLAT can be read as extra fields. Names, units and descriptions follow Registry/registry.fire of release W4.4-S0.1. + - XTIME gives the output times in minutes since the simulation start; arrays are returned north-up by default (origin='upper') or in WRF's south-up order. +typical_use_cases: + - Training or evaluating spread models on physics-based simulations of chosen scenarios. + - Comparing learned spread models with a coupled atmosphere-fire model on the same domain. + - Extracting arrival-time maps and burned-area time series from WRF-SFIRE runs. +access_links: + - label: WRF-SFIRE repository (official code) + url: https://github.com/openwfm/WRF-SFIRE + - label: Running WRF-SFIRE with real data in the WRFx system + url: https://wiki.openwfm.org/wiki/Running_WRF-SFIRE_with_real_data_in_the_WRFx_system + - label: wrfxpy (official Python workflow for real-data runs) + url: https://github.com/openwfm/wrfxpy +inspection: + command: python -m pyhazards.datasets.wrf_sfire.inspection --path /path/to/wrfout_d01_* + notes: + - Prints the fire-grid size and spacing, the burned area of each output frame and the range of fire arrival times. +registry: + name: wrf_sfire_spread + example: | + from pyhazards.datasets import load_dataset + from pyhazards.datasets.wrf_sfire import read_wrf_sfire_fire_grid + + # Next-frame spread samples: burned mask (LFN < 0) plus chosen fields -> next burned mask. + data = load_dataset("wrf_sfire_spread", paths="run/wrfout_d01_*", horizon=1, features=("NFUEL_CAT", "ZSF")).load() + train = data.get_split("train") + print(train.inputs.shape, train.targets.shape) # (N, 3, rows, cols), (N, 1, rows, cols) + + # Or the raw fire grid: arrival time (s since simulation start) and burned masks. + grid = read_wrf_sfire_fire_grid("run/wrfout_d01_*", variables=("TIGN_G", "LFN", "FIRE_AREA")) + print(grid.arrival_time().shape, grid.burned_masks().shape, grid.fire_dx) + notes: + - There is no synthetic fallback; paths must point at wrfout files from a real WRF-SFIRE run. + - Splits are chronological over the output frames of the run. +primary_references: + - citation: "Mandel, Beezley and Kochanski (2011). Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011. Geoscientific Model Development 4:591-610." + url: https://doi.org/10.5194/gmd-4-591-2011 + repo_url: https://github.com/openwfm/WRF-SFIRE + - citation: "Mandel et al. (2014). Recent advances and applications of WRF-SFIRE. Natural Hazards and Earth System Sciences 14:2829-2845." + url: https://doi.org/10.5194/nhess-14-2829-2014 +pyhazards_usage: + - Use load_dataset('wrf_sfire_spread', paths=...) for wildfire.spread samples, or read_wrf_sfire_fire_grid for the raw fire grid. + - PyHazards only reads WRF-SFIRE outputs; producing them needs the official WRF-SFIRE build and its inputs (meteorology, fuels, topography), for example through wrfxpy. +related_models: [] +related_benchmarks: + - wildfire_benchmark +notes: + - The reader was checked on a real history file of the official ideal case test/em_fire/hill (WRF-SFIRE W4.4-S0.1 built locally); the header of that file is kept in tests/fixtures/wrf_sfire_hill_wrfout_header.json and the unit tests write synthetic files with the same layout. + - The former wrf_sfire model entry was a fixed diffusion kernel unrelated to WRF-SFIRE and was removed; this reader replaces it. diff --git a/pyhazards/dataset_catalog.py b/pyhazards/dataset_catalog.py index 73501e4c..70255e24 100644 --- a/pyhazards/dataset_catalog.py +++ b/pyhazards/dataset_catalog.py @@ -30,12 +30,12 @@ HAZARD_SECTION_SUMMARIES = { "Shared Forcing": ( - "Cross-hazard meteorology and imagery sources that support multiple " - "PyHazards workflows, inspections, and forcing pipelines." + "Cross-hazard meteorology, imagery, snow and population sources: some feed " + "PyHazards inspections and forcing pipelines, others are external references." ), "Wildfire": ( - "Wildfire datasets span authoritative incident records, active-fire " - "detections, fuels, burn severity, and forecast-ready benchmark adapters." + "Wildfire datasets span authoritative incident records, perimeters, active-fire " + "detections, smoke, fuels, burn severity, exposure, and forecast-ready benchmark adapters." ), "Flood": ( "Flood datasets combine event records with streamflow and inundation " @@ -75,6 +75,7 @@ "Inundation Benchmark": "secondary", "Track Archive": "secondary", "Track Benchmark": "secondary", + "Occurrence Benchmark": "secondary", } GEOMETRY_BADGE_ROLES = { @@ -92,6 +93,7 @@ "Graph-temporal basin or node sequences": "info", "Raster inundation sequences": "info", "Storm-track history sequences": "info", + "Daily latitude-longitude grids": "info", } @@ -652,7 +654,7 @@ def render_dataset_api_page(cards: Sequence[DatasetCard]) -> str: "", " print(available_datasets())", " data = load_dataset(", - ' \"seisbench_waveforms\",', + ' \"earthquake_waveforms_synthetic\",', " micro=True,", " ).load()", " print(sorted(data.splits.keys()))", @@ -843,7 +845,7 @@ def render_dataset_detail_page(card: DatasetCard) -> str: lines.append(f"- {_single_line(note)}") if card.registry.notes: lines.append("") - else: + elif card.inspection is not None: lines.extend( [ "This dataset is currently documented as an external or inspection-first", @@ -875,7 +877,7 @@ def render_dataset_detail_page(card: DatasetCard) -> str: lines.append(f"- {_single_line(note)}") if card.inspection.notes: lines.append("") - else: + elif card.registry is not None: lines.extend( [ "This dataset is currently surfaced as a registry-backed benchmark adapter,", @@ -883,6 +885,14 @@ def render_dataset_detail_page(card: DatasetCard) -> str: "", ] ) + else: + lines.extend( + [ + "PyHazards has no inspection command or loader for this source; it is listed", + "as an external reference. Use the provider's access links above.", + "", + ] + ) if card.notes: lines.extend(["Notes", "-----", ""]) for note in card.notes: diff --git a/pyhazards/datasets/__init__.py b/pyhazards/datasets/__init__.py index 1850e566..277fe027 100644 --- a/pyhazards/datasets/__init__.py +++ b/pyhazards/datasets/__init__.py @@ -1,29 +1,43 @@ from .base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec from .earthquake import ( - AEFADataset, - PickBenchmarkWaveformDataset, SeisBenchWaveformDataset, SyntheticEarthquakeForecastDataset, SyntheticEarthquakeWaveformDataset, + SyntheticEarthquakeWavefieldDataset, ) from .flood import ( + CamelsUSStreamflowDataset, CaravanStreamflowDataset, - FloodCastBenchInundationDataset, - HydroBenchStreamflowDataset, + HydroGraphNetWhiteRiverDataset, SyntheticFloodInundationDataset, + SyntheticFloodMeshDataset, SyntheticFloodStreamflowDataset, - WaterBenchStreamflowDataset, + SyntheticUrbanFloodCastDataset, ) from .fpa_fod import FPAFODTabularDataset, FPAFODWeeklyDataset from .graph import GraphTemporalDataset, graph_collate from .registry import available_datasets, load_dataset, register_dataset from .tc import ( + HurricastDataset, IBTrACSTropicalCycloneDataset, + SHIPSXu2021Dataset, + SyntheticHurricastDataset, + SyntheticSAFNetDataset, + SyntheticSHIPSDataset, + SyntheticTCIFFusionDataset, + SyntheticTCNDDataset, SyntheticTropicalCycloneDataset, - TCBenchAlphaDataset, TropiCycloneNetDataset, ) -from .wildfire import SyntheticWildfireSpreadDataset, SyntheticWildfireSpreadTemporalDataset +from .wildfire import ( + SyntheticWildfireDangerDataset, + SyntheticWildfireSpreadDataset, + SyntheticWildfireSpreadTemporalDataset, + WildfireTrackORasterDataset, + WildfireTrackOTabularDataset, + WildfireTrackOTemporalDataset, +) +from .wrf_sfire import WRFSFireSpreadDataset __all__ = [ "DataBundle", @@ -31,17 +45,17 @@ "Dataset", "FeatureSpec", "LabelSpec", - "AEFADataset", - "PickBenchmarkWaveformDataset", "SeisBenchWaveformDataset", "SyntheticEarthquakeForecastDataset", "SyntheticEarthquakeWaveformDataset", + "SyntheticEarthquakeWavefieldDataset", + "CamelsUSStreamflowDataset", "CaravanStreamflowDataset", - "FloodCastBenchInundationDataset", - "HydroBenchStreamflowDataset", + "HydroGraphNetWhiteRiverDataset", "SyntheticFloodInundationDataset", + "SyntheticFloodMeshDataset", "SyntheticFloodStreamflowDataset", - "WaterBenchStreamflowDataset", + "SyntheticUrbanFloodCastDataset", "FPAFODTabularDataset", "FPAFODWeeklyDataset", "available_datasets", @@ -49,30 +63,53 @@ "register_dataset", "GraphTemporalDataset", "graph_collate", + "HurricastDataset", "IBTrACSTropicalCycloneDataset", + "SHIPSXu2021Dataset", + "SyntheticHurricastDataset", + "SyntheticSAFNetDataset", + "SyntheticSHIPSDataset", + "SyntheticTCIFFusionDataset", + "SyntheticTCNDDataset", "SyntheticTropicalCycloneDataset", - "TCBenchAlphaDataset", "TropiCycloneNetDataset", + "SyntheticWildfireDangerDataset", "SyntheticWildfireSpreadDataset", "SyntheticWildfireSpreadTemporalDataset", + "WRFSFireSpreadDataset", + "WildfireTrackORasterDataset", + "WildfireTrackOTabularDataset", + "WildfireTrackOTemporalDataset", ] -register_dataset(SyntheticEarthquakeForecastDataset.name, SyntheticEarthquakeForecastDataset) +register_dataset(SyntheticEarthquakeWavefieldDataset.name, SyntheticEarthquakeWavefieldDataset) +# Deprecated alias of earthquake_wavefield_synthetic (the former name). +register_dataset("earthquake_forecast_synthetic", SyntheticEarthquakeWavefieldDataset) register_dataset(SyntheticEarthquakeWaveformDataset.name, SyntheticEarthquakeWaveformDataset) register_dataset(SeisBenchWaveformDataset.name, SeisBenchWaveformDataset) -register_dataset(PickBenchmarkWaveformDataset.name, PickBenchmarkWaveformDataset) -register_dataset(AEFADataset.name, AEFADataset) register_dataset(SyntheticFloodInundationDataset.name, SyntheticFloodInundationDataset) register_dataset(SyntheticFloodStreamflowDataset.name, SyntheticFloodStreamflowDataset) +register_dataset(SyntheticFloodMeshDataset.name, SyntheticFloodMeshDataset) +register_dataset(HydroGraphNetWhiteRiverDataset.name, HydroGraphNetWhiteRiverDataset) +register_dataset(SyntheticUrbanFloodCastDataset.name, SyntheticUrbanFloodCastDataset) +register_dataset(CamelsUSStreamflowDataset.name, CamelsUSStreamflowDataset) register_dataset(CaravanStreamflowDataset.name, CaravanStreamflowDataset) -register_dataset(WaterBenchStreamflowDataset.name, WaterBenchStreamflowDataset) -register_dataset(HydroBenchStreamflowDataset.name, HydroBenchStreamflowDataset) -register_dataset(FloodCastBenchInundationDataset.name, FloodCastBenchInundationDataset) register_dataset(FPAFODTabularDataset.name, FPAFODTabularDataset) register_dataset(FPAFODWeeklyDataset.name, FPAFODWeeklyDataset) register_dataset(SyntheticTropicalCycloneDataset.name, SyntheticTropicalCycloneDataset) register_dataset(IBTrACSTropicalCycloneDataset.name, IBTrACSTropicalCycloneDataset) -register_dataset(TCBenchAlphaDataset.name, TCBenchAlphaDataset) +register_dataset(SHIPSXu2021Dataset.name, SHIPSXu2021Dataset) +register_dataset(SyntheticSHIPSDataset.name, SyntheticSHIPSDataset) +register_dataset(SyntheticSAFNetDataset.name, SyntheticSAFNetDataset) +register_dataset(SyntheticTCNDDataset.name, SyntheticTCNDDataset) +register_dataset(HurricastDataset.name, HurricastDataset) +register_dataset(SyntheticHurricastDataset.name, SyntheticHurricastDataset) +register_dataset(SyntheticTCIFFusionDataset.name, SyntheticTCIFFusionDataset) register_dataset(TropiCycloneNetDataset.name, TropiCycloneNetDataset) +register_dataset(SyntheticWildfireDangerDataset.name, SyntheticWildfireDangerDataset) register_dataset(SyntheticWildfireSpreadDataset.name, SyntheticWildfireSpreadDataset) register_dataset(SyntheticWildfireSpreadTemporalDataset.name, SyntheticWildfireSpreadTemporalDataset) +register_dataset(WRFSFireSpreadDataset.name, WRFSFireSpreadDataset) +register_dataset(WildfireTrackORasterDataset.name, WildfireTrackORasterDataset) +register_dataset(WildfireTrackOTemporalDataset.name, WildfireTrackOTemporalDataset) +register_dataset(WildfireTrackOTabularDataset.name, WildfireTrackOTabularDataset) diff --git a/pyhazards/datasets/earthquake/__init__.py b/pyhazards/datasets/earthquake/__init__.py index 183cae99..6f46d68e 100644 --- a/pyhazards/datasets/earthquake/__init__.py +++ b/pyhazards/datasets/earthquake/__init__.py @@ -1,218 +1,17 @@ -from __future__ import annotations - -import math - -import torch - -from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec - - -class SyntheticEarthquakeWaveformDataset(Dataset): - """Synthetic waveform dataset for earthquake phase-picking smoke runs.""" - - name = "earthquake_waveforms" - - def __init__( - self, - cache_dir: str | None = None, - samples: int = 96, - channels: int = 3, - length: int = 256, - micro: bool = False, - ): - super().__init__(cache_dir=cache_dir) - self.samples = 24 if micro else int(samples) - self.channels = int(channels) - self.length = int(length) - - def _load(self) -> DataBundle: - timeline = torch.linspace(0.0, 1.0, steps=self.length, dtype=torch.float32) - x = torch.zeros(self.samples, self.channels, self.length, dtype=torch.float32) - y = torch.zeros(self.samples, 2, dtype=torch.float32) - - for idx in range(self.samples): - p_pick = 32 + (idx % 40) - s_pick = min(self.length - 12, p_pick + 24 + (idx % 24)) - - for channel in range(self.channels): - phase = 0.5 * channel - base = torch.sin(2.0 * math.pi * (channel + 1) * timeline + phase) - pulse_p = torch.exp(-0.5 * ((torch.arange(self.length) - p_pick) / 6.0) ** 2) - pulse_s = 0.8 * torch.exp(-0.5 * ((torch.arange(self.length) - s_pick) / 8.0) ** 2) - x[idx, channel] = base + pulse_p + pulse_s - - y[idx, 0] = float(p_pick) - y[idx, 1] = float(s_pick) - - train_end = max(1, int(0.7 * self.samples)) - val_end = max(train_end + 1, int(0.85 * self.samples)) - splits = { - "train": DataSplit(x[:train_end], y[:train_end]), - "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), - "test": DataSplit(x[val_end:], y[val_end:]), - } - return DataBundle( - splits=splits, - feature_spec=FeatureSpec( - channels=self.channels, - description="Synthetic multichannel seismic waveforms with Gaussian phase arrivals.", - extra={"length": self.length}, - ), - label_spec=LabelSpec( - num_targets=2, - task_type="regression", - description="P- and S-arrival sample indices.", - ), - metadata={ - "dataset": self.name, - "source_dataset": self.name, - "hazard_task": "earthquake.picking", - }, - ) - - -class SyntheticEarthquakeForecastDataset(Dataset): - """Synthetic wavefield dataset for earthquake forecasting smoke runs.""" - - name = "earthquake_forecast_synthetic" - - def __init__( - self, - cache_dir: str | None = None, - samples: int = 40, - channels: int = 3, - temporal_in: int = 5, - temporal_out: int = 4, - height: int = 12, - width: int = 10, - micro: bool = False, - ): - super().__init__(cache_dir=cache_dir) - self.samples = 10 if micro else int(samples) - self.channels = int(channels) - self.temporal_in = int(temporal_in) - self.temporal_out = int(temporal_out) - self.height = int(height) - self.width = int(width) - - def _load(self) -> DataBundle: - grid_y = torch.linspace(-1.0, 1.0, steps=self.height, dtype=torch.float32).view(self.height, 1) - grid_x = torch.linspace(-1.0, 1.0, steps=self.width, dtype=torch.float32).view(1, self.width) - total_steps = self.temporal_in + self.temporal_out - - x = torch.zeros( - self.samples, - self.channels, - self.temporal_in, - self.height, - self.width, - dtype=torch.float32, - ) - y = torch.zeros( - self.samples, - self.channels, - self.temporal_out, - self.height, - self.width, - dtype=torch.float32, - ) - - row_index = torch.arange(self.height, dtype=torch.float32).view(self.height, 1) - col_index = torch.arange(self.width, dtype=torch.float32).view(1, self.width) - - for idx in range(self.samples): - sequence = torch.zeros( - self.channels, - total_steps, - self.height, - self.width, - dtype=torch.float32, - ) - for step in range(total_steps): - center_r = 2.0 + ((idx + step) % max(3, self.height - 2)) - center_c = 1.0 + ((2 * idx + step) % max(2, self.width - 1)) - gaussian = torch.exp( - -0.18 * ((row_index - center_r) ** 2 + (col_index - center_c) ** 2) - ) - for channel in range(self.channels): - phase = 0.5 * channel + 0.2 * step - base = torch.sin( - math.pi * (channel + 1) * grid_y + phase - ) + torch.cos(math.pi * (channel + 1) * grid_x - phase) - sequence[channel, step] = base + (0.6 + 0.1 * channel) * gaussian - - x[idx] = sequence[:, : self.temporal_in] - y[idx] = sequence[:, self.temporal_in :] - - train_end = max(1, int(0.7 * self.samples)) - val_end = max(train_end + 1, int(0.85 * self.samples)) - splits = { - "train": DataSplit(x[:train_end], y[:train_end]), - "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), - "test": DataSplit(x[val_end:], y[val_end:]), - } - return DataBundle( - splits=splits, - feature_spec=FeatureSpec( - channels=self.channels, - description="Synthetic dense-grid wavefield history tensors for forecasting benchmarks.", - extra={ - "temporal_in": self.temporal_in, - "temporal_out": self.temporal_out, - "height": self.height, - "width": self.width, - }, - ), - label_spec=LabelSpec( - num_targets=self.channels * self.temporal_out, - task_type="regression", - description="Future dense-grid wavefield frames over the forecast horizon.", - ), - metadata={ - "dataset": self.name, - "source_dataset": self.name, - "hazard_task": "earthquake.forecasting", - }, - ) - - -class SeisBenchWaveformDataset(SyntheticEarthquakeWaveformDataset): - """Synthetic-backed adapter with the SeisBench public dataset surface.""" - - name = "seisbench_waveforms" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "SeisBench", "source_dataset": self.name}) - return bundle - - -class PickBenchmarkWaveformDataset(SyntheticEarthquakeWaveformDataset): - """Synthetic-backed adapter with the pick-benchmark public dataset surface.""" - - name = "pick_benchmark_waveforms" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "pick-benchmark", "source_dataset": self.name}) - return bundle - - -class AEFADataset(SyntheticEarthquakeForecastDataset): - """Synthetic-backed adapter for AEFA-style earthquake forecasting inputs.""" - - name = "aefa_forecast" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "AEFA", "source_dataset": self.name}) - return bundle +"""Earthquake datasets: a reader for real SeisBench-format / STEAD waveform datasets and synthetic smoke data.""" +from .seisbench import SeisBenchWaveformDataset, parse_trace_name, read_data_format +from .synthetic import ( + SyntheticEarthquakeForecastDataset, + SyntheticEarthquakeWaveformDataset, + SyntheticEarthquakeWavefieldDataset, +) __all__ = [ - "AEFADataset", - "PickBenchmarkWaveformDataset", "SeisBenchWaveformDataset", "SyntheticEarthquakeForecastDataset", "SyntheticEarthquakeWaveformDataset", + "SyntheticEarthquakeWavefieldDataset", + "parse_trace_name", + "read_data_format", ] diff --git a/pyhazards/datasets/earthquake/seisbench.py b/pyhazards/datasets/earthquake/seisbench.py new file mode 100644 index 00000000..cb548ed5 --- /dev/null +++ b/pyhazards/datasets/earthquake/seisbench.py @@ -0,0 +1,357 @@ +"""Reader for seismic waveform benchmark datasets in the SeisBench format and in STEAD's own layout. + +PyHazards reads these files itself (``h5py`` and the ``csv`` module); SeisBench (GPL-3.0) is neither +imported nor required. The datasets are not redistributed: download them from their providers and +point ``path`` at the directory. + +SeisBench format (``layout="seisbench"``), as documented in SeisBench's "The SeisBench Data Format": +``metadata.csv`` + ``waveforms.hdf5`` in one directory, or chunks ``metadata.csv`` + +``waveforms.hdf5`` (listed in a ``chunks`` file when present). The HDF5 file has a ``data`` group +with one array per trace at ``data/`` and a ``data_format`` group with +``dimension_order`` (e.g. ``"CW"``), ``component_order`` (e.g. ``"ZNE"``) and optionally +``sampling_rate``. Trace names of the form ``$`` (e.g. ``bucket3$12,:3,:6000``) address a +trace inside a block array ``data/``. The metadata column ``split`` (train/dev/test) defines the +splits; sampling rates come from ``trace_sampling_rate_hz`` / ``trace_dt_s`` or ``data_format``. + +STEAD layout (``layout="stead"``): the files distributed by the STEAD authors +(https://github.com/smousavi05/STEAD; ``merged.csv`` / ``merged.hdf5``, the six ``chunk`` pairs, or +any ``.csv`` + ``.hdf5`` pair such as EQTransformer's ``100samples``). Each trace is +``data/``, shape ``(6000, 3)``, components E, N, Z, 100 Hz; P and S arrivals are the +``p_arrival_sample`` / ``s_arrival_sample`` columns. STEAD has no split column: ``test_trace_names`` +(e.g. EQTransformer's ``ModelsAndSampleData/test.npy``) selects the test traces and the others go to +``train``; without it every trace is in ``test``. + +Known datasets (``preset``): ``"stead"`` (Mousavi et al. 2019, CC BY 4.0) and ``"instance"`` (Michelini +et al. 2021, INGV, CC BY 4.0; 120-s traces at 100 Hz stored as ``(3, 12000)`` in E, N, Z order per the +INGV notebooks). A preset only fills in values that the files do not provide. +""" + +from __future__ import annotations + +import csv +import math +import re +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +# Arrival-sample columns, in order of preference, used when ``phase_columns`` is not given. +DEFAULT_PHASE_COLUMNS: Dict[str, Tuple[str, ...]] = { + "P": ("trace_p_arrival_sample", "trace_P_arrival_sample", "trace_P1_arrival_sample", + "trace_Pg_arrival_sample", "trace_Pn_arrival_sample", "p_arrival_sample"), + "S": ("trace_s_arrival_sample", "trace_S_arrival_sample", "trace_S1_arrival_sample", + "trace_Sg_arrival_sample", "trace_Sn_arrival_sample", "s_arrival_sample"), +} + +PRESETS: Dict[str, Dict[str, object]] = { + "stead": {"layout": "stead", "component_order": "ENZ", "dimension_order": "WC", "sampling_rate": 100.0}, + "instance": {"layout": "seisbench", "component_order": "ENZ", "dimension_order": "CW", "sampling_rate": 100.0}, +} + +_SPLIT_NAMES = {"train": "train", "dev": "val", "val": "val", "validation": "val", "test": "test"} +_SLICE_ITEM = re.compile(r"^\s*(-?\d*)\s*(?::\s*(-?\d*)\s*(?::\s*(-?\d*)\s*)?)?$") + + +def parse_trace_name(trace_name: str) -> Tuple[str, Optional[Tuple[Union[int, slice], ...]]]: + """``"block$1,:3,:6000"`` -> ``("block", (1, slice(None, 3), slice(None, 6000)))``.""" + if "$" not in trace_name: + return trace_name, None + block, _, location = trace_name.partition("$") + items: List[Union[int, slice]] = [] + for item in location.split(","): + match = _SLICE_ITEM.match(item) + if match is None or item.strip() == "": + raise ValueError(f"Cannot parse the trace location {location!r} of {trace_name!r}.") + start, stop, step = match.groups() + if ":" not in item: + items.append(int(start)) + else: + to_int = lambda value: int(value) if value not in (None, "") else None # noqa: E731 + items.append(slice(to_int(start), to_int(stop), to_int(step))) + return block, tuple(items) + + +def _decode(value) -> object: + if isinstance(value, bytes): + return value.decode("utf-8") + if isinstance(value, np.ndarray) and value.dtype.kind in ("S", "O"): + return "".join(_decode(v) for v in value.ravel()) + if isinstance(value, np.generic): + return value.item() + return value + + +def read_data_format(handle) -> Dict[str, object]: + """The ``data_format`` group of a SeisBench waveform file (empty when absent).""" + if "data_format" not in handle: + return {} + group = handle["data_format"] + return {key: _decode(group[key][()]) for key in group.keys()} + + +def _float(value: Optional[str]) -> float: + if value is None: + return math.nan + text = str(value).strip() + if text in ("", "nan", "NaN", "None", "none"): + return math.nan + try: + return float(text) + except ValueError: + return math.nan + + +def _read_rows(path: Path) -> List[Dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def _seisbench_chunks(root: Path) -> List[Tuple[Path, Path]]: + if (root / "chunks").is_file(): + names = [line.strip() for line in (root / "chunks").read_text(encoding="utf-8").splitlines() if line.strip()] + elif (root / "metadata.csv").is_file(): + names = [""] + else: + names = sorted(path.stem[len("metadata"):] for path in root.glob("metadata*.csv")) + pairs = [(root / f"metadata{name}.csv", root / f"waveforms{name}.hdf5") for name in names] + if not pairs: + raise FileNotFoundError(f"No SeisBench metadata*.csv / waveforms*.hdf5 files in {root}.") + for metadata, waveforms in pairs: + if not metadata.is_file() or not waveforms.is_file(): + raise FileNotFoundError(f"Incomplete SeisBench chunk in {root}: need {metadata.name} and {waveforms.name}.") + return pairs + + +def _stead_pairs(root: Path) -> List[Tuple[Path, Path]]: + pairs = [(csv_path, csv_path.with_suffix(".hdf5")) for csv_path in sorted(root.glob("*.csv"))] + pairs = [pair for pair in pairs if pair[1].is_file()] + if not pairs: + raise FileNotFoundError(f"No STEAD .csv + .hdf5 pair in {root}.") + return pairs + + +class SeisBenchWaveformDataset(Dataset): + """Labelled three-component waveforms from a SeisBench-format (or STEAD-layout) dataset. + + Inputs are ``(n, 3, window)`` float32 waveforms in the dataset's component order (reported in + ``metadata["component_order"]``; the picking benchmark reorders channels for each model), targets + ``(n, 2)`` P and S arrival samples relative to the window start (NaN when absent or outside the + window). Splits ``train``/``val``/``test`` follow the dataset's ``split`` column (``dev`` -> ``val``). + + ``window_samples`` / ``window_start`` cut a fixed window from every trace (zero-padded when a + trace is shorter); without ``window_samples`` all traces must have the same length. + ``max_traces`` keeps the first rows of each split (``micro=True`` keeps 8), ``trace_category`` + keeps rows with that ``trace_category`` value (e.g. ``"earthquake_local"`` or ``"noise"`` in STEAD). + """ + + name = "seisbench_waveforms" + + def __init__( + self, + path: Union[str, Path, None] = None, + cache_dir: Optional[str] = None, + layout: Optional[str] = None, + preset: Optional[str] = None, + component_order: Optional[str] = None, + dimension_order: Optional[str] = None, + sampling_rate: Optional[float] = None, + window_samples: Optional[int] = None, + window_start: int = 0, + phase_columns: Optional[Dict[str, Sequence[str]]] = None, + test_trace_names: Union[str, Path, Sequence[str], None] = None, + trace_category: Optional[str] = None, + max_traces: Optional[int] = None, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + if path is None: + raise ValueError( + "seisbench_waveforms reads a downloaded dataset: pass path=.csv and .hdf5 (STEAD layout)>. " + "For synthetic smoke data use 'earthquake_waveforms_synthetic'." + ) + self.path = Path(path).expanduser() + if not self.path.is_dir(): + raise FileNotFoundError(f"Dataset directory not found: {self.path}") + if preset is not None and preset not in PRESETS: + raise ValueError(f"Unknown preset {preset!r}; expected one of {sorted(PRESETS)}.") + defaults = dict(PRESETS[preset]) if preset is not None else {} + self.preset = preset + self.layout = (layout or defaults.get("layout") or "seisbench").lower() + if self.layout not in ("seisbench", "stead"): + raise ValueError(f"layout must be 'seisbench' or 'stead', got {self.layout!r}.") + if self.layout == "stead": + defaults = {**PRESETS["stead"], **defaults} + self.defaults = defaults + self.component_order = component_order + self.dimension_order = dimension_order + self.sampling_rate = sampling_rate + self.window_samples = None if window_samples is None else int(window_samples) + self.window_start = int(window_start) + if self.window_samples is not None and self.window_samples < 1: + raise ValueError(f"window_samples must be positive, got {window_samples}.") + if self.window_start < 0: + raise ValueError(f"window_start must be >= 0, got {window_start}.") + self.phase_columns = { + phase: tuple(columns) for phase, columns in (phase_columns or DEFAULT_PHASE_COLUMNS).items() + } + if set(self.phase_columns) != {"P", "S"}: + raise ValueError("phase_columns needs exactly the phases 'P' and 'S'.") + self.test_trace_names = test_trace_names + self.trace_category = trace_category + self.max_traces = 8 if micro and max_traces is None else max_traces + + # -- metadata ------------------------------------------------------------------------------- + def _resolve(self, key: str, file_value: object) -> object: + explicit = getattr(self, key) + if explicit is not None: + return explicit + if file_value not in (None, ""): + return file_value + return self.defaults.get(key) + + def _test_names(self) -> Optional[set]: + names = self.test_trace_names + if names is None: + return None + if isinstance(names, (str, Path)): + path = Path(names).expanduser() + if path.suffix == ".npy": + return {str(_decode(name)) for name in np.load(path, allow_pickle=True).tolist()} + return {line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()} + return {str(name) for name in names} + + def _split_of(self, row: Dict[str, str], test_names: Optional[set]) -> Optional[str]: + if self.layout == "stead": + if test_names is None: + return "test" + return "test" if row["trace_name"] in test_names else "train" + if "split" not in row or row["split"] in (None, ""): + return "test" + return _SPLIT_NAMES.get(row["split"].strip().lower()) + + def _arrival(self, row: Dict[str, str], phase: str) -> float: + for column in self.phase_columns[phase]: + value = _float(row.get(column)) + if not math.isnan(value): + return value + return math.nan + + # -- waveforms ------------------------------------------------------------------------------ + def _trace(self, handle, trace_name: str, dimension_order: str) -> np.ndarray: + block, location = parse_trace_name(trace_name) + if block not in handle["data"]: + raise KeyError(f"Trace {trace_name!r} not found in {handle.filename}.") + dataset = handle["data"][block] + array = np.asarray(dataset[location] if location is not None else dataset[()], dtype=np.float32) + order = dimension_order.upper() + if len(order) == 3 and order[0] == "N": # block arrays carry a leading trace axis + order = order[1:] + if array.ndim != 2 or sorted(order) != ["C", "W"]: + raise ValueError(f"Trace {trace_name!r} has shape {array.shape}; expected 2-D data in order {dimension_order!r}.") + return array if order == "CW" else array.T + + def _window(self, trace: np.ndarray) -> np.ndarray: + if self.window_samples is None: + return trace + window = np.zeros((trace.shape[0], self.window_samples), dtype=np.float32) + piece = trace[:, self.window_start : self.window_start + self.window_samples] + window[:, : piece.shape[1]] = piece + return window + + def _load(self) -> DataBundle: + import h5py + + pairs = _stead_pairs(self.path) if self.layout == "stead" else _seisbench_chunks(self.path) + test_names = self._test_names() + collected: Dict[str, Dict[str, list]] = { + split: {"x": [], "y": [], "names": []} for split in ("train", "val", "test") + } + component_order = sampling_rate = None + for metadata_path, waveform_path in pairs: + rows = _read_rows(metadata_path) + with h5py.File(waveform_path, "r") as handle: + data_format = read_data_format(handle) if self.layout == "seisbench" else {} + chunk_components = self._resolve("component_order", data_format.get("component_order")) + chunk_dimensions = self._resolve("dimension_order", data_format.get("dimension_order")) or "CW" + chunk_rate = self._resolve("sampling_rate", data_format.get("sampling_rate")) + if chunk_components is None: + raise ValueError( + f"{waveform_path} has no data_format/component_order; pass component_order (e.g. 'ZNE')." + ) + chunk_components = str(chunk_components).upper() + if len(chunk_components) != 3: + raise ValueError(f"Expected three components, got {chunk_components!r}.") + if component_order not in (None, chunk_components): + raise ValueError(f"Chunks disagree on the component order ({component_order} vs {chunk_components}).") + component_order = chunk_components + for row in rows: + if self.trace_category is not None and row.get("trace_category") != self.trace_category: + continue + split = self._split_of(row, test_names) + if split is None: + continue + bucket = collected[split] + if self.max_traces is not None and len(bucket["names"]) >= self.max_traces: + continue + rate = _float(row.get("trace_sampling_rate_hz")) + if math.isnan(rate) and not math.isnan(_float(row.get("trace_dt_s"))): + rate = 1.0 / _float(row.get("trace_dt_s")) + if math.isnan(rate): + rate = float(chunk_rate) if chunk_rate is not None else math.nan + if math.isnan(rate): + raise ValueError("No sampling rate in the metadata or data_format; pass sampling_rate.") + if sampling_rate is not None and not math.isclose(rate, sampling_rate): + raise ValueError(f"Mixed sampling rates ({sampling_rate} and {rate} Hz) are not supported.") + sampling_rate = rate + trace = self._window(self._trace(handle, row["trace_name"], str(chunk_dimensions))) + arrivals = [] + for phase in ("P", "S"): + sample = self._arrival(row, phase) - self.window_start + inside = 0 <= sample < trace.shape[-1] + arrivals.append(sample if inside else math.nan) + bucket["x"].append(trace) + bucket["y"].append(arrivals) + bucket["names"].append(row["trace_name"]) + + lengths = {trace.shape[-1] for split in collected.values() for trace in split["x"]} + if len(lengths) > 1: + raise ValueError(f"Traces have different lengths {sorted(lengths)}; pass window_samples.") + length = lengths.pop() if lengths else int(self.window_samples or 0) + splits = {} + for split, bucket in collected.items(): + inputs = torch.from_numpy(np.stack(bucket["x"])) if bucket["x"] else torch.zeros(0, 3, length) + targets = torch.tensor(bucket["y"], dtype=torch.float32).reshape(-1, 2) + splits[split] = DataSplit(inputs, targets, metadata={"trace_names": bucket["names"]}) + if not any(len(bucket["names"]) for bucket in collected.values()): + raise ValueError(f"No traces selected from {self.path}.") + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=3, + description=f"Three-component waveforms ({component_order}) read from {self.path.name}.", + extra={"length": length, "sampling_rate": sampling_rate, "component_order": component_order}, + ), + label_spec=LabelSpec( + num_targets=2, + task_type="picking", + description="P and S arrival samples relative to the window start (NaN = no arrival).", + ), + metadata={ + "dataset": self.name, + "source_dataset": self.preset or self.path.name, + "hazard_task": "earthquake.picking", + "layout": self.layout, + "path": str(self.path), + "sampling_rate": sampling_rate, + "component_order": component_order, + "synthetic": False, + }, + ) + + +__all__ = ["DEFAULT_PHASE_COLUMNS", "PRESETS", "SeisBenchWaveformDataset", "parse_trace_name", "read_data_format"] diff --git a/pyhazards/datasets/earthquake/synthetic.py b/pyhazards/datasets/earthquake/synthetic.py new file mode 100644 index 00000000..a3a1cef6 --- /dev/null +++ b/pyhazards/datasets/earthquake/synthetic.py @@ -0,0 +1,229 @@ +"""Synthetic earthquake datasets for smoke runs. Neither reads real data.""" + +from __future__ import annotations + +import math + +import torch + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + + +class SyntheticEarthquakeWaveformDataset(Dataset): + """Synthetic three-component windows with P and S arrivals, for phase-picking smoke runs. + + Not real data. Each event window is Gaussian background noise plus two damped sinusoids that start + at the P arrival (about 8 Hz, strongest on Z) and at the S arrival (about 4 Hz, strongest on N and + E); noise windows have no arrival (targets NaN). Values are drawn from a seeded generator, so a + given configuration always gives the same data. + + Targets are ``(n, 2)`` arrival samples ``[P, S]`` with NaN for "no arrival", the layout that the + ``earthquake.picking`` benchmark scores. ``length`` defaults to 6000 samples at 100 Hz (60 s, the + EQTransformer window; PhaseNet and GPD take any length >= 400). + """ + + name = "earthquake_waveforms_synthetic" + component_order = "ZNE" + + def __init__( + self, + cache_dir: str | None = None, + samples: int = 96, + length: int = 6000, + sampling_rate: float = 100.0, + noise_fraction: float = 0.25, + seed: int = 0, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + self.samples = 24 if micro else int(samples) + self.length = int(length) + self.sampling_rate = float(sampling_rate) + self.noise_fraction = float(noise_fraction) + self.seed = int(seed) + if self.samples < 3: + raise ValueError(f"samples must be at least 3 (one per split), got {self.samples}.") + if self.length < 2 * int(self.sampling_rate): + raise ValueError(f"length must cover at least 2 s ({2 * int(self.sampling_rate)} samples), got {self.length}.") + if not 0.0 <= self.noise_fraction < 1.0: + raise ValueError(f"noise_fraction must be in [0, 1), got {self.noise_fraction}.") + + def _wavelet(self, onset: float, frequency: float, decay_s: float, generator: torch.Generator) -> torch.Tensor: + t = (torch.arange(self.length, dtype=torch.float64) - onset) / self.sampling_rate + phase = float(torch.rand(1, generator=generator)) * 2.0 * math.pi + envelope = torch.where(t >= 0, (1.0 - torch.exp(-t / 0.05)) * torch.exp(-t / decay_s), torch.zeros_like(t)) + return envelope * torch.sin(2.0 * math.pi * frequency * t.clamp_min(0.0) + phase) + + def _load(self) -> DataBundle: + generator = torch.Generator().manual_seed(self.seed) + rate = self.sampling_rate + x = torch.randn(self.samples, 3, self.length, generator=generator, dtype=torch.float64) + y = torch.full((self.samples, 2), float("nan"), dtype=torch.float32) + n_noise = int(round(self.noise_fraction * self.samples)) + # Interleave noise windows so that every split gets some (deterministic positions). + noise_rows = set(torch.linspace(0, self.samples - 1, n_noise).round().long().tolist()) if n_noise else set() + for idx in range(self.samples): + if idx in noise_rows: + continue + p_pick = float(torch.randint(int(0.1 * self.length), int(0.4 * self.length), (1,), generator=generator)) + gap = float(torch.empty(1).uniform_(1.0, 12.0, generator=generator)) * rate + s_pick = min(p_pick + gap, self.length - 0.5 * rate) + amplitude = float(torch.empty(1).uniform_(4.0, 20.0, generator=generator)) + p_wave = self._wavelet(p_pick, 8.0, 1.0, generator) + s_wave = self._wavelet(s_pick, 4.0, 2.5, generator) + for channel, (p_gain, s_gain) in enumerate(((1.0, 0.4), (0.4, 1.2), (0.4, 1.0))): # Z, N, E + x[idx, channel] += amplitude * (p_gain * p_wave + s_gain * s_wave) + y[idx, 0] = p_pick + y[idx, 1] = round(s_pick) + x = x.float() + + train_end = max(1, int(0.7 * self.samples)) + val_end = max(train_end + 1, int(0.85 * self.samples)) + splits = { + "train": DataSplit(x[:train_end], y[:train_end]), + "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), + "test": DataSplit(x[val_end:], y[val_end:]), + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=3, + description="Synthetic three-component waveforms (Z, N, E) with P and S wavelets; not real data.", + extra={"length": self.length, "sampling_rate": rate, "component_order": self.component_order}, + ), + label_spec=LabelSpec( + num_targets=2, + task_type="picking", + description="P and S arrival samples (NaN = no arrival).", + ), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "earthquake.picking", + "synthetic": True, + "sampling_rate": rate, + "component_order": self.component_order, + }, + ) + + +class SyntheticEarthquakeWavefieldDataset(Dataset): + """Synthetic ground-motion wavefields for wavefield-forecasting smoke runs (not real data). + + Each sequence is a point source at a random grid position and onset time radiating a P and an S + wavefront (Ricker pulses travelling at ``vp`` and ``vs`` grid cells per frame, amplitudes decaying as + ``1 / sqrt(1 + r)``) on a ``height x width`` grid. The three channels are the X, Y and Z particle + velocities: P moves particles radially (and vertically, half amplitude), S transversally. This only + mimics the layout of WaveCastNet's data (three velocity components on a regular grid, Lyu et al. + 2025); it is not an elastic simulation. Values come from a seeded generator. + + Inputs ``(n, 3, temporal_in, height, width)`` and targets ``(n, 3, temporal_out, height, width)``, + the layout of the ``earthquake.forecasting`` task; ``height`` and ``width`` default to multiples of 8 + (WaveCastNet's latent grid is 1/8 of the input). + """ + + name = "earthquake_wavefield_synthetic" + channel_names = ("x", "y", "z") + + def __init__( + self, + cache_dir: str | None = None, + samples: int = 24, + temporal_in: int = 6, + temporal_out: int = 6, + height: int = 32, + width: int = 24, + vp: float = 2.0, + vs: float = 1.2, + seed: int = 0, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + self.samples = 6 if micro else int(samples) + self.temporal_in = int(temporal_in) + self.temporal_out = int(temporal_out) + self.height = int(height) + self.width = int(width) + self.vp = float(vp) + self.vs = float(vs) + self.seed = int(seed) + if self.samples < 3: + raise ValueError(f"samples must be at least 3 (one per split), got {self.samples}.") + if min(self.temporal_in, self.temporal_out, self.height, self.width) < 1: + raise ValueError("temporal_in, temporal_out, height and width must be positive.") + if not self.vp > self.vs > 0: + raise ValueError(f"Need vp > vs > 0, got vp={self.vp}, vs={self.vs}.") + + @staticmethod + def _ricker(t: torch.Tensor, width: float) -> torch.Tensor: + a = (t / width) ** 2 + return (1.0 - 2.0 * a) * torch.exp(-a) + + def _load(self) -> DataBundle: + generator = torch.Generator().manual_seed(self.seed) + steps = self.temporal_in + self.temporal_out + rows = torch.arange(self.height, dtype=torch.float64).view(self.height, 1) + cols = torch.arange(self.width, dtype=torch.float64).view(1, self.width) + frames = torch.arange(steps, dtype=torch.float64).view(steps, 1, 1) + data = torch.zeros(self.samples, 3, steps, self.height, self.width, dtype=torch.float64) + for idx in range(self.samples): + u = torch.rand(4, generator=generator, dtype=torch.float64) + row, col = u[0] * (self.height - 1), u[1] * (self.width - 1) + onset = -2.0 + 3.0 * float(u[2]) + amplitude = 0.5 + 1.5 * float(u[3]) + dy, dx = rows - row, cols - col + r = torch.sqrt(dx**2 + dy**2) + radial_x, radial_y = dx / r.clamp_min(1e-6), dy / r.clamp_min(1e-6) + spreading = amplitude / torch.sqrt(1.0 + r) + p_wave = spreading * self._ricker(frames - onset - r / self.vp, 1.0) + s_wave = 1.5 * spreading * self._ricker(frames - onset - r / self.vs, 1.5) + data[idx, 0] = radial_x * p_wave - radial_y * s_wave + data[idx, 1] = radial_y * p_wave + radial_x * s_wave + data[idx, 2] = 0.5 * p_wave + data = data.float() + x, y = data[:, :, : self.temporal_in], data[:, :, self.temporal_in :] + + train_end = max(1, int(0.7 * self.samples)) + val_end = max(train_end + 1, int(0.85 * self.samples)) + splits = { + "train": DataSplit(x[:train_end], y[:train_end]), + "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), + "test": DataSplit(x[val_end:], y[val_end:]), + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=3, + description="Synthetic X, Y, Z velocity wavefields of point sources (P and S Ricker wavefronts); not real data.", + extra={ + "temporal_in": self.temporal_in, + "temporal_out": self.temporal_out, + "height": self.height, + "width": self.width, + "channel_names": list(self.channel_names), + }, + ), + label_spec=LabelSpec( + num_targets=3 * self.temporal_out, + task_type="regression", + description="Future wavefield frames (n, 3, temporal_out, height, width).", + ), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "earthquake.forecasting", + "synthetic": True, + "channel_names": list(self.channel_names), + }, + ) + + +# Deprecated name of the synthetic wavefield generator (kept for existing imports). +SyntheticEarthquakeForecastDataset = SyntheticEarthquakeWavefieldDataset + + +__all__ = [ + "SyntheticEarthquakeForecastDataset", + "SyntheticEarthquakeWaveformDataset", + "SyntheticEarthquakeWavefieldDataset", +] diff --git a/pyhazards/datasets/figlib_smokebench/__init__.py b/pyhazards/datasets/figlib_smokebench/__init__.py new file mode 100644 index 00000000..57e1ca5a --- /dev/null +++ b/pyhazards/datasets/figlib_smokebench/__init__.py @@ -0,0 +1,321 @@ +"""SmokeBench evaluation set: HPWREN FIgLib frames with the SmokeyNet smoke boxes. + +SmokeBench (Qi, Li & Barnes, WACV 2026, arXiv:2512.11215) uses "a subset of 5,046 images with +ground-truth bounding box annotations provided in [Dewangan et al. 2022]" as smoke images and 1,000 +smoke-free images. SmokeBench itself released no data, image list or split (its evaluation script, +github.com/SoraLink/MLLM, expects them in a git-ignored ``dataset/`` folder). The pieces come from: + +* boxes: ``bbox_labels`` of ``data/metadata.pkl`` in the SmokeyNet repository (Dewangan et al., + Remote Sensing 14:1007, 2022; gitlab.nrp-nautilus.io/anshumand/pytorch-lightning-smoke-detection, + Apache-2.0), pinned to commit d8d52b9 and checked by sha256. It holds exactly 5,046 boxes, one per + image, on 145 FIgLib sequences, and their area quintiles are exactly SmokeBench's area bins + (42, 4356, 11232, 28565, 83157, 2232020), so this is the SmokeBench smoke set; +* images: the FIgLib per-sequence archives on the HPWREN CDN (``HPWREN-FIgLib-Data/Tar``). HPWREN + makes the data public and asks that derivative work credit https://www.hpwren.ucsd.edu/; no + licence file is given, so PyHazards downloads from the official source and redistributes nothing; +* smoke-free images: frames before the visible plume (negative offset in the file name + ``_.jpg``). The authors drew 1,000 of them with an unseeded ``random.sample`` + over all FIgLib sequences they had downloaded and did not release the list, so it cannot be + rebuilt; PyHazards draws ``negatives`` frames with a seeded generator from the pre-ignition frames + of the selected sequences. + +Boxes are ``[x1, y1, x2, y2]`` integer pixel coordinates of the original frame (the rounded extremes +of the annotated polygon). Frames are 1600 x 1200, 2048 x 1536 or 3072 x 2048 RGB JPEGs. +""" + +from __future__ import annotations + +import hashlib +import importlib +import io +import pickle +import random +import re +import tarfile +import urllib.request +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union + +import numpy as np + +SMOKEYNET_REPO_URL = "https://gitlab.nrp-nautilus.io/anshumand/pytorch-lightning-smoke-detection" +SMOKEYNET_COMMIT = "d8d52b957891de10d4bef08943535fa4f9c3cd43" +SMOKEYNET_METADATA_URL = f"{SMOKEYNET_REPO_URL}/-/raw/{SMOKEYNET_COMMIT}/data/metadata.pkl" +SMOKEYNET_METADATA_SHA256 = "c3465c121669b0f92426451799140b0d30bc7caf7512aff9326fefa698ecb1a6" +METADATA_FILENAME = "smokeynet_metadata.pkl" +FIGLIB_ARCHIVE_URL = "https://cdn.hpwren.ucsd.edu/HPWREN-FIgLib-Data/Tar/{sequence}.tgz" +FIGLIB_HOME_URL = "https://www.hpwren.ucsd.edu/FIgLib/" + +NUM_SMOKE_IMAGES = 5046 +NUM_SEQUENCES = 145 +NUM_NEGATIVES = 1000 + +_FRAME_NAME = re.compile(r"^(\d+)_([+-])(\d+)\.jpg$") +_COMPLETE_MARKER = ".complete" + +PathLike = Union[str, Path] + + +@dataclass(frozen=True) +class SmokeSample: + """One SmokeBench image: ``image_id`` is ``"/"``.""" + + image_id: str + path: Path + label: bool + boxes: Tuple[Tuple[int, int, int, int], ...] = () + + @property + def sequence(self) -> str: + return self.image_id.split("/")[0] + + @property + def offset_seconds(self) -> int: + """Seconds from the first visible plume (negative before ignition).""" + match = _FRAME_NAME.match(self.image_id.split("/")[1] + ".jpg") + if match is None: + raise ValueError(f"unexpected FIgLib frame name {self.image_id!r}") + sign = -1 if match.group(2) == "-" else 1 + return sign * int(match.group(3)) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +_PICKLE_ALLOWED = { + ("builtins", "dict"), + ("builtins", "list"), + ("builtins", "tuple"), + ("builtins", "set"), + ("builtins", "frozenset"), + ("numpy", "dtype"), + ("numpy", "ndarray"), + ("numpy.core.multiarray", "scalar"), + ("numpy.core.multiarray", "_reconstruct"), + ("numpy._core.multiarray", "scalar"), + ("numpy._core.multiarray", "_reconstruct"), +} + + +class _MetadataUnpickler(pickle.Unpickler): + """Unpickler that only builds containers and numpy arrays/scalars (no arbitrary code).""" + + def find_class(self, module: str, name: str) -> Any: + if (module, name) not in _PICKLE_ALLOWED: + raise pickle.UnpicklingError(f"refusing to load {module}.{name} from the SmokeyNet metadata") + try: + return getattr(importlib.import_module(module), name) + except ImportError: + swapped = module.replace("numpy.core", "numpy._core") if "numpy.core" in module else module.replace("numpy._core", "numpy.core") + return getattr(importlib.import_module(swapped), name) + + +def load_smokeynet_boxes(path: PathLike, *, verify: bool = True) -> Dict[str, List[List[int]]]: + """``{"/": [[x1, y1, x2, y2], ...]}`` from SmokeyNet's ``metadata.pkl``.""" + path = Path(path) + if verify: + actual = _sha256(path) + if actual != SMOKEYNET_METADATA_SHA256: + raise ValueError(f"{path} has sha256 {actual}, expected the pinned {SMOKEYNET_METADATA_SHA256}") + metadata = _MetadataUnpickler(io.BytesIO(path.read_bytes())).load() + boxes = metadata["bbox_labels"] + return { + str(image_id): [[int(v) for v in np.asarray(box).ravel()] for box in image_boxes] + for image_id, image_boxes in boxes.items() + } + + +def _download_file(url: str, target: Path) -> None: + tmp = target.with_suffix(target.suffix + ".part") + with urllib.request.urlopen(url, timeout=120) as response, tmp.open("wb") as handle: + while True: + chunk = response.read(1 << 20) + if not chunk: + break + handle.write(chunk) + tmp.replace(target) + + +def download_metadata(root: PathLike) -> Path: + """Fetch the pinned SmokeyNet ``metadata.pkl`` into ``root`` (verified by sha256).""" + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + target = root / METADATA_FILENAME + if not target.exists() or _sha256(target) != SMOKEYNET_METADATA_SHA256: + _download_file(SMOKEYNET_METADATA_URL, target) + actual = _sha256(target) + if actual != SMOKEYNET_METADATA_SHA256: + raise ValueError(f"downloaded {target} has sha256 {actual}, expected {SMOKEYNET_METADATA_SHA256}") + return target + + +def download_sequence(root: PathLike, sequence: str) -> int: + """Stream one FIgLib archive from HPWREN and extract its JPEG frames to ``root//``. + + Only regular files named ``/_.jpg`` are written (the time-lapse MP4 + is skipped). Returns the number of frames; a ``.complete`` marker makes later calls no-ops. + """ + root = Path(root) + if "/" in sequence or sequence in {"", ".", ".."}: + raise ValueError(f"invalid FIgLib sequence name {sequence!r}") + directory = root / sequence + marker = directory / _COMPLETE_MARKER + if marker.exists(): + return int(marker.read_text() or 0) + count = 0 + url = FIGLIB_ARCHIVE_URL.format(sequence=sequence) + with urllib.request.urlopen(url, timeout=120) as response, tarfile.open(fileobj=response, mode="r|gz") as archive: + for member in archive: + parts = member.name.split("/") + if not member.isfile() or len(parts) != 2 or parts[0] != sequence or not _FRAME_NAME.match(parts[1]): + continue + handle = archive.extractfile(member) + if handle is None: + continue + directory.mkdir(parents=True, exist_ok=True) + (directory / parts[1]).write_bytes(handle.read()) + count += 1 + marker.write_text(str(count)) + return count + + +def download_smokebench(root: PathLike, sequences: Optional[Sequence[str]] = None, *, progress: bool = True) -> Path: + """Download the SmokeyNet boxes and the FIgLib sequences SmokeBench uses (about 11.4 GB for all 145).""" + root = Path(root) + metadata = download_metadata(root) + wanted = sorted(sequences) if sequences is not None else sorted({key.split("/")[0] for key in load_smokeynet_boxes(metadata)}) + for index, sequence in enumerate(wanted, 1): + frames = download_sequence(root, sequence) + if progress: + print(f"[{index}/{len(wanted)}] {sequence}: {frames} frames", flush=True) + return root + + +class FIgLibSmokeBench(Sequence[SmokeSample]): + """The SmokeBench images: smoke images (with boxes) first, then the sampled smoke-free images. + + Args: + root: directory holding ``smokeynet_metadata.pkl`` and one folder of JPEG frames per FIgLib + sequence (the layout of the HPWREN archives; :func:`download_smokebench` creates it). + sequences: restrict to these FIgLib sequences (default: the 145 annotated ones). + negatives: number of smoke-free frames to draw (SmokeBench: 1,000); 0 for none. + negative_seed: seed of the draw. + download: fetch missing files first (:func:`download_smokebench`). + """ + + def __init__( + self, + root: PathLike, + *, + sequences: Optional[Sequence[str]] = None, + negatives: int = NUM_NEGATIVES, + negative_seed: int = 0, + download: bool = False, + ) -> None: + self.root = Path(root) + if negatives < 0: + raise ValueError(f"negatives must be >= 0, got {negatives}") + if download: + download_smokebench(self.root, sequences, progress=True) + metadata = self.root / METADATA_FILENAME + if not metadata.exists(): + raise FileNotFoundError( + f"{metadata} not found; call pyhazards.datasets.figlib_smokebench.download_smokebench({str(self.root)!r}) " + "or pass download=True" + ) + boxes = load_smokeynet_boxes(metadata) + annotated = sorted({key.split("/")[0] for key in boxes}) + if sequences is None: + selected = annotated + else: + selected = sorted(set(sequences)) + unknown = [name for name in selected if name not in annotated] + if unknown: + raise ValueError(f"sequences without SmokeyNet boxes: {unknown[:5]}") + chosen = set(selected) + positives = [ + SmokeSample(key, self.root / f"{key}.jpg", True, tuple(tuple(box) for box in boxes[key])) + for key in sorted(boxes) + if key.split("/")[0] in chosen + ] + missing = [sample.image_id for sample in positives if not sample.path.exists()] + if missing: + raise FileNotFoundError( + f"{len(missing)} annotated frames are missing under {self.root} (e.g. {missing[:3]}); " + "download the sequences with pyhazards.datasets.figlib_smokebench.download_smokebench" + ) + pool = sorted( + f"{sequence}/{path.stem}" + for sequence in selected + for path in (self.root / sequence).glob("*_-*.jpg") + if _FRAME_NAME.match(path.name) + ) + drawn = sorted(random.Random(negative_seed).sample(pool, min(negatives, len(pool)))) if negatives else [] + self.negative_pool_size = len(pool) + self.negative_seed = negative_seed + self.sequences = selected + self.samples: List[SmokeSample] = positives + [SmokeSample(key, self.root / f"{key}.jpg", False) for key in drawn] + + def __len__(self) -> int: + return len(self.samples) + + def __getitem__(self, index): # type: ignore[override] + return self.samples[index] + + def __iter__(self) -> Iterator[SmokeSample]: + return iter(self.samples) + + @property + def positives(self) -> List[SmokeSample]: + return [sample for sample in self.samples if sample.label] + + @property + def negatives(self) -> List[SmokeSample]: + return [sample for sample in self.samples if not sample.label] + + @staticmethod + def load_image(sample: SmokeSample) -> np.ndarray: + """Decode a frame to an RGB uint8 ``(H, W, 3)`` array (needs Pillow).""" + try: + from PIL import Image # noqa: PLC0415 + except ImportError as exc: + raise ImportError("Reading FIgLib frames needs Pillow: `pip install pyhazards[prompted]`.") from exc + with Image.open(sample.path) as image: + return np.array(image.convert("RGB")) + + def describe(self) -> Dict[str, Any]: + return { + "dataset": "figlib_smokebench", + "root": str(self.root), + "sequences": len(self.sequences), + "smoke_images": len(self.positives), + "smoke_free_images": len(self.negatives), + "smoke_free_pool": self.negative_pool_size, + "negative_seed": self.negative_seed, + "boxes": f"{SMOKEYNET_METADATA_URL} (sha256 {SMOKEYNET_METADATA_SHA256})", + "images": FIGLIB_ARCHIVE_URL, + } + + +__all__ = [ + "FIGLIB_ARCHIVE_URL", + "FIgLibSmokeBench", + "METADATA_FILENAME", + "NUM_NEGATIVES", + "NUM_SEQUENCES", + "NUM_SMOKE_IMAGES", + "SMOKEYNET_COMMIT", + "SMOKEYNET_METADATA_SHA256", + "SMOKEYNET_METADATA_URL", + "SmokeSample", + "download_metadata", + "download_sequence", + "download_smokebench", + "load_smokeynet_boxes", +] diff --git a/pyhazards/datasets/figlib_smokebench/inspection.py b/pyhazards/datasets/figlib_smokebench/inspection.py new file mode 100644 index 00000000..ad5194cc --- /dev/null +++ b/pyhazards/datasets/figlib_smokebench/inspection.py @@ -0,0 +1,50 @@ +"""Inspect (and optionally download) the SmokeBench images: counts, frame sizes, smoke-area bins. + +usage: python -m pyhazards.datasets.figlib_smokebench.inspection --root /path/to/figlib [--download] +""" + +from __future__ import annotations + +import argparse +from collections import Counter +from typing import List, Optional + +from . import FIgLibSmokeBench, NUM_NEGATIVES, download_smokebench + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", required=True, help="directory with smokeynet_metadata.pkl and the FIgLib sequences") + parser.add_argument("--download", action="store_true", help="download missing boxes / sequences first") + parser.add_argument("--sequences", nargs="*", default=None, help="restrict to these FIgLib sequences") + parser.add_argument("--negatives", type=int, default=NUM_NEGATIVES) + parser.add_argument("--negative-seed", type=int, default=0) + args = parser.parse_args(argv) + + if args.download: + download_smokebench(args.root, args.sequences) + data = FIgLibSmokeBench(args.root, sequences=args.sequences, negatives=args.negatives, negative_seed=args.negative_seed) + from pyhazards.prompted.metrics import AREA_BIN_EDGES, AREA_BIN_LABELS, assign_bin, quantile_edges, smoke_area # noqa: PLC0415 + + for key, value in data.describe().items(): + print(f"{key:>18}: {value}") + areas = [smoke_area(sample.boxes) for sample in data.positives] + bins = Counter(AREA_BIN_LABELS[assign_bin(area, AREA_BIN_EDGES)] for area in areas) + print("smoke images per SmokeBench area bin:", ", ".join(f"{label} {bins[label]}" for label in AREA_BIN_LABELS)) + if areas: + print("area quintiles of these images:", [round(edge, 1) for edge in quantile_edges(areas)]) + try: + from PIL import Image # noqa: PLC0415 + except ImportError: + print("(install Pillow to list frame sizes)") + return 0 + sizes = Counter() + for sample in data: + with Image.open(sample.path) as image: + sizes[image.size] += 1 + print("frame sizes (W x H):", ", ".join(f"{w}x{h}: {n}" for (w, h), n in sizes.most_common())) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyhazards/datasets/flood/__init__.py b/pyhazards/datasets/flood/__init__.py index 8b225c1a..a81c1e14 100644 --- a/pyhazards/datasets/flood/__init__.py +++ b/pyhazards/datasets/flood/__init__.py @@ -1,66 +1,134 @@ +"""Flood datasets: real readers (CAMELS-US, Caravan, HydroGraphNet White River) and synthetic smoke-test data. + +``camels_us_streamflow``, ``caravan_streamflow`` and ``hydrographnet_white_river`` read real data (from a +local copy of the official release). The ``*_synthetic`` datasets generate random numbers in the layout +of a task so that models and evaluators can be exercised without data; they read no benchmark's data. +""" + from __future__ import annotations +import numpy as np +import pandas as pd import torch from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec -from ..graph import GraphTemporalDataset +from .camels_us import ( + CAMELS_US_TARGET, + KRATZERT2019_CHECKPOINT_STATIC_ORDER, + KRATZERT2019_DYNAMIC_INPUTS, + KRATZERT2019_PERIODS, + KRATZERT2019_STATIC_ATTRIBUTES, + CamelsUSStreamflowDataset, + load_camels_us_attributes, + load_camels_us_basin, + load_camels_us_discharge, + load_camels_us_forcings, +) +from .caravan import CaravanStreamflowDataset, load_caravan_attributes, load_caravan_timeseries +from .hydrograph import ( + HydroGraphNetWhiteRiverDataset, + HydrographRollouts, + HydrographWindows, + SyntheticFloodMeshDataset, + build_hydrograph_bundle, + hydrograph_collate, + read_hydrograph, + read_static, +) +from .urbanfloodcast import ( + SyntheticUrbanFloodCastDataset, + prepare_urbanfloodcast_event, + synthetic_urbanfloodcast_event, +) +from .streamflow import ( + StreamflowScaler, + StreamflowWindows, + build_streamflow_bundle, + read_basin_list, + scaler_from_metadata, +) class SyntheticFloodStreamflowDataset(Dataset): - """Synthetic graph-temporal flood dataset for streamflow smoke runs.""" + """Synthetic daily basins in the streamflow layout (random forcings, toy linear-reservoir discharge). + + Same structure as the real readers (``x_d`` windows, static attributes, per-basin dates, train / + val / test periods, NeuralHydrology-style normalisation), so streamflow models and the flood + benchmark run without data. The numbers mean nothing hydrologically. + """ name = "flood_streamflow_synthetic" def __init__( self, cache_dir: str | None = None, - samples: int = 40, - history: int = 4, - nodes: int = 6, - features: int = 2, + basins: int = 6, + days: int = 730, + n_dynamic: int = 5, + n_static: int = 27, + seq_length: int = 30, + predict_last_n: int = 1, + seed: int = 0, micro: bool = False, ): super().__init__(cache_dir=cache_dir) - self.samples = 12 if micro else int(samples) - self.history = int(history) - self.nodes = int(nodes) - self.features = int(features) - - def _make_split(self, x: torch.Tensor, y: torch.Tensor, adj: torch.Tensor) -> DataSplit: - dataset = GraphTemporalDataset(x, y, adjacency=adj) - return DataSplit(inputs=dataset, targets=None) + self.n_basins = 3 if micro else int(basins) + self.days = 300 if micro else int(days) + self.n_dynamic = int(n_dynamic) + self.n_static = int(n_static) + self.seq_length = int(seq_length) + self.predict_last_n = int(predict_last_n) + self.seed = int(seed) + if self.n_basins < 2: + raise ValueError("flood_streamflow_synthetic needs at least 2 basins (static attributes are standardised).") + if self.n_dynamic < 1: + raise ValueError("n_dynamic must be positive.") + if self.days < 3 * self.seq_length: + raise ValueError(f"days ({self.days}) must be at least 3 * seq_length ({3 * self.seq_length}).") def _load(self) -> DataBundle: - x = torch.randn(self.samples, self.history, self.nodes, self.features, dtype=torch.float32) - adjacency = torch.eye(self.nodes, dtype=torch.float32) - adjacency += torch.diag(torch.ones(self.nodes - 1), diagonal=1) - adjacency += torch.diag(torch.ones(self.nodes - 1), diagonal=-1) - y = x[:, -1, :, :1] * 0.7 + 0.1 - - train_end = max(1, int(0.7 * self.samples)) - val_end = max(train_end + 1, int(0.85 * self.samples)) - splits = { - "train": self._make_split(x[:train_end], y[:train_end], adjacency), - "val": self._make_split(x[train_end:val_end], y[train_end:val_end], adjacency), - "test": self._make_split(x[val_end:], y[val_end:], adjacency), + rng = np.random.default_rng(self.seed) + dates = pd.date_range("2000-01-01", periods=self.days, freq="1D") + dynamic = [f"synthetic_forcing_{i}" for i in range(self.n_dynamic)] + static = [f"synthetic_attribute_{i:02d}" for i in range(self.n_static)] + target = "discharge" + attributes = pd.DataFrame( + rng.normal(size=(self.n_basins, self.n_static)), + index=[f"synthetic_{i:03d}" for i in range(self.n_basins)], + columns=static, + ) + frames = {} + season = np.sin(2 * np.pi * np.arange(self.days) / 365.25) + for b, basin in enumerate(attributes.index): + rain = rng.gamma(0.8, 6.0, size=self.days) * (rng.random(self.days) < 0.35) + forcings = {dynamic[0]: rain} + for i in range(1, self.n_dynamic): + forcings[dynamic[i]] = 10 * season * (1 + 0.1 * i) + rng.normal(scale=2.0, size=self.days) + k = 0.05 + 0.2 / (1 + np.exp(-attributes.iloc[b, 0])) if self.n_static else 0.1 + storage, discharge = 0.0, np.empty(self.days) + for t in range(self.days): + storage = storage * (1 - k) + rain[t] + discharge[t] = k * storage + discharge[rng.choice(self.days, size=max(1, self.days // 50), replace=False)] = np.nan + frames[basin] = pd.DataFrame({**forcings, target: discharge}, index=pd.DatetimeIndex(dates, name="date")) + train_end = dates[int(0.5 * self.days)] + val_end = dates[int(0.7 * self.days)] + periods = { + "train": (dates[self.seq_length], train_end), + "val": (train_end + pd.Timedelta(days=1), val_end), + "test": (val_end + pd.Timedelta(days=1), dates[-1]), } - return DataBundle( - splits=splits, - feature_spec=FeatureSpec( - input_dim=self.features, - description="Synthetic node features for streamflow forecasting on a line graph.", - extra={"nodes": self.nodes, "history": self.history}, - ), - label_spec=LabelSpec( - num_targets=1, - task_type="regression", - description="Next-step nodewise streamflow target.", - ), - metadata={ - "dataset": self.name, - "source_dataset": self.name, - "hazard_task": "flood.streamflow", - }, + return build_streamflow_bundle( + frames, + attributes if static else None, + dynamic, + static, + [target], + periods, + self.seq_length, + self.predict_last_n, + dataset_name=self.name, + metadata={"synthetic": True}, ) @@ -135,59 +203,41 @@ def _load(self) -> DataBundle: "dataset": self.name, "source_dataset": self.name, "hazard_task": "flood.inundation", + "synthetic": True, }, ) -class CaravanStreamflowDataset(SyntheticFloodStreamflowDataset): - """Synthetic-backed streamflow adapter for Caravan-style smoke runs.""" - - name = "caravan_streamflow" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "Caravan", "source_dataset": self.name}) - return bundle - - -class WaterBenchStreamflowDataset(SyntheticFloodStreamflowDataset): - """Synthetic-backed streamflow adapter for WaterBench-style smoke runs.""" - - name = "waterbench_streamflow" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "WaterBench", "source_dataset": self.name}) - return bundle - - -class HydroBenchStreamflowDataset(SyntheticFloodStreamflowDataset): - """Synthetic-backed streamflow adapter for HydroBench diagnostics.""" - - name = "hydrobench_streamflow" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "HydroBench", "source_dataset": self.name}) - return bundle - - -class FloodCastBenchInundationDataset(SyntheticFloodInundationDataset): - """Synthetic-backed inundation adapter for FloodCastBench-style smoke runs.""" - - name = "floodcastbench_inundation" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "FloodCastBench", "source_dataset": self.name}) - return bundle - - __all__ = [ + "CAMELS_US_TARGET", + "CamelsUSStreamflowDataset", "CaravanStreamflowDataset", - "FloodCastBenchInundationDataset", - "HydroBenchStreamflowDataset", + "HydroGraphNetWhiteRiverDataset", + "HydrographRollouts", + "HydrographWindows", + "KRATZERT2019_CHECKPOINT_STATIC_ORDER", + "KRATZERT2019_DYNAMIC_INPUTS", + "KRATZERT2019_PERIODS", + "KRATZERT2019_STATIC_ATTRIBUTES", + "StreamflowScaler", + "StreamflowWindows", "SyntheticFloodInundationDataset", + "SyntheticFloodMeshDataset", "SyntheticFloodStreamflowDataset", - "WaterBenchStreamflowDataset", + "SyntheticUrbanFloodCastDataset", + "build_hydrograph_bundle", + "build_streamflow_bundle", + "hydrograph_collate", + "load_camels_us_attributes", + "load_camels_us_basin", + "load_camels_us_discharge", + "load_camels_us_forcings", + "load_caravan_attributes", + "load_caravan_timeseries", + "prepare_urbanfloodcast_event", + "read_basin_list", + "read_hydrograph", + "read_static", + "scaler_from_metadata", + "synthetic_urbanfloodcast_event", ] diff --git a/pyhazards/datasets/flood/camels_us.py b/pyhazards/datasets/flood/camels_us.py new file mode 100644 index 00000000..a0551de0 --- /dev/null +++ b/pyhazards/datasets/flood/camels_us.py @@ -0,0 +1,201 @@ +"""CAMELS-US reader (Addor et al., HESS 2017; Newman et al., HESS 2015), as NeuralHydrology reads it. + +The file readers are ported from NeuralHydrology, ``neuralhydrology/datasetzoo/camelsus.py`` at commit +ea94a40 (https://github.com/neuralhydrology/neuralhydrology, BSD-3-Clause, Copyright (c) 2021, +NeuralHydrology). They expect the original CAMELS-US directory layout under ``data_dir``:: + + basin_mean_forcing//[/]_*_forcing_leap.txt (daymet, maurer, nldas, maurer_extended, ...) + usgs_streamflow/[/]_streamflow_qc.txt + camels_attributes_v2.0/camels_*.txt (';'-separated, column gauge_id) + +Discharge is converted from cubic feet per second to mm/day with the catchment area in the forcing +file header (``QObs(mm/d)``); negative discharge (missing-value flags) becomes NaN. PyHazards does not +download CAMELS-US (CC BY 4.0, Zenodo record 15529996); point ``data_dir`` at a local copy. The extended +Maurer forcings used by Kratzert et al. (2019) are a separate download (HydroShare, +doi 10.4211/hs.17c896843cf940339c3c3496d0c1c077). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np +import pandas as pd + +from ..base import DataBundle, Dataset +from .streamflow import build_streamflow_bundle, read_basin_list + +# Kratzert et al. (HESS 2019), Sect. 2.6 and Appendix A: the five extended-Maurer forcings and the 27 +# CAMELS attributes (frac_snow is "frac_snow_daily" in the paper's table), train 1999-10-01 to +# 2008-09-30, test 1989-10-01 to 1999-09-30, 270-day input sequences. The validation period is the +# one of NeuralHydrology's example configuration (the paper used none). +KRATZERT2019_DYNAMIC_INPUTS = ["prcp(mm/day)", "srad(W/m2)", "tmax(C)", "tmin(C)", "vp(Pa)"] +KRATZERT2019_STATIC_ATTRIBUTES = [ + "elev_mean", "slope_mean", "area_gages2", "frac_forest", "lai_max", "lai_diff", "gvf_max", "gvf_diff", + "soil_depth_pelletier", "soil_depth_statsgo", "soil_porosity", "soil_conductivity", "max_water_content", + "sand_frac", "silt_frac", "clay_frac", "carbonate_rocks_frac", "geol_permeability", "p_mean", "pet_mean", + "aridity", "frac_snow", "high_prec_freq", "high_prec_dur", "low_prec_freq", "low_prec_dur", "p_seasonality", +] +# Column order of the 27 attributes in the official 2019 checkpoints (the attributes.db of every HydroShare +# run). PyHazards, like NeuralHydrology, feeds static attributes in alphabetical order; to apply a 2019 +# checkpoint to real data, permute x_s with KRATZERT2019_CHECKPOINT_STATIC_ORDER. +KRATZERT2019_CHECKPOINT_STATIC_ORDER = [ + "carbonate_rocks_frac", "geol_permeability", "frac_forest", "lai_max", "lai_diff", "gvf_max", "gvf_diff", + "p_mean", "pet_mean", "p_seasonality", "frac_snow", "aridity", "high_prec_freq", "high_prec_dur", + "low_prec_freq", "low_prec_dur", "elev_mean", "slope_mean", "area_gages2", "soil_depth_pelletier", + "soil_depth_statsgo", "soil_porosity", "soil_conductivity", "max_water_content", "sand_frac", "silt_frac", + "clay_frac", +] +KRATZERT2019_PERIODS = { + "train": ("1999-10-01", "2008-09-30"), + "val": ("1980-10-01", "1989-09-30"), + "test": ("1989-10-01", "1999-09-30"), +} +CAMELS_US_TARGET = "QObs(mm/d)" + + +def load_camels_us_attributes(data_dir: Union[str, Path], basins: Optional[Sequence[str]] = None) -> pd.DataFrame: + """Basin-indexed table of all CAMELS-US attributes (``camels_attributes_v2.0/camels_*.txt``).""" + attributes_path = Path(data_dir) / "camels_attributes_v2.0" + if not attributes_path.exists(): + raise FileNotFoundError(f"Attribute folder not found at {attributes_path}") + dfs = [] + for txt_file in sorted(attributes_path.glob("camels_*.txt")): + df_temp = pd.read_csv(txt_file, sep=";", header=0, dtype={"gauge_id": str}) + dfs.append(df_temp.set_index("gauge_id")) + if not dfs: + raise FileNotFoundError(f"No camels_*.txt attribute files in {attributes_path}") + df = pd.concat(dfs, axis=1) + # convert huc column to double digit strings + df["huc"] = df["huc_02"].apply(lambda x: str(x).zfill(2)) + df = df.drop("huc_02", axis=1) + if basins: + missing = [b for b in basins if b not in df.index] + if missing: + raise ValueError(f"Some basins are missing static attributes: {missing}") + df = df.loc[list(basins)] + return df + + +def load_camels_us_forcings(data_dir: Union[str, Path], basin: str, forcings: str) -> Tuple[pd.DataFrame, int]: + """Forcing table of one basin (date-indexed) and the catchment area (m2) from the file header.""" + forcing_path = Path(data_dir) / "basin_mean_forcing" / forcings + if not forcing_path.is_dir(): + raise OSError(f"{forcing_path} does not exist") + file_paths = sorted(forcing_path.glob(f"**/{basin}_*_forcing_leap.txt")) + if not file_paths: + raise FileNotFoundError(f"No file for Basin {basin} at {forcing_path}") + with open(file_paths[0], "r") as fp: + # load area from header + fp.readline() + fp.readline() + area = int(fp.readline()) + # load the dataframe from the rest of the stream + df = pd.read_csv(fp, sep=r"\s+") + df["date"] = pd.to_datetime( + df.Year.map(str) + "/" + df.Mnth.map(str) + "/" + df.Day.map(str), format="%Y/%m/%d" + ) + return df.set_index("date"), area + + +def load_camels_us_discharge(data_dir: Union[str, Path], basin: str, area: int) -> pd.Series: + """Daily discharge of one basin in mm/day (USGS cubic feet per second divided by the area).""" + discharge_path = Path(data_dir) / "usgs_streamflow" + file_paths = sorted(discharge_path.glob(f"**/{basin}_streamflow_qc.txt")) + if not file_paths: + raise FileNotFoundError(f"No file for Basin {basin} at {discharge_path}") + col_names = ["basin", "Year", "Mnth", "Day", "QObs", "flag"] + df = pd.read_csv(file_paths[0], sep=r"\s+", header=None, names=col_names) + df["date"] = pd.to_datetime( + df.Year.map(str) + "/" + df.Mnth.map(str) + "/" + df.Day.map(str), format="%Y/%m/%d" + ) + df = df.set_index("date") + # normalize discharge from cubic feet per second to mm per day + return 28316846.592 * df.QObs * 86400 / (area * 10**6) + + +def load_camels_us_basin(data_dir: Union[str, Path], basin: str, forcings: Sequence[str]) -> pd.DataFrame: + """Forcings (suffixed ``_`` when several products are used) and ``QObs(mm/d)`` of one basin.""" + dfs = [] + area = None + for forcing in forcings: + df, area = load_camels_us_forcings(data_dir, basin, forcing) + if len(forcings) > 1: + df = df.rename(columns={col: f"{col}_{forcing}" for col in df.columns}) + dfs.append(df) + df = pd.concat(dfs, axis=1) + df[CAMELS_US_TARGET] = load_camels_us_discharge(data_dir, basin, area) + # replace invalid discharge values by NaNs + for col in [c for c in df.columns if "qobs" in c.lower()]: + df.loc[df[col] < 0, col] = np.nan + return df + + +class CamelsUSStreamflowDataset(Dataset): + """CAMELS-US daily streamflow in the Kratzert et al. (2019) setup, read from a local copy. + + ``basins`` is a list of 8-digit USGS ids or a basin file (one id per line). Defaults reproduce the + paper: extended Maurer forcings, the 27 static attributes, 270-day windows, train 1999-10-01 to + 2008-09-30 and test 1989-10-01 to 1999-09-30. + """ + + name = "camels_us_streamflow" + + def __init__( + self, + data_dir: Optional[Union[str, Path]] = None, + basins: Any = None, + forcings: Union[str, Sequence[str]] = "maurer_extended", + dynamic_inputs: Sequence[str] = tuple(KRATZERT2019_DYNAMIC_INPUTS), + static_attributes: Sequence[str] = tuple(KRATZERT2019_STATIC_ATTRIBUTES), + target_variables: Sequence[str] = (CAMELS_US_TARGET,), + periods: Optional[Dict[str, Sequence[str]]] = None, + seq_length: int = 270, + predict_last_n: int = 1, + cache_dir: Optional[str] = None, + ): + super().__init__(cache_dir=cache_dir) + if data_dir is None: + raise ValueError("camels_us_streamflow needs data_dir, the root of a local CAMELS-US copy.") + self.data_dir = Path(data_dir) + self.basins = read_basin_list(basins) + self.forcings = [forcings] if isinstance(forcings, str) else list(forcings) + self.dynamic_inputs = list(dynamic_inputs) + self.static_attributes = list(static_attributes) + self.target_variables = list(target_variables) + self.periods = dict(periods or KRATZERT2019_PERIODS) + self.seq_length = int(seq_length) + self.predict_last_n = int(predict_last_n) + + def _load(self) -> DataBundle: + frames = {basin: load_camels_us_basin(self.data_dir, basin, self.forcings) for basin in self.basins} + attributes = ( + load_camels_us_attributes(self.data_dir, self.basins) if self.static_attributes else None + ) + return build_streamflow_bundle( + frames, + attributes, + self.dynamic_inputs, + self.static_attributes, + self.target_variables, + self.periods, + self.seq_length, + self.predict_last_n, + dataset_name=self.name, + metadata={"forcings": self.forcings, "data_dir": str(self.data_dir)}, + ) + + +__all__ = [ + "CAMELS_US_TARGET", + "KRATZERT2019_CHECKPOINT_STATIC_ORDER", + "CamelsUSStreamflowDataset", + "KRATZERT2019_DYNAMIC_INPUTS", + "KRATZERT2019_PERIODS", + "KRATZERT2019_STATIC_ATTRIBUTES", + "load_camels_us_attributes", + "load_camels_us_basin", + "load_camels_us_discharge", + "load_camels_us_forcings", +] diff --git a/pyhazards/datasets/flood/caravan.py b/pyhazards/datasets/flood/caravan.py new file mode 100644 index 00000000..2e330ddd --- /dev/null +++ b/pyhazards/datasets/flood/caravan.py @@ -0,0 +1,157 @@ +"""Caravan reader (Kratzert et al., Scientific Data 10:61, 2023), as NeuralHydrology reads it. + +The file readers follow NeuralHydrology, ``neuralhydrology/datasetzoo/caravan.py`` at commit ea94a40 +(https://github.com/neuralhydrology/neuralhydrology, BSD-3-Clause, Copyright (c) 2021, NeuralHydrology). +They expect the layout of the official Caravan release (Zenodo, CC BY 4.0; per-source licence notes in +its ``licenses/`` folder) under ``data_dir``:: + + attributes//attributes_{caravan,hydroatlas,other}_.csv (column gauge_id) + timeseries/netcdf//_.nc (dimension date) + timeseries/csv//_.csv (column date) + +Basin ids have the form ``_`` (e.g. ``camelsgb_28015``). Time series are daily ERA5-Land +forcings and states (e.g. ``total_precipitation_sum``, ``temperature_2m_mean``, +``potential_evaporation_sum``) and observed ``streamflow`` in mm/day. PyHazards downloads nothing; +point ``data_dir`` at a local copy. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Union + +import pandas as pd +import xarray + +from ..base import DataBundle, Dataset +from .streamflow import build_streamflow_bundle, read_basin_list + +CARAVAN_TARGET = "streamflow" + + +def load_caravan_attributes( + data_dir: Union[str, Path], + basins: Optional[Sequence[str]] = None, + subdataset: Optional[str] = None, +) -> pd.DataFrame: + """Basin-indexed table merging every attribute CSV of the requested source datasets.""" + data_dir = Path(data_dir) + if subdataset: + subdataset_dir = data_dir / "attributes" / subdataset + if not subdataset_dir.is_dir(): + raise FileNotFoundError(f"No subdataset {subdataset} found at {subdataset_dir}.") + subdataset_dirs = [subdataset_dir] + else: + subdataset_dirs = sorted(d for d in (data_dir / "attributes").glob("*") if d.is_dir()) + + if basins: + subdataset_names = sorted(set(x.split("_")[0] for x in basins)) + if subdataset: + if len(subdataset_names) > 1 or subdataset_names[0] != subdataset: + raise ValueError("At least one of the passed basins is not part of the passed subdataset.") + else: + missing_subdatasets = [s for s in subdataset_names if not (data_dir / "attributes" / s).is_dir()] + if missing_subdatasets: + raise FileNotFoundError(f"Could not find subdataset directories for {missing_subdatasets}.") + subdataset_dirs = [s for s in subdataset_dirs if s.name in subdataset_names] + + dfs = [] + for subdataset_dir in subdataset_dirs: + files = [pd.read_csv(csv_file, index_col="gauge_id") for csv_file in sorted(subdataset_dir.glob("*.csv"))] + if files: + dfs.append(pd.concat(files, axis=1)) + if not dfs: + raise FileNotFoundError(f"No attribute CSV files under {data_dir / 'attributes'}.") + df = pd.concat(dfs, axis=0) + + if basins: + missing = [b for b in basins if b not in df.index] + if missing: + raise ValueError(f"Some basins are missing static attributes: {missing}") + df = df.loc[list(basins)] + return df + + +def load_caravan_timeseries(data_dir: Union[str, Path], basin: str, filetype: str = "netcdf") -> pd.DataFrame: + """Date-indexed time series of one basin from ``timeseries/netcdf`` (default) or ``timeseries/csv``.""" + subdataset_name = basin.split("_")[0] + if filetype == "netcdf": + filepath = Path(data_dir) / "timeseries" / "netcdf" / subdataset_name / f"{basin}.nc" + elif filetype == "csv": + filepath = Path(data_dir) / "timeseries" / "csv" / subdataset_name / f"{basin}.csv" + else: + raise ValueError("filetype has to be either 'csv' or 'netcdf'.") + if not filepath.is_file(): + raise FileNotFoundError(f"No basin file found at {filepath}.") + if filetype == "netcdf": + with xarray.open_dataset(filepath) as ds: + df = ds.to_dataframe() + else: + df = pd.read_csv(filepath, parse_dates=["date"]).set_index("date") + return df + + +class CaravanStreamflowDataset(Dataset): + """Caravan daily streamflow, read from a local copy of the official release. + + Caravan has no single published input set or split, so ``basins``, ``dynamic_inputs`` and + ``periods`` must be given; ``static_attributes`` may be any columns of the attribute CSVs. + """ + + name = "caravan_streamflow" + + def __init__( + self, + data_dir: Optional[Union[str, Path]] = None, + basins: Any = None, + dynamic_inputs: Optional[Sequence[str]] = None, + static_attributes: Sequence[str] = (), + target_variables: Sequence[str] = (CARAVAN_TARGET,), + periods: Optional[Dict[str, Sequence[str]]] = None, + seq_length: int = 365, + predict_last_n: int = 1, + filetype: str = "netcdf", + cache_dir: Optional[str] = None, + ): + super().__init__(cache_dir=cache_dir) + if data_dir is None: + raise ValueError("caravan_streamflow needs data_dir, the root of a local Caravan copy.") + if not dynamic_inputs: + raise ValueError("caravan_streamflow needs dynamic_inputs, e.g. ['total_precipitation_sum', ...].") + if not periods: + raise ValueError("caravan_streamflow needs periods, e.g. {'train': (start, end), 'test': (start, end)}.") + if filetype not in ("netcdf", "csv"): + raise ValueError("filetype has to be either 'csv' or 'netcdf'.") + self.data_dir = Path(data_dir) + self.basins: List[str] = read_basin_list(basins) + self.dynamic_inputs = list(dynamic_inputs) + self.static_attributes = list(static_attributes) + self.target_variables = list(target_variables) + self.periods = dict(periods) + self.seq_length = int(seq_length) + self.predict_last_n = int(predict_last_n) + self.filetype = filetype + + def _load(self) -> DataBundle: + frames = {basin: load_caravan_timeseries(self.data_dir, basin, self.filetype) for basin in self.basins} + attributes = load_caravan_attributes(self.data_dir, self.basins) if self.static_attributes else None + return build_streamflow_bundle( + frames, + attributes, + self.dynamic_inputs, + self.static_attributes, + self.target_variables, + self.periods, + self.seq_length, + self.predict_last_n, + dataset_name=self.name, + metadata={"data_dir": str(self.data_dir), "filetype": self.filetype}, + ) + + +__all__ = [ + "CARAVAN_TARGET", + "CaravanStreamflowDataset", + "load_caravan_attributes", + "load_caravan_timeseries", +] diff --git a/pyhazards/datasets/flood/hydrograph.py b/pyhazards/datasets/flood/hydrograph.py new file mode 100644 index 00000000..2b9eb4d7 --- /dev/null +++ b/pyhazards/datasets/flood/hydrograph.py @@ -0,0 +1,729 @@ +"""HydroGraphNet mesh flood data: the White River (Indiana) HEC-RAS dataset and a synthetic stand-in. + +The reading, normalisation, graph construction and sample layout follow PhysicsNeMo's +``HydroGraphDataset`` (``physicsnemo/datapipes/gnn/hydrographnet_dataset.py`` @ eb7a329, Apache-2.0, +Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES) used by the HydroGraphNet example; the +oracle test compares every sample with it. + +File layout (Zenodo record 14969507, ``HydroGraphNet.zip``, CC BY 4.0; tab-separated text, prefix ``M80``): + +- static, one value per mesh cell: ``M80_XY.txt`` (x, y), ``M80_CA.txt`` (cell area), ``M80_CE.txt`` + (elevation), ``M80_CS.txt`` (slope), ``M80_A.txt`` (aspect), ``M80_CU.txt`` (curvature), ``M80_N.txt`` + (Manning's n), ``M80_FA.txt`` (flow accumulation), ``M80_IP.txt`` (infiltration); rows beyond the + number of XY points are ignored; +- per hydrograph ```` (``H1`` ... ``H500``): ``M80_WD_.txt`` / ``M80_V_.txt`` (water depth / + volume, one row per 20-minute step, one column per cell), ``M80_US_InF_.txt`` (upstream inflow in + column 1), ``M80_Pr_.txt`` (precipitation); +- ``train.txt``: hydrograph ids, one per line. + +Each hydrograph drops its first 72 steps and is cut 25 steps after the inflow peak; precipitation is +multiplied by 2.7778e-7. Static features are standardised per column, the dynamic series with one mean +and standard deviation each over the training hydrographs (``std + 1e-8`` in the denominator). The +graph links every cell to its 4 nearest neighbours (k-d tree on standardised coordinates, edges point +from the cell to its neighbours); edge features are the standardised offsets and distance. + +Training samples are sliding windows: 16 node features (x, y, area, elevation, slope, aspect, +curvature, Manning, flow accumulation, infiltration, inflow and precipitation at the window start, +depth and volume over the ``n_time_steps=2`` window) and the next change of depth and volume as target, +with the physics data of the continuity loss. Test samples are whole hydrographs for autoregressive +rollouts (the first window, the forcings and the true depth / volume of the next ``rollout_length`` +steps). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +from torch.utils.data import Dataset as TorchDataset + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +EPSILON = 1e-8 +HYDROGRAPH_PREFIX = "M80" +# PyHazards key -> HydroGraphDataset static key and file code. +STATIC_FILES = { + "xy_coords": "XY", + "area": "CA", + "elevation": "CE", + "slope": "CS", + "aspect": "A", + "curvature": "CU", + "manning": "N", + "flow_accum": "FA", + "infiltration": "IP", +} +STATIC_ORDER = tuple(STATIC_FILES) +DYNAMIC_KEYS = ("water_depth", "volume", "precipitation", "inflow_hydrograph") +STATIC_NORM_STATS_FILE = "static_norm_stats.json" +DYNAMIC_NORM_STATS_FILE = "dynamic_norm_stats.json" + + +def _normalize(data: np.ndarray, mean, std) -> np.ndarray: + mean = np.array(mean) if isinstance(mean, list) else mean + std = np.array(std) if isinstance(std, list) else std + return (data - mean) / (std + EPSILON) + + +def _denormalize(data: np.ndarray, mean, std) -> np.ndarray: + mean = np.array(mean) if isinstance(mean, list) else mean + std = np.array(std) if isinstance(std, list) else std + return data * (std + EPSILON) + mean + + +def read_static(data_dir: Union[str, Path], prefix: str = HYDROGRAPH_PREFIX) -> Dict[str, np.ndarray]: + """Raw static mesh arrays: ``xy_coords`` (N, 2) and one (N, 1) column per other attribute.""" + root = Path(data_dir) + path = root / f"{prefix}_XY.txt" + if not path.exists(): + raise FileNotFoundError(f"{path} not found; data_dir must hold the HydroGraphNet files ({prefix}_XY.txt, ...).") + xy = np.loadtxt(path, delimiter="\t") + if xy.ndim != 2 or xy.shape[1] != 2: + raise ValueError(f"{path} must have two tab-separated columns (x, y); got shape {xy.shape}.") + raw: Dict[str, np.ndarray] = {"xy_coords": xy} + for key, code in list(STATIC_FILES.items())[1:]: + raw[key] = np.loadtxt(root / f"{prefix}_{code}.txt", delimiter="\t")[: xy.shape[0]].reshape(-1, 1) + return raw + + +def standardize_static( + raw: Mapping[str, np.ndarray], stats: Optional[Mapping[str, Mapping[str, Any]]] = None +) -> Tuple[Dict[str, np.ndarray], Dict[str, Dict[str, list]]]: + """Standardise each static array with ``stats`` (or its own column means / standard deviations).""" + stats = {key: dict(value) for key, value in (stats or {}).items()} + out: Dict[str, np.ndarray] = {} + for key in STATIC_ORDER: + data = np.asarray(raw[key], dtype=np.float64) + if key in stats: + mean_val = np.array(stats[key]["mean"]) + std_val = np.array(stats[key]["std"]) + else: + mean_val = np.mean(data, axis=0) + std_val = np.std(data, axis=0) + stats[key] = {"mean": mean_val.tolist(), "std": std_val.tolist()} + out[key] = (data - mean_val) / (std_val + EPSILON) + return out, stats + + +def read_hydrograph( + data_dir: Union[str, Path], + hydrograph_id: str, + num_points: int, + prefix: str = HYDROGRAPH_PREFIX, + interval: int = 1, + skip: int = 72, +) -> Dict[str, np.ndarray]: + """Raw series of one hydrograph: ``water_depth`` / ``volume`` (T, N), ``inflow_hydrograph`` / ``precipitation`` (T,).""" + root = Path(data_dir) + water_depth = np.loadtxt(root / f"{prefix}_WD_{hydrograph_id}.txt", delimiter="\t")[skip::interval, :num_points] + inflow = np.loadtxt(root / f"{prefix}_US_InF_{hydrograph_id}.txt", delimiter="\t")[skip::interval, 1] + volume = np.loadtxt(root / f"{prefix}_V_{hydrograph_id}.txt", delimiter="\t")[skip::interval, :num_points] + precipitation = np.loadtxt(root / f"{prefix}_Pr_{hydrograph_id}.txt", delimiter="\t")[skip::interval] + peak = int(np.argmax(inflow)) + return { + "water_depth": water_depth[: peak + 25], + "volume": volume[: peak + 25], + "precipitation": precipitation[: peak + 25] * 2.7778e-7, + "inflow_hydrograph": inflow[: peak + 25], + } + + +def list_hydrograph_ids(data_dir: Union[str, Path], prefix: str = HYDROGRAPH_PREFIX) -> List[str]: + """Ids of every ``_WD_.txt`` file in ``data_dir`` (directory order, like HydroGraphDataset).""" + ids = [] + for path in Path(data_dir).iterdir(): + name = path.name + if name.startswith(f"{prefix}_WD_") and name.endswith(".txt"): + parts = name.split("_") + if len(parts) >= 3: + ids.append(Path(parts[2]).stem) + return ids + + +def read_hydrograph_ids(spec: Union[str, Path, Sequence[str]], data_dir: Union[str, Path]) -> List[str]: + """Hydrograph ids from a list or from a file (absolute, or relative to ``data_dir``), one id per line.""" + if isinstance(spec, (str, Path)): + path = Path(spec) + if not path.is_absolute(): + path = Path(data_dir) / path + if not path.exists(): + raise FileNotFoundError(f"Hydrograph IDs file not found: {path}") + return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + return [str(item) for item in spec] + + +def knn_edge_index(xy_coords: np.ndarray, k: int = 4) -> np.ndarray: + """``(2, E)`` edges from every node to its ``k`` nearest other nodes (k-d tree query of ``k + 1``).""" + from scipy.spatial import KDTree + + _, neighbors = KDTree(xy_coords).query(xy_coords, k=k + 1) + return np.vstack([(i, nbr) for i, nbrs in enumerate(neighbors) for nbr in nbrs if nbr != i]).T + + +def mesh_edge_features(xy_coords: np.ndarray, edge_index: np.ndarray) -> np.ndarray: + """Standardised (dx, dy, distance) of every edge (source minus destination).""" + row, col = edge_index + relative = xy_coords[row] - xy_coords[col] + distance = np.linalg.norm(relative, axis=1) + relative = (relative - np.mean(relative, axis=0)) / (np.std(relative, axis=0) + EPSILON) + distance = (distance - np.mean(distance)) / (np.std(distance) + EPSILON) + return np.hstack([relative, distance[:, None]]) + + +def mesh_node_features( + static: Mapping[str, np.ndarray], + water_depth: np.ndarray, + volume: np.ndarray, + precipitation: np.ndarray, + inflow: np.ndarray, + time_step: int, +) -> np.ndarray: + """HydroGraphDataset.create_node_features: 12 static / forcing columns, then depth and volume windows.""" + num_nodes = static["xy_coords"].shape[0] + return np.hstack( + [static[key] for key in STATIC_ORDER] + + [ + np.full((num_nodes, 1), inflow[time_step]), + np.full((num_nodes, 1), precipitation[time_step]), + water_depth.T, + volume.T, + ] + ) + + +def dynamic_stats(hydrographs: Iterable[Mapping[str, np.ndarray]]) -> Dict[str, Dict[str, float]]: + """Mean and standard deviation of every dynamic variable over all values of the given hydrographs.""" + series = list(hydrographs) + if not series: + raise ValueError("Dynamic normalisation statistics need at least one training hydrograph.") + stats: Dict[str, Dict[str, float]] = {} + for key in DYNAMIC_KEYS: + values = np.concatenate([np.asarray(item[key]).flatten() for item in series]) + stats[key] = {"mean": float(np.mean(values)), "std": float(np.std(values))} + return stats + + +class HydrographMesh: + """Normalised static fields, graph and normalised hydrographs shared by the training and test samples.""" + + def __init__( + self, + static: Mapping[str, np.ndarray], + area_denorm: np.ndarray, + hydrographs: Mapping[str, Mapping[str, np.ndarray]], + static_stats: Mapping[str, Any], + dynamic_stats: Mapping[str, Mapping[str, float]], + k: int = 4, + ): + self.static = dict(static) + self.area_denorm = np.asarray(area_denorm) + self.static_stats = {key: dict(value) for key, value in static_stats.items()} + self.dynamic_stats = {key: dict(value) for key, value in dynamic_stats.items()} + self.num_nodes = int(self.static["xy_coords"].shape[0]) + self.edge_index = knn_edge_index(self.static["xy_coords"], k=k) + self.edge_features = mesh_edge_features(self.static["xy_coords"], self.edge_index) + self.edge_index_tensor = torch.from_numpy(np.ascontiguousarray(self.edge_index)).long() + self.edge_features_tensor = torch.tensor(self.edge_features, dtype=torch.float) + self.hydrographs = { + hid: { + key: _normalize(np.asarray(series[key]), self.dynamic_stats[key]["mean"], self.dynamic_stats[key]["std"]) + for key in DYNAMIC_KEYS + } + for hid, series in hydrographs.items() + } + infiltration = _denormalize( + self.static["infiltration"], self.static_stats["infiltration"]["mean"], self.static_stats["infiltration"]["std"] + ) + self.area_sum = float(np.sum(self.area_denorm)) + self.infiltration_area_sum = float(np.sum(infiltration * self.area_denorm)) / 100.0 + + def node_features(self, hydrograph_id: str, start: int, end: int, time_step: int) -> np.ndarray: + dyn = self.hydrographs[hydrograph_id] + return mesh_node_features( + self.static, + dyn["water_depth"][start:end, :], + dyn["volume"][start:end, :], + dyn["precipitation"], + dyn["inflow_hydrograph"], + time_step, + ) + + def _denorm(self, value: float, key: str) -> float: + return value * self.dynamic_stats[key]["std"] + self.dynamic_stats[key]["mean"] + + def physics_data(self, hydrograph_id: str, t_idx: int, n_time_steps: int) -> Dict[str, float]: + """Physics dict of the training sample starting at ``t_idx`` (HydroGraphDataset, ``return_physics=True``).""" + dyn = self.hydrographs[hydrograph_id] + inflow, precipitation, volume = dyn["inflow_hydrograph"], dyn["precipitation"], dyn["volume"] + target_time = t_idx + n_time_steps + prev_time = target_time - 1 + has_next = target_time + 1 < volume.shape[0] + future_volume = float(np.sum(volume[target_time + 1, :])) if has_next else float(np.sum(volume[target_time, :])) + next_index = target_time + 1 if target_time + 1 < inflow.shape[0] else target_time + stats = self.dynamic_stats + return { + "flow_future": float(self._denorm(inflow[t_idx + n_time_steps], "inflow_hydrograph")), + "precip_future": float(self._denorm(precipitation[t_idx + n_time_steps], "precipitation")), + "past_volume": float(np.sum(volume[prev_time, :])), + "future_volume": future_volume, + "avg_inflow": self._denorm(float((inflow[prev_time] + inflow[target_time]) / 2), "inflow_hydrograph"), + "avg_precipitation": self._denorm(float((precipitation[prev_time] + precipitation[target_time]) / 2), "precipitation"), + "next_inflow": float(self._denorm(inflow[next_index], "inflow_hydrograph")), + "next_precip": float(self._denorm(precipitation[next_index], "precipitation")), + "volume_mean": float(stats["volume"]["mean"]), + "volume_std": float(stats["volume"]["std"]), + "inflow_mean": float(stats["inflow_hydrograph"]["mean"]), + "inflow_std": float(stats["inflow_hydrograph"]["std"]), + "precip_mean": float(stats["precipitation"]["mean"]), + "precip_std": float(stats["precipitation"]["std"]), + "num_nodes": float(self.num_nodes), + "area_sum": self.area_sum, + "infiltration_area_sum": self.infiltration_area_sum, + } + + +class HydrographWindows(TorchDataset): + """Training samples: ``({"node_features", "edge_features", "edge_index", "physics"}, target (N, 2))``. + + The target is the normalised change of water depth and volume from the last window step to the next. + Batch several samples with :func:`hydrograph_collate`. + """ + + def __init__(self, mesh: HydrographMesh, hydrograph_ids: Sequence[str], n_time_steps: int = 2): + self.mesh = mesh + self.hydrograph_ids = list(hydrograph_ids) + self.n_time_steps = int(n_time_steps) + self.sample_index: List[Tuple[str, int]] = [] + for hid in self.hydrograph_ids: + length = mesh.hydrographs[hid]["water_depth"].shape[0] + self.sample_index.extend((hid, t) for t in range(length - self.n_time_steps)) + + def __len__(self) -> int: + return len(self.sample_index) + + def __getitem__(self, idx: int): + hid, t_idx = self.sample_index[idx] + dyn = self.mesh.hydrographs[hid] + n = self.n_time_steps + features = self.mesh.node_features(hid, t_idx, t_idx + n, t_idx) + target_time = t_idx + n + target = np.stack( + [ + dyn["water_depth"][target_time, :] - dyn["water_depth"][target_time - 1, :], + dyn["volume"][target_time, :] - dyn["volume"][target_time - 1, :], + ], + axis=1, + ) + inputs = { + "node_features": torch.tensor(features, dtype=torch.float), + "edge_features": self.mesh.edge_features_tensor, + "edge_index": self.mesh.edge_index_tensor, + "physics": self.mesh.physics_data(hid, t_idx, n), + } + return inputs, torch.tensor(target, dtype=torch.float) + + +class HydrographRollouts(TorchDataset): + """Test hydrographs for autoregressive rollouts. + + Item ``i``: ``({"node_features" (N, 16) of the first window, "edge_features", "edge_index", "inflow", + "precipitation" (rollout_length,)}, {"water_depth", "volume"} (rollout_length, N))``, all normalised; + the forcings and targets cover the steps ``n_time_steps ... n_time_steps + rollout_length - 1``. + """ + + def __init__(self, mesh: HydrographMesh, hydrograph_ids: Sequence[str], n_time_steps: int = 2, rollout_length: int = 30): + self.mesh = mesh + self.hydrograph_ids = list(hydrograph_ids) + self.n_time_steps = int(n_time_steps) + self.rollout_length = int(rollout_length) + for hid in self.hydrograph_ids: + length = mesh.hydrographs[hid]["water_depth"].shape[0] + if length < self.n_time_steps + self.rollout_length: + raise ValueError( + f"Hydrograph {hid} does not have enough time steps for the specified rollout_length " + f"({length} < {self.n_time_steps} + {self.rollout_length})." + ) + + @property + def depth_stats(self) -> Dict[str, float]: + return dict(self.mesh.dynamic_stats["water_depth"]) + + @property + def volume_stats(self) -> Dict[str, float]: + return dict(self.mesh.dynamic_stats["volume"]) + + def __len__(self) -> int: + return len(self.hydrograph_ids) + + def __getitem__(self, idx: int): + hid = self.hydrograph_ids[idx] + dyn = self.mesh.hydrographs[hid] + n, length = self.n_time_steps, self.rollout_length + features = self.mesh.node_features(hid, 0, n, 0) + window = slice(n, n + length) + inputs = { + "node_features": torch.tensor(features, dtype=torch.float), + "edge_features": self.mesh.edge_features_tensor, + "edge_index": self.mesh.edge_index_tensor, + "inflow": torch.tensor(dyn["inflow_hydrograph"][window], dtype=torch.float), + "precipitation": torch.tensor(dyn["precipitation"][window], dtype=torch.float), + } + targets = { + "water_depth": torch.tensor(dyn["water_depth"][window], dtype=torch.float), + "volume": torch.tensor(dyn["volume"][window], dtype=torch.float), + } + return inputs, targets + + +def hydrograph_collate(batch: Sequence[Tuple[Mapping[str, Any], torch.Tensor]]): + """Concatenate mesh samples into one graph (like PyTorch Geometric ``Batch.from_data_list``). + + Returns ``({"node_features", "edge_features", "edge_index" (offset per sample), "batch" (graph index + per node), "physics" (float32 tensors, one value per sample)}, targets (sum of N, 2))``. + """ + inputs, targets = zip(*batch) + offsets, offset = [], 0 + for item in inputs: + offsets.append(offset) + offset += item["node_features"].shape[0] + collated: Dict[str, Any] = { + "node_features": torch.cat([item["node_features"] for item in inputs], dim=0), + "edge_features": torch.cat([item["edge_features"] for item in inputs], dim=0), + "edge_index": torch.cat([item["edge_index"] + shift for item, shift in zip(inputs, offsets)], dim=1), + "batch": torch.cat( + [torch.full((item["node_features"].shape[0],), i, dtype=torch.long) for i, item in enumerate(inputs)] + ), + } + if all("physics" in item for item in inputs): + collated["physics"] = { + key: torch.tensor([item["physics"][key] for item in inputs], dtype=torch.float) for key in inputs[0]["physics"] + } + return collated, torch.cat(list(targets), dim=0) + + +def build_hydrograph_bundle( + static_raw: Mapping[str, np.ndarray], + hydrographs: Mapping[str, Mapping[str, np.ndarray]], + train_ids: Sequence[str], + test_ids: Sequence[str], + *, + n_time_steps: int = 2, + k: int = 4, + rollout_length: int = 30, + static_stats: Optional[Mapping[str, Any]] = None, + dyn_stats: Optional[Mapping[str, Mapping[str, float]]] = None, + val_ids: Sequence[str] = (), + dataset_name: str, + metadata: Optional[Mapping[str, Any]] = None, +) -> DataBundle: + """Normalise raw mesh data and build the train (windows), optional val and test (rollouts) splits.""" + train_ids, val_ids, test_ids = list(train_ids), list(val_ids), list(test_ids) + if not train_ids: + raise ValueError("At least one training hydrograph is needed (normalisation statistics come from them).") + unknown = [hid for hid in train_ids + val_ids + test_ids if hid not in hydrographs] + if unknown: + raise ValueError(f"Hydrographs {unknown} were not loaded.") + static, static_stats = standardize_static(static_raw, static_stats) + if dyn_stats is None: + dyn_stats = dynamic_stats(hydrographs[hid] for hid in train_ids) + mesh = HydrographMesh(static, np.asarray(static_raw["area"]), hydrographs, static_stats, dyn_stats, k=k) + splits = {"train": DataSplit(inputs=HydrographWindows(mesh, train_ids, n_time_steps), targets=None)} + if val_ids: + splits["val"] = DataSplit(inputs=HydrographRollouts(mesh, val_ids, n_time_steps, rollout_length), targets=None) + splits["test"] = DataSplit(inputs=HydrographRollouts(mesh, test_ids, n_time_steps, rollout_length), targets=None) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=12 + 2 * int(n_time_steps), + description=( + "Mesh node features: x, y, area, elevation, slope, aspect, curvature, Manning's n, flow " + "accumulation, infiltration, inflow, precipitation, then the water depth and volume windows; " + "edge features: standardised dx, dy, distance of the k-nearest-neighbour graph." + ), + extra={"edge_dim": 3, "num_nodes": mesh.num_nodes, "num_edges": int(mesh.edge_index.shape[1]), "n_time_steps": int(n_time_steps)}, + ), + label_spec=LabelSpec( + num_targets=2, + task_type="regression", + description="Normalised change of water depth and volume per mesh node over one 20-minute step.", + extra={"rollout_length": int(rollout_length)}, + ), + metadata={ + "dataset": dataset_name, + "source_dataset": dataset_name, + "hazard_task": "flood.inundation", + "inundation_layout": "mesh_rollout", + "static_stats": mesh.static_stats, + "dynamic_stats": mesh.dynamic_stats, + "n_time_steps": int(n_time_steps), + "rollout_length": int(rollout_length), + "train_ids": train_ids, + "val_ids": val_ids, + "test_ids": test_ids, + **dict(metadata or {}), + }, + ) + + +class HydroGraphNetWhiteRiverDataset(Dataset): + """Reader for a local copy of the HydroGraphNet White River dataset (Zenodo 14969507). + + ``data_dir`` holds the unzipped ``HydroGraphNet.zip`` (4,787-cell HEC-RAS mesh of the White River near + Muncie, Indiana, 500 hydrographs). ``train_ids`` defaults to the release's ``train.txt``; the release + has no test list (the example's ``Test/test.txt`` is not published and ``train.txt`` lists all 500 + hydrographs), so ``test_ids`` (a list or a file) must be given; by default it is every hydrograph not in + ``train_ids``. Ids in ``test_ids`` are removed from the training list. Normalisation statistics are + computed from the training hydrographs as the example's training run does (``norm_stats="compute"``); + ``norm_stats="files"`` uses the released ``static_norm_stats.json`` / ``dynamic_norm_stats.json`` + instead, as the example's inference script does. PyHazards downloads nothing. + """ + + name = "hydrographnet_white_river" + + def __init__( + self, + data_dir: Optional[str] = None, + cache_dir: Optional[str] = None, + prefix: str = HYDROGRAPH_PREFIX, + train_ids: Union[str, Sequence[str], None] = "train.txt", + test_ids: Union[str, Sequence[str], None] = None, + val_ids: Union[str, Sequence[str], None] = None, + n_time_steps: int = 2, + k: int = 4, + rollout_length: int = 30, + norm_stats: str = "compute", + skip: int = 72, + interval: int = 1, + ): + super().__init__(cache_dir=cache_dir) + if data_dir is None: + raise ValueError( + "hydrographnet_white_river needs data_dir: the unzipped HydroGraphNet.zip from " + "https://zenodo.org/records/14969507 (8.3 GB, CC BY 4.0)." + ) + if norm_stats not in {"compute", "files"}: + raise ValueError("norm_stats must be 'compute' or 'files'.") + self.data_dir = Path(data_dir).expanduser() + self.prefix = prefix + self.train_ids, self.test_ids, self.val_ids = train_ids, test_ids, val_ids + self.n_time_steps = int(n_time_steps) + self.k = int(k) + self.rollout_length = int(rollout_length) + self.norm_stats = norm_stats + self.skip = int(skip) + self.interval = int(interval) + + def _ids(self) -> Tuple[List[str], List[str], List[str]]: + available = list_hydrograph_ids(self.data_dir, self.prefix) + train = read_hydrograph_ids(self.train_ids, self.data_dir) if self.train_ids is not None else list(available) + val = read_hydrograph_ids(self.val_ids, self.data_dir) if self.val_ids is not None else [] + if self.test_ids is not None: + test = read_hydrograph_ids(self.test_ids, self.data_dir) + else: + test = [hid for hid in available if hid not in set(train) | set(val)] + if not test: + raise ValueError( + "No test hydrographs: the HydroGraphNet release lists all 500 hydrographs in train.txt and ships " + "no test list, so pass test_ids (a list or a file of ids)." + ) + held_out = set(test) | set(val) + return [hid for hid in train if hid not in held_out], val, test + + def _load(self) -> DataBundle: + static_raw = read_static(self.data_dir, self.prefix) + num_points = static_raw["xy_coords"].shape[0] + train_ids, val_ids, test_ids = self._ids() + hydrographs = { + hid: read_hydrograph(self.data_dir, hid, num_points, self.prefix, interval=self.interval, skip=self.skip) + for hid in dict.fromkeys(train_ids + val_ids + test_ids) + } + static_stats = dyn_stats = None + if self.norm_stats == "files": + static_stats = json.loads((self.data_dir / STATIC_NORM_STATS_FILE).read_text(encoding="utf-8")) + dyn_stats = json.loads((self.data_dir / DYNAMIC_NORM_STATS_FILE).read_text(encoding="utf-8")) + return build_hydrograph_bundle( + static_raw, + hydrographs, + train_ids, + test_ids, + val_ids=val_ids, + n_time_steps=self.n_time_steps, + k=self.k, + rollout_length=self.rollout_length, + static_stats=static_stats, + dyn_stats=dyn_stats, + dataset_name=self.name, + metadata={"data_dir": str(self.data_dir), "prefix": self.prefix, "norm_stats": self.norm_stats}, + ) + + +def synthetic_hydrograph_mesh( + nodes: int = 64, + hydrographs: int = 5, + steps: int = 48, + seed: int = 0, +) -> Tuple[Dict[str, np.ndarray], Dict[str, Dict[str, np.ndarray]]]: + """Random static fields on scattered points and toy hydrographs, in the layout :func:`read_static` / + :func:`read_hydrograph` return. The numbers mean nothing hydrologically.""" + rng = np.random.default_rng(seed) + xy = np.column_stack([406000 + rng.uniform(0, 2000, nodes), 1802000 + rng.uniform(0, 1000, nodes)]) + elevation = 285 + 0.002 * (xy[:, 0] - xy[:, 0].min()) + rng.normal(0, 0.5, nodes) + static = { + "xy_coords": xy, + "area": rng.uniform(5000, 8000, (nodes, 1)), + "elevation": elevation.reshape(-1, 1), + "slope": rng.gamma(1.0, 2.0, (nodes, 1)), + "aspect": rng.uniform(0, 360, (nodes, 1)), + "curvature": rng.normal(0, 1.5, (nodes, 1)), + "manning": rng.choice([0.035, 0.06, 0.1, 0.15], (nodes, 1)), + "flow_accum": rng.integers(0, 200, (nodes, 1)).astype(float), + "infiltration": rng.uniform(1, 100, (nodes, 1)), + } + series: Dict[str, Dict[str, np.ndarray]] = {} + low = elevation - elevation.min() + for h in range(hydrographs): + peak = rng.integers(steps // 3, steps - 26) if steps > 30 else steps // 2 + rise = np.clip(np.arange(steps) / max(peak, 1), 0, None) + inflow = 20 + rng.uniform(150, 400) * np.where(np.arange(steps) <= peak, rise, np.exp(-(np.arange(steps) - peak) / 15)) + precipitation = np.clip(rng.normal(1.5e-6, 1e-6, steps), 0, None) + stage = (inflow - inflow.min()) / (np.ptp(inflow) + 1e-9) * 2.5 + depth = np.clip(stage[:, None] - low[None, :] + rng.normal(0, 0.05, (steps, nodes)), 0, None) + series[f"H{h + 1}"] = { + "water_depth": depth, + "volume": depth * static["area"].reshape(1, -1), + "precipitation": precipitation, + "inflow_hydrograph": inflow, + } + return static, series + + +def write_hydrograph_files( + directory: Union[str, Path], + static_raw: Mapping[str, np.ndarray], + hydrographs: Mapping[str, Mapping[str, np.ndarray]], + prefix: str = HYDROGRAPH_PREFIX, + skip: int = 72, + extra_cells: int = 0, + train_ids: Optional[Sequence[str]] = None, +) -> Path: + """Write mesh data in the HydroGraphNet release layout (e.g. synthetic data for the official code). + + ``skip`` copies of the first step are prepended to every series (the reader drops them again), + precipitation is written in the release's units (divided by 2.7778e-7), the inflow file gets a + leading time column, and ``extra_cells`` padding rows / columns imitate the release's files, which + hold more cells than ``M80_XY.txt``. ``train_ids`` are written to ``train.txt``. + """ + root = Path(directory) + root.mkdir(parents=True, exist_ok=True) + fmt = "%.9f" + xy = np.asarray(static_raw["xy_coords"], dtype=np.float64) + np.savetxt(root / f"{prefix}_XY.txt", xy, delimiter="\t", fmt=fmt) + for key, code in list(STATIC_FILES.items())[1:]: + column = np.asarray(static_raw[key], dtype=np.float64).reshape(-1) + column = np.concatenate([column, np.full(extra_cells, column[-1])]) + np.savetxt(root / f"{prefix}_{code}.txt", column, fmt=fmt) + + def _pad(series: np.ndarray) -> np.ndarray: + return np.concatenate([np.repeat(series[:1], skip, axis=0), series], axis=0) + + for hid, series in hydrographs.items(): + depth = np.asarray(series["water_depth"], dtype=np.float64) + volume = np.asarray(series["volume"], dtype=np.float64) + if extra_cells: + depth = np.hstack([depth, np.zeros((depth.shape[0], extra_cells))]) + volume = np.hstack([volume, np.zeros((volume.shape[0], extra_cells))]) + inflow = _pad(np.asarray(series["inflow_hydrograph"], dtype=np.float64)) + np.savetxt(root / f"{prefix}_WD_{hid}.txt", _pad(depth), delimiter="\t", fmt=fmt) + np.savetxt(root / f"{prefix}_V_{hid}.txt", _pad(volume), delimiter="\t", fmt=fmt) + np.savetxt( + root / f"{prefix}_US_InF_{hid}.txt", + np.column_stack([np.arange(inflow.shape[0]) * 1200.0, inflow]), + delimiter="\t", + fmt=fmt, + ) + np.savetxt( + root / f"{prefix}_Pr_{hid}.txt", _pad(np.asarray(series["precipitation"], dtype=np.float64) / 2.7778e-7), fmt=fmt + ) + if train_ids is not None: + (root / "train.txt").write_text("".join(f"{hid}\n" for hid in train_ids), encoding="utf-8") + return root + + +class SyntheticFloodMeshDataset(Dataset): + """Synthetic mesh hydrographs in the HydroGraphNet layout (random fields; for smoke tests only). + + Same pipeline as ``hydrographnet_white_river`` (normalisation, k-nearest-neighbour graph, 16 node + features, windows with physics data, rollout test split) on random points with toy hydrographs. + """ + + name = "flood_mesh_synthetic" + + def __init__( + self, + cache_dir: Optional[str] = None, + nodes: int = 64, + train_hydrographs: int = 4, + test_hydrographs: int = 2, + steps: int = 48, + n_time_steps: int = 2, + k: int = 4, + rollout_length: int = 30, + seed: int = 0, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + self.nodes = 24 if micro else int(nodes) + self.train_hydrographs = 2 if micro else int(train_hydrographs) + self.test_hydrographs = 1 if micro else int(test_hydrographs) + self.steps = 16 if micro else int(steps) + self.rollout_length = 6 if micro else int(rollout_length) + self.n_time_steps = int(n_time_steps) + self.k = int(k) + self.seed = int(seed) + if self.nodes <= self.k: + raise ValueError(f"nodes ({self.nodes}) must exceed k ({self.k}).") + if self.steps < self.n_time_steps + self.rollout_length: + raise ValueError(f"steps ({self.steps}) must be at least n_time_steps + rollout_length.") + + def _load(self) -> DataBundle: + total = self.train_hydrographs + self.test_hydrographs + static, series = synthetic_hydrograph_mesh(self.nodes, total, self.steps, self.seed) + ids = list(series) + return build_hydrograph_bundle( + static, + series, + ids[: self.train_hydrographs], + ids[self.train_hydrographs :], + n_time_steps=self.n_time_steps, + k=self.k, + rollout_length=self.rollout_length, + dataset_name=self.name, + metadata={"synthetic": True}, + ) + + +__all__ = [ + "DYNAMIC_KEYS", + "HydroGraphNetWhiteRiverDataset", + "HydrographMesh", + "HydrographRollouts", + "HydrographWindows", + "STATIC_FILES", + "SyntheticFloodMeshDataset", + "build_hydrograph_bundle", + "dynamic_stats", + "hydrograph_collate", + "knn_edge_index", + "list_hydrograph_ids", + "mesh_edge_features", + "mesh_node_features", + "read_hydrograph", + "read_hydrograph_ids", + "read_static", + "standardize_static", + "synthetic_hydrograph_mesh", + "write_hydrograph_files", +] diff --git a/pyhazards/datasets/flood/streamflow.py b/pyhazards/datasets/flood/streamflow.py new file mode 100644 index 00000000..07bc177f --- /dev/null +++ b/pyhazards/datasets/flood/streamflow.py @@ -0,0 +1,367 @@ +"""Daily streamflow samples in the NeuralHydrology layout. + +A streamflow sample is one basin and one target day: the ``seq_length`` days of dynamic forcings that +end on that day, ``x_d`` of shape ``(seq_length, n_dynamic)``, the basin's static attributes, ``x_s`` of +shape ``(n_static,)``, and the discharge series ``y`` of shape ``(seq_length, n_targets)`` over the same +days. Models predict every step; training uses the last ``predict_last_n`` steps and evaluation the last +one. This is the setup of Kratzert et al. (HESS 2019) and of NeuralHydrology. + +:func:`build_streamflow_bundle` turns per-basin daily DataFrames and an attribute table into a +:class:`~pyhazards.datasets.base.DataBundle` the way NeuralHydrology's ``BaseDataset`` does (from +``neuralhydrology/datasetzoo/basedataset.py`` at commit ea94a40, BSD-3-Clause, Copyright (c) 2021, +NeuralHydrology; reimplemented for one input frequency without NeuralHydrology's config object): + +- each period is read with a warm-up of ``seq_length - predict_last_n`` days before its start date, + reindexed to a gap-free daily range, and targets inside the warm-up are set to NaN; +- dynamic inputs and targets are standardised with the mean and population standard deviation over all + training basins and days (warm-up included, NaN skipped); static attributes with the mean and sample + standard deviation over the training basins, after sorting them alphabetically by name, which is the + order NeuralHydrology feeds them to its models; +- training samples are dropped when any dynamic input in the window is NaN or when all targets of the + last ``predict_last_n`` steps are NaN; validation and test keep every sample with a full window, so + that predictions exist for every day of the period (NaN inputs give NaN predictions, which the + metrics skip). + +Splits hold a :class:`StreamflowWindows` dataset; the bundle metadata carry the scaler (needed to put +predictions back into discharge units) and the feature names. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import pandas as pd +import torch +from torch.utils.data import Dataset as TorchDataset + +from ..base import DataBundle, DataSplit, FeatureSpec, LabelSpec + +PERIOD_NAMES = ("train", "val", "test") +Period = Tuple[str, str] + + +def _timestamp(value: Any) -> pd.Timestamp: + return pd.Timestamp(value).normalize() + + +def _validate_periods(periods: Mapping[str, Sequence[Any]]) -> Dict[str, Tuple[pd.Timestamp, pd.Timestamp]]: + if "train" not in periods: + raise ValueError("periods needs a 'train' entry (start, end); its data define the scaler.") + parsed: Dict[str, Tuple[pd.Timestamp, pd.Timestamp]] = {} + for name, value in periods.items(): + if name not in PERIOD_NAMES: + raise ValueError(f"Unknown period {name!r}; expected a subset of {PERIOD_NAMES}.") + if len(value) != 2: + raise ValueError(f"Period {name!r} must be (start, end), got {value!r}.") + start, end = _timestamp(value[0]), _timestamp(value[1]) + if end < start: + raise ValueError(f"Period {name!r} ends ({end.date()}) before it starts ({start.date()}).") + parsed[name] = (start, end) + return parsed + + +def period_frame( + df: pd.DataFrame, + columns: Sequence[str], + target_variables: Sequence[str], + start: pd.Timestamp, + end: pd.Timestamp, + seq_length: int, + predict_last_n: int, + add_missing_targets: bool = False, +) -> pd.DataFrame: + """One basin's period with warm-up, on a gap-free daily index, targets NaN before ``start``.""" + if not isinstance(df.index, pd.DatetimeIndex): + raise ValueError("Basin data must be indexed by a pandas DatetimeIndex of days.") + df = df.copy() + if add_missing_targets: + for target in target_variables: + if target not in df.columns: + df[target] = np.nan + missing = [column for column in columns if column not in df.columns] + if missing: + raise ValueError( + f"The following features are not available in the data: {missing}. " + f"These are the available features: {df.columns.tolist()}" + ) + df = df[list(columns)].sort_index() + warmup_start = start - pd.Timedelta(days=seq_length - predict_last_n) + full_range = pd.date_range(start=warmup_start, end=end, freq="1D") + df = df.loc[warmup_start: end + pd.Timedelta(days=1, seconds=-1)] + df = df[~df.index.duplicated(keep="first")] + df = df.reindex(pd.DatetimeIndex(full_range, name="date")) + df.loc[df.index < start, list(target_variables)] = np.nan + return df.astype(np.float32) + + +@dataclass +class StreamflowScaler: + """Centre and scale of every input; applied as ``(value - center) / scale``.""" + + dynamic_center: np.ndarray + dynamic_scale: np.ndarray + target_center: np.ndarray + target_scale: np.ndarray + static_mean: np.ndarray = field(default_factory=lambda: np.zeros(0)) + static_std: np.ndarray = field(default_factory=lambda: np.zeros(0)) + + def to_dict(self) -> Dict[str, List[float]]: + return {key: [float(v) for v in np.asarray(value)] for key, value in self.__dict__.items()} + + def rescale_target(self, values: np.ndarray) -> np.ndarray: + """Normalised targets or predictions ``(..., n_targets)`` back to physical units.""" + return values * self.target_scale + self.target_center + + +class StreamflowWindows(TorchDataset): + """Lazy sliding windows over per-basin arrays. + + Item ``i`` is ``({"x_d": (seq_length, n_dynamic), "x_s": (n_static,)}, y)`` with ``y`` of shape + ``(seq_length, n_targets)``; ``x_s`` is left out when there are no static attributes. + ``sample_basin[i]`` indexes ``basins`` and ``sample_date[i]`` is the date of the window's last day. + """ + + def __init__( + self, + basins: Sequence[str], + x_d: Sequence[np.ndarray], + y: Sequence[np.ndarray], + dates: Sequence[np.ndarray], + x_s: Optional[np.ndarray], + seq_length: int, + predict_last_n: int, + drop_invalid: bool, + ): + if not (len(basins) == len(x_d) == len(y) == len(dates)): + raise ValueError("basins, x_d, y and dates must have one entry per basin.") + if x_s is not None and x_s.shape[0] != len(basins): + raise ValueError(f"x_s must have shape (n_basins, n_static); got {x_s.shape} for {len(basins)} basins.") + self.basins = list(basins) + self._x_d = [torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) for a in x_d] + self._y = [torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) for a in y] + self._dates = [np.asarray(d, dtype="datetime64[ns]") for d in dates] + self._x_s = None if x_s is None else torch.from_numpy(np.ascontiguousarray(x_s, dtype=np.float32)) + self.seq_length = int(seq_length) + self.predict_last_n = int(predict_last_n) + basin_index: List[np.ndarray] = [] + end_index: List[np.ndarray] = [] + for i, (xd, yy) in enumerate(zip(x_d, y)): + ends = np.arange(self.seq_length - 1, len(xd)) + if drop_invalid and ends.size: + ends = ends[self._valid(np.asarray(xd), np.asarray(yy), ends)] + basin_index.append(np.full(ends.shape, i, dtype=np.int64)) + end_index.append(ends.astype(np.int64)) + self.sample_basin = np.concatenate(basin_index) if basin_index else np.zeros(0, dtype=np.int64) + self._end = np.concatenate(end_index) if end_index else np.zeros(0, dtype=np.int64) + self.sample_date = ( + np.array([self._dates[b][e] for b, e in zip(self.sample_basin, self._end)], dtype="datetime64[ns]") + if len(self._end) + else np.zeros(0, dtype="datetime64[ns]") + ) + + def _valid(self, x_d: np.ndarray, y: np.ndarray, ends: np.ndarray) -> np.ndarray: + # NeuralHydrology's _validate_samples: any NaN input in the window or an all-NaN target + # over the last predict_last_n steps invalidates a training sample. + nan_inputs = np.isnan(x_d).any(axis=1).astype(np.int64) + cumulative = np.concatenate([[0], np.cumsum(nan_inputs)]) + window_nan = cumulative[ends + 1] - cumulative[ends + 1 - self.seq_length] > 0 + valid_target = ~np.isnan(y).all(axis=1) + cumulative_t = np.concatenate([[0], np.cumsum(valid_target.astype(np.int64))]) + any_target = cumulative_t[ends + 1] - cumulative_t[ends + 1 - self.predict_last_n] > 0 + if self.predict_last_n == 0: + any_target = np.ones_like(any_target, dtype=bool) + return ~window_nan & any_target + + def __len__(self) -> int: + return int(self._end.size) + + def __getitem__(self, item: int): + basin = int(self.sample_basin[item]) + end = int(self._end[item]) + 1 + start = end - self.seq_length + inputs = {"x_d": self._x_d[basin][start:end]} + if self._x_s is not None: + inputs["x_s"] = self._x_s[basin] + return inputs, self._y[basin][start:end] + + def __repr__(self) -> str: + return ( + f"StreamflowWindows(basins={len(self.basins)}, samples={len(self)}, " + f"seq_length={self.seq_length}, predict_last_n={self.predict_last_n})" + ) + + +def build_streamflow_bundle( + basin_frames: Mapping[str, pd.DataFrame], + attributes: Optional[pd.DataFrame], + dynamic_inputs: Sequence[str], + static_attributes: Sequence[str], + target_variables: Sequence[str], + periods: Mapping[str, Sequence[Any]], + seq_length: int, + predict_last_n: int = 1, + dataset_name: str = "streamflow", + metadata: Optional[Mapping[str, Any]] = None, +) -> DataBundle: + """Normalise, window and split per-basin daily data (see the module docstring). + + ``basin_frames`` maps basin ids to DataFrames indexed by date with the dynamic inputs and targets as + columns; ``attributes`` is indexed by basin id. ``periods`` maps ``train`` (required), ``val`` and + ``test`` to ``(start, end)`` dates, both inclusive. + """ + if seq_length < 1: + raise ValueError(f"seq_length must be positive, got {seq_length}.") + if not 0 <= predict_last_n <= seq_length: + raise ValueError(f"predict_last_n must be in [0, seq_length], got {predict_last_n}.") + if not dynamic_inputs: + raise ValueError("At least one dynamic input is required.") + if not target_variables: + raise ValueError("At least one target variable is required.") + if not basin_frames: + raise ValueError("No basins to load.") + parsed = _validate_periods(periods) + dynamic_inputs = list(dynamic_inputs) + target_variables = list(target_variables) + columns = dynamic_inputs + [t for t in target_variables if t not in dynamic_inputs] + basins = list(basin_frames) + + frames: Dict[str, List[pd.DataFrame]] = {} + for name, (start, end) in parsed.items(): + frames[name] = [ + period_frame( + basin_frames[basin], + columns, + target_variables, + start, + end, + seq_length, + predict_last_n, + add_missing_targets=name != "train", + ) + for basin in basins + ] + + train_values = np.concatenate([frame.to_numpy(dtype=np.float64) for frame in frames["train"]], axis=0) + with np.errstate(invalid="ignore"): + center = np.nanmean(train_values, axis=0) + scale = np.nanstd(train_values, axis=0) + dyn_idx = [columns.index(c) for c in dynamic_inputs] + tgt_idx = [columns.index(c) for c in target_variables] + for label, values in (("center", center), ("scale", scale)): + bad = [columns[i] for i in range(len(columns)) if not np.isfinite(values[i])] + if bad: + raise ValueError(f"Training data give no finite {label} for {bad}; check the training period.") + + static_names = sorted(static_attributes) + x_s = None + static_mean = static_std = np.zeros(0) + if static_names: + if attributes is None: + raise ValueError("static_attributes were requested but no attribute table was given.") + missing = [a for a in static_names if a not in attributes.columns] + if missing: + raise ValueError(f"Static attributes {missing} are missing.") + missing_basins = [b for b in basins if b not in attributes.index] + if missing_basins: + raise ValueError(f"Some basins are missing static attributes: {missing_basins}") + table = attributes.loc[basins, static_names].astype(np.float64) + static_mean = table.mean().to_numpy() + static_std = table.std().to_numpy() + bad = [name for name, std in zip(static_names, static_std) if not np.isfinite(std) or std == 0] + if bad: + raise ValueError( + f"Static attributes {bad} have a zero or undefined standard deviation over the training basins." + ) + x_s = ((table - static_mean) / static_std).to_numpy(dtype=np.float32) + + scaler = StreamflowScaler( + dynamic_center=center[dyn_idx].astype(np.float32), + dynamic_scale=scale[dyn_idx].astype(np.float32), + target_center=center[tgt_idx].astype(np.float32), + target_scale=scale[tgt_idx].astype(np.float32), + static_mean=static_mean.astype(np.float32), + static_std=static_std.astype(np.float32), + ) + + splits: Dict[str, DataSplit] = {} + for name in parsed: + x_d, y, dates = [], [], [] + for frame in frames[name]: + values = frame.to_numpy(dtype=np.float32) + x_d.append((values[:, dyn_idx] - scaler.dynamic_center) / scaler.dynamic_scale) + y.append((values[:, tgt_idx] - scaler.target_center) / scaler.target_scale) + dates.append(frame.index.to_numpy()) + windows = StreamflowWindows( + basins, x_d, y, dates, x_s, seq_length, predict_last_n, drop_invalid=name == "train" + ) + splits[name] = DataSplit( + inputs=windows, + targets=None, + metadata={"period": [str(parsed[name][0].date()), str(parsed[name][1].date())]}, + ) + + info: Dict[str, Any] = { + "dataset": dataset_name, + "source_dataset": dataset_name, + "hazard_task": "flood.streamflow", + "basins": basins, + "dynamic_inputs": dynamic_inputs, + "static_attributes": static_names, + "target_variables": target_variables, + "seq_length": int(seq_length), + "predict_last_n": int(predict_last_n), + "periods": {name: [str(s.date()), str(e.date())] for name, (s, e) in parsed.items()}, + "scaler": scaler.to_dict(), + } + info.update(dict(metadata or {})) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=len(dynamic_inputs), + description="Daily dynamic forcings x_d (seq_length, n_dynamic) and static attributes x_s (n_static,).", + extra={"n_dynamic": len(dynamic_inputs), "n_static": len(static_names), "seq_length": int(seq_length)}, + ), + label_spec=LabelSpec( + num_targets=len(target_variables), + task_type="regression", + description="Daily discharge over the input window (normalised; see metadata['scaler']).", + ), + metadata=info, + ) + + +def scaler_from_metadata(metadata: Mapping[str, Any]) -> StreamflowScaler: + raw = metadata.get("scaler") + if raw is None: + raise ValueError("Streamflow bundles carry their scaler in metadata['scaler'].") + return StreamflowScaler(**{key: np.asarray(value, dtype=np.float32) for key, value in raw.items()}) + + +def read_basin_list(basins: Any) -> List[str]: + """Basin ids from a list or from a text file with one id per line (NeuralHydrology basin files).""" + if basins is None: + raise ValueError("basins is required: a list of basin ids or a path to a basin file.") + if isinstance(basins, (str, bytes)) or hasattr(basins, "__fspath__"): + from pathlib import Path + + path = Path(basins) + if not path.is_file(): + raise FileNotFoundError(f"Basin file not found: {path}") + return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + ids = [str(basin) for basin in basins] + if not ids: + raise ValueError("basins is empty.") + return ids + + +__all__ = [ + "PERIOD_NAMES", + "StreamflowScaler", + "StreamflowWindows", + "build_streamflow_bundle", + "period_frame", + "read_basin_list", + "scaler_from_metadata", +] diff --git a/pyhazards/datasets/flood/urbanfloodcast.py b/pyhazards/datasets/flood/urbanfloodcast.py new file mode 100644 index 00000000..4b0cee70 --- /dev/null +++ b/pyhazards/datasets/flood/urbanfloodcast.py @@ -0,0 +1,180 @@ +"""UrbanFloodCast inputs: one-shot event samples for the deep neural operator, and a synthetic stand-in. + +The UrbanFloodCast benchmark (Xu et al., J. Hydrology 2025; Zenodo 10.5281/zenodo.15700880, 7.3 GB, +CC BY 4.0) stores hydrodynamic simulations of design storms over two areas of Berlin as GeoTIFF rasters +(water depth ``H`` and unit discharges ``U`` / ``V`` every 300 s, rainfall tables, terrain). The official +code first stacks one event into a tensor ``(Sy, Sx, 25, 5)`` with the channels depth, x discharge, +y discharge, rainfall and terrain elevation (``TIFF2PT``), then builds the one-shot sample +(``flood_data`` in ``DNO/utils25.py``). :func:`prepare_urbanfloodcast_event` does the second step the +same way (written from the reference behaviour, which the oracle test compares): + +- input: depth / discharges at the first ``T_in`` steps, discharges set to 0 where the depth is 0, NaN + set to 0, repeated over the ``T_out`` output steps; rainfall of each output step as + ``log(1 + p / 0.01) / 10``; terrain of each output step with NaN replaced by ``max + 30`` and + L2-normalised along the x axis (``torch.nn.functional.normalize`` over dimension 1); +- target: depth / discharges of the ``T_out`` output steps, discharges 0 where the depth is 0, NaN set + to 0, and a mask that is False where the simulation is NaN (buildings, outside the domain). + +PyHazards does not read the Berlin GeoTIFFs yet (the official TIFF-to-tensor script is incomplete as +released); ``urbanfloodcast_synthetic`` generates random events in this layout for smoke tests. +""" + +from __future__ import annotations + +from typing import Optional, Tuple + +import torch +import torch.nn.functional as F + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +URBANFLOODCAST_EVENT_CHANNELS = ("water_depth", "discharge_x", "discharge_y", "rainfall", "elevation") +URBANFLOODCAST_INPUT_CHANNELS = ("water_depth", "discharge_x", "discharge_y", "rainfall_log", "elevation_normalized") +URBANFLOODCAST_TARGETS = ("water_depth", "discharge_x", "discharge_y") + + +def _log_transform(data: torch.Tensor, eps: float = 1e-2) -> torch.Tensor: + return torch.log(1 + data / eps) + + +def prepare_urbanfloodcast_event( + event: torch.Tensor, T_in: int = 1, T_out: int = 24 # noqa: N803 (reference names) +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """One-shot sample of an event tensor ``(Sy, Sx, >= T_in + T_out, 5)``. + + Returns ``x`` ``(Sy, Sx, T_out, T_in, 5)``, ``y`` ``(Sy, Sx, T_out, 3)`` and ``mask`` (bool, like ``y``). + The event tensor is not modified. + """ + if event.ndim != 4 or event.shape[-1] != 5: + raise ValueError( + f"UrbanFloodCast events must have shape (Sy, Sx, time, 5) with channels {URBANFLOODCAST_EVENT_CHANNELS}; " + f"got {tuple(event.shape)}." + ) + if event.shape[2] < T_in + T_out: + raise ValueError(f"The event has {event.shape[2]} steps; T_in + T_out = {T_in + T_out} are needed.") + if T_in != 1: + raise ValueError("The one-shot UrbanFloodCast sample is defined for T_in=1 (the reference concatenation needs it).") + pde = event.clone() + x = pde[..., :T_in, :3] + mask = x[..., 0:1] == 0.0 + x[..., 1:2][mask] = 0.0 + x[..., 2:3][mask] = 0.0 + x[..., :3] = torch.nan_to_num(x[..., :3], nan=0.0) + x1 = x.unsqueeze(-3).repeat([1, 1, T_out, 1, 1]) + rain = pde[..., T_in : T_in + T_out, 3:4] + x2 = torch.unsqueeze(_log_transform(rain) / 10.0, dim=-1) + z = pde[..., T_in : T_in + T_out, 4:5] + z = torch.nan_to_num(z, nan=z.max() + 30.0) + x3 = torch.unsqueeze(F.normalize(z), dim=-1) + inputs = torch.cat((torch.cat((x1, x2), dim=-1), x3), dim=-1) + y = pde[..., T_in : T_in + T_out, :3] + mask_y = y[..., 0:1] == 0.0 + y[..., 1:2][mask_y] = 0.0 + y[..., 2:3][mask_y] = 0.0 + valid = ~torch.isnan(y) + return inputs, torch.nan_to_num(y, nan=0.0), valid + + +def synthetic_urbanfloodcast_event( + height: int = 32, width: int = 32, steps: int = 25, generator: Optional[torch.Generator] = None +) -> torch.Tensor: + """A random event tensor ``(height, width, steps, 5)``: rain on a tilted terrain with buildings (NaN).""" + rows = torch.linspace(0, 1, height).view(height, 1) + cols = torch.linspace(0, 1, width).view(1, width) + terrain = 34.0 + 2.0 * rows + 1.0 * cols + 0.2 * torch.rand(height, width, generator=generator) + rain_total = 10 + 40 * torch.rand(1, generator=generator).item() + profile = torch.exp(-((torch.arange(steps) - steps / 3) ** 2) / (2 * (steps / 6) ** 2)) + rain = rain_total * profile / profile.sum() + cumulative = torch.cumsum(rain, 0) / 1000.0 + low = (terrain.max() - terrain) / (terrain.max() - terrain.min()) + depth = cumulative.view(1, 1, steps) * (0.5 + 3 * low).unsqueeze(-1) + depth = depth * (torch.rand(height, width, 1, generator=generator) > 0.1) + qx = 0.1 * depth * torch.randn(height, width, 1, generator=generator) + qy = 0.1 * depth * torch.randn(height, width, 1, generator=generator) + event = torch.stack( + [depth, qx, qy, rain.view(1, 1, steps).expand(height, width, steps), terrain.unsqueeze(-1).expand(height, width, steps)], + dim=-1, + ) + buildings = torch.rand(height, width, generator=generator) < 0.05 + event[buildings, :, :3] = float("nan") + return event + + +class SyntheticUrbanFloodCastDataset(Dataset): + """Synthetic urban flood events in the UrbanFloodCast one-shot layout (random numbers; smoke tests only). + + Every split holds ``inputs`` ``(n, Sy, Sx, T_out, 1, 5)`` and ``targets`` ``(n, Sy, Sx, T_out, 3)`` + built by :func:`prepare_urbanfloodcast_event`; the NaN mask is ``split.metadata["mask"]``. + """ + + name = "urbanfloodcast_synthetic" + + def __init__( + self, + cache_dir: Optional[str] = None, + events: int = 8, + height: int = 32, + width: int = 32, + T_out: int = 24, # noqa: N803 + seed: int = 0, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + self.events = 4 if micro else int(events) + self.height = int(height) + self.width = int(width) + self.T_out = int(T_out) + self.seed = int(seed) + if self.events < 3: + raise ValueError("urbanfloodcast_synthetic needs at least 3 events (train / val / test).") + + def _load(self) -> DataBundle: + generator = torch.Generator().manual_seed(self.seed) + samples = [ + prepare_urbanfloodcast_event( + synthetic_urbanfloodcast_event(self.height, self.width, self.T_out + 1, generator), 1, self.T_out + ) + for _ in range(self.events) + ] + x = torch.stack([s[0] for s in samples]) + y = torch.stack([s[1] for s in samples]) + mask = torch.stack([s[2] for s in samples]) + n_test = max(1, self.events // 4) + n_val = max(1, self.events // 4) + n_train = self.events - n_val - n_test + bounds = {"train": (0, n_train), "val": (n_train, n_train + n_val), "test": (n_train + n_val, self.events)} + splits = { + name: DataSplit(x[a:b], y[a:b], metadata={"mask": mask[a:b]}) for name, (a, b) in bounds.items() + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=5, + description="Synthetic UrbanFloodCast inputs: " + ", ".join(URBANFLOODCAST_INPUT_CHANNELS) + " per cell and output step.", + extra={"height": self.height, "width": self.width, "T_out": self.T_out, "initial_step": 1}, + ), + label_spec=LabelSpec( + num_targets=3, + task_type="regression", + description="Synthetic water depth and x / y unit discharge at every output step.", + extra={"variables": list(URBANFLOODCAST_TARGETS)}, + ), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "flood.inundation", + "inundation_layout": "channels_last", + "depth_channel": 0, + "synthetic": True, + }, + ) + + +__all__ = [ + "SyntheticUrbanFloodCastDataset", + "URBANFLOODCAST_EVENT_CHANNELS", + "URBANFLOODCAST_INPUT_CHANNELS", + "URBANFLOODCAST_TARGETS", + "prepare_urbanfloodcast_event", + "synthetic_urbanfloodcast_event", +] diff --git a/pyhazards/datasets/tc/__init__.py b/pyhazards/datasets/tc/__init__.py index c52d815a..a0418a2c 100644 --- a/pyhazards/datasets/tc/__init__.py +++ b/pyhazards/datasets/tc/__init__.py @@ -1,100 +1,52 @@ -from __future__ import annotations - -import torch - -from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec - - -class SyntheticTropicalCycloneDataset(Dataset): - """Synthetic storm-history dataset for track/intensity smoke runs.""" - - name = "tc_tracks_synthetic" - - def __init__( - self, - cache_dir: str | None = None, - samples: int = 64, - history: int = 6, - horizon: int = 5, - features: int = 8, - micro: bool = False, - ): - super().__init__(cache_dir=cache_dir) - self.samples = 20 if micro else int(samples) - self.history = int(history) - self.horizon = int(horizon) - self.features = int(features) - - def _load(self) -> DataBundle: - x = torch.randn(self.samples, self.history, self.features, dtype=torch.float32) - last_state = x[:, -1, :3] - deltas = torch.linspace(0.2, 1.0, steps=self.horizon, dtype=torch.float32).view(1, self.horizon, 1) - direction = torch.tensor([0.4, 0.2, 1.5], dtype=torch.float32).view(1, 1, 3) - y = last_state.unsqueeze(1) + deltas * direction - - train_end = max(1, int(0.7 * self.samples)) - val_end = max(train_end + 1, int(0.85 * self.samples)) - splits = { - "train": DataSplit(x[:train_end], y[:train_end]), - "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), - "test": DataSplit(x[val_end:], y[val_end:]), - } - return DataBundle( - splits=splits, - feature_spec=FeatureSpec( - input_dim=self.features, - description="Synthetic storm history with environmental context features.", - extra={"history": self.history, "horizon": self.horizon}, - ), - label_spec=LabelSpec( - num_targets=3, - task_type="regression", - description="Forecast track latitude/longitude and intensity trajectory.", - ), - metadata={ - "dataset": self.name, - "source_dataset": self.name, - "hazard_task": "tc.track_intensity", - }, - ) - - -class IBTrACSTropicalCycloneDataset(SyntheticTropicalCycloneDataset): - """Synthetic-backed adapter for IBTrACS-style storm tracks.""" +"""Tropical cyclone datasets: real readers (IBTrACS, Xu et al. 2021 SHIPS predictors, TCND, Hurricast IBTrACS + ERA5) and synthetic smoke data.""" - name = "ibtracs_tracks" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "IBTrACS", "source_dataset": self.name}) - return bundle - - -class TCBenchAlphaDataset(SyntheticTropicalCycloneDataset): - """Synthetic-backed adapter for TCBench Alpha evaluation runs.""" - - name = "tcbench_alpha" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "TCBench Alpha", "source_dataset": self.name}) - return bundle - - -class TropiCycloneNetDataset(SyntheticTropicalCycloneDataset): - """Synthetic-backed adapter for TropiCycloneNet-Dataset style smoke runs.""" - - name = "tropicyclonenet_dataset" - - def _load(self) -> DataBundle: - bundle = super()._load() - bundle.metadata.update({"adapter": "TropiCycloneNet-Dataset", "source_dataset": self.name}) - return bundle +from __future__ import annotations +from .ibtracs import ( + IBTrACSTropicalCycloneDataset, + build_track_samples, + download_ibtracs, + ibtracs_url, + read_ibtracs, + read_ibtracs_csv, + read_ibtracs_netcdf, +) +from .hurricast import HurricastDataset, era5_maps, hurricast_storms, hurricast_windows, open_era5 +from .ships import SHIPSXu2021Dataset, read_xu2021_table +from .tcnd import TropiCycloneNetDataset, gph_to_image, read_tcnd_track +from .synthetic import ( + SyntheticHurricastDataset, + SyntheticSAFNetDataset, + SyntheticSHIPSDataset, + SyntheticTCIFFusionDataset, + SyntheticTCNDDataset, + SyntheticTropicalCycloneDataset, + synthetic_tcnd_batch, +) __all__ = [ + "HurricastDataset", "IBTrACSTropicalCycloneDataset", + "SHIPSXu2021Dataset", + "SyntheticHurricastDataset", + "SyntheticSAFNetDataset", + "SyntheticSHIPSDataset", + "SyntheticTCIFFusionDataset", + "SyntheticTCNDDataset", "SyntheticTropicalCycloneDataset", - "TCBenchAlphaDataset", "TropiCycloneNetDataset", + "build_track_samples", + "download_ibtracs", + "era5_maps", + "hurricast_storms", + "hurricast_windows", + "ibtracs_url", + "open_era5", + "read_ibtracs", + "read_ibtracs_csv", + "read_ibtracs_netcdf", + "gph_to_image", + "read_tcnd_track", + "read_xu2021_table", + "synthetic_tcnd_batch", ] diff --git a/pyhazards/datasets/tc/hurricast.py b/pyhazards/datasets/tc/hurricast.py new file mode 100644 index 00000000..f07770dd --- /dev/null +++ b/pyhazards/datasets/tc/hurricast.py @@ -0,0 +1,462 @@ +"""Hurricast inputs: IBTrACS statistical features and ERA5 reanalysis maps (Boussioux et al. 2022). + +Hurricast (Weather and Forecasting 37(6), 2022, doi:10.1175/WAF-D-21-0091.1) forecasts the 24-hour +intensity and displacement of a tropical cyclone from its last 8 three-hourly time steps (t-21 h ... t): + +* **Statistical data** (paper Section 2a, Table 2) from IBTrACS: per step the 30 features of + :data:`pyhazards.models.hurricast.HURRICAST_STAT_FEATURES` (position, WMO wind and pressure, distance + to land, translation speed, cosine / sine of the day of year, direction, latitude and longitude, + Saffir-Simpson category value, one-hot basin and storm nature, and the latitude / longitude change + since the previous step). WMO wind and pressure, which IBTrACS reports only at synoptic times, are + interpolated linearly to every 3-hour step, and 10-minute winds are converted to 1-minute winds by + dividing by 0.93 (samples outside the North Atlantic and Eastern Pacific, as in the official notebooks). +* **Reanalysis maps** (Section 2b) from ERA5: u, v and geopotential z at 225, 500 and 700 hPa on a + 25 x 25 grid of 1 degree centred on the storm, per step. + +Storms are selected as in the official ``sort_storm`` (src/utils/data_processing.py of leobix/hurricast; +read as a test oracle only, the repository has no licence): a storm is kept when more than ``min_steps`` +of its rows have a WMO wind of at least ``min_wind`` knots (34 kt and 20 rows, i.e. 60 h, in the paper), +and its rows from the first time it reaches ``min_wind`` on (at most ``max_steps``, 120) form its track. +Every window of ``window_size`` steps followed by ``predict_at`` steps gives one sample; as the official +``remove_zeros``, windows whose 24-hour target period contains a step with zero latitude and longitude +change are dropped. Targets: WMO wind ``predict_at`` steps after the last input step (24 h), or the +latitude / longitude 24 h ahead (the model predicts the displacement from the current position). + +PyHazards reads IBTrACS v04 (:func:`pyhazards.datasets.tc.read_ibtracs`) and ERA5 pressure-level data +the user has (a netCDF / zarr file or an ``xarray.Dataset`` with u, v, z at 225, 500, 700 hPa, e.g. a +Copernicus Climate Data Store download or the NCAR RDA copy); nothing is downloaded or redistributed. +""" + +from __future__ import annotations + +import math +from pathlib import Path +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np +import torch + +from ...models.hurricast import HURRICAST_MAP_CHANNELS, HURRICAST_STAT_FEATURES +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec +from .ibtracs import read_ibtracs + +ERA5_LEVELS: Tuple[int, ...] = (225, 500, 700) +ERA5_VARIABLES: Tuple[str, ...] = ("u", "v", "z") +# Paper Section 4b: train 1980-2011, validation 2012-2015, test 2016-2019 (test: NA and EP only). +PAPER_SEASONS = {"train": tuple(range(1980, 2012)), "val": tuple(range(2012, 2016)), "test": tuple(range(2016, 2020))} +PAPER_TEST_BASINS = ("NA", "EP") +BASIN_COLUMNS = (("NA", "cat_basin_AN"), ("EP", "cat_basin_EP"), ("NI", "cat_basin_NI"), ("SA", "cat_basin_SA"), ("SI", "cat_basin_SI"), ("SP", "cat_basin_SP"), ("WP", "cat_basin_WP")) +NATURE_COLUMNS = tuple((code, f"cat_nature_{code}") for code in ("DS", "ET", "MX", "NR", "SS", "TS")) +# Table 2: these numerical features are standardised; cyclic encodings and categories are not. +STANDARDISED_FEATURES = ("LAT", "LON", "WMO_WIND", "WMO_PRES", "DIST2LAND", "STORM_SPEED", "STORM_DISPLACEMENT_X", "STORM_DISPLACEMENT_Y") +TEN_MINUTE_TO_ONE_MINUTE = 0.93 # Harper et al. (2010), as in the paper + +_ERA5_NAMES = { + "u": ("u", "U", "u_component_of_wind"), + "v": ("v", "V", "v_component_of_wind"), + "z": ("z", "Z", "geopotential"), +} +_DIM_NAMES = { + "time": ("time", "valid_time"), + "level": ("level", "pressure_level", "isobaricInhPa", "plev"), + "latitude": ("latitude", "lat"), + "longitude": ("longitude", "lon"), +} + + +def wind_category(wind: Union[float, np.ndarray]) -> np.ndarray: + """Saffir-Simpson category value of the official ``sust_wind_to_cat_val`` (knots): TD 0, TS 1, H1-H5 2-6, missing 7.""" + wind = np.asarray(wind, dtype=np.float64) + edges = np.array([33.0, 63.0, 82.0, 95.0, 112.0, 136.0]) + category = np.searchsorted(edges, wind, side="left").astype(np.float64) + return np.where(np.isnan(wind), 7.0, category) + + +def _storm_features(storm) -> "Any": + """The 30 features of one storm's rows (pandas DataFrame in, DataFrame out).""" + import pandas as pd + + out = pd.DataFrame(index=storm.index) + out["LAT"] = storm["LAT"].astype(float) + out["LON"] = storm["LON"].astype(float) + out["WMO_WIND"] = storm["WMO_WIND"].astype(float) + out["WMO_PRES"] = storm["WMO_PRES"].astype(float) + out["DIST2LAND"] = storm["DIST2LAND"].astype(float) + out["STORM_SPEED"] = storm["STORM_SPEED"].astype(float) + day = storm["ISO_TIME"].dt.dayofyear.to_numpy(dtype=np.float64) + out["cat_cos_day"] = np.cos(2 * np.pi * day / 365) + out["cat_sign_day"] = np.sin(2 * np.pi * day / 365) + direction = np.deg2rad(storm["STORM_DIR"].to_numpy(dtype=np.float64)) + out["COS_STORM_DIR"] = np.cos(direction) + out["SIN_STORM_DIR"] = np.sin(direction) + lat, lon = np.deg2rad(out["LAT"].to_numpy()), np.deg2rad(out["LON"].to_numpy()) + out["COS_LAT"], out["SIN_LAT"] = np.cos(lat), np.sin(lat) + out["COS_LON"], out["SIN_LON"] = np.cos(lon), np.sin(lon) + out["cat_storm_category"] = wind_category(out["WMO_WIND"].to_numpy()) + basin = storm["BASIN"].astype(str).to_numpy() + for code, column in BASIN_COLUMNS: + out[column] = (basin == code).astype(np.float64) + nature = storm["NATURE"].astype(str).to_numpy() if "NATURE" in storm else np.full(len(storm), "") + for code, column in NATURE_COLUMNS: + out[column] = (nature == code).astype(np.float64) + # Change since the previous step; 0 for the first row of the (cut) track, as the official + # add_displacement_lat_lon2. + out["STORM_DISPLACEMENT_X"] = out["LAT"].diff().fillna(0.0) + out["STORM_DISPLACEMENT_Y"] = out["LON"].diff().fillna(0.0) + return out[list(HURRICAST_STAT_FEATURES)] + + +def hurricast_storms( + table, + min_wind: float = 34.0, + min_steps: int = 20, + max_steps: int = 120, + include_spur: bool = False, +) -> List[Dict[str, Any]]: + """Select and cut storms like the official ``sort_storm`` and compute their statistical features. + + ``table`` is an IBTrACS table (:func:`pyhazards.datasets.tc.read_ibtracs`). Rows off the 3-hour + grid (e.g. landfall records at 10:15) are dropped; WMO wind and pressure are interpolated linearly + within each storm (values after the last report repeat it). Returns one dict per kept storm with + ``sid``, ``season``, ``basin`` (first row), ``times`` and ``features`` ``(rows, 30)``. + """ + required = ("SID", "SEASON", "BASIN", "ISO_TIME", "LAT", "LON", "WMO_WIND", "WMO_PRES", "DIST2LAND", "STORM_SPEED", "STORM_DIR") + missing = [column for column in required if column not in table.columns] + if missing: + raise ValueError(f"the IBTrACS table lacks column(s) {missing} needed by Hurricast") + frame = table + times = frame["ISO_TIME"] + frame = frame[(times.dt.hour % 3 == 0) & (times.dt.minute == 0) & (times.dt.second == 0)] + if not include_spur and "TRACK_TYPE" in frame.columns: + frame = frame[~frame["TRACK_TYPE"].astype(str).str.contains("spur", case=False, na=False)] + storms = [] + for sid, storm in frame.groupby("SID", sort=True): + storm = storm.sort_values("ISO_TIME", kind="stable").reset_index(drop=True) + storm = storm.copy() + for column in ("WMO_WIND", "WMO_PRES"): + storm[column] = storm[column].astype(float).interpolate(method="linear") + strong = np.flatnonzero(storm["WMO_WIND"].to_numpy() >= min_wind) + if len(strong) <= min_steps: + continue + cut = storm.iloc[strong[0] : strong[0] + int(max_steps)].reset_index(drop=True) + storms.append( + { + "sid": sid, + "season": int(cut["SEASON"].iloc[0]), + "basin": str(cut["BASIN"].iloc[0]), + "times": cut["ISO_TIME"].to_numpy(dtype="datetime64[ns]"), + "features": _storm_features(cut).to_numpy(dtype=np.float64), + } + ) + return storms + + +def hurricast_windows( + storms: Sequence[Mapping[str, Any]], + window_size: int = 8, + predict_at: int = 8, + one_minute_winds: bool = True, +) -> Dict[str, Any]: + """Forecast samples from :func:`hurricast_storms`. + + Returns ``x_stat`` ``(N, window_size, 30)``, ``position`` ``(N, 2)`` (latitude, longitude at the + last input step), ``intensity`` ``(N,)`` (WMO wind ``predict_at`` steps later), ``displacement`` + ``(N, 2)`` (sum of the latitude / longitude changes over those steps), and per-sample ``sid``, + ``season``, ``basin``, ``iso_time`` and ``rows`` (index of each input step in its storm). + """ + names = list(HURRICAST_STAT_FEATURES) + i_lat, i_lon, i_wind = names.index("LAT"), names.index("LON"), names.index("WMO_WIND") + i_dx, i_dy = names.index("STORM_DISPLACEMENT_X"), names.index("STORM_DISPLACEMENT_Y") + i_na, i_ep = names.index("cat_basin_AN"), names.index("cat_basin_EP") + out: Dict[str, List[Any]] = {key: [] for key in ("x_stat", "position", "intensity", "displacement", "sid", "season", "basin", "iso_time", "storm", "rows")} + for k, storm in enumerate(storms): + values = storm["features"] + for start in range(0, len(values) - window_size - predict_at + 1): + last = start + window_size - 1 + future = values[last + 1 : last + 1 + predict_at] + if np.any((future[:, i_dx] == 0) & (future[:, i_dy] == 0)): + continue # official remove_zeros + x = values[start : last + 1].copy() + target = values[last + predict_at, i_wind] + if one_minute_winds and x[0, i_na] + x[0, i_ep] < 1: + x[:, i_wind] = x[:, i_wind] / TEN_MINUTE_TO_ONE_MINUTE + target = target / TEN_MINUTE_TO_ONE_MINUTE + out["x_stat"].append(x) + out["position"].append(values[last, [i_lat, i_lon]]) + out["intensity"].append(target) + out["displacement"].append([future[:, i_dx].sum(), future[:, i_dy].sum()]) + out["sid"].append(storm["sid"]) + out["season"].append(storm["season"]) + out["basin"].append(storm["basin"]) + out["iso_time"].append(str(np.datetime_as_string(storm["times"][last], unit="s"))) + out["storm"].append(k) + out["rows"].append(list(range(start, last + 1))) + width = len(names) + return { + "x_stat": np.asarray(out["x_stat"], dtype=np.float64).reshape(-1, window_size, width), + "position": np.asarray(out["position"], dtype=np.float64).reshape(-1, 2), + "intensity": np.asarray(out["intensity"], dtype=np.float64), + "displacement": np.asarray(out["displacement"], dtype=np.float64).reshape(-1, 2), + **{key: out[key] for key in ("sid", "season", "basin", "iso_time", "storm", "rows")}, + } + + +# --------------------------------------------------------------------------------------------------- +# ERA5 + + +def _rename(ds): + """Rename an ERA5 dataset to dims (time, level, latitude, longitude) and variables u, v, z.""" + renames = {} + for target, options in _DIM_NAMES.items(): + found = next((name for name in options if name in ds.dims or name in ds.coords), None) + if found is None: + raise ValueError(f"ERA5 data has no {target} coordinate (looked for {options})") + if found != target: + renames[found] = target + for target, options in _ERA5_NAMES.items(): + found = next((name for name in options if name in ds.data_vars), None) + if found is None: + raise ValueError(f"ERA5 data has no {target} variable (looked for {options})") + if found != target: + renames[found] = target + return ds.rename(renames) if renames else ds + + +def open_era5(source: Any): + """Open ERA5 pressure-level data (netCDF file, zarr store or ``xarray.Dataset``) with u, v, z.""" + import xarray as xr + + if isinstance(source, xr.Dataset): + ds = source + else: + path = Path(source).expanduser() + if not path.exists(): + raise FileNotFoundError(f"ERA5 data {path} not found") + ds = xr.open_zarr(path) if path.suffix == ".zarr" or (path / ".zgroup").exists() else xr.open_dataset(path) + return _rename(ds) + + +def era5_maps( + ds, + times: Sequence[Any], + lats: Sequence[float], + lons: Sequence[float], + size: int = 25, + resolution: float = 1.0, + levels: Sequence[int] = ERA5_LEVELS, +) -> np.ndarray: + """Storm-centred ERA5 maps ``(n, 9, size, size)``: u, v, z at ``levels``, north to south, west to east. + + The centre is the grid point (at ``resolution`` degrees) nearest to the storm; the maps take every + grid point within ``size // 2`` steps of it, so a 0.25-degree source is sampled at whole degrees. + """ + ds = _rename(ds) + lon_coord = ds["longitude"].values + east_360 = float(np.nanmax(lon_coord)) > 180.0 + offsets = (np.arange(size) - size // 2) * resolution + maps = np.empty((len(times), len(ERA5_VARIABLES) * len(levels), size, size), dtype=np.float32) + tol = resolution / 100.0 + for i, (time, lat, lon) in enumerate(zip(times, lats, lons)): + centre_lat = math.floor(float(lat) / resolution + 0.5) * resolution + centre_lon = math.floor(float(lon) / resolution + 0.5) * resolution + wanted_lat = centre_lat - offsets # north to south + wanted_lon = centre_lon + offsets + wanted_lon = np.mod(wanted_lon, 360.0) if east_360 else np.mod(wanted_lon + 180.0, 360.0) - 180.0 + try: + step = ds[list(ERA5_VARIABLES)].sel(time=np.datetime64(time, "ns"), level=list(levels)) + step = step.sel(latitude=wanted_lat, longitude=wanted_lon, method="nearest", tolerance=tol) + except KeyError as exc: + raise KeyError(f"ERA5 data lacks the maps around ({lat}, {lon}) at {time}: {exc}") from exc + for v, name in enumerate(ERA5_VARIABLES): + block = step[name].transpose("level", "latitude", "longitude").values + maps[i, v * len(levels) : (v + 1) * len(levels)] = block + if not np.isfinite(maps).all(): + raise ValueError("ERA5 maps contain missing values (outside the data's area or time range?)") + return maps + + +# --------------------------------------------------------------------------------------------------- +# Dataset + + +class HurricastDataset(Dataset): + """24-hour Hurricast samples from an IBTrACS file and (optionally) ERA5 pressure-level data. + + Inputs per split: ``{"x_stat": (N, 8, 30), "x_viz": (N, 8, 9, 25, 25), "position": (N, 2)}`` (no + ``x_viz`` without ``era5``; HUML-(stat, xgb) needs none). With ``standardize`` the numerical + statistical features of Table 2 and every map channel are standardised with the training split's + mean and standard deviation (over samples and steps, and pixels for maps); ``position`` stays in + degrees. Targets: ``target="intensity"`` the WMO wind 24 h ahead ``(N,)`` in 1-minute knots + (``tc.intensity``); ``target="displacement"`` the latitude / longitude 24 h ahead ``(N, 1, 2)`` + (``tc.track_intensity``, lead 24 h). Splits are by season (paper: 1980-2011 / 2012-2015 / + 2016-2019); the test split keeps only ``test_basins`` (paper: NA and EP); ``basins`` restricts every + split. ERA5 maps are read only for samples of a split. + """ + + name = "hurricast_ibtracs_era5" + + def __init__( + self, + path: Optional[Union[str, Path]] = None, + era5: Any = None, + cache_dir: Optional[str] = None, + target: str = "intensity", + window_size: int = 8, + predict_at: int = 8, + min_wind: float = 34.0, + min_steps: int = 20, + max_steps: int = 120, + train_seasons: Optional[Sequence[int]] = PAPER_SEASONS["train"], + val_seasons: Optional[Sequence[int]] = PAPER_SEASONS["val"], + test_seasons: Optional[Sequence[int]] = PAPER_SEASONS["test"], + test_basins: Optional[Sequence[str]] = PAPER_TEST_BASINS, + basins: Optional[Sequence[str]] = None, + standardize: bool = True, + one_minute_winds: bool = True, + include_spur: bool = False, + ): + super().__init__(cache_dir=cache_dir) + if path is None: + raise ValueError("hurricast_ibtracs_era5 needs path= to an IBTrACS v04 CSV or netCDF file (see ibtracs_tracks)") + self.path = Path(path) + if not self.path.exists(): + raise FileNotFoundError(f"{self.path} not found") + if target not in ("intensity", "displacement"): + raise ValueError("target must be 'intensity' or 'displacement'") + if window_size < 1 or predict_at < 1: + raise ValueError("window_size and predict_at must be positive") + self.era5 = era5 + self.target = target + self.window_size, self.predict_at = int(window_size), int(predict_at) + self.min_wind, self.min_steps, self.max_steps = float(min_wind), int(min_steps), int(max_steps) + self.seasons = {"train": train_seasons, "val": val_seasons, "test": test_seasons} + self.test_basins = None if test_basins is None else tuple(b.upper() for b in test_basins) + self.basins = None if basins is None else tuple(b.upper() for b in basins) + self.standardize = standardize + self.one_minute_winds = one_minute_winds + self.include_spur = include_spur + + def _load(self) -> DataBundle: + columns = ("NATURE", "TRACK_TYPE", "WMO_WIND", "WMO_PRES", "DIST2LAND", "STORM_SPEED", "STORM_DIR") + storms = hurricast_storms(read_ibtracs(self.path, columns), self.min_wind, self.min_steps, self.max_steps, self.include_spur) + samples = hurricast_windows(storms, self.window_size, self.predict_at, self.one_minute_winds) + if len(samples["intensity"]) == 0: + raise ValueError(f"no Hurricast samples in {self.path} (min_wind={self.min_wind}, min_steps={self.min_steps})") + seasons = np.asarray(samples["season"]) + basins = np.asarray(samples["basin"]) + keep_basin = np.ones(len(seasons), dtype=bool) if self.basins is None else np.isin(basins, self.basins) + masks = {} + for split, years in self.seasons.items(): + mask = np.zeros(len(seasons), dtype=bool) if years is None else np.isin(seasons, list(years)) + mask &= keep_basin + if split == "test" and self.test_basins is not None: + mask &= np.isin(basins, self.test_basins) + masks[split] = mask + if not any(mask.any() for mask in masks.values()): + raise ValueError("no Hurricast sample falls into the train / val / test seasons and basins") + + x_stat = samples["x_stat"] + x_viz = None + if self.era5 is not None: + # Maps are read only for samples that belong to a split. + ds = open_era5(self.era5) + wanted = np.flatnonzero(np.logical_or.reduce(list(masks.values()))) + used = sorted({(samples["storm"][i], r) for i in wanted for r in samples["rows"][i]}) + i_lat, i_lon = HURRICAST_STAT_FEATURES.index("LAT"), HURRICAST_STAT_FEATURES.index("LON") + crops = era5_maps( + ds, + [storms[k]["times"][r] for k, r in used], + [storms[k]["features"][r, i_lat] for k, r in used], + [storms[k]["features"][r, i_lon] for k, r in used], + ) + where = {key: i for i, key in enumerate(used)} + blank = np.zeros_like(crops[0]) # samples outside every split are never returned + x_viz = np.stack([[crops[where[(k, r)]] if (k, r) in where else blank for r in rows] for k, rows in zip(samples["storm"], samples["rows"])]) + + stat_mean = np.zeros(x_stat.shape[-1]) + stat_std = np.ones(x_stat.shape[-1]) + viz_mean = viz_std = None + train = masks["train"] + if self.standardize: + if not train.any(): + raise ValueError("standardize=True needs training samples (train_seasons)") + for name in STANDARDISED_FEATURES: + j = HURRICAST_STAT_FEATURES.index(name) + values = torch.as_tensor(x_stat[train][:, :, j]) + stat_mean[j], stat_std[j] = float(values.mean()), float(values.std()) or 1.0 + x_stat = (x_stat - stat_mean) / stat_std + if x_viz is not None: + maps = torch.as_tensor(x_viz[train], dtype=torch.float32) + viz_mean = maps.mean(dim=(0, 1, 3, 4)).numpy() + viz_std = maps.std(dim=(0, 1, 3, 4)).numpy() + viz_std = np.where(viz_std > 0, viz_std, 1.0) + x_viz = ((x_viz - viz_mean[None, None, :, None, None]) / viz_std[None, None, :, None, None]).astype(np.float32) + + position = samples["position"] + if self.target == "intensity": + targets = samples["intensity"] + else: + targets = (position + samples["displacement"])[:, None, :] + splits = {} + for split, mask in masks.items(): + index = np.flatnonzero(mask) + inputs = {"x_stat": torch.as_tensor(x_stat[index], dtype=torch.float32), "position": torch.as_tensor(position[index], dtype=torch.float32)} + if x_viz is not None: + inputs["x_viz"] = torch.as_tensor(x_viz[index]) + splits[split] = DataSplit( + inputs, + torch.as_tensor(targets[index], dtype=torch.float32), + metadata={ + "groups": [samples["season"][i] for i in index], + "sid": [samples["sid"][i] for i in index], + "basin": [samples["basin"][i] for i in index], + "iso_time": [samples["iso_time"][i] for i in index], + }, + ) + metadata = { + "dataset": self.name, + "source_dataset": "IBTrACS v04" + (" + ERA5" if x_viz is not None else ""), + "lead_hours": [3 * self.predict_at], + "window_size": self.window_size, + "stat_features": list(HURRICAST_STAT_FEATURES), + "map_channels": list(HURRICAST_MAP_CHANNELS) if x_viz is not None else [], + "standardization": { + "stat_mean": stat_mean.tolist(), + "stat_std": stat_std.tolist(), + "map_mean": None if viz_mean is None else viz_mean.tolist(), + "map_std": None if viz_std is None else viz_std.tolist(), + }, + "source_file": str(self.path), + "synthetic": False, + } + if self.target == "intensity": + metadata.update({"hazard_task": "tc.intensity", "units": {"wind": "kt"}, "intensity_target": "1-minute WMO wind 24 h ahead"}) + label = LabelSpec(num_targets=1, task_type="regression", description="Maximum sustained wind 24 hours ahead (1-minute, kt).") + else: + metadata.update({"hazard_task": "tc.track_intensity", "target_variables": ["lat", "lon"], "units": {}}) + label = LabelSpec(num_targets=2, task_type="regression", description="Latitude and longitude 24 hours ahead (degrees).") + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=len(HURRICAST_STAT_FEATURES), + description=f"{self.window_size} three-hourly steps of 30 IBTrACS statistical features" + (" and 9 ERA5 maps (25 x 25)" if x_viz is not None else ""), + extra={"window_size": self.window_size}, + ), + label_spec=label, + metadata=metadata, + ) + + +__all__ = [ + "ERA5_LEVELS", + "ERA5_VARIABLES", + "HurricastDataset", + "PAPER_SEASONS", + "STANDARDISED_FEATURES", + "era5_maps", + "hurricast_storms", + "hurricast_windows", + "open_era5", + "wind_category", +] diff --git a/pyhazards/datasets/tc/ibtracs.py b/pyhazards/datasets/tc/ibtracs.py new file mode 100644 index 00000000..e4c78120 --- /dev/null +++ b/pyhazards/datasets/tc/ibtracs.py @@ -0,0 +1,438 @@ +"""Reader for NOAA NCEI's International Best Track Archive for Climate Stewardship (IBTrACS) v04. + +IBTrACS (Knapp et al. 2010, BAMS 91:363-376; Gahtan et al. 2024, doi:10.25921/82ty-9e16) merges the +best tracks of the WMO Regional Specialized Meteorological Centres and other agencies. NCEI +distributes it as CSV (``ibtracs..list.v04r01.csv``) and netCDF +(``IBTrACS..v04r01.nc``) files, where ```` is ``ALL``, ``since1980``, +``last3years``, ``ACTIVE`` or a basin (``NA``, ``EP``, ``WP``, ``NI``, ``SI``, ``SP``, ``SA``). +Access follows the World Data Center for Meteorology policy (full and open access; WMO +Resolution 40 guides commercial use); PyHazards downloads the files from NCEI on request and never +redistributes them. + +:func:`read_ibtracs` returns one row per track point with the CSV column names (``SID``, +``SEASON``, ``BASIN``, ``NAME``, ``ISO_TIME``, ``NATURE``, ``LAT``, ``LON``, ``WMO_WIND``, +``WMO_PRES``, ``WMO_AGENCY``, ``TRACK_TYPE``, ``USA_WIND``, ``TOKYO_WIND``, ``CMA_WIND``, ...) from +either format. CSV specifics handled here: the second line holds units, missing values are a single +space, and ``NA`` is the North Atlantic basin code, not a missing value. Positions: ``LAT``/``LON`` +are IBTrACS' merged position (``LON`` stays continuous across the dateline, so it can exceed 180); +agency positions (``USA_LON``, ...) are wrapped to [-180, 180). + +:class:`IBTrACSTropicalCycloneDataset` (registry name ``ibtracs_tracks``) turns the tracks into +forecasting samples: ``history`` six-hourly observations of the chosen variables before a forecast +time and the same variables at ``lead_hours`` after it. Winds are in knots (agency averaging periods +differ: 1 minute for the US agencies, 10 minutes for most others, 2 minutes for CMA; IBTrACS does +not convert them), pressures in hPa (mb). +""" + +from __future__ import annotations + +import hashlib +import urllib.request +from pathlib import Path +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np +import torch + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +IBTRACS_VERSION = "v04r01" +IBTRACS_BASE_URL = ( + "https://www.ncei.noaa.gov/data/international-best-track-archive-for-climate-stewardship-ibtracs/v04r01/access" +) +IBTRACS_SUBSETS = ("ALL", "since1980", "last3years", "ACTIVE", "NA", "EP", "WP", "NI", "SI", "SP", "SA") +BASINS = ("NA", "SA", "EP", "WP", "NI", "SI", "SP") +# Agencies with _LAT/_LON/_WIND/_PRES columns (WMO has only WIND/PRES). +AGENCIES = ("wmo", "usa", "tokyo", "cma", "hko", "kma", "newdelhi", "reunion", "bom", "nadi", "wellington", "ds824", "td9636", "td9635", "neumann", "mlc") +REQUIRED_COLUMNS = ("SID", "SEASON", "BASIN", "NAME", "ISO_TIME", "LAT", "LON") +STRING_COLUMNS = ( + "SID", "BASIN", "SUBBASIN", "NAME", "ISO_TIME", "NATURE", "WMO_AGENCY", "TRACK_TYPE", "MAIN_TRACK_SID", + "IFLAG", "USA_AGENCY", "USA_ATCF_ID", "USA_RECORD", "USA_STATUS", +) +VARIABLE_UNITS = {"lat": "degrees_north", "lon": "degrees_east", "wind": "kt", "pres": "hPa"} + + +def ibtracs_url(subset: str = "ALL", fmt: str = "csv") -> str: + """NCEI download URL of an IBTrACS v04r01 file.""" + if subset not in IBTRACS_SUBSETS: + raise ValueError(f"unknown IBTrACS subset {subset!r}; choose from {IBTRACS_SUBSETS}") + if fmt == "csv": + return f"{IBTRACS_BASE_URL}/csv/ibtracs.{subset}.list.{IBTRACS_VERSION}.csv" + if fmt in {"netcdf", "nc"}: + return f"{IBTRACS_BASE_URL}/netcdf/IBTrACS.{subset}.{IBTRACS_VERSION}.nc" + raise ValueError("fmt must be 'csv' or 'netcdf'") + + +def download_ibtracs(dest: Union[str, Path], subset: str = "ALL", fmt: str = "csv", overwrite: bool = False) -> Path: + """Download an IBTrACS file from NCEI into ``dest`` (the ALL CSV is about 300 MB). + + IBTrACS is updated several times a week, so files cannot be pinned by checksum; the dataset + records the sha256 of the file it read in its metadata. + """ + url = ibtracs_url(subset, fmt) + dest = Path(dest).expanduser() + dest.mkdir(parents=True, exist_ok=True) + target = dest / url.rsplit("/", 1)[1] + if overwrite or not target.exists(): + partial = target.with_suffix(target.suffix + ".part") + urllib.request.urlretrieve(url, partial) + partial.replace(target) + return target + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _finish_table(frame): + import pandas as pd + + missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns] + if missing: + raise ValueError(f"not an IBTrACS v04 table: missing columns {missing}") + for column in frame.columns: + if column == "ISO_TIME": + continue + if column in STRING_COLUMNS: + frame[column] = frame[column].fillna("").astype(str).str.strip() + continue + # Numeric columns become floats; category columns (e.g. NEWDELHI_GRADE, DS824_STAGE) stay text. + converted = pd.to_numeric(frame[column], errors="coerce") + if int(converted.notna().sum()) == int(frame[column].notna().sum()): + frame[column] = converted + frame["ISO_TIME"] = pd.to_datetime(frame["ISO_TIME"], format="%Y-%m-%d %H:%M:%S") + frame = frame.sort_values(["SID", "ISO_TIME"], kind="stable").reset_index(drop=True) + return frame + + +def read_ibtracs_csv(path: Union[str, Path], usecols: Optional[Iterable[str]] = None): + """Read an IBTrACS v04 CSV file into a pandas DataFrame (one row per track point).""" + import pandas as pd + + path = Path(path) + with path.open("r", encoding="utf-8", newline="") as handle: + header = handle.readline().rstrip("\r\n").split(",") + second = handle.readline().rstrip("\r\n").split(",") + if "SID" not in header: + raise ValueError(f"{path} does not start with the IBTrACS header (SID, SEASON, ...)") + # Line 2 is the units row (" ,Year, , , , , , ,degrees_north,degrees_east,kts,mb,..."). + units_row = len(second) == len(header) and second[0].strip() == "" and "degrees_north" in second + if usecols is not None: + usecols = [column for column in header if column in set(usecols) | set(REQUIRED_COLUMNS)] + frame = pd.read_csv( + path, + skiprows=[1] if units_row else None, + usecols=usecols, + dtype=str, + keep_default_na=False, # "NA" is the North Atlantic basin + na_values=[" ", ""], + ) + return _finish_table(frame) + + +def _decode(values: np.ndarray) -> np.ndarray: + if values.dtype.kind == "S": + return np.char.strip(np.char.decode(values, "utf-8", errors="replace")) + return values + + +def read_ibtracs_netcdf(path: Union[str, Path], variables: Optional[Iterable[str]] = None): + """Read an IBTrACS v04 netCDF file (dimensions ``storm`` x ``date_time``) into the CSV table layout.""" + import pandas as pd + import xarray as xr + + with xr.open_dataset(Path(path), decode_times=False, mask_and_scale=True) as ds: + if "sid" not in ds or "iso_time" not in ds or "numobs" not in ds: + raise ValueError(f"{path} is not an IBTrACS v04 netCDF file (needs sid, iso_time, numobs)") + wanted = list(ds.variables) if variables is None else sorted(set(v.lower() for v in variables) | {c.lower() for c in REQUIRED_COLUMNS}) + storm_count, slot_count = ds.sizes["storm"], ds.sizes["date_time"] + numobs = np.nan_to_num(ds["numobs"].values).astype(int) + valid = np.arange(slot_count)[None, :] < numobs[:, None] + columns: Dict[str, np.ndarray] = {} + for name in wanted: + if name not in ds or name in {"time", "numobs"}: + continue + var = ds[name] + dims = var.dims + if dims == ("storm",): + values = np.repeat(_decode(var.values)[:, None], slot_count, axis=1) + elif dims == ("storm", "date_time"): + values = _decode(var.values) + else: + continue # wind radii and other per-quadrant variables are not tabulated + columns[name.upper()] = values[valid] + frame = pd.DataFrame(columns) + for column in frame.columns: + if frame[column].dtype.kind in "OUS": + frame[column] = frame[column].replace("", np.nan) + return _finish_table(frame) + + +def read_ibtracs(path: Union[str, Path], columns: Optional[Iterable[str]] = None): + """Read an IBTrACS v04 CSV or netCDF file (chosen by suffix) into a DataFrame.""" + path = Path(path) + if path.suffix.lower() in {".nc", ".nc4", ".cdf", ".netcdf"}: + return read_ibtracs_netcdf(path, columns) + return read_ibtracs_csv(path, columns) + + +def _variable_columns(agency: str, positions: str) -> Dict[str, str]: + agency = agency.lower() + if agency not in AGENCIES: + raise ValueError(f"unknown agency {agency!r}; choose from {AGENCIES}") + if positions not in {"merged", "agency"}: + raise ValueError("positions must be 'merged' (LAT/LON) or 'agency' (_LAT/_LON)") + prefix = agency.upper() + if positions == "agency" and agency == "wmo": + raise ValueError("WMO has no position columns; use positions='merged'") + lat, lon = ("LAT", "LON") if positions == "merged" else (f"{prefix}_LAT", f"{prefix}_LON") + return {"lat": lat, "lon": lon, "wind": f"{prefix}_WIND", "pres": f"{prefix}_PRES"} + + +def _unwrap_degrees(lon: np.ndarray) -> np.ndarray: + return np.rad2deg(np.unwrap(np.deg2rad(lon))) + + +def build_track_samples( + table, + variables: Sequence[str] = ("lat", "lon", "wind", "pres"), + history: int = 4, + lead_hours: Sequence[int] = (6, 12, 18, 24), + agency: str = "usa", + positions: str = "merged", + basins: Optional[Sequence[str]] = None, + include_spur: bool = False, + min_wind: Optional[float] = None, +) -> Tuple[np.ndarray, np.ndarray, Dict[str, List[Any]]]: + """Forecast windows from an IBTrACS table. + + Keeps synoptic times (00, 06, 12, 18 UTC). A window ending at time ``t`` needs observations at + ``t - 6 h * (history - 1) ... t`` and at ``t + lead`` for every lead, all with the requested + variables present. Longitudes are unwrapped within each window so they are continuous. + Returns inputs ``(N, history, V)``, targets ``(N, len(lead_hours), V)`` and per-sample + metadata lists. + """ + variables = [v.lower() for v in variables] + unknown = sorted(set(variables) - set(VARIABLE_UNITS)) + if unknown or not variables: + raise ValueError(f"unknown variables {unknown}; choose from {sorted(VARIABLE_UNITS)}") + lead_steps = [] + for hours in lead_hours: + if int(hours) != hours or int(hours) <= 0 or int(hours) % 6: + raise ValueError("lead_hours must be positive multiples of 6") + lead_steps.append(int(hours) // 6) + history = int(history) + if history < 1: + raise ValueError("history must be at least 1") + columns = _variable_columns(agency, positions) + missing = [columns[v] for v in variables if columns[v] not in table.columns] + if missing: + raise ValueError(f"IBTrACS table has no column(s) {missing} for agency={agency!r}") + + frame = table + times = frame["ISO_TIME"] + frame = frame[(times.dt.hour % 6 == 0) & (times.dt.minute == 0) & (times.dt.second == 0)] + if not include_spur and "TRACK_TYPE" in frame.columns: + frame = frame[~frame["TRACK_TYPE"].str.contains("spur", case=False, na=False)] + + inputs, targets = [], [] + meta: Dict[str, List[Any]] = {"sid": [], "name": [], "basin": [], "season": [], "iso_time": []} + six_hours = np.timedelta64(6, "h") + max_lead = max(lead_steps) + for sid, storm in frame.groupby("SID", sort=True): + stamps = storm["ISO_TIME"].to_numpy(dtype="datetime64[ns]") + values = np.stack([storm[columns[v]].to_numpy(dtype=np.float64) for v in variables], axis=1) + index_of = {stamp: i for i, stamp in enumerate(stamps)} + basin_col = storm["BASIN"].to_numpy() + name, season = storm["NAME"].iloc[0], storm["SEASON"].iloc[0] + for i in range(history - 1, len(stamps)): + origin = stamps[i] + wanted = [origin - six_hours * k for k in range(history - 1, -1, -1)] + wanted += [origin + six_hours * step for step in lead_steps] + if origin + six_hours * max_lead > stamps[-1]: + break + rows = [index_of.get(stamp) for stamp in wanted] + if any(row is None for row in rows): + continue + window = values[rows] + if np.isnan(window).any(): + continue + if basins is not None and basin_col[i] not in basins: + continue + if min_wind is not None and "wind" in variables and window[history - 1, variables.index("wind")] < min_wind: + continue + if "lon" in variables: + col = variables.index("lon") + window[:, col] = _unwrap_degrees(window[:, col]) + inputs.append(window[:history]) + targets.append(window[history:]) + meta["sid"].append(sid) + meta["name"].append(name) + meta["basin"].append(basin_col[i]) + meta["season"].append(int(season)) + meta["iso_time"].append(str(np.datetime_as_string(origin, unit="s"))) + width = len(variables) + x = np.asarray(inputs, dtype=np.float32).reshape(-1, history, width) + y = np.asarray(targets, dtype=np.float32).reshape(-1, len(lead_steps), width) + return x, y, meta + + +def _season_split(seasons: Sequence[int], sids: Sequence[str], splits: Mapping[str, Optional[Sequence[int]]]) -> Dict[str, np.ndarray]: + seasons = np.asarray(seasons) + given = {name: years for name, years in splits.items() if years is not None} + if given: + masks = {name: np.isin(seasons, list(years)) for name, years in given.items()} + if "train" not in given: + other = np.zeros(len(seasons), dtype=bool) + for mask in masks.values(): + other |= mask + masks["train"] = ~other + return masks + distinct = sorted(set(seasons.tolist())) + if len(distinct) >= 3: + return { + "train": np.isin(seasons, distinct[:-2]), + "val": seasons == distinct[-2], + "test": seasons == distinct[-1], + } + # Fewer than three seasons: split whole storms (sorted by SID) 70 / 15 / 15. + storms = sorted(set(sids)) + n = len(storms) + train_end = max(1, int(round(0.7 * n))) + val_end = min(n, max(train_end, int(round(0.85 * n)))) + groups = {"train": set(storms[:train_end]), "val": set(storms[train_end:val_end]), "test": set(storms[val_end:])} + return {name: np.asarray([sid in members for sid in sids], dtype=bool) for name, members in groups.items()} + + +class IBTrACSTropicalCycloneDataset(Dataset): + """Best-track forecasting samples read from an IBTrACS v04 CSV or netCDF file. + + Inputs ``(samples, history, V)`` and targets ``(samples, len(lead_hours), V)`` hold the + ``variables`` (default latitude, longitude, maximum sustained wind in knots and central + pressure in hPa) in physical units. Splits are by season: pass ``train_seasons``, + ``val_seasons``, ``test_seasons`` (seasons not listed go to train), otherwise the last season + is the test split, the one before validation and the rest training. + """ + + name = "ibtracs_tracks" + + def __init__( + self, + path: Optional[Union[str, Path]] = None, + cache_dir: Optional[str] = None, + subset: str = "ALL", + file_format: str = "csv", + download: bool = False, + variables: Sequence[str] = ("lat", "lon", "wind", "pres"), + history: int = 4, + lead_hours: Sequence[int] = (6, 12, 18, 24), + agency: str = "usa", + positions: str = "merged", + basins: Optional[Sequence[str]] = None, + include_spur: bool = False, + min_wind: Optional[float] = None, + train_seasons: Optional[Sequence[int]] = None, + val_seasons: Optional[Sequence[int]] = None, + test_seasons: Optional[Sequence[int]] = None, + ): + super().__init__(cache_dir=cache_dir) + if path is None: + if cache_dir is None: + raise ValueError( + "ibtracs_tracks needs path= (an IBTrACS v04 CSV or netCDF file) or cache_dir= with download=True" + ) + name = ibtracs_url(subset, file_format).rsplit("/", 1)[1] + candidate = Path(cache_dir).expanduser() / name + if not candidate.exists(): + if not download: + raise FileNotFoundError(f"{candidate} not found; pass download=True to fetch it from NCEI") + candidate = download_ibtracs(cache_dir, subset=subset, fmt=file_format) + path = candidate + self.path = Path(path) + if basins is not None: + basins = [b.upper() for b in basins] + unknown = sorted(set(basins) - set(BASINS)) + if unknown: + raise ValueError(f"unknown basins {unknown}; choose from {BASINS}") + self.variables = tuple(v.lower() for v in variables) + self.history = int(history) + self.lead_hours = tuple(int(h) for h in lead_hours) + self.agency = agency.lower() + self.positions = positions + self.basins = basins + self.include_spur = include_spur + self.min_wind = min_wind + self.splits = {"train": train_seasons, "val": val_seasons, "test": test_seasons} + + def _load(self) -> DataBundle: + columns = _variable_columns(self.agency, self.positions) + needed = {"TRACK_TYPE", *(columns[v] for v in self.variables)} + table = read_ibtracs(self.path, needed) + x, y, meta = build_track_samples( + table, + variables=self.variables, + history=self.history, + lead_hours=self.lead_hours, + agency=self.agency, + positions=self.positions, + basins=self.basins, + include_spur=self.include_spur, + min_wind=self.min_wind, + ) + if len(x) == 0: + raise ValueError(f"no complete {self.history}-step + {self.lead_hours} h windows in {self.path}") + masks = _season_split(meta["season"], meta["sid"], self.splits) + splits = {} + for split_name in ("train", "val", "test"): + mask = masks.get(split_name, np.zeros(len(x), dtype=bool)) + index = np.flatnonzero(mask) + splits[split_name] = DataSplit( + torch.from_numpy(x[index]), + torch.from_numpy(y[index]), + metadata={key: [values[i] for i in index] for key, values in meta.items()}, + ) + units = {v: VARIABLE_UNITS[v] for v in self.variables} + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=len(self.variables), + description=f"{self.history} six-hourly IBTrACS observations of {', '.join(self.variables)}.", + extra={"history": self.history, "variables": list(self.variables)}, + ), + label_spec=LabelSpec( + num_targets=len(self.variables), + task_type="regression", + description=f"Best-track {', '.join(self.variables)} at {list(self.lead_hours)} h.", + ), + metadata={ + "dataset": self.name, + "source_dataset": "IBTrACS " + IBTRACS_VERSION, + "hazard_task": "tc.track_intensity", + "lead_hours": list(self.lead_hours), + "target_variables": list(self.variables), + "units": units, + "agency": self.agency, + "positions": self.positions, + "source_file": str(self.path), + "source_sha256": _sha256(self.path), + "synthetic": False, + }, + ) + + +__all__ = [ + "AGENCIES", + "BASINS", + "IBTRACS_SUBSETS", + "IBTrACSTropicalCycloneDataset", + "build_track_samples", + "download_ibtracs", + "ibtracs_url", + "read_ibtracs", + "read_ibtracs_csv", + "read_ibtracs_netcdf", +] diff --git a/pyhazards/datasets/tc/ships.py b/pyhazards/datasets/tc/ships.py new file mode 100644 index 00000000..13b2c120 --- /dev/null +++ b/pyhazards/datasets/tc/ships.py @@ -0,0 +1,127 @@ +"""SHIPS predictor table of Xu et al. (2021) for 24-hour intensity-change forecasting. + +Data: "Supporting data for Xu et al. 2021 - Weather and Forecasting" (Zenodo +doi:10.5281/zenodo.4784610, CC BY 4.0), built from the SHIPS developmental data (NHC / CIRA). The +file read here, ``train_global_fill_REA_na_wo_img_scaled.csv`` (392 MB), holds one row per storm +and 6-hourly time with the standardised SHIPS predictors, the identifiers ``name``, ``year``, +``basin`` and ``type`` (``rea``: predictors from reanalysis, global 1982-2017; ``opr``: +operational predictors, Atlantic 2010-2018) and the target ``dvs24``, the change of the maximum +sustained wind over the next 24 hours in knots. PyHazards reads the file the user downloaded; it +never redistributes it. + +The split reproduces ``utils.load_loyo_data`` of the official code (wenweixu/tropicalcyclone_MLP, +BSD-2-Clause) with the options of ``loyo_testing.py`` for the MLP (``remove_oprfortraining=True``): +for a left-out year ``Y``, training rows are all ``rea`` rows except Atlantic (``AL``) rows of +``Y``; test rows are the ``opr`` rows of ``Y``. Validation is a random 10 % of the training rows +(``ShuffleSplit(test_size=0.1)`` in the official script, seeded here). The official script reads a +``..._w2020.csv`` variant of the file that is not in the Zenodo record. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Optional, Sequence, Union + +import numpy as np +import torch + +from ...models.tropicalcyclone_mlp import SHIPS_PREDICTORS +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +XU2021_ZENODO_RECORD = "https://doi.org/10.5281/zenodo.4784610" +XU2021_TRAIN_FILE = "train_global_fill_REA_na_wo_img_scaled.csv" +_ID_COLUMNS = ("name", "year", "basin", "type", "dvs24") + + +def read_xu2021_table(path: Union[str, Path], predictors: Sequence[str] = SHIPS_PREDICTORS): + """Read the identifier, target and predictor columns of the Xu et al. (2021) CSV.""" + import pandas as pd + + path = Path(path) + header = pd.read_csv(path, nrows=0).columns + wanted = list(_ID_COLUMNS) + list(predictors) + missing = [column for column in wanted if column not in header] + if missing: + raise ValueError(f"{path} lacks the Xu et al. (2021) column(s) {missing[:8]}{' ...' if len(missing) > 8 else ''}") + frame = pd.read_csv(path, usecols=wanted) + frame["year"] = frame["year"].astype(int) + return frame + + +class SHIPSXu2021Dataset(Dataset): + """Leave-one-year-out fold of the Xu et al. (2021) SHIPS predictor table. + + Inputs ``(samples, 121)`` are the standardised predictors of + :data:`pyhazards.models.tropicalcyclone_mlp.SHIPS_PREDICTORS`; targets ``(samples,)`` are + ``dvs24`` in knots. ``leave_out_year`` is the test year (2010-2018 in the paper). + """ + + name = "ships_xu2021" + + def __init__( + self, + path: Optional[Union[str, Path]] = None, + cache_dir: Optional[str] = None, + leave_out_year: int = 2018, + val_fraction: float = 0.1, + seed: int = 0, + drop_missing: bool = True, + ): + super().__init__(cache_dir=cache_dir) + if path is None: + if cache_dir is None: + raise ValueError(f"ships_xu2021 needs path= to {XU2021_TRAIN_FILE} (download it from {XU2021_ZENODO_RECORD})") + path = Path(cache_dir) / XU2021_TRAIN_FILE + self.path = Path(path) + if not self.path.exists(): + raise FileNotFoundError(f"{self.path} not found; download {XU2021_TRAIN_FILE} from {XU2021_ZENODO_RECORD}") + if not 0.0 <= float(val_fraction) < 1.0: + raise ValueError("val_fraction must be in [0, 1)") + self.leave_out_year = int(leave_out_year) + self.val_fraction = float(val_fraction) + self.seed = int(seed) + self.drop_missing = drop_missing + + def _load(self) -> DataBundle: + frame = read_xu2021_table(self.path) + if self.drop_missing: + frame = frame.dropna(subset=["dvs24", *SHIPS_PREDICTORS]) + year = self.leave_out_year + train = frame[~((frame["basin"] == "AL") & (frame["year"] == year)) & (frame["type"] != "opr")] + test = frame[(frame["year"] == year) & (frame["type"] == "opr")] + rng = np.random.default_rng(self.seed) + order = rng.permutation(len(train)) + n_val = int(np.ceil(self.val_fraction * len(train))) if self.val_fraction > 0 else 0 + val_index, train_index = order[:n_val], order[n_val:] + + def split(part, index=None): + rows = part if index is None else part.iloc[np.sort(index)] + return DataSplit( + torch.as_tensor(rows[list(SHIPS_PREDICTORS)].to_numpy(dtype=np.float32)), + torch.as_tensor(rows["dvs24"].to_numpy(dtype=np.float32)), + metadata={"groups": rows["year"].tolist(), "name": rows["name"].tolist(), "basin": rows["basin"].tolist()}, + ) + + return DataBundle( + splits={"train": split(train, train_index), "val": split(train, val_index), "test": split(test)}, + feature_spec=FeatureSpec( + input_dim=len(SHIPS_PREDICTORS), + description="121 standardised SHIPS predictors (Xu et al. 2021).", + extra={"predictors": list(SHIPS_PREDICTORS)}, + ), + label_spec=LabelSpec(num_targets=1, task_type="regression", description="24-hour change of the maximum sustained wind (kt)."), + metadata={ + "dataset": self.name, + "source_dataset": "Xu et al. (2021) SHIPS predictors, Zenodo 4784610", + "hazard_task": "tc.intensity", + "lead_hours": [24], + "units": {"wind": "kt"}, + "intensity_target": "dvs24 (24-hour intensity change)", + "leave_out_year": year, + "source_file": str(self.path), + "synthetic": False, + }, + ) + + +__all__ = ["SHIPSXu2021Dataset", "XU2021_TRAIN_FILE", "read_xu2021_table"] diff --git a/pyhazards/datasets/tc/synthetic.py b/pyhazards/datasets/tc/synthetic.py new file mode 100644 index 00000000..df0ef9ce --- /dev/null +++ b/pyhazards/datasets/tc/synthetic.py @@ -0,0 +1,375 @@ +"""Synthetic tropical cyclone datasets for smoke tests. + +Every dataset here generates random numbers in the input layout of a model; none of them contains +or imitates real storms, and scores on them mean nothing. Real data: ``ibtracs_tracks`` (IBTrACS +best tracks), ``ships_xu2021`` (SHIPS predictors of Xu et al. 2021), ``tropicyclonenet_dataset`` +(TropiCycloneNet Dataset) and ``hurricast_ibtracs_era5`` (IBTrACS statistics and ERA5 maps). +""" + +from __future__ import annotations + +from typing import Dict + +import torch + +from ...models.hurricast import HURRICAST_STAT_FEATURES +from ...models.tropicalcyclone_mlp import SHIPS_PREDICTORS +from ...models.tropicyclonenet import ENV_FEATURES, TCND_NORMALIZATION +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + + +def _split_bounds(samples: int): + train_end = max(1, int(0.7 * samples)) + val_end = max(train_end + 1, int(0.85 * samples)) + return train_end, val_end + + +def _slice(value, start, end, batch_dim: int = 0): + if isinstance(value, dict): + return {key: _slice(item, start, end, batch_dim) for key, item in value.items()} + index = [slice(None)] * value.ndim + index[batch_dim] = slice(start, end) + return value[tuple(index)] + + +class SyntheticTropicalCycloneDataset(Dataset): + """Random "storm histories" ``(samples, history, features)`` and targets ``(samples, horizon, 3)``. + + The targets are the last input step's first three features plus a fixed linear drift; they + are labelled ``lat``, ``lon``, ``wind`` only so that the cyclone evaluator can run. Kept for + smoke tests of the experimental generic storm adapters. + """ + + name = "tc_tracks_synthetic" + + def __init__( + self, + cache_dir: str | None = None, + samples: int = 64, + history: int = 6, + horizon: int = 5, + features: int = 8, + micro: bool = False, + ): + super().__init__(cache_dir=cache_dir) + self.samples = 20 if micro else int(samples) + self.history = int(history) + self.horizon = int(horizon) + self.features = int(features) + if self.features < 3: + raise ValueError("features must be at least 3") + + def _load(self) -> DataBundle: + x = torch.randn(self.samples, self.history, self.features, dtype=torch.float32) + last_state = x[:, -1, :3] + deltas = torch.linspace(0.2, 1.0, steps=self.horizon, dtype=torch.float32).view(1, self.horizon, 1) + direction = torch.tensor([0.4, 0.2, 1.5], dtype=torch.float32).view(1, 1, 3) + y = last_state.unsqueeze(1) + deltas * direction + train_end, val_end = _split_bounds(self.samples) + splits = { + "train": DataSplit(x[:train_end], y[:train_end]), + "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), + "test": DataSplit(x[val_end:], y[val_end:]), + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=self.features, + description="Synthetic random storm-history features (no real storms).", + extra={"history": self.history, "horizon": self.horizon}, + ), + label_spec=LabelSpec(num_targets=3, task_type="regression", description="Synthetic lat / lon / intensity targets."), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "tc.track_intensity", + "lead_hours": [6 * (step + 1) for step in range(self.horizon)], + "target_variables": ["lat", "lon", "wind"], + "units": {"wind": "synthetic"}, + "synthetic": True, + }, + ) + + +class SyntheticSHIPSDataset(Dataset): + """Random inputs in the layout of ``ships_xu2021``: 121 predictors -> 24-hour intensity change (kt).""" + + name = "ships_xu2021_synthetic" + + def __init__(self, cache_dir: str | None = None, samples: int = 64, micro: bool = False): + super().__init__(cache_dir=cache_dir) + self.samples = 24 if micro else int(samples) + + def _load(self) -> DataBundle: + x = torch.randn(self.samples, len(SHIPS_PREDICTORS)) + y = (5.0 * x[:, 0] - 3.0 * x[:, -1] + 2.0 * torch.randn(self.samples)).round() + years = [2017 + (i % 2) for i in range(self.samples)] + train_end, val_end = _split_bounds(self.samples) + splits = { + name: DataSplit(x[a:b], y[a:b], metadata={"groups": years[a:b]}) + for name, (a, b) in {"train": (0, train_end), "val": (train_end, val_end), "test": (val_end, self.samples)}.items() + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec(input_dim=len(SHIPS_PREDICTORS), description="Synthetic standard-normal SHIPS-like predictors."), + label_spec=LabelSpec(num_targets=1, task_type="regression", description="Synthetic 24-hour intensity change (kt)."), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "tc.intensity", + "lead_hours": [24], + "units": {"wind": "kt"}, + "synthetic": True, + }, + ) + + +class SyntheticSAFNetDataset(Dataset): + """Random inputs in the SAF-Net layout: 96 wide predictors and ``(2, 4, 31, 31, 4)`` u/v fields. + + Inputs are uniform in [0, 1] like the MinMax-scaled official inputs; targets are uniform + "24-hour intensities" in m/s, and ``prediction_transform`` maps the model's scaled output back + to m/s with the synthetic target range. + """ + + name = "safnet_cma_era_interim_synthetic" + wind_range = (10.0, 70.0) + + def __init__(self, cache_dir: str | None = None, samples: int = 32, micro: bool = False): + super().__init__(cache_dir=cache_dir) + self.samples = 8 if micro else int(samples) + + def _load(self) -> DataBundle: + wide = torch.rand(self.samples, 96) + deep = torch.rand(self.samples, 2, 4, 31, 31, 4) + low, high = self.wind_range + y = low + (high - low) * torch.rand(self.samples) + years = [2015 + (i % 4) for i in range(self.samples)] + train_end, val_end = _split_bounds(self.samples) + splits = {} + for name, (a, b) in {"train": (0, train_end), "val": (train_end, val_end), "test": (val_end, self.samples)}.items(): + splits[name] = DataSplit({"wide": wide[a:b], "deep": deep[a:b]}, y[a:b], metadata={"groups": years[a:b]}) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=96, + description="Synthetic MinMax-scaled wide predictors and u/v wind cubes (batch, 2, level, 31, 31, time).", + ), + label_spec=LabelSpec(num_targets=1, task_type="regression", description="Synthetic 24-hour maximum sustained wind (m/s)."), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "tc.intensity", + "lead_hours": [24], + "units": {"wind": "m/s"}, + "prediction_transform": {"kind": "minmax", "min": low, "max": high}, + "synthetic": True, + }, + ) + + +def _one_hot(index: torch.Tensor, width: int) -> torch.Tensor: + return torch.nn.functional.one_hot(index.long() % width, width).float() + + +def synthetic_tcnd_batch(samples: int, obs_len: int = 8, pred_len: int = 4, generator: torch.Generator | None = None) -> Dict[str, object]: + """Random TropiCycloneNet inputs and physical targets (lat, lon, pres, wind).""" + g = generator + start = torch.stack( + [torch.rand(samples, generator=g) * 2 - 1, torch.rand(samples, generator=g) * 4 - 2, torch.rand(samples, generator=g), torch.rand(samples, generator=g) - 0.5], + dim=-1, + ) + steps = 0.05 * torch.randn(obs_len + pred_len, samples, 4, generator=g) + steps[0] = 0 + track = start.unsqueeze(0) + torch.cumsum(steps, dim=0) + obs = track[:obs_len] + rel = torch.zeros_like(obs) + rel[1:] = obs[1:] - obs[:-1] + future = track[obs_len:] + physical = torch.stack( + [future[..., 1] * TCND_NORMALIZATION["lat"][0] + TCND_NORMALIZATION["lat"][1], + future[..., 0] * TCND_NORMALIZATION["lon"][0] + TCND_NORMALIZATION["lon"][1], + future[..., 2] * TCND_NORMALIZATION["pres"][0] + TCND_NORMALIZATION["pres"][1], + future[..., 3] * TCND_NORMALIZATION["wind"][0] + TCND_NORMALIZATION["wind"][1]], + dim=-1, + ).permute(1, 0, 2) + env = {} + for key, width in ENV_FEATURES: + if width == 1: + env[key] = torch.rand(samples, obs_len, 1, generator=g) + else: + env[key] = _one_hot(torch.randint(0, width, (samples, obs_len), generator=g), width) + inputs = { + "obs_traj": obs, + "obs_traj_rel": rel, + "image_obs": torch.rand(samples, 1, obs_len, 64, 64, generator=g), + "env_data": env, + } + return {"inputs": inputs, "targets": physical} + + +class SyntheticTCNDDataset(Dataset): + """Random inputs in the TropiCycloneNet (TCND) layout with random-walk targets. + + Inputs are the official generator's: ``obs_traj`` / ``obs_traj_rel`` ``(8, samples, 4)`` + (normalised lon, lat, pressure, wind and their steps), ``image_obs`` ``(samples, 1, 8, 64, 64)`` + and ``env_data`` (nine one-hot or scalar features per step). Targets ``(samples, 4, 4)`` hold + latitude, longitude, pressure (hPa) and wind (m/s) at 6, 12, 18 and 24 h. + """ + + name = "tropicyclonenet_dataset_synthetic" + + def __init__(self, cache_dir: str | None = None, samples: int = 32, micro: bool = False, seed: int = 0): + super().__init__(cache_dir=cache_dir) + self.samples = 6 if micro else int(samples) + self.seed = int(seed) + + def _load(self) -> DataBundle: + generator = torch.Generator().manual_seed(self.seed) + batch = synthetic_tcnd_batch(self.samples, generator=generator) + inputs, targets = batch["inputs"], batch["targets"] + train_end, val_end = _split_bounds(self.samples) + splits = {} + for name, (a, b) in {"train": (0, train_end), "val": (train_end, val_end), "test": (val_end, self.samples)}.items(): + split_inputs = { + "obs_traj": inputs["obs_traj"][:, a:b], + "obs_traj_rel": inputs["obs_traj_rel"][:, a:b], + "image_obs": inputs["image_obs"][a:b], + "env_data": _slice(inputs["env_data"], a, b), + } + splits[name] = DataSplit(split_inputs, targets[a:b]) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec(description="Synthetic TCND-layout inputs (track, GPH frames, Env-Data)."), + label_spec=LabelSpec(num_targets=4, task_type="regression", description="Synthetic lat, lon, pressure and wind at 6-24 h."), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "tc.track_intensity", + "lead_hours": [6, 12, 18, 24], + "target_variables": ["lat", "lon", "pres", "wind"], + "units": {"wind": "m/s", "pres": "hPa"}, + "batch_dims": {"obs_traj": 1, "obs_traj_rel": 1}, + "synthetic": True, + }, + ) + + +class SyntheticHurricastDataset(Dataset): + """Random inputs in the ``hurricast_ibtracs_era5`` layout. + + ``x_stat`` ``(samples, 8, 30)``: standard-normal numerical features, cyclic encodings in [-1, 1], + a category value and one-hot basin / nature columns at the positions of + :data:`pyhazards.models.hurricast.HURRICAST_STAT_FEATURES`; ``x_viz`` ``(samples, 8, 9, 25, 25)`` + standard normal; ``position`` random latitude / longitude. Targets: random 24-hour winds (kt) or + positions ``(samples, 1, 2)`` (``target="displacement"``). + """ + + name = "hurricast_synthetic" + + def __init__(self, cache_dir: str | None = None, samples: int = 24, micro: bool = False, target: str = "intensity", window_size: int = 8, seed: int = 0): + super().__init__(cache_dir=cache_dir) + if target not in ("intensity", "displacement"): + raise ValueError("target must be 'intensity' or 'displacement'") + self.samples = 8 if micro else int(samples) + self.target = target + self.window_size = int(window_size) + self.seed = int(seed) + + def _load(self) -> DataBundle: + g = torch.Generator().manual_seed(self.seed) + n, t = self.samples, self.window_size + names = list(HURRICAST_STAT_FEATURES) + x_stat = torch.randn(n, t, len(names), generator=g) + for j, name in enumerate(names): + if name.startswith(("COS_", "SIN_", "cat_cos", "cat_sign")): + x_stat[..., j] = torch.rand(n, t, generator=g) * 2 - 1 + elif name == "cat_storm_category": + x_stat[..., j] = torch.randint(0, 7, (n, 1), generator=g).float().expand(n, t) + for prefix in ("cat_basin_", "cat_nature_"): + columns = [j for j, name in enumerate(names) if name.startswith(prefix)] + pick = torch.randint(0, len(columns), (n,), generator=g) + x_stat[..., columns] = torch.nn.functional.one_hot(pick, len(columns)).float().unsqueeze(1).expand(n, t, len(columns)) + x_viz = torch.randn(n, t, 9, 25, 25, generator=g) + position = torch.stack([torch.rand(n, generator=g) * 30 + 10, torch.rand(n, generator=g) * 60 - 100], dim=1) + if self.target == "intensity": + y = 30 + 100 * torch.rand(n, generator=g) + else: + y = (position + torch.randn(n, 2, generator=g)).unsqueeze(1) + years = [2016 + (i % 4) for i in range(n)] + train_end, val_end = _split_bounds(n) + splits = {} + for name, (a, b) in {"train": (0, train_end), "val": (train_end, val_end), "test": (val_end, n)}.items(): + splits[name] = DataSplit({"x_stat": x_stat[a:b], "x_viz": x_viz[a:b], "position": position[a:b]}, y[a:b], metadata={"groups": years[a:b]}) + metadata = {"dataset": self.name, "source_dataset": self.name, "lead_hours": [24], "window_size": t, "synthetic": True} + if self.target == "intensity": + metadata.update({"hazard_task": "tc.intensity", "units": {"wind": "kt"}}) + else: + metadata.update({"hazard_task": "tc.track_intensity", "target_variables": ["lat", "lon"], "units": {}}) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec(input_dim=len(names), description="Synthetic Hurricast statistics (8 x 30) and ERA5-like maps (8 x 9 x 25 x 25)."), + label_spec=LabelSpec(num_targets=1 if self.target == "intensity" else 2, task_type="regression", description="Synthetic 24-hour intensity (kt) or position."), + metadata=metadata, + ) + + +class SyntheticTCIFFusionDataset(Dataset): + """Random inputs in the TCIF-fusion layout (channels last): ``u``, ``v``, ``w`` + ``(samples, grid, grid, times, levels)``, ``sst`` ``(samples, grid, grid, times, 1)``, ``all`` + ``(samples, grid, grid, 3 * times * levels + times)``, ``his`` ``(samples, 30)``, ``ir`` + ``(samples, ir_size, ir_size, 5)``; targets uniform 10-70 m/s. The defaults are the paper's sizes; + smoke configs use smaller grids together with a small model. + """ + + name = "tcif_fusion_synthetic" + + def __init__(self, cache_dir: str | None = None, samples: int = 8, micro: bool = False, grid_size: int = 25, time_steps: int = 5, levels: int = 4, his_dim: int = 30, ir_size: int = 224, ir_channels: int = 5, seed: int = 0): + super().__init__(cache_dir=cache_dir) + self.samples = 4 if micro else int(samples) + self.grid_size, self.time_steps, self.levels = int(grid_size), int(time_steps), int(levels) + self.his_dim, self.ir_size, self.ir_channels = int(his_dim), int(ir_size), int(ir_channels) + self.seed = int(seed) + + def _load(self) -> DataBundle: + g = torch.Generator().manual_seed(self.seed) + n, s, t, z = self.samples, self.grid_size, self.time_steps, self.levels + inputs = { + "u": torch.randn(n, s, s, t, z, generator=g), + "v": torch.randn(n, s, s, t, z, generator=g), + "w": torch.randn(n, s, s, t, z, generator=g), + "sst": torch.rand(n, s, s, t, 1, generator=g), + "his": torch.rand(n, self.his_dim, generator=g), + "ir": torch.rand(n, self.ir_size, self.ir_size, self.ir_channels, generator=g), + } + inputs["all"] = torch.cat([inputs[k].reshape(n, s, s, -1) for k in ("u", "v", "w", "sst")], dim=-1) + y = 10 + 60 * torch.rand(n, generator=g) + years = [2020 + (i % 2) for i in range(n)] + train_end, val_end = _split_bounds(n) + splits = { + name: DataSplit({k: v[a:b] for k, v in inputs.items()}, y[a:b], metadata={"groups": years[a:b]}) + for name, (a, b) in {"train": (0, train_end), "val": (train_end, val_end), "test": (val_end, n)}.items() + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec(description="Synthetic TCIF-fusion inputs (ERA5 U, V, W, SST, ALL, history, IR)."), + label_spec=LabelSpec(num_targets=1, task_type="regression", description="Synthetic 24-hour maximum sustained wind (m/s)."), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "tc.intensity", + "lead_hours": [24], + "units": {"wind": "m/s"}, + "synthetic": True, + }, + ) + +__all__ = [ + "SyntheticHurricastDataset", + "SyntheticSAFNetDataset", + "SyntheticSHIPSDataset", + "SyntheticTCIFFusionDataset", + "SyntheticTCNDDataset", + "SyntheticTropicalCycloneDataset", + "synthetic_tcnd_batch", +] diff --git a/pyhazards/datasets/tc/tcnd.py b/pyhazards/datasets/tc/tcnd.py new file mode 100644 index 00000000..bc7bb4d1 --- /dev/null +++ b/pyhazards/datasets/tc/tcnd.py @@ -0,0 +1,215 @@ +"""Reader for the TropiCycloneNet Dataset (TCND) in the layout used to train and test TropiCycloneNet. + +Dataset: Huang et al., "Benchmark dataset and deep learning method for global tropical cyclone +forecasting", Nature Communications 16, 5923 (2025). Releases (CC BY 4.0): the dataset itself +(Zenodo doi:10.5281/zenodo.15009527: ``TCND_Data1D``, ``TCND_Env-Data``, ``TCND_Data3D_``) +and the preprocessed training data of the model (Zenodo record 17104690: ``data1d.zip``, +``env_data.zip``, ``data_3d.zip`` with 500 hPa geopotential crops). PyHazards reads the files the +user downloaded and extracted; it never redistributes them. + +Expected directories (the official test loader's names under one ``root``; each can also be +passed separately): + +* ``BST_data///BST.txt`` (Data1d): tab-separated rows + ``frame, id, lon, lat, pres, wind, YYYYMMDDHH, name`` with the normalised values of + :data:`pyhazards.models.tropicyclonenet.TCND_NORMALIZATION`; +* ``Env_data////.npy``: pickled dicts of the Env-Data features; +* ``ERA5_gph500////.npy``: 500 hPa geopotential crops (100 x 100). + +Samples follow the official ``TrajectoryDataset`` (TCNM/data/trajectoriesWithMe_unet.py) and +``seq_collate``: windows of ``obs_len + pred_len`` consecutive records of a file (stride ``skip``); +``obs_traj`` / ``obs_traj_rel`` hold the observed normalised values and their steps (0 at the first +step); GPH crops are resized to 64 x 64 (bilinear, as ``cv2.resize``), scaled with the range +(44490.578125, 58768.4486860389) and clipped to [0, 1]; Env-Data values of ``-1`` (feature not +available yet, e.g. the 24-hour history at a track's start) are replaced by the first available +value of the same feature in the window. Targets are the future positions (degrees), central +pressure (hPa) and maximum sustained wind (m/s) at 6, 12, 18 and 24 h. +""" + +from __future__ import annotations + +import math +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn.functional as F + +from ...models.tropicyclonenet import ENV_FEATURES, TCND_NORMALIZATION +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +TCND_AREAS = ("EP", "NA", "NI", "SI", "SP", "WP") +GPH_RANGE = (44490.578125, 58768.4486860389) +IMAGE_SIZE = 64 + + +def read_tcnd_track(path: Union[str, Path]) -> Tuple[np.ndarray, List[str], List[str]]: + """Rows of a Data1d file: values ``(n, 6)`` (frame, id, lon, lat, pres, wind), dates, names.""" + values, dates, names = [], [], [] + with Path(path).open("r", encoding="utf-8") as handle: + for line in handle: + fields = line.strip().split("\t") + if len(fields) < 8: + if line.strip(): + raise ValueError(f"{path}: expected 8 tab-separated fields, got {len(fields)}: {line!r}") + continue + values.append([float(field) for field in fields[:-2]]) + dates.append(fields[-2]) + names.append(fields[-1]) + return np.asarray(values, dtype=np.float64).reshape(-1, 6), dates, names + + +def gph_to_image(gph: np.ndarray) -> np.ndarray: + """Resize a GPH crop to 64 x 64 (bilinear, half-pixel centres) and scale it to [0, 1].""" + tensor = torch.as_tensor(np.asarray(gph, dtype=np.float64))[None, None] + resized = F.interpolate(tensor, size=(IMAGE_SIZE, IMAGE_SIZE), mode="bilinear", align_corners=False)[0, 0].numpy() + low, high = GPH_RANGE + return np.clip((resized - low) / (high - low), 0.0, 1.0) + + +def _storm_dir(base: Path, area: str, year: str, name: str) -> Path: + for candidate in (name, name.lower().capitalize(), name.upper()): + path = base / area / year / candidate + if path.exists(): + return path + raise FileNotFoundError(f"no directory for storm {name} ({area} {year}) under {base}") + + +def _missing(value) -> bool: + return type(value) is int and value == -1 + + +def _env_window(env_dir: Path, area: str, year: str, name: str, dates: Sequence[str]) -> Dict[str, np.ndarray]: + storm = _storm_dir(env_dir, area, year, name) + records = [np.load(storm / f"{date}.npy", allow_pickle=True).item() for date in dates] + window: Dict[str, np.ndarray] = {} + for key, width in ENV_FEATURES: + values = [record[key] for record in records] + # The official loader tests ``value is -1``: only Python int -1 marks a missing feature. + available = [value for value in values if not _missing(value)] + if not available: + raise ValueError(f"Env-Data feature {key!r} is -1 at every observed step of {name} {dates[0]}") + filled = [available[0] if _missing(value) else value for value in values] + window[key] = np.asarray(filled, dtype=np.float32).reshape(len(dates), width) + return window + + +class TropiCycloneNetDataset(Dataset): + """TCND samples in the input layout of :class:`pyhazards.models.TropiCycloneNet`. + + ``inputs`` of each split is a dict with ``obs_traj`` and ``obs_traj_rel`` ``(obs_len, N, 4)``, + ``image_obs`` ``(N, 1, obs_len, 64, 64)`` and ``env_data`` (nine arrays ``(N, obs_len, width)``); + ``targets`` is ``(N, pred_len, 4)`` with latitude, longitude, pressure and wind. The whole + split is loaded into memory (about 0.13 MB per sample); use ``areas``, ``splits`` and + ``max_samples`` to limit it. + """ + + name = "tropicyclonenet_dataset" + + def __init__( + self, + root: Optional[Union[str, Path]] = None, + data1d_dir: Optional[Union[str, Path]] = None, + env_dir: Optional[Union[str, Path]] = None, + gph_dir: Optional[Union[str, Path]] = None, + cache_dir: Optional[str] = None, + areas: Sequence[str] = TCND_AREAS, + splits: Sequence[str] = ("train", "val", "test"), + obs_len: int = 8, + pred_len: int = 4, + skip: int = 1, + max_samples: Optional[int] = None, + ): + super().__init__(cache_dir=cache_dir) + base = Path(root) if root is not None else None + resolved = {} + for label, given, default in (("data1d_dir", data1d_dir, "BST_data"), ("env_dir", env_dir, "Env_data"), ("gph_dir", gph_dir, "ERA5_gph500")): + if given is None and base is None: + raise ValueError("tropicyclonenet_dataset needs root= (with BST_data, Env_data, ERA5_gph500) or the three directories") + resolved[label] = Path(given) if given is not None else base / default + if not resolved[label].is_dir(): + raise FileNotFoundError(f"{label} {resolved[label]} does not exist") + self.data1d_dir, self.env_dir, self.gph_dir = resolved["data1d_dir"], resolved["env_dir"], resolved["gph_dir"] + unknown = sorted(set(areas) - set(TCND_AREAS)) + if unknown: + raise ValueError(f"unknown TCND areas {unknown}; choose from {TCND_AREAS}") + self.areas = tuple(areas) + self.splits = tuple(splits) + self.obs_len, self.pred_len, self.skip = int(obs_len), int(pred_len), int(skip) + self.max_samples = max_samples + + def _windows(self, split: str): + seq_len = self.obs_len + self.pred_len + for area in self.areas: + folder = self.data1d_dir / area / split + if not folder.is_dir(): + continue + for path in sorted(folder.glob("*.txt")): + values, dates, names = read_tcnd_track(path) + if len(values) > 1 and not np.all(np.diff(values[:, 0]) > 0): + raise ValueError(f"{path}: frame numbers (first column) must increase") + frames = np.unique(values[:, 0]).tolist() + count = int(math.ceil((len(frames) - seq_len + 1) / self.skip)) + for start in range(0, count * self.skip + 1, self.skip): + rows = values[start : start + seq_len] + if len(rows) != seq_len or len(np.unique(rows[:, 0])) != seq_len: + continue + yield path.stem, area, rows, dates[start : start + seq_len], names[start + self.obs_len - 1] + + def _load_split(self, split: str): + obs, obs_rel, targets, images = [], [], [], [] + env: Dict[str, List[np.ndarray]] = {key: [] for key, _ in ENV_FEATURES} + meta: Dict[str, List[str]] = {"storm": [], "area": [], "origin": []} + for stem, area, rows, dates, name in self._windows(split): + if self.max_samples is not None and len(obs) >= int(self.max_samples): + break + year = stem[2:6] + track = np.round(rows[:, 2:6], 4) # (seq_len, 4): lon, lat, pres, wind (normalised) + rel = np.zeros_like(track) + rel[1:] = track[1:] - track[:-1] + gph_storm = _storm_dir(self.gph_dir, area, year, name) + frames = [gph_to_image(np.load(gph_storm / f"{date}.npy")) for date in dates[: self.obs_len]] + for key, value in _env_window(self.env_dir, area, year, name, dates[: self.obs_len]).items(): + env[key].append(value) + obs.append(track[: self.obs_len]) + obs_rel.append(rel[: self.obs_len]) + future = track[self.obs_len :] + physical = {var: future[:, i] * TCND_NORMALIZATION[var][0] + TCND_NORMALIZATION[var][1] for i, var in enumerate(("lon", "lat", "pres", "wind"))} + targets.append(np.stack([physical["lat"], physical["lon"], physical["pres"], physical["wind"]], axis=-1)) + images.append(np.stack(frames)) + meta["storm"].append(stem) + meta["area"].append(area) + meta["origin"].append(dates[self.obs_len - 1]) + n = len(obs) + inputs = { + "obs_traj": torch.as_tensor(np.asarray(obs, dtype=np.float32).reshape(n, self.obs_len, 4)).permute(1, 0, 2).contiguous(), + "obs_traj_rel": torch.as_tensor(np.asarray(obs_rel, dtype=np.float32).reshape(n, self.obs_len, 4)).permute(1, 0, 2).contiguous(), + "image_obs": torch.as_tensor(np.asarray(images, dtype=np.float32).reshape(n, self.obs_len, IMAGE_SIZE, IMAGE_SIZE)).unsqueeze(1), + "env_data": {key: torch.as_tensor(np.asarray(values, dtype=np.float32).reshape(n, self.obs_len, width)) for (key, width), values in zip(ENV_FEATURES, env.values())}, + } + return DataSplit(inputs, torch.as_tensor(np.asarray(targets, dtype=np.float32).reshape(n, self.pred_len, 4)), metadata=meta) + + def _load(self) -> DataBundle: + splits = {split: self._load_split(split) for split in self.splits} + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + description="TCND Data1d tracks, Env-Data features and 64x64 500 hPa GPH frames (TropiCycloneNet layout).", + extra={"obs_len": self.obs_len, "pred_len": self.pred_len}, + ), + label_spec=LabelSpec(num_targets=4, task_type="regression", description="Latitude, longitude, pressure (hPa) and wind (m/s) at 6-24 h."), + metadata={ + "dataset": self.name, + "source_dataset": "TropiCycloneNet Dataset (TCND)", + "hazard_task": "tc.track_intensity", + "lead_hours": [6 * (step + 1) for step in range(self.pred_len)], + "target_variables": ["lat", "lon", "pres", "wind"], + "units": {"wind": "m/s", "pres": "hPa"}, + "batch_dims": {"obs_traj": 1, "obs_traj_rel": 1}, + "synthetic": False, + }, + ) + + +__all__ = ["GPH_RANGE", "TCND_AREAS", "TropiCycloneNetDataset", "gph_to_image", "read_tcnd_track"] diff --git a/pyhazards/datasets/wildfire/__init__.py b/pyhazards/datasets/wildfire/__init__.py index 7efeb044..d7f11017 100644 --- a/pyhazards/datasets/wildfire/__init__.py +++ b/pyhazards/datasets/wildfire/__init__.py @@ -3,6 +3,7 @@ import torch from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec +from .track_o import WildfireTrackORasterDataset, WildfireTrackOTabularDataset, WildfireTrackOTemporalDataset class SyntheticWildfireSpreadDataset(Dataset): @@ -144,4 +145,92 @@ def _load(self) -> DataBundle: ) -__all__ = ["SyntheticWildfireSpreadDataset", "SyntheticWildfireSpreadTemporalDataset"] +class SyntheticWildfireDangerDataset(Dataset): + """Synthetic next-day fire-danger samples shaped like the Kondylatos et al. (2022) datasets. + + ``access_mode="temporal"`` gives per-cell series ``(samples, history, channels)`` for the LSTM; + ``access_mode="spatiotemporal"`` gives ``(samples, history, channels, patch_size, patch_size)`` + blocks for the ConvLSTM. Labels are ``int64`` (0 = no fire, 1 = fire) with two negatives per + positive, the paper's sampling ratio. Positives get a warmer, drier signal on their first two + channels over the last days so that smoke runs have something to learn; the values are random + and carry no physical meaning. + """ + + name = "wildfire_danger_synthetic" + + def __init__( + self, + cache_dir: str | None = None, + samples: int = 96, + access_mode: str = "temporal", + history: int = 10, + channels: int = 25, + patch_size: int = 25, + micro: bool = False, + seed: int = 7, + ): + super().__init__(cache_dir=cache_dir) + if access_mode not in {"temporal", "spatiotemporal"}: + raise ValueError(f"access_mode must be 'temporal' or 'spatiotemporal', got {access_mode!r}") + if channels < 2: + raise ValueError(f"channels must be at least 2, got {channels}") + self.samples = 24 if micro else int(samples) + self.access_mode = access_mode + self.history = int(history) + self.channels = int(channels) + self.patch_size = int(patch_size) + self.seed = int(seed) + + def _load(self) -> DataBundle: + generator = torch.Generator().manual_seed(self.seed) + positives = max(1, self.samples // 3) + y = torch.zeros(self.samples, dtype=torch.long) + y[:positives] = 1 + y = y[torch.randperm(self.samples, generator=generator)] + + spatial = (self.patch_size, self.patch_size) if self.access_mode == "spatiotemporal" else () + shape = (self.samples, self.history, self.channels, *spatial) + x = torch.randn(*shape, generator=generator) + recent = max(1, self.history // 3) + signal = torch.zeros(self.history, self.channels, *spatial) + signal[-recent:, 0] = 1.5 # e.g. maximum temperature + signal[-recent:, 1] = -1.5 # e.g. minimum relative humidity + x = x + y.view(-1, *([1] * (x.ndim - 1))).float() * signal + + train_end = max(1, int(0.7 * self.samples)) + val_end = max(train_end + 1, int(0.85 * self.samples)) + splits = { + "train": DataSplit(x[:train_end], y[:train_end]), + "val": DataSplit(x[train_end:val_end], y[train_end:val_end]), + "test": DataSplit(x[val_end:], y[val_end:]), + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=self.channels, + channels=self.channels, + description="Synthetic daily dynamic, static and land-cover covariates for fire danger.", + extra={"history": self.history, "access_mode": self.access_mode, "patch_size": self.patch_size}, + ), + label_spec=LabelSpec( + num_targets=2, + task_type="classification", + description="Whether the cell burns on the next day (0 = no fire, 1 = fire).", + ), + metadata={ + "dataset": self.name, + "source_dataset": self.name, + "hazard_task": "wildfire.danger", + "access_mode": self.access_mode, + }, + ) + + +__all__ = [ + "SyntheticWildfireDangerDataset", + "SyntheticWildfireSpreadDataset", + "SyntheticWildfireSpreadTemporalDataset", + "WildfireTrackORasterDataset", + "WildfireTrackOTabularDataset", + "WildfireTrackOTemporalDataset", +] diff --git a/pyhazards/datasets/wildfire/track_o.py b/pyhazards/datasets/wildfire/track_o.py new file mode 100644 index 00000000..95d40eb8 --- /dev/null +++ b/pyhazards/datasets/wildfire/track_o.py @@ -0,0 +1,500 @@ +"""Track-O wildfire occurrence datasets: daily fire / no-fire grids with weather and fuel covariates. + +Track-O ("occurrence") is the real-data wildfire setting of PyHazards PR #33 by runyangxu: on a daily +latitude-longitude grid, predict whether a cell has at least one satellite fire detection on day +``t`` from the weather of day ``t`` (and, for the temporal layout, of the days before it) and a +static fuel layer. The datasets here read a cache written by +:func:`pyhazards.datasets.wildfire.track_o_cache.build_track_o_cache` (CLI: +``scripts/build_wildfire_track_o_cache.py``):: + + / + metadata/lat.npy, lon.npy cell-centre coordinates, both ascending (row 0 = southernmost) + metadata/vars.json {"weather_vars": [...]} + met/.npy (n_weather_vars, n_lat, n_lon) float32 daily means + labels/.npy (n_lat, n_lon) 1.0 where a fire detection fell in the cell + static/fuel.npy, fuel_mask.npy optional fuel-model codes on the grid and their valid mask + splits/{train,val,test}_dates.txt + +Three layouts read the same cache: + +- ``wildfire_track_o_raster``: one day per sample, ``(N, C, H, W)`` -> ``(N, 1, H, W)``; +- ``wildfire_track_o_temporal``: ``history`` consecutive days ending on the target day, + ``(N, history, C, H, W)`` -> ``(N, 1, H, W)``; windows that would span a missing day are skipped; +- ``wildfire_track_o_tabular``: one row per cell and day, ``(N, F)`` -> ``(N,)`` int64 labels. + +Weather channels are standardised with the mean and standard deviation of the training split +(NaN-aware; NaNs, e.g. MERRA-2 land variables over the ocean, become 0 after standardisation). The +fuel layer enters as two channels: the fuel-model code divided by 100 (a numeric stand-in for a +categorical code, kept from PR #33) and the valid-fuel mask. ``downsample_factor`` keeps every +``f``-th row and column of the native grid (a subset of native cells; nothing is averaged), and the +grid is then cropped to a multiple of ``spatial_multiple`` (dropping northern rows and eastern +columns) so that encoder-decoder models can pool it. + +``micro=True`` replaces the cache with a small deterministic synthetic one (random fields, no +physical meaning) for smoke tests and examples. +""" + +from __future__ import annotations + +import json +import math +from datetime import date, timedelta +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Tuple + +import numpy as np +import torch + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec + +SPLIT_NAMES = ("train", "val", "test") + +# The 14 MERRA-2 surface variables PR #33 read from its Prithvi-WxC output files. +DEFAULT_WEATHER_VARS = ( + "T2M", + "QV2M", + "TQV", + "U10M", + "V10M", + "GWETROOT", + "TS", + "LAI", + "EFLUX", + "HFLUX", + "SWGNT", + "SWTNT", + "LWGAB", + "LWGEM", +) + +# PR #33's 2024 split: train January-September, validation October, test November-December. +DEFAULT_SPLITS_2024 = { + "train": ("2024-01-01", "2024-09-30"), + "val": ("2024-10-01", "2024-10-31"), + "test": ("2024-11-01", "2024-12-31"), +} + +STATIC_FEATURE_NAMES = ("fuel_code_div100", "fuel_valid_mask") + + +def _parse_date(text: str) -> date: + return date.fromisoformat(str(text)) + + +def _read_lines(path: Path) -> List[str]: + if not path.exists(): + raise FileNotFoundError(f"Track-O cache is missing the split file {path}.") + return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _limit(dates: Sequence[str], limit: Optional[int]) -> List[str]: + if limit is None or int(limit) <= 0: + return list(dates) + return list(dates[: int(limit)]) + + +class _CacheSource: + """Reads a Track-O cache directory.""" + + def __init__(self, root: Path): + self.root = Path(root) + if not self.root.is_dir(): + raise FileNotFoundError( + f"Track-O cache directory not found: {self.root}. Build one with " + "scripts/build_wildfire_track_o_cache.py, or pass micro=True for synthetic data." + ) + vars_path = self.root / "metadata" / "vars.json" + if not vars_path.exists(): + raise FileNotFoundError(f"{self.root} is not a Track-O cache: {vars_path} is missing.") + self.weather_vars = list(json.loads(vars_path.read_text(encoding="utf-8"))["weather_vars"]) + self.lat = np.asarray(np.load(self.root / "metadata" / "lat.npy"), dtype=np.float64) + self.lon = np.asarray(np.load(self.root / "metadata" / "lon.npy"), dtype=np.float64) + + def split_dates(self) -> Dict[str, List[str]]: + return {name: _read_lines(self.root / "splits" / f"{name}_dates.txt") for name in SPLIT_NAMES} + + def met(self, day: str) -> np.ndarray: + return np.load(self.root / "met" / f"{day}.npy") + + def label(self, day: str) -> np.ndarray: + return np.load(self.root / "labels" / f"{day}.npy") + + def static(self) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]: + fuel_path = self.root / "static" / "fuel.npy" + if not fuel_path.exists(): + return None, None + fuel = np.load(fuel_path) + mask_path = self.root / "static" / "fuel_mask.npy" + mask = np.load(mask_path) if mask_path.exists() else (fuel > 0) + return fuel, mask + + +class _MicroSource: + """Deterministic synthetic stand-in for a cache (random fields; no physical meaning).""" + + weather_vars = ["T2M", "QV2M", "GWETROOT"] + n_lat, n_lon = 64, 96 + n_days = {"train": 24, "val": 8, "test": 8} + + def __init__(self, seed: int = 7): + rng = np.random.default_rng(seed) + self.lat = np.linspace(-79.0, 79.0, self.n_lat) + self.lon = np.linspace(-180.0, 176.25, self.n_lon) + start = date(2024, 1, 1) + days = [str(start + timedelta(days=i)) for i in range(sum(self.n_days.values()))] + train_end = self.n_days["train"] + val_end = train_end + self.n_days["val"] + self._dates = {"train": days[:train_end], "val": days[train_end:val_end], "test": days[val_end:]} + rows = np.linspace(0.0, 1.0, self.n_lat)[:, None] + cols = np.linspace(0.0, 1.0, self.n_lon)[None, :] + self._met: Dict[str, np.ndarray] = {} + self._labels: Dict[str, np.ndarray] = {} + for index, day in enumerate(days): + warm = np.sin(2 * np.pi * (rows + 0.05 * index)) * np.cos(2 * np.pi * cols) * 8.0 + 290.0 + fields = np.stack( + [ + warm + rng.normal(0.0, 1.0, (self.n_lat, self.n_lon)), + 0.01 + 0.002 * rng.standard_normal((self.n_lat, self.n_lon)), + np.clip(0.5 + 0.2 * rng.standard_normal((self.n_lat, self.n_lon)), 0.0, 1.0), + ] + ).astype(np.float32) + fields[2, :, :8] = np.nan # a land-only variable undefined over an "ocean" strip + logit = 0.8 * (fields[0] - 290.0) - 3.0 + self._labels[day] = (rng.random((self.n_lat, self.n_lon)) < 1.0 / (1.0 + np.exp(-logit))).astype( + np.float32 + ) + self._met[day] = fields + self._fuel = np.zeros((self.n_lat, self.n_lon), dtype=np.int16) + self._fuel[16:48, 24:72] = rng.integers(1, 14, size=(32, 48)) + self._fuel_mask = (self._fuel > 0).astype(np.uint8) + + def split_dates(self) -> Dict[str, List[str]]: + return {name: list(days) for name, days in self._dates.items()} + + def met(self, day: str) -> np.ndarray: + return self._met[day] + + def label(self, day: str) -> np.ndarray: + return self._labels[day] + + def static(self) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]: + return self._fuel, self._fuel_mask + + +class _TrackOBase(Dataset): + """Shared loading logic of the three Track-O layouts.""" + + name = "wildfire_track_o_base" + default_downsample = 1 + + def __init__( + self, + cache_dir: Optional[str] = None, + *, + downsample_factor: Optional[int] = None, + spatial_multiple: int = 4, + train_limit_days: Optional[int] = None, + val_limit_days: Optional[int] = None, + test_limit_days: Optional[int] = None, + micro: bool = False, + seed: int = 7, + ): + super().__init__(cache_dir=cache_dir) + if not micro and cache_dir is None: + raise ValueError( + f"{self.name} needs cache_dir (a cache built by scripts/build_wildfire_track_o_cache.py), " + "or micro=True for the synthetic smoke-test data." + ) + factor = self.default_downsample if downsample_factor is None else int(downsample_factor) + if factor < 1: + raise ValueError(f"downsample_factor must be >= 1, got {downsample_factor}") + if int(spatial_multiple) < 1: + raise ValueError(f"spatial_multiple must be >= 1, got {spatial_multiple}") + self.downsample_factor = factor + self.spatial_multiple = int(spatial_multiple) + self.limits = {"train": train_limit_days, "val": val_limit_days, "test": test_limit_days} + self.micro = bool(micro) + self.seed = int(seed) + + # -- source and grid helpers ------------------------------------------------------------- + def _source(self): + if self.micro: + return _MicroSource(seed=self.seed) + return _CacheSource(Path(self.cache_dir)) + + def _split_dates(self, source) -> Dict[str, List[str]]: + dates = source.split_dates() + out = {name: _limit(dates[name], self.limits[name]) for name in SPLIT_NAMES} + for name, days in out.items(): + if not days: + raise ValueError(f"{self.name}: split '{name}' has no dates.") + return out + + def _grid_shape(self, n_lat: int, n_lon: int) -> Tuple[int, int]: + f, m = self.downsample_factor, self.spatial_multiple + h, w = -(-n_lat // f), -(-n_lon // f) + if h < m or w < m: + raise ValueError( + f"{self.name}: the {n_lat} x {n_lon} grid downsampled by {f} is {h} x {w}, smaller than " + f"spatial_multiple={m}; lower downsample_factor or spatial_multiple." + ) + return h - h % m, w - w % m + + def _resample(self, array: np.ndarray, shape: Tuple[int, int]) -> np.ndarray: + f = self.downsample_factor + h, w = shape + if array.ndim == 2: + return np.asarray(array[::f, ::f][:h, :w], dtype=np.float32) + if array.ndim == 3: + return np.asarray(array[:, ::f, ::f][:, :h, :w], dtype=np.float32) + raise ValueError(f"expected a 2-D or 3-D grid array, got shape {array.shape}") + + def _prepare(self): + """Read the source once: per-split standardised weather, labels and the static block.""" + source = self._source() + split_dates = self._split_dates(source) + lat, lon = np.asarray(source.lat), np.asarray(source.lon) + shape = self._grid_shape(lat.size, lon.size) + weather_vars = list(source.weather_vars) + + raw = { + name: {day: self._resample(source.met(day), shape) for day in days} + for name, days in split_dates.items() + } + for name, arrays in raw.items(): + for day, array in arrays.items(): + if array.shape[0] != len(weather_vars): + raise ValueError( + f"{self.name}: met/{day}.npy has {array.shape[0]} channels, " + f"vars.json lists {len(weather_vars)}." + ) + + train_stack = np.stack([raw["train"][day] for day in split_dates["train"]], axis=0).astype(np.float64) + with np.errstate(invalid="ignore"): + mean = np.nanmean(train_stack, axis=(0, 2, 3)) + std = np.nanstd(train_stack, axis=(0, 2, 3)) + mean = np.where(np.isfinite(mean), mean, 0.0) + std = np.where(np.isfinite(std) & (std > 1e-12), std, 1.0) + del train_stack + + met = { + name: { + day: np.nan_to_num( + (array - mean[:, None, None]) / std[:, None, None], nan=0.0, posinf=0.0, neginf=0.0 + ).astype(np.float32) + for day, array in arrays.items() + } + for name, arrays in raw.items() + } + labels = { + name: {day: (self._resample(source.label(day), shape) > 0.5).astype(np.float32) for day in days} + for name, days in split_dates.items() + } + + fuel, fuel_mask = source.static() + static = None + if fuel is not None: + mask = self._resample(np.asarray(fuel_mask, dtype=np.float32), shape) > 0.5 + code = self._resample(np.asarray(fuel, dtype=np.float32), shape) + static = np.stack([np.where(mask, code / 100.0, 0.0), mask.astype(np.float32)]).astype(np.float32) + + grid = { + "lat": np.asarray(lat[:: self.downsample_factor][: shape[0]], dtype=np.float32), + "lon": np.asarray(lon[:: self.downsample_factor][: shape[1]], dtype=np.float32), + } + normalization = {"mean": mean.tolist(), "std": std.tolist(), "fit_split": "train"} + return split_dates, met, labels, static, weather_vars, grid, normalization + + def _metadata(self, weather_vars, grid, normalization, static, splits) -> Dict[str, object]: + return { + "dataset": self.name, + "source_dataset": "micro_synthetic" if self.micro else "track_o_cache", + "hazard_task": "wildfire.danger", + "cache_root": None if self.micro else str(self.cache_dir), + "micro": self.micro, + "weather_vars": list(weather_vars), + "static_feature_names": list(STATIC_FEATURE_NAMES) if static is not None else [], + "has_static_fuel": static is not None, + "downsample_factor": self.downsample_factor, + "lat": grid["lat"].tolist(), + "lon": grid["lon"].tolist(), + "normalization": normalization, + "splits": {name: int(split.inputs.shape[0]) for name, split in splits.items()}, + } + + +class WildfireTrackORasterDataset(_TrackOBase): + """One day per sample: ``(N, C, H, W)`` covariates and ``(N, 1, H, W)`` fire-occurrence masks.""" + + name = "wildfire_track_o_raster" + default_downsample = 4 + + def _load(self) -> DataBundle: + split_dates, met, labels, static, weather_vars, grid, normalization = self._prepare() + splits: Dict[str, DataSplit] = {} + for name, days in split_dates.items(): + frames = [met[name][day] if static is None else np.concatenate([met[name][day], static]) for day in days] + splits[name] = DataSplit( + inputs=torch.from_numpy(np.stack(frames).astype(np.float32)), + targets=torch.from_numpy(np.stack([labels[name][day][None] for day in days])), + metadata={"dates": list(days)}, + ) + shape = splits["train"].inputs.shape + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=int(shape[1]), + description="Standardised daily-mean weather plus fuel channels on the Track-O grid.", + extra={"height": int(shape[2]), "width": int(shape[3]), "weather_vars": weather_vars}, + ), + label_spec=LabelSpec( + num_targets=1, + task_type="segmentation", + description="1 where the cell has at least one fire detection on the same day, else 0.", + ), + metadata=self._metadata(weather_vars, grid, normalization, static, splits), + ) + + +class WildfireTrackOTemporalDataset(_TrackOBase): + """``history`` consecutive days per sample: ``(N, history, C, H, W)`` -> ``(N, 1, H, W)``.""" + + name = "wildfire_track_o_temporal" + default_downsample = 8 + + def __init__(self, cache_dir: Optional[str] = None, *, history: int = 6, **kwargs): + super().__init__(cache_dir=cache_dir, **kwargs) + if int(history) < 1: + raise ValueError(f"history must be >= 1, got {history}") + self.history = int(history) + + def _load(self) -> DataBundle: + split_dates, met, labels, static, weather_vars, grid, normalization = self._prepare() + splits: Dict[str, DataSplit] = {} + for name, days in split_dates.items(): + available = set(days) + frames: Dict[str, np.ndarray] = { + day: met[name][day] if static is None else np.concatenate([met[name][day], static]) for day in days + } + inputs, targets, used = [], [], [] + for day in days: + window = [str(_parse_date(day) - timedelta(days=lag)) for lag in range(self.history - 1, -1, -1)] + if not all(item in available for item in window): + continue # the window would reach before the split start or across a missing day + inputs.append(np.stack([frames[item] for item in window])) + targets.append(labels[name][day][None]) + used.append(day) + if not inputs: + raise ValueError( + f"{self.name}: split '{name}' has no run of {self.history} consecutive days " + f"({len(days)} dates)." + ) + splits[name] = DataSplit( + inputs=torch.from_numpy(np.stack(inputs).astype(np.float32)), + targets=torch.from_numpy(np.stack(targets).astype(np.float32)), + metadata={"dates": used, "history": self.history}, + ) + shape = splits["train"].inputs.shape + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=int(shape[2]), + description="Windows of standardised daily weather plus fuel channels on the Track-O grid.", + extra={ + "history": self.history, + "height": int(shape[3]), + "width": int(shape[4]), + "weather_vars": weather_vars, + }, + ), + label_spec=LabelSpec( + num_targets=1, + task_type="segmentation", + description="Fire-occurrence mask of the last day of each window (1 = at least one detection).", + ), + metadata=self._metadata(weather_vars, grid, normalization, static, splits), + ) + + +def _day_of_year_features(day: str) -> Tuple[float, float]: + parsed = _parse_date(day) + days_in_year = 366 if parsed.year % 4 == 0 and (parsed.year % 100 != 0 or parsed.year % 400 == 0) else 365 + angle = 2.0 * math.pi * (parsed.timetuple().tm_yday - 1) / days_in_year + return math.sin(angle), math.cos(angle) + + +class WildfireTrackOTabularDataset(_TrackOBase): + """One row per grid cell and day: ``(N, F)`` features and ``(N,)`` int64 labels (1 = fire).""" + + name = "wildfire_track_o_tabular" + default_downsample = 8 + + def __init__( + self, + cache_dir: Optional[str] = None, + *, + include_coords: bool = True, + include_day_of_year: bool = True, + **kwargs, + ): + super().__init__(cache_dir=cache_dir, **kwargs) + self.include_coords = bool(include_coords) + self.include_day_of_year = bool(include_day_of_year) + + def _load(self) -> DataBundle: + split_dates, met, labels, static, weather_vars, grid, normalization = self._prepare() + lat_grid, lon_grid = np.meshgrid(grid["lat"], grid["lon"], indexing="ij") + coords = np.stack([lat_grid.ravel(), lon_grid.ravel()], axis=1).astype(np.float64) + coords = ((coords - coords.mean(axis=0)) / (coords.std(axis=0) + 1e-6)).astype(np.float32) + n_cells = coords.shape[0] + static_cols = static.reshape(static.shape[0], -1).T if static is not None else None + + splits: Dict[str, DataSplit] = {} + for name, days in split_dates.items(): + rows, targets = [], [] + for day in days: + blocks = [met[name][day].reshape(met[name][day].shape[0], -1).T] + if self.include_coords: + blocks.append(coords) + if self.include_day_of_year: + blocks.append(np.tile(np.asarray(_day_of_year_features(day), dtype=np.float32), (n_cells, 1))) + if static_cols is not None: + blocks.append(static_cols) + rows.append(np.concatenate(blocks, axis=1)) + targets.append(labels[name][day].reshape(-1)) + splits[name] = DataSplit( + inputs=torch.from_numpy(np.concatenate(rows).astype(np.float32)), + targets=torch.from_numpy(np.concatenate(targets).astype(np.int64)), + metadata={"dates": list(days), "cells_per_day": n_cells}, + ) + + feature_names = list(weather_vars) + if self.include_coords: + feature_names += ["lat", "lon"] + if self.include_day_of_year: + feature_names += ["sin_day_of_year", "cos_day_of_year"] + if static is not None: + feature_names += list(STATIC_FEATURE_NAMES) + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + input_dim=len(feature_names), + description="Per-cell, per-day Track-O features (rows are day-major, cells in row-major order).", + extra={"feature_names": feature_names, "height": int(lat_grid.shape[0]), "width": int(lat_grid.shape[1])}, + ), + label_spec=LabelSpec( + num_targets=2, + task_type="classification", + description="Whether the cell has at least one fire detection that day (0 = no, 1 = yes).", + ), + metadata=self._metadata(weather_vars, grid, normalization, static, splits), + ) + + +__all__ = [ + "DEFAULT_SPLITS_2024", + "DEFAULT_WEATHER_VARS", + "WildfireTrackORasterDataset", + "WildfireTrackOTabularDataset", + "WildfireTrackOTemporalDataset", +] diff --git a/pyhazards/datasets/wildfire/track_o_cache.py b/pyhazards/datasets/wildfire/track_o_cache.py new file mode 100644 index 00000000..2e6b8208 --- /dev/null +++ b/pyhazards/datasets/wildfire/track_o_cache.py @@ -0,0 +1,457 @@ +"""Build a Track-O cache from daily weather NetCDF files, NASA FIRMS CSVs and a LANDFIRE fuel raster. + +Adapted from the cache builder of PyHazards PR #33 by runyangxu +(``pyhazards/benchmarks/wildfire_benchmark/cache_builder.py``), with these changes: + +- weather files: any NetCDF files holding the requested variables on a regular latitude-longitude + grid, with the date read from the file name. Variables may be spread over several files of the + same day (e.g. the MERRA-2 ``tavg1_2d_slv/flx/rad/lnd`` collections) and every non-spatial + dimension (time, a length-1 level) is averaged, so a day of hourly files becomes a daily mean. + PR #33 read the outputs of its own Prithvi-WxC runs (``pred_YYYYMMDD_HH.nc``), which are not + public; the MERRA-2 surface files written by ``python -m pyhazards.datasets.merra2.inspection`` + (``MERRA2_sfc_YYYYMMDD.nc``) hold the same 14 variables; +- the grid is stored south-to-north and west-to-east whatever the order in the files, and every + weather file must share it; +- FIRMS CSVs: the archive / NRT downloads are read with the standard library ``csv`` module and + grouped by their ``acq_date`` column (UTC); a file without that column must be named after its + day. Rows whose FIRMS ``type`` is not in ``firms_types`` (by default only 0, presumed vegetation + fire, which drops volcanoes, other static land sources and offshore detections) are skipped when + the column exists. Detections are snapped to the nearest cell centre; detections more than half a + cell outside the grid are dropped instead of being piled onto the border cells; +- LANDFIRE fuel: reprojected with rasterio (optional extra ``pyhazards[geo]``) onto the cell + edges implied by the grid's cell centres, with mode resampling, and flipped to the cache's + south-to-north row order. PR #33 called ``gdalwarp -te -180 -90 180 90`` and stored the north-up + result unflipped, which on a south-to-north latitude axis such as MERRA-2's puts the fuel layer + upside down (CONUS fuels land at 22-52 degrees south) and shifts it by half a cell. LANDFIRE's + -9999 fill value is excluded from the mode even when the file's nodata tag says 32767; +- days are processed one at a time instead of holding the whole year in memory. +""" + +from __future__ import annotations + +import csv +import json +import re +from datetime import date, timedelta +from pathlib import Path +from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np + +from .track_o import DEFAULT_SPLITS_2024, DEFAULT_WEATHER_VARS, SPLIT_NAMES + +PathLike = Union[str, Path] + +DEFAULT_DATE_PATTERN = r"(? str: + digits = stamp.replace("-", "") + if len(digits) != 8 or not digits.isdigit(): + raise ValueError(f"not a YYYYMMDD / YYYY-MM-DD date: {stamp!r}") + return str(date(int(digits[:4]), int(digits[4:6]), int(digits[6:8]))) + + +def date_from_name(path: PathLike, pattern: str = DEFAULT_DATE_PATTERN) -> Optional[str]: + """ISO date taken from the first group of ``pattern`` in the file name, or ``None``.""" + match = re.search(pattern, Path(path).name) + if not match: + return None + try: + return _to_iso(match.group(1)) + except ValueError: + return None + + +# --------------------------------------------------------------------------------------------- +# Weather +# --------------------------------------------------------------------------------------------- +def _coord_name(ds, candidates: Sequence[str]) -> str: + for name in candidates: + if name in ds.coords or name in ds.variables: + return name + raise KeyError(f"no coordinate among {list(candidates)} in a weather file (have {list(ds.coords)})") + + +def _daily_field(da, lat_name: str, lon_name: str) -> np.ndarray: + """Average every dimension except latitude and longitude and return ``(lat, lon)``.""" + extra = [dim for dim in da.dims if dim not in (lat_name, lon_name)] + if extra: + da = da.mean(dim=extra, skipna=True) + return np.asarray(da.transpose(lat_name, lon_name).values, dtype=np.float64) + + +def read_daily_weather( + paths: Sequence[PathLike], + weather_vars: Sequence[str], +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Daily mean of ``weather_vars`` over ``paths`` (the files of one day). + + Returns ``(fields, lat, lon)`` with ``fields`` of shape ``(len(weather_vars), n_lat, n_lon)`` + (float32), latitude and longitude ascending. A variable found in several files is averaged + over them; a variable missing from all of them raises ``KeyError``. + """ + import xarray as xr + + sums: Dict[str, np.ndarray] = {} + counts: Dict[str, int] = {} + grid: Optional[Tuple[np.ndarray, np.ndarray]] = None + for path in paths: + with xr.open_dataset(path) as ds: + lat_name = _coord_name(ds, ("lat", "latitude")) + lon_name = _coord_name(ds, ("lon", "longitude")) + lat = np.asarray(ds[lat_name].values, dtype=np.float64) + lon = np.asarray(ds[lon_name].values, dtype=np.float64) + lat_order, lon_order = np.argsort(lat), np.argsort(lon) + lat, lon = lat[lat_order], lon[lon_order] + if grid is None: + grid = (lat, lon) + elif not ( + grid[0].shape == lat.shape + and grid[1].shape == lon.shape + and np.allclose(grid[0], lat) + and np.allclose(grid[1], lon) + ): + raise ValueError(f"{path} is on a different latitude-longitude grid than the other files of its day.") + for name in weather_vars: + if name not in ds.data_vars: + continue + field = _daily_field(ds[name], lat_name, lon_name)[np.ix_(lat_order, lon_order)] + sums[name] = sums.get(name, 0.0) + field + counts[name] = counts.get(name, 0) + 1 + missing = [name for name in weather_vars if name not in sums] + if missing: + raise KeyError(f"weather variables {missing} are in none of {[str(p) for p in paths]}") + if grid is None: + raise ValueError("read_daily_weather needs at least one file") + fields = np.stack([sums[name] / counts[name] for name in weather_vars]).astype(np.float32) + return fields, grid[0], grid[1] + + +# --------------------------------------------------------------------------------------------- +# FIRMS labels +# --------------------------------------------------------------------------------------------- +def read_firms_detections( + csv_paths: Iterable[PathLike], + *, + firms_types: Optional[Sequence[int]] = (0,), + date_pattern: str = DEFAULT_DATE_PATTERN, +) -> Tuple[Dict[str, Tuple[np.ndarray, np.ndarray]], Dict[str, int]]: + """Group FIRMS detections by day. + + Returns ``({iso_date: (latitudes, longitudes)}, stats)``. The day comes from ``acq_date`` when + the file has that column, else from the file name. ``firms_types`` keeps rows whose ``type`` + is listed (when the column exists; ``None`` keeps everything). + """ + by_day: Dict[str, Tuple[List[float], List[float]]] = {} + stats = {"files": 0, "rows": 0, "kept": 0, "dropped_type": 0, "files_without_type": 0} + allowed = None if firms_types is None else {int(value) for value in firms_types} + for path in csv_paths: + path = Path(path) + stats["files"] += 1 + with path.open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle) + columns = set(reader.fieldnames or []) + if not {"latitude", "longitude"} <= columns: + raise KeyError(f"FIRMS CSV {path} lacks 'latitude' / 'longitude' columns (has {sorted(columns)}).") + file_day = None + if "acq_date" not in columns: + file_day = date_from_name(path, date_pattern) + if file_day is None: + raise ValueError(f"FIRMS CSV {path} has no acq_date column and no date in its name.") + if "type" not in columns: + stats["files_without_type"] += 1 + for row in reader: + stats["rows"] += 1 + if allowed is not None and "type" in columns and row.get("type", "") != "": + if int(float(row["type"])) not in allowed: + stats["dropped_type"] += 1 + continue + try: + lat, lon = float(row["latitude"]), float(row["longitude"]) + except (TypeError, ValueError): + continue + if not (np.isfinite(lat) and np.isfinite(lon)): + continue + day = file_day or _to_iso(row["acq_date"].strip()) + lats, lons = by_day.setdefault(day, ([], [])) + lats.append(lat) + lons.append(lon) + stats["kept"] += 1 + return {day: (np.asarray(v[0]), np.asarray(v[1])) for day, v in by_day.items()}, stats + + +def _regular_step(values: np.ndarray, name: str) -> float: + steps = np.diff(values) + if values.size < 2 or not np.allclose(steps, steps[0], rtol=1e-4, atol=1e-6) or steps[0] <= 0: + raise ValueError(f"the {name} axis must be regular and ascending") + return float(steps[0]) + + +def rasterize_points( + point_lat: np.ndarray, + point_lon: np.ndarray, + lat: np.ndarray, + lon: np.ndarray, +) -> np.ndarray: + """``(n_lat, n_lon)`` float32 grid with 1.0 in every cell whose centre is nearest to a point. + + ``lat`` and ``lon`` are ascending, regular cell centres. Longitudes are compared modulo 360 + (a grid on 0..360 accepts -180..180 points); a grid that spans the globe wraps around. + Points more than half a cell outside the grid are ignored. + """ + grid = np.zeros((lat.size, lon.size), dtype=np.float32) + point_lat = np.asarray(point_lat, dtype=np.float64) + point_lon = np.asarray(point_lon, dtype=np.float64) + if point_lat.size == 0: + return grid + dlat, dlon = _regular_step(lat, "latitude"), _regular_step(lon, "longitude") + rows = np.rint((point_lat - lat[0]) / dlat).astype(np.int64) + offset = np.mod(point_lon - lon[0] + dlon / 2.0, 360.0) - dlon / 2.0 + cols = np.rint(offset / dlon).astype(np.int64) + if abs(lon.size * dlon - 360.0) < 1e-6: + cols = np.mod(cols, lon.size) + keep = (rows >= 0) & (rows < lat.size) & (cols >= 0) & (cols < lon.size) + grid[rows[keep], cols[keep]] = 1.0 + return grid + + +# --------------------------------------------------------------------------------------------- +# LANDFIRE fuel +# --------------------------------------------------------------------------------------------- +def grid_bounds(lat: np.ndarray, lon: np.ndarray) -> Tuple[float, float, float, float]: + """``(west, south, east, north)`` cell edges of an ascending, regular cell-centre grid.""" + dlat, dlon = _regular_step(lat, "latitude"), _regular_step(lon, "longitude") + return ( + float(lon[0] - dlon / 2.0), + float(lat[0] - dlat / 2.0), + float(lon[-1] + dlon / 2.0), + float(lat[-1] + dlat / 2.0), + ) + + +def _import_rasterio(): + try: + import rasterio + from rasterio.warp import Resampling, reproject + except ImportError as exc: + raise ImportError( + "Aligning a LANDFIRE fuel raster needs the optional rasterio package: pip install 'pyhazards[geo]'." + ) from exc + return rasterio, reproject, Resampling + + +def align_fuel_to_grid( + raster_path: PathLike, + lat: np.ndarray, + lon: np.ndarray, + *, + src_nodata: Optional[float] = LANDFIRE_NODATA, + invalid_codes: Sequence[int] = LANDFIRE_INVALID_CODES, + num_threads: int = 4, +) -> Tuple[np.ndarray, np.ndarray]: + """Mode-resample a categorical fuel raster onto the cache grid. + + ``lat`` / ``lon`` are the ascending cell centres of the cache. Returns ``(fuel, mask)`` as + ``(n_lat, n_lon)`` int32 codes (0 where invalid) and uint8 validity, rows south-to-north. + Source pixels equal to ``src_nodata`` (LANDFIRE's -9999 by default; ``None`` uses the raster's + nodata tag) are left out of the mode. A cell whose mode is negative or in ``invalid_codes`` is + marked invalid. Only the cells overlapping the raster's footprint are warped (a CONUS raster on + a global grid). + """ + rasterio, reproject, Resampling = _import_rasterio() + from rasterio.transform import from_origin + from rasterio.warp import transform_bounds + + dlat, dlon = _regular_step(lat, "latitude"), _regular_step(lon, "longitude") + fuel = np.full((lat.size, lon.size), FUEL_NODATA_OUT, dtype=np.int32) + with rasterio.open(raster_path) as src: + nodata = src.nodata if src_nodata is None else src_nodata + left, bottom, right, top = transform_bounds(src.crs, "EPSG:4326", *src.bounds, densify_pts=21) + rows = np.flatnonzero((lat + dlat / 2.0 > bottom) & (lat - dlat / 2.0 < top)) + cols = np.flatnonzero((lon + dlon / 2.0 > left) & (lon - dlon / 2.0 < right)) + if left > right: # footprint crosses the antimeridian: warp every column + cols = np.arange(lon.size) + if rows.size and cols.size: + r0, r1, c0, c1 = rows[0], rows[-1] + 1, cols[0], cols[-1] + 1 + window = np.full((r1 - r0, c1 - c0), FUEL_NODATA_OUT, dtype=np.int32) + reproject( + source=rasterio.band(src, 1), + destination=window, + src_nodata=nodata, + # north-up rows: the window's top edge is the northern edge of its last cache row + dst_transform=from_origin(lon[c0] - dlon / 2.0, lat[r1 - 1] + dlat / 2.0, dlon, dlat), + dst_crs="EPSG:4326", + dst_nodata=FUEL_NODATA_OUT, + resampling=Resampling.mode, + num_threads=int(num_threads), + ) + fuel[r0:r1, c0:c1] = window[::-1] # north-up rows -> the cache's south-to-north rows + mask = (fuel >= 0) & ~np.isin(fuel, np.asarray(list(invalid_codes), dtype=np.int64)) + return np.where(mask, fuel, 0).astype(np.int32), mask.astype(np.uint8) + + +# --------------------------------------------------------------------------------------------- +# Cache +# --------------------------------------------------------------------------------------------- +def _date_range(start: str, end: str) -> List[str]: + first, last = date.fromisoformat(str(start)), date.fromisoformat(str(end)) + return [str(first + timedelta(days=offset)) for offset in range((last - first).days + 1)] + + +def build_track_o_cache( + cache_dir: PathLike, + weather_files: Sequence[PathLike], + firms_files: Sequence[PathLike], + *, + weather_vars: Sequence[str] = DEFAULT_WEATHER_VARS, + splits: Mapping[str, Sequence[str]] = DEFAULT_SPLITS_2024, + weather_date_pattern: str = DEFAULT_DATE_PATTERN, + firms_types: Optional[Sequence[int]] = (0,), + fuel_raster: Optional[PathLike] = None, + fuel_nodata: Optional[float] = LANDFIRE_NODATA, + limit_days: int = 0, +) -> Dict[str, object]: + """Write a Track-O cache (layout in :mod:`pyhazards.datasets.wildfire.track_o`) and return a summary. + + A day inside the split ranges is written when it has weather files and FIRMS coverage: a CSV + named after the day, or a date between the first and last detection of the CSVs (archive + downloads span many days). A covered day without detections gets an all-zero label. + ``fuel_raster`` adds the static fuel layer (needs ``pyhazards[geo]``); it can also be added + later with :func:`add_fuel_to_cache`. + """ + for name in SPLIT_NAMES: + if name not in splits: + raise ValueError(f"splits must define {SPLIT_NAMES}, missing '{name}'") + wanted = {day: name for name in SPLIT_NAMES for day in _date_range(*splits[name])} + if len(wanted) != sum(len(_date_range(*splits[name])) for name in SPLIT_NAMES): + raise ValueError("split date ranges overlap") + + weather_by_day: Dict[str, List[Path]] = {} + for path in sorted(Path(p) for p in weather_files): + day = date_from_name(path, weather_date_pattern) + if day is not None and day in wanted: + weather_by_day.setdefault(day, []).append(path) + + firms_paths = sorted(Path(p) for p in firms_files) + detections, firms_stats = read_firms_detections(firms_paths, firms_types=firms_types) + per_day_files = {date_from_name(path) for path in firms_paths} + covered = set(detections) | {day for day in per_day_files if day is not None} + if detections: + # acq_date-grouped downloads: every day between the first and last detection is covered. + covered |= set(_date_range(min(detections), max(detections))) + + days = sorted(day for day in weather_by_day if day in covered) + if limit_days > 0: + days = days[: int(limit_days)] + if not days: + raise ValueError("no day has both weather files and FIRMS coverage inside the split ranges") + + root = Path(cache_dir) + for sub in ("met", "labels", "static", "metadata", "splits"): + (root / sub).mkdir(parents=True, exist_ok=True) + + lat = lon = None + positives = 0 + for day in days: + fields, day_lat, day_lon = read_daily_weather(weather_by_day[day], weather_vars) + if lat is None: + lat, lon = day_lat, day_lon + _regular_step(lat, "latitude") + _regular_step(lon, "longitude") + elif not (day_lat.shape == lat.shape and day_lon.shape == lon.shape and np.allclose(day_lat, lat) and np.allclose(day_lon, lon)): + raise ValueError(f"weather files of {day} are on a different grid than {days[0]}") + point_lat, point_lon = detections.get(day, (np.empty(0), np.empty(0))) + label = rasterize_points(point_lat, point_lon, lat, lon) + positives += int(label.sum()) + np.save(root / "met" / f"{day}.npy", fields) + np.save(root / "labels" / f"{day}.npy", label) + + np.save(root / "metadata" / "lat.npy", lat.astype(np.float32)) + np.save(root / "metadata" / "lon.npy", lon.astype(np.float32)) + (root / "metadata" / "vars.json").write_text(json.dumps({"weather_vars": list(weather_vars)}, indent=2), encoding="utf-8") + west, south, east, north = grid_bounds(lat, lon) + (root / "metadata" / "grid.json").write_text( + json.dumps( + { + "n_lat": int(lat.size), + "n_lon": int(lon.size), + "cell_centres": {"lat": [float(lat[0]), float(lat[-1])], "lon": [float(lon[0]), float(lon[-1])]}, + "bounds": {"west": west, "south": south, "east": east, "north": north}, + "row_order": "south_to_north", + }, + indent=2, + ), + encoding="utf-8", + ) + + split_counts = {} + for name in SPLIT_NAMES: + split_days = [day for day in days if wanted[day] == name] + (root / "splits" / f"{name}_dates.txt").write_text("\n".join(split_days), encoding="utf-8") + split_counts[name] = len(split_days) + + summary: Dict[str, object] = { + "cache_dir": str(root), + "weather_vars": list(weather_vars), + "days": len(days), + "first_day": days[0], + "last_day": days[-1], + "splits": split_counts, + "label_positive_cells": positives, + "label_positive_fraction": positives / float(len(days) * lat.size * lon.size), + "firms": firms_stats, + "firms_types_kept": None if firms_types is None else [int(v) for v in firms_types], + "static_fuel": None, + } + (root / "cache_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") + if fuel_raster is not None: + summary["static_fuel"] = add_fuel_to_cache(root, fuel_raster, src_nodata=fuel_nodata) + return summary + + +def add_fuel_to_cache( + cache_dir: PathLike, + fuel_raster: PathLike, + *, + src_nodata: Optional[float] = LANDFIRE_NODATA, +) -> Dict[str, object]: + """Align ``fuel_raster`` to an existing cache's grid and write ``static/fuel.npy`` and ``fuel_mask.npy``.""" + root = Path(cache_dir) + lat = np.load(root / "metadata" / "lat.npy").astype(np.float64) + lon = np.load(root / "metadata" / "lon.npy").astype(np.float64) + fuel, mask = align_fuel_to_grid(fuel_raster, lat, lon, src_nodata=src_nodata) + (root / "static").mkdir(parents=True, exist_ok=True) + np.save(root / "static" / "fuel.npy", fuel) + np.save(root / "static" / "fuel_mask.npy", mask) + info: Dict[str, object] = { + "source": str(fuel_raster), + "resampling": "mode", + "valid_cells": int(mask.sum()), + "valid_fraction": float(mask.mean()), + "codes": sorted(int(code) for code in np.unique(fuel[mask > 0])), + } + summary_path = root / "cache_summary.json" + if summary_path.exists(): + summary = json.loads(summary_path.read_text(encoding="utf-8")) + summary["static_fuel"] = info + summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8") + return info + + +__all__ = [ + "DEFAULT_DATE_PATTERN", + "add_fuel_to_cache", + "align_fuel_to_grid", + "build_track_o_cache", + "date_from_name", + "grid_bounds", + "rasterize_points", + "read_daily_weather", + "read_firms_detections", +] diff --git a/pyhazards/datasets/wrf_sfire/__init__.py b/pyhazards/datasets/wrf_sfire/__init__.py new file mode 100644 index 00000000..c53c9def --- /dev/null +++ b/pyhazards/datasets/wrf_sfire/__init__.py @@ -0,0 +1,17 @@ +"""WRF-SFIRE outputs: read fire-grid fields from ``wrfout`` files written by the official model.""" + +from .dataset import WRFSFireSpreadDataset +from .reader import ( + DEFAULT_VARIABLES, + WRF_SFIRE_FIRE_GRID_VARIABLES, + WRFSFireFireGrid, + read_wrf_sfire_fire_grid, +) + +__all__ = [ + "DEFAULT_VARIABLES", + "WRF_SFIRE_FIRE_GRID_VARIABLES", + "WRFSFireFireGrid", + "WRFSFireSpreadDataset", + "read_wrf_sfire_fire_grid", +] diff --git a/pyhazards/datasets/wrf_sfire/dataset.py b/pyhazards/datasets/wrf_sfire/dataset.py new file mode 100644 index 00000000..a8d0ae37 --- /dev/null +++ b/pyhazards/datasets/wrf_sfire/dataset.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import os +from typing import Optional, Sequence, Union + +import torch + +from ..base import DataBundle, DataSplit, Dataset, FeatureSpec, LabelSpec +from .reader import read_wrf_sfire_fire_grid + + +class WRFSFireSpreadDataset(Dataset): + """Next-step fire-spread samples cut from the outputs of a WRF-SFIRE run. + + Each sample pairs the burned mask (``LFN < 0``) at output frame ``t`` plus the requested fire-grid + ``features`` at ``t`` with the burned mask at frame ``t + horizon``. Splits are chronological. + There is no synthetic fallback: ``paths`` must point at real ``wrfout`` files produced by the + official WRF-SFIRE (https://github.com/openwfm/WRF-SFIRE), which PyHazards does not run. + """ + + name = "wrf_sfire_spread" + + def __init__( + self, + paths: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]], None] = None, + cache_dir: Optional[str] = None, + horizon: int = 1, + features: Sequence[str] = (), + origin: str = "upper", + train_fraction: float = 0.7, + val_fraction: float = 0.15, + ): + super().__init__(cache_dir=cache_dir) + if paths is None: + raise ValueError( + "wrf_sfire_spread reads WRF-SFIRE wrfout files: pass paths='run/wrfout_d01_*' " + "(PyHazards does not run WRF-SFIRE or ship its outputs)." + ) + if not (0.0 < train_fraction < 1.0 and 0.0 <= val_fraction < 1.0 and train_fraction + val_fraction < 1.0): + raise ValueError("need 0 < train_fraction, 0 <= val_fraction and train_fraction + val_fraction < 1") + self.paths = paths + self.horizon = int(horizon) + self.features = tuple(features) + self.origin = origin + self.train_fraction = float(train_fraction) + self.val_fraction = float(val_fraction) + + def _load(self) -> DataBundle: + variables = ("LFN", "TIGN_G", *self.features) + grid = read_wrf_sfire_fire_grid(self.paths, variables=variables, origin=self.origin) + inputs, targets, times = grid.spread_pairs(horizon=self.horizon, features=self.features) + x = torch.from_numpy(inputs) + y = torch.from_numpy(targets) + n = x.shape[0] + train_end = max(1, int(round(self.train_fraction * n))) + val_end = min(n, train_end + int(round(self.val_fraction * n))) + splits = { + "train": DataSplit(x[:train_end], y[:train_end], metadata={"times_s": times[:train_end]}), + "val": DataSplit(x[train_end:val_end], y[train_end:val_end], metadata={"times_s": times[train_end:val_end]}), + "test": DataSplit(x[val_end:], y[val_end:], metadata={"times_s": times[val_end:]}), + } + return DataBundle( + splits=splits, + feature_spec=FeatureSpec( + channels=int(x.shape[1]), + description="WRF-SFIRE burned mask (LFN < 0) at frame t, then the requested fire-grid fields.", + extra={"channels": ["burned_mask", *self.features], "fire_dx_m": grid.fire_dx, "fire_dy_m": grid.fire_dy}, + ), + label_spec=LabelSpec( + num_targets=1, + task_type="segmentation", + description=f"WRF-SFIRE burned mask {self.horizon} output frame(s) later.", + ), + metadata={ + "dataset": self.name, + "source_dataset": "WRF-SFIRE outputs", + "hazard_task": "wildfire.spread", + "files": grid.source_files, + "horizon_frames": self.horizon, + "origin": self.origin, + "sr_x": grid.sr_x, + "sr_y": grid.sr_y, + }, + ) + + +__all__ = ["WRFSFireSpreadDataset"] diff --git a/pyhazards/datasets/wrf_sfire/inspection.py b/pyhazards/datasets/wrf_sfire/inspection.py new file mode 100644 index 00000000..2991f4fb --- /dev/null +++ b/pyhazards/datasets/wrf_sfire/inspection.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +import argparse + +import numpy as np + +from .reader import read_wrf_sfire_fire_grid + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m pyhazards.datasets.wrf_sfire.inspection", + description="Summarise the fire grid of WRF-SFIRE wrfout files (burned area and arrival times).", + ) + parser.add_argument("--path", nargs="+", default=None, help="wrfout file(s) or glob pattern(s) of one domain.") + parser.add_argument("--max-frames", type=int, default=10, help="Number of output frames to list.") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + if not args.path: + print("[INFO] WRF-SFIRE output inspection is callable; pass --path run/wrfout_d01_* to read files.") + print("[INFO] Model: https://github.com/openwfm/WRF-SFIRE") + return 0 + try: + grid = read_wrf_sfire_fire_grid(args.path, variables=("TIGN_G", "LFN"), origin="lower") + except (FileNotFoundError, KeyError, ValueError) as exc: + print(f"[ERROR] {exc}") + return 2 + rows, cols = grid.shape + print(f"[OK] files: {len(grid.source_files)} | frames: {len(grid.times)}") + print(f"[OK] fire grid: {rows} x {cols} cells of {grid.fire_dx:g} x {grid.fire_dy:g} m (sr_x={grid.sr_x}, sr_y={grid.sr_y})") + cell_area = grid.fire_dx * grid.fire_dy + masks = grid.burned_masks() + for index in range(min(args.max_frames, len(grid.times))): + label = grid.time_strings[index] if grid.time_strings else f"t={grid.times[index]:g} s" + print(f" {label}: burned area {masks[index].sum() * cell_area:.0f} m^2") + arrival = grid.arrival_time() + burned = np.isfinite(arrival) + if burned.any(): + print(f"[OK] arrival time (TIGN_G) over burned cells: {arrival[burned].min():g} .. {arrival[burned].max():g} s") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyhazards/datasets/wrf_sfire/reader.py b/pyhazards/datasets/wrf_sfire/reader.py new file mode 100644 index 00000000..9552324e --- /dev/null +++ b/pyhazards/datasets/wrf_sfire/reader.py @@ -0,0 +1,279 @@ +"""Read WRF-SFIRE fire-grid outputs (``wrfout`` history files) into PyHazards spread rasters. + +WRF-SFIRE couples the WRF atmosphere model with the SFIRE level-set fire-spread model: + +- Mandel, Beezley, Kochanski, "Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE + 2011", Geoscientific Model Development 4:591-610 (2011), doi:10.5194/gmd-4-591-2011. +- Mandel, Amram, Beezley, Kelman, Kochanski, Kondratenko, Lynn, Regev, Vejmelka, "Recent advances + and applications of WRF-SFIRE", Natural Hazards and Earth System Sciences 14:2829-2845 (2014), + doi:10.5194/nhess-14-2829-2014. +- Official code: https://github.com/openwfm/WRF-SFIRE (Fortran, WRF public-domain notice), release + ``W4.4-S0.1``. + +PyHazards does not run WRF-SFIRE (an MPI Fortran model built per machine) and reimplements none of +it. This module only reads the NetCDF files that a WRF-SFIRE run writes. The layout it assumes was +taken from the official sources, not guessed: + +- Variable names, descriptions and units: ``Registry/registry.fire`` at ``W4.4-S0.1`` (package + ``fire_sfire1``, ``ifire = 1``); every variable read here has ``h`` (history output) in its I/O + column. +- Fire-grid ("subgrid") variables have dimensions ``(Time, south_north_subgrid, west_east_subgrid)``. + WRF sizes the fire mesh from the staggered atmospheric dimensions, so it holds + ``(south_north + 1) * sr_y`` by ``(west_east + 1) * sr_x`` points, and the last ``sr_y`` rows and + ``sr_x`` columns are padding. ``sr_x``/``sr_y`` (namelist ``&domains``) are read from global + attributes when present, otherwise from the dimension sizes; the same rules are used by the + OpenWFM post-processing tools (wrfxpy, MIT: ``src/clamp2mesh.py:get_subgrid_coordinates`` and + ``src/vis/var_wisdom.py:strip_end``). +- ``TIGN_G`` is the fire arrival ("ignition") time in seconds since the simulation start. In cells + that are not burning SFIRE stores a time one fire step in the future (``prop_ls`` in + ``phys/module_fr_sfire_core.F``), so ``TIGN_G`` is only an arrival time where the cell has burned. +- ``LFN`` is the level-set function; the fire region is ``LFN < 0``. +- ``XTIME`` is minutes since the simulation start; the fire-mesh spacing is ``DX / sr_x`` by + ``DY / sr_y`` metres. + +Checked on a real history file of the official ideal case ``test/em_fire/hill`` (WRF-SFIRE +``W4.4-S0.1`` built locally): its header is recorded in +``tests/fixtures/wrf_sfire_hill_wrfout_header.json``. In that file the subgrid is 420 x 420 for a +41 x 41 atmospheric grid with ``sr = 10`` (no ``sr_x``/``sr_y`` attributes), ``TIGN_G`` is the frame +time plus one fire step (0.25 s) wherever ``LFN >= 0``, and ``LFN < 0`` coincides with +``TIGN_G <= frame time`` in every frame. +""" + +from __future__ import annotations + +import glob +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union + +import numpy as np + +# name -> (description, units), from Registry/registry.fire (WRF-SFIRE W4.4-S0.1, package fire_sfire1). +WRF_SFIRE_FIRE_GRID_VARIABLES: Dict[str, Tuple[str, str]] = { + "TIGN_G": ("ignition time on ground", "s"), + "LFN": ("level function", "1"), + "FIRE_AREA": ("fraction of cell area on fire", "1"), + "FUEL_FRAC": ("fuel remaining", "1"), + "FGRNHFX": ("heat flux from ground fire", "W/m^2"), + "FGRNQFX": ("moisture flux from ground fire", "W/m^2"), + "FCANHFX": ("heat flux from crown fire", "W/m^2"), + "ROS": ("rate of spread", "m/s"), + "F_ROS": ("max spread rate in any direction", "m/s"), + "F_INT": ("fire reaction intensity for risk rating, without fire", "J/m^2/s"), + "FLINEINT": ("fireline intensity", "W/m"), + "NFUEL_CAT": ("fuel data", "-"), + "ZSF": ("height of surface above sea level", "m"), + "FMC_G": ("ground fuel moisture contents", "1"), + "UF": ("fire wind", "m/s"), + "VF": ("fire wind", "m/s"), + "FXLONG": ("longitude of midpoints of fire cells", "degrees"), + "FXLAT": ("latitude of midpoints of fire cells", "degrees"), +} + +DEFAULT_VARIABLES: Tuple[str, ...] = ("TIGN_G", "LFN", "FIRE_AREA", "FGRNHFX", "ROS") +SUBGRID_DIMS = ("south_north_subgrid", "west_east_subgrid") +_ORIGINS = ("upper", "lower") + +PathLike = Union[str, os.PathLike] + + +def _expand_paths(paths: Union[PathLike, Sequence[PathLike]]) -> List[Path]: + items = [paths] if isinstance(paths, (str, os.PathLike)) else list(paths) + found: List[Path] = [] + for item in items: + text = os.fspath(item) + pattern = any(char in text for char in "*?[") + matches = sorted(glob.glob(os.path.expanduser(text))) if pattern else [os.path.expanduser(text)] + if not matches: + raise FileNotFoundError(f"no WRF-SFIRE output matches {text!r}") + for match in matches: + path = Path(match) + if not path.is_file(): + raise FileNotFoundError(f"WRF-SFIRE output not found: {path}") + found.append(path) + if not found: + raise ValueError("give at least one wrfout path") + return found + + +def _time_strings(ds) -> List[str]: + if "Times" not in ds.variables: + return [] + raw = np.asarray(ds["Times"].values) + if raw.dtype.kind == "S" and raw.ndim == 2: # undecoded (Time, DateStrLen) characters + raw = np.array([b"".join(row) for row in raw]) + return [item.decode() if isinstance(item, bytes) else str(item) for item in raw.reshape(-1)] + + +def _refinement(ds) -> Tuple[int, int]: + attrs = ds.attrs + if "sr_x" in attrs and "sr_y" in attrs and int(attrs["sr_x"]) > 0 and int(attrs["sr_y"]) > 0: + return int(attrs["sr_x"]), int(attrs["sr_y"]) + for name in ("west_east", "south_north", *SUBGRID_DIMS): + if name not in ds.sizes: + raise ValueError(f"wrfout file has no {name!r} dimension and no sr_x/sr_y attributes") + srx, rx = divmod(ds.sizes["west_east_subgrid"], ds.sizes["west_east"] + 1) + sry, ry = divmod(ds.sizes["south_north_subgrid"], ds.sizes["south_north"] + 1) + if rx or ry or srx < 1 or sry < 1: + raise ValueError( + "fire subgrid dimensions are not multiples of the staggered atmospheric dimensions: " + f"{dict(ds.sizes)}" + ) + return srx, sry + + +@dataclass +class WRFSFireFireGrid: + """Fire-grid fields of one WRF-SFIRE run, padding removed. + + ``variables[name]`` has shape ``(time, rows, cols)``; with ``origin="upper"`` (default) row 0 is the + northern edge, with ``origin="lower"`` it is the southern edge (WRF's own order). ``times`` are + seconds since the simulation start. + """ + + times: np.ndarray + variables: Dict[str, np.ndarray] + fire_dx: float + fire_dy: float + sr_x: int + sr_y: int + origin: str = "upper" + time_strings: List[str] = field(default_factory=list) + source_files: List[str] = field(default_factory=list) + + @property + def shape(self) -> Tuple[int, int]: + first = next(iter(self.variables.values())) + return int(first.shape[1]), int(first.shape[2]) + + def burned_masks(self) -> np.ndarray: + """``(time, rows, cols)`` boolean fire region: ``LFN < 0``, else ``TIGN_G <= frame time``.""" + if "LFN" in self.variables: + return self.variables["LFN"] < 0 + if "TIGN_G" in self.variables: + tign = self.variables["TIGN_G"] + # Before the fire model has run (t = 0) the file can hold zeros; nothing has burned yet. + return (tign <= self.times[:, None, None]) & (self.times[:, None, None] > 0) + raise KeyError("burned masks need LFN or TIGN_G; read them with variables=(..., 'LFN', 'TIGN_G')") + + def arrival_time(self, frame: int = -1) -> np.ndarray: + """``TIGN_G`` (s since simulation start) where the cell has burned by ``frame``, ``inf`` elsewhere.""" + if "TIGN_G" not in self.variables: + raise KeyError("arrival_time needs TIGN_G; read it with variables=(..., 'TIGN_G')") + burned = self.burned_masks()[frame] + return np.where(burned, self.variables["TIGN_G"][frame].astype(np.float64), np.inf) + + def spread_pairs( + self, + horizon: int = 1, + features: Sequence[str] = (), + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Next-mask pairs for the ``wildfire.spread`` task. + + Returns ``inputs`` ``(N, 1 + len(features), rows, cols)`` (burned mask at frame ``t``, then the + requested fields at ``t``), ``targets`` ``(N, 1, rows, cols)`` (burned mask at ``t + horizon``) + and the input frame times ``(N,)``, all ``float32`` except the times. + """ + if horizon < 1: + raise ValueError(f"horizon must be >= 1 output frames, got {horizon}") + missing = [name for name in features if name not in self.variables] + if missing: + raise KeyError(f"features {missing} were not read; available: {sorted(self.variables)}") + masks = self.burned_masks().astype(np.float32) + steps = masks.shape[0] - horizon + if steps < 1: + raise ValueError(f"need more than {horizon} output frames to build spread pairs, got {masks.shape[0]}") + channels = [masks[:steps, None]] + [self.variables[name][:steps, None].astype(np.float32) for name in features] + inputs = np.concatenate(channels, axis=1) + targets = masks[horizon:, None] + return inputs, targets, self.times[:steps].copy() + + +def read_wrf_sfire_fire_grid( + paths: Union[PathLike, Sequence[PathLike]], + variables: Iterable[str] = DEFAULT_VARIABLES, + origin: str = "upper", + strip_padding: bool = True, +) -> WRFSFireFireGrid: + """Read fire-grid variables from one or more ``wrfout`` files of one WRF-SFIRE domain. + + Args: + paths: a file, a glob pattern (e.g. ``"run/wrfout_d01_*"``) or a list of them. Frames from all + files are concatenated and sorted by ``XTIME``. + variables: fire-grid variable names (see :data:`WRF_SFIRE_FIRE_GRID_VARIABLES`); any other + variable on the fire subgrid is accepted too. + origin: ``"upper"`` (row 0 = north, PyHazards / GeoTIFF order) or ``"lower"`` (WRF order). + strip_padding: drop the ``sr_y`` padding rows and ``sr_x`` padding columns (default). + """ + import xarray as xr + + if origin not in _ORIGINS: + raise ValueError(f"origin must be 'upper' or 'lower', got {origin!r}") + names = list(dict.fromkeys(variables)) + if not names: + raise ValueError("give at least one fire-grid variable to read") + files = _expand_paths(paths) + + times: List[np.ndarray] = [] + strings: List[str] = [] + fields: Dict[str, List[np.ndarray]] = {name: [] for name in names} + geometry: Optional[Tuple[int, int, float, float, Tuple[int, int]]] = None + for path in files: + with xr.open_dataset(path, decode_times=False, mask_and_scale=False) as ds: + if "XTIME" not in ds.variables: + raise ValueError(f"{path} has no XTIME variable; is it a WRF history (wrfout) file?") + srx, sry = _refinement(ds) + for key in ("DX", "DY"): + if key not in ds.attrs: + raise ValueError(f"{path} has no {key} global attribute") + dx, dy = float(ds.attrs["DX"]) / srx, float(ds.attrs["DY"]) / sry + sub_shape = (int(ds.sizes.get(SUBGRID_DIMS[0], 0)), int(ds.sizes.get(SUBGRID_DIMS[1], 0))) + current = (srx, sry, dx, dy, sub_shape) + if geometry is None: + geometry = current + elif geometry != current: + raise ValueError(f"{path} has a different fire grid ({current}) than earlier files ({geometry})") + for name in names: + if name not in ds.variables: + available = sorted(v for v in ds.variables if ds[v].dims[-2:] == SUBGRID_DIMS) + raise KeyError(f"{name!r} is not in {path}; fire-grid variables in the file: {available}") + var = ds[name] + if var.dims != ("Time", *SUBGRID_DIMS): + raise ValueError( + f"{name} has dimensions {var.dims}, expected ('Time', {SUBGRID_DIMS[0]!r}, " + f"{SUBGRID_DIMS[1]!r}); only fire-grid variables are read here" + ) + values = np.asarray(var.values, dtype=np.float32) + if strip_padding: + values = values[:, :-sry, :-srx] + fields[name].append(values) + times.append(np.asarray(ds["XTIME"].values, dtype=np.float64).reshape(-1) * 60.0) + strings.extend(_time_strings(ds)) + + assert geometry is not None + seconds = np.concatenate(times) + order = np.argsort(seconds, kind="stable") + arrays = {name: np.concatenate(parts, axis=0)[order] for name, parts in fields.items()} + if origin == "upper": + arrays = {name: np.ascontiguousarray(values[:, ::-1, :]) for name, values in arrays.items()} + srx, sry, dx, dy, _ = geometry + return WRFSFireFireGrid( + times=seconds[order], + variables=arrays, + fire_dx=dx, + fire_dy=dy, + sr_x=srx, + sr_y=sry, + origin=origin, + time_strings=[strings[i] for i in order] if len(strings) == len(seconds) else [], + source_files=[str(path) for path in files], + ) + + +__all__ = [ + "DEFAULT_VARIABLES", + "WRF_SFIRE_FIRE_GRID_VARIABLES", + "WRFSFireFireGrid", + "read_wrf_sfire_fire_grid", +] diff --git a/pyhazards/engine/trainer.py b/pyhazards/engine/trainer.py index 5c4944d1..e4901149 100644 --- a/pyhazards/engine/trainer.py +++ b/pyhazards/engine/trainer.py @@ -53,7 +53,16 @@ def fit( """ Minimal fit loop that works for tensor-based splits. Extend/replace with custom DataLoaders for complex data. + + Models that are not trained as one network by gradient descent declare a + ``custom_fit_reason`` (scikit-learn estimator wrappers such as ``random_forest`` and + ``xgboost``, and ``deep_ensemble``, whose members train independently); ``fit`` raises + ``TypeError`` with that reason instead of running a loop that would not train them. + ``evaluate`` and ``predict`` work for them. """ + custom_fit_reason = getattr(self.model, "custom_fit_reason", None) + if custom_fit_reason: + raise TypeError(f"Trainer.fit cannot train this model: {custom_fit_reason}") if optimizer is None or loss_fn is None: raise ValueError("optimizer and loss_fn must be provided.") diff --git a/pyhazards/forecasts/__init__.py b/pyhazards/forecasts/__init__.py new file mode 100644 index 00000000..29d3b278 --- /dev/null +++ b/pyhazards/forecasts/__init__.py @@ -0,0 +1,115 @@ +"""Tropical cyclone tracks from global ML weather models: forecast sources, trackers and scoring. + +FourCastNet, GraphCast and Pangu-Weather are global weather models (36-75M parameters, 0.25-degree +global fields). Their cyclone results come from running a tracker on their forecast fields and +comparing the tracks with best tracks; they are not cyclone models and are not reimplemented here. +This package is the honest PyHazards integration of that pipeline: + +forecast fields + :mod:`.tcbench` reads TCBench's released Pangu-Weather / FourCastNet v2 / AIFS fields (slices over + HTTP) and their tracks; :mod:`.weatherbench2` reads WeatherBench 2's GraphCast and Pangu-Weather + forecasts; :mod:`.earth2studio_runner` runs the models through NVIDIA earth2studio, which the user + installs (weights downloaded by earth2studio, under their own licences). +trackers + :mod:`.tempest` - TempestExtremes DetectNodes / StitchNodes rules (TCBench's tracker), checked + against the official binaries and TCBench's released tracks; :mod:`.following` - the ECMWF-style + tracker described in the Pangu-Weather and GraphCast papers (no official code exists). +matching and scoring + :mod:`.matching` assigns IBTrACS storm IDs (HuracanPy's rule, as in TCBench); :mod:`.scoring` + reports great-circle track error (km) and intensity errors (kt, hPa) per lead time against IBTrACS, + optionally exactly as TCBench's evaluation computes them. + +See :data:`.catalog.FOUNDATION_MODELS` for licences, parameter counts and each paper's protocol. +Nothing here is a ``torch.nn.Module`` or appears in the model registry. +""" + +from .catalog import FOUNDATION_MODELS, FoundationModel +from .fields import EARTH_RADIUS_KM, TRACKER_VARIABLES, great_circle_km, relative_vorticity, standardize_fields +from .following import ( + ECMWF_TRACKER, + GRAPHCAST_TRACKER, + PANGU_TRACKER, + FollowingTrackerConfig, + follow_cyclone, + required_variables, +) +from .matching import match_tracks, matched_forecast_tracks +from .pipeline import follow_forecast_tracks, storms_at, tempest_forecast_tracks +from .scoring import KT_PER_MS, TCBENCH_KT_PER_MS, forecast_track_errors, score_forecast_tracks, tcbench_position_error_km +from .tcbench import ( + TCBENCH_MODELS, + TCBENCH_REVISION, + download_tcbench_file, + read_tcbench_fields, + read_tcbench_matched_tracks, + read_tcbench_unmatched_tracks, + tcbench_ibtracs, + tcbench_path, +) +from .tempest import ( + TCBENCH_DETECT_NODES, + TCBENCH_STITCH_NODES, + ClosedContourCriterion, + DetectNodesConfig, + NodeOutput, + StitchNodesConfig, + StitchThreshold, + detect_nodes, + read_stitchnodes_csv, + stitch_nodes, + tempest_tracks, + write_stitchnodes_csv, +) +from .weatherbench2 import WEATHERBENCH2_FORECASTS, read_weatherbench2_forecast +from .earth2studio_runner import EARTH2STUDIO_MODELS, load_earth2studio_model, run_earth2studio_forecast + +__all__ = [ + "ClosedContourCriterion", + "DetectNodesConfig", + "EARTH2STUDIO_MODELS", + "EARTH_RADIUS_KM", + "ECMWF_TRACKER", + "FOUNDATION_MODELS", + "FollowingTrackerConfig", + "FoundationModel", + "GRAPHCAST_TRACKER", + "KT_PER_MS", + "NodeOutput", + "PANGU_TRACKER", + "StitchNodesConfig", + "StitchThreshold", + "TCBENCH_DETECT_NODES", + "TCBENCH_KT_PER_MS", + "TCBENCH_MODELS", + "TCBENCH_REVISION", + "TCBENCH_STITCH_NODES", + "TRACKER_VARIABLES", + "WEATHERBENCH2_FORECASTS", + "detect_nodes", + "download_tcbench_file", + "follow_cyclone", + "follow_forecast_tracks", + "forecast_track_errors", + "great_circle_km", + "load_earth2studio_model", + "match_tracks", + "matched_forecast_tracks", + "read_stitchnodes_csv", + "read_tcbench_fields", + "read_tcbench_matched_tracks", + "read_tcbench_unmatched_tracks", + "read_weatherbench2_forecast", + "relative_vorticity", + "required_variables", + "run_earth2studio_forecast", + "score_forecast_tracks", + "standardize_fields", + "stitch_nodes", + "storms_at", + "tcbench_ibtracs", + "tcbench_path", + "tcbench_position_error_km", + "tempest_forecast_tracks", + "tempest_tracks", + "write_stitchnodes_csv", +] diff --git a/pyhazards/forecasts/catalog.py b/pyhazards/forecasts/catalog.py new file mode 100644 index 00000000..97f8ac7a --- /dev/null +++ b/pyhazards/forecasts/catalog.py @@ -0,0 +1,95 @@ +"""What PyHazards offers for each global ML weather model whose cyclone skill is cited in Appendix A. + +These models are not reimplemented in PyHazards and are not in the model registry: their cyclone +results come from running a tracker on their forecast fields and scoring the tracks against best +tracks. Each entry lists the paper, the official code and weights with their licences, how the paper +evaluated cyclones, and the PyHazards routes (published forecasts or tracks that can be read, runners, +trackers). Parameter counts were measured on the official code or checkpoints during the PyHazards +audit (``notes/inventory_other/inventory_tc.json`` in the project repository). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, Tuple + +__all__ = ["FOUNDATION_MODELS", "FoundationModel"] + + +@dataclass(frozen=True) +class FoundationModel: + name: str + paper: str + paper_url: str + code_url: str + code_license: str + weights: str + weights_license: str + parameters: str + paper_tc_evaluation: str + sources: Tuple[str, ...] + runner: str + tracker: str + notes: Tuple[str, ...] = field(default_factory=tuple) + + +FOUNDATION_MODELS: Dict[str, FoundationModel] = { + "fourcastnet": FoundationModel( + name="FourCastNet", + paper="Pathak et al., FourCastNet: A Global Data-driven High-resolution Weather Model using Adaptive Fourier Neural Operators, arXiv:2202.11214 (2022)", + paper_url="https://arxiv.org/abs/2202.11214", + code_url="https://github.com/NVlabs/FourCastNet", + code_license="BSD-3-Clause", + weights="NERSC FCN_weights_v0 (20 variables); earth2studio FCN = HF nvidia/fourcastnet1 (26-variable retrain)", + weights_license="v0: not stated (do not redistribute); nvidia/fourcastnet1: Apache-2.0 (model card)", + parameters="74,691,840 (20-channel AFNO backbone, official networks/afnonet.py)", + paper_tc_evaluation="Qualitative only: Hurricane Michael (2018) ensemble, eye = MSLP minimum (Sec. 3.1).", + sources=( + "TCBench 2023 tracks and fields of FourCastNet v2 (SFNO small), a different model: pyhazards.forecasts.tcbench (model='fourcastnet_v2')", + ), + runner="earth2studio FCN (26-variable AFNO) or SFNO: pyhazards.forecasts.earth2studio_runner", + tracker="TempestExtremes rules (TCBench) or the ECMWF-style follower; the paper used no aggregate tracker.", + notes=("No public archive of FourCastNet (v1) forecasts was found; WeatherBench 2 does not host it.",), + ), + "graphcast": FoundationModel( + name="GraphCast", + paper="Lam et al., Learning skillful medium-range global weather forecasting, Science 382(6677):1416-1421 (2023), doi:10.1126/science.adi2336", + paper_url="https://doi.org/10.1126/science.adi2336", + code_url="https://github.com/google-deepmind/weathernext", + code_license="Apache-2.0", + weights="gs://dm_graphcast (GraphCast 0.25 deg / 37 levels, GraphCast_operational, GraphCast_small)", + weights_license="CC BY 4.0 per the repository README since 2026-08-06; the checkpoint metadata still says CC BY-NC-SA 4.0", + parameters="36,348,131 used by the model code (36,464,582 arrays in the checkpoint); the paper states 36.7M", + paper_tc_evaluation=( + "Supplement 8.1: modified ECMWF tracker (not released) on 06/18 UTC forecasts, IBTrACS 2018-2021, " + "homogeneous sample with HRES (TIGGE), median and mean geodesic track error to 5 days; numbers only in figures." + ), + sources=( + "WeatherBench 2 GraphCast forecasts (2018 from the 1979-2017 model, 2020; 00/12 UTC, ERA5 initial conditions): pyhazards.forecasts.weatherbench2", + ), + runner="earth2studio GraphCastOperational / GraphCastSmall (JAX): pyhazards.forecasts.earth2studio_runner", + tracker="pyhazards.forecasts.following.GRAPHCAST_TRACKER (re-implemented from the supplement's description)", + notes=("GenCast is a different model (Price et al., Nature 2025) and is not covered here.",), + ), + "pangu_weather": FoundationModel( + name="Pangu-Weather", + paper="Bi et al., Accurate medium-range global weather forecasting with 3D neural networks, Nature 619:533-538 (2023), doi:10.1038/s41586-023-06185-3; technical report arXiv:2211.02556", + paper_url="https://doi.org/10.1038/s41586-023-06185-3", + code_url="https://github.com/198808xc/Pangu-Weather", + code_license="none (no LICENSE file; only ONNX inference scripts and pseudocode are released)", + weights="pangu_weather_1/3/6/24.onnx (about 1.1 GB each)", + weights_license="CC BY-NC-SA 4.0: commercial use forbidden", + parameters="about 64.2M learnable per lead-time model (derived from the 24 h ONNX graph; ~256M for the four models)", + paper_tc_evaluation=( + "arXiv:2211.02556 Sec. 4.2.2: ECMWF-style tracker (MSLP minimum, 445 / 278 km rules) on deterministic " + "forecasts of 88 named 2018 cyclones (TC2018); mean direct position error 120.29 km at 3 days and 195.65 km at 5 days " + "(ECMWF-HRES 162.28 / 272.10 km)." + ), + sources=( + "TCBench 2023 Pangu-Weather tracks and raw fields: pyhazards.forecasts.tcbench (model='pangu')", + "WeatherBench 2 Pangu-Weather forecasts 2018-2022 (ERA5 and HRES initial conditions): pyhazards.forecasts.weatherbench2", + ), + runner="earth2studio Pangu6 / Pangu24 (official ONNX graphs): pyhazards.forecasts.earth2studio_runner", + tracker="pyhazards.forecasts.following.PANGU_TRACKER (paper's rules) or the TempestExtremes rules (TCBench)", + ), +} diff --git a/pyhazards/forecasts/earth2studio_runner.py b/pyhazards/forecasts/earth2studio_runner.py new file mode 100644 index 00000000..74d19d25 --- /dev/null +++ b/pyhazards/forecasts/earth2studio_runner.py @@ -0,0 +1,152 @@ +"""Optional runner: produce forecast fields with NVIDIA earth2studio, then track them with PyHazards. + +earth2studio (https://github.com/NVIDIA/earth2studio, Apache-2.0) wraps the official FourCastNet, +SFNO (FourCastNet v2), Pangu-Weather and GraphCast checkpoints behind one prognostic-model interface. +PyHazards does not install it or any weights: install it yourself (Python >= 3.11; checked with +0.19.0) together with the extra each model needs (see the earth2studio documentation), and accept the +weights' licences. Weights are downloaded by earth2studio when a model is loaded: + +========================= ====================================== ============================================= +``model`` earth2studio class weights and licence (as stated by the providers) +========================= ====================================== ============================================= +``fourcastnet`` ``earth2studio.models.px.FCN`` 26-variable AFNO retrain of FourCastNet (HF + ``nvidia/fourcastnet1``, model card: Apache-2.0); + not the 20-variable checkpoint of Pathak et al. +``fourcastnet_v2`` ``earth2studio.models.px.SFNO`` SFNO ``sfno_73ch_small`` (NGC; the model TCBench + calls FourCastNet v2) +``pangu_6`` / ``pangu_24`` ``earth2studio.models.px.Pangu6/24`` official ONNX graphs, CC BY-NC-SA 4.0: + non-commercial use only +``graphcast_operational`` ``earth2studio.models.px.GraphCastOperational`` DeepMind checkpoint (needs JAX); the +``graphcast_small`` ``earth2studio.models.px.GraphCastSmall`` repository README states CC BY 4.0 since + 2026-08-06, the checkpoint metadata + still says CC BY-NC-SA 4.0 +========================= ====================================== ============================================= + +:func:`run_earth2studio_forecast` follows ``earth2studio.run.deterministic``: fetch the initial state +from a data source, iterate the prognostic model and keep the variables a tracker needs, renamed to +the PyHazards conventions (:mod:`pyhazards.forecasts.fields`). Global 0.25-degree models need a GPU +with about 40 GB of memory (earth2studio's badges). +""" + +from __future__ import annotations + +import importlib +from typing import Dict, Optional, Sequence + +import numpy as np + +__all__ = [ + "EARTH2STUDIO_MODELS", + "EARTH2STUDIO_VARIABLES", + "load_earth2studio_model", + "run_earth2studio_forecast", +] + +EARTH2STUDIO_MODELS: Dict[str, str] = { + "fourcastnet": "FCN", + "fourcastnet_v2": "SFNO", + "pangu_3": "Pangu3", + "pangu_6": "Pangu6", + "pangu_24": "Pangu24", + "graphcast_operational": "GraphCastOperational", + "graphcast_small": "GraphCastSmall", +} + +EARTH2STUDIO_VARIABLES: Dict[str, str] = {"u10": "u10m", "v10": "v10m", "t2m": "t2m", "msl": "msl"} +"""PyHazards name -> earth2studio name where they differ (pressure levels: ``u850`` in both).""" + + +def _earth2studio(): + try: + return importlib.import_module("earth2studio") + except ImportError as exc: + raise ImportError( + "run_earth2studio_forecast needs NVIDIA earth2studio, which PyHazards does not install. " + "Install it yourself (pip install earth2studio, plus the model's extra; Python >= 3.11)." + ) from exc + + +def load_earth2studio_model(model: str, device: Optional[str] = None): + """Load an earth2studio prognostic model with its default (downloaded) checkpoint.""" + if model not in EARTH2STUDIO_MODELS: + raise ValueError(f"unknown model {model!r}; choose from {sorted(EARTH2STUDIO_MODELS)}") + _earth2studio() + px = importlib.import_module("earth2studio.models.px") + cls = getattr(px, EARTH2STUDIO_MODELS[model]) + prognostic = cls.load_model(cls.load_default_package()) + return prognostic.to(device) if device is not None else prognostic + + +def run_earth2studio_forecast( + prognostic, + data, + init_time, + lead_hours: int = 120, + variables: Sequence[str] = ("msl", "u10", "v10", "z300", "z500"), + device: Optional[str] = None, +): + """Run ``prognostic`` from ``init_time`` and return the tracker fields as an ``xarray.Dataset``. + + ``prognostic`` is an earth2studio prognostic model (or a name from :data:`EARTH2STUDIO_MODELS`, + loaded with :func:`load_earth2studio_model`); ``data`` an earth2studio data source (e.g. + ``earth2studio.data.ARCO()`` for ERA5, ``GFS()``, ``WB2ERA5()``). The model's own time step sets + the output times, from the initial state (lead 0) to ``lead_hours``. + """ + import pandas as pd + import torch + import xarray as xr + + _earth2studio() + from earth2studio.data import fetch_data + + if isinstance(prognostic, str): + prognostic = load_earth2studio_model(prognostic, device) + device = torch.device(device) if device is not None else torch.device("cpu") + prognostic = prognostic.to(device) + wanted = [EARTH2STUDIO_VARIABLES.get(name, name) for name in variables] + input_coords = prognostic.input_coords() + output_variables = list(prognostic.output_coords(input_coords)["variable"]) + missing = [name for name, e2s in zip(variables, wanted) if e2s not in output_variables] + if missing: + raise KeyError(f"the model does not predict {missing} (earth2studio names {output_variables})") + init = pd.Timestamp(init_time) + x, coords = fetch_data( + source=data, + time=np.array([init.to_datetime64()]), + variable=input_coords["variable"], + lead_time=input_coords["lead_time"], + device=device, + ) + frames, valid_times = [], [] + lat = lon = None + with torch.inference_mode(): + for state, state_coords in prognostic.create_iterator(x, coords): + names = list(state_coords["variable"]) + axis = list(state_coords).index("variable") + index = torch.as_tensor([names.index(v) for v in wanted], device=state.device) + selected = torch.index_select(state, axis, index).detach().cpu().numpy() + keys = list(state_coords) + # Reduce the batch / time / lead_time axes (size 1 for a deterministic single run). + for name in [k for k in keys if k not in ("variable", "lat", "lon")]: + position = keys.index(name) + selected = np.take(selected, -1, axis=position) + keys.pop(position) + selected = np.moveaxis(selected, keys.index("variable"), 0) + lead = np.asarray(state_coords["lead_time"]).ravel()[-1] + hours = float(lead / np.timedelta64(1, "h")) + if hours > lead_hours + 1e-9: + break + frames.append(selected.astype(np.float32)) + valid_times.append(init + pd.Timedelta(hours=hours)) + lat, lon = np.asarray(state_coords["lat"]), np.asarray(state_coords["lon"]) + if hours >= lead_hours - 1e-9: + break + if not frames: + raise RuntimeError("the model produced no output") + stacked = np.stack(frames, axis=1) # (variable, time, lat, lon) + ds = xr.Dataset( + {name: (("time", "lat", "lon"), stacked[k]) for k, name in enumerate(variables)}, + coords={"time": valid_times, "lat": lat.astype(np.float64), "lon": lon.astype(np.float64)}, + ) + ds.attrs.update({"source": f"earth2studio:{type(prognostic).__name__}", "init_time": str(init)}) + return ds diff --git a/pyhazards/forecasts/fields.py b/pyhazards/forecasts/fields.py new file mode 100644 index 00000000..598baedd --- /dev/null +++ b/pyhazards/forecasts/fields.py @@ -0,0 +1,176 @@ +"""Forecast-field conventions shared by the cyclone trackers and the forecast sources. + +Trackers take an ``xarray.Dataset`` with dimensions ``(time, lat, lon)`` (``time`` = valid times, +``lat`` / ``lon`` in degrees, any orientation; longitudes are treated as periodic when they cover the +globe) and variables with these canonical names and SI units: + +======================== ============================================= ========== +name quantity unit +======================== ============================================= ========== +``msl`` mean sea-level pressure Pa +``u10``, ``v10`` 10 m wind components m s-1 +``u

``, ``v

`` wind components at ``p`` hPa (e.g. ``u850``) m s-1 +``z

`` geopotential at ``p`` hPa (e.g. ``z500``) m2 s-2 +``t

`` temperature at ``p`` hPa K +``lsm`` land-sea mask (1 = land), optional, static 1 +======================== ============================================= ========== + +:func:`standardize_fields` renames the variable names used by WeatherBench 2, earth2studio, ECMWF +``ai-models`` / TCBench outputs and ERA5 to these names and splits pressure-level variables. +""" + +from __future__ import annotations + +import math +from typing import Dict, Iterable, Mapping, Optional, Sequence + +import numpy as np + +__all__ = [ + "EARTH_RADIUS_KM", + "SURFACE_ALIASES", + "LEVEL_ALIASES", + "TRACKER_VARIABLES", + "great_circle_km", + "relative_vorticity", + "standardize_fields", +] + +EARTH_RADIUS_KM = 6371.0 +"""Sphere radius used for track distances (the PyHazards cyclone benchmark and TCBench use 6371 km).""" + +SURFACE_ALIASES: Dict[str, str] = { + # WeatherBench 2 / ERA5 long names + "mean_sea_level_pressure": "msl", + "10m_u_component_of_wind": "u10", + "10m_v_component_of_wind": "v10", + "land_sea_mask": "lsm", + # earth2studio + "u10m": "u10", + "v10m": "v10", + # CF / ECMWF short names + "MSL": "msl", + "u10": "u10", + "v10": "v10", + "msl": "msl", + "lsm": "lsm", +} + +LEVEL_ALIASES: Dict[str, str] = { + "u_component_of_wind": "u", + "v_component_of_wind": "v", + "geopotential": "z", + "temperature": "t", + "u": "u", + "v": "v", + "z": "z", + "t": "t", +} + +TRACKER_VARIABLES = { + "tempest": ("msl", "u10", "v10", "z300", "z500"), + "pangu": ("msl", "u10", "v10", "u850", "v850", "z200", "z850"), + "graphcast": ("msl", "u10", "v10", "u200", "v200", "u500", "v500", "u700", "v700", "u850", "v850", "z200", "z850"), +} +"""Fields each tracker reads (``tempest`` = the TCBench TempestExtremes configuration).""" + + +def great_circle_km(lat1, lon1, lat2, lon2, radius_km: float = EARTH_RADIUS_KM) -> np.ndarray: + """Haversine distance in km between points in degrees (numpy, broadcasting).""" + lat1, lon1, lat2, lon2 = (np.deg2rad(np.asarray(v, dtype=np.float64)) for v in (lat1, lon1, lat2, lon2)) + h = np.sin((lat2 - lat1) / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2 + return 2 * radius_km * np.arcsin(np.sqrt(np.clip(h, 0.0, 1.0))) + + +def relative_vorticity(u: np.ndarray, v: np.ndarray, lat: Sequence[float], lon: Sequence[float], periodic: Optional[bool] = None) -> np.ndarray: + """Relative vorticity (s-1) of ``(..., lat, lon)`` winds on a regular lat-lon grid. + + zeta = (dv/dlambda) / (a cos phi) - (du/dphi) / a + u tan(phi) / a with second-order centred + differences (one-sided at the edges), a = 6371 km. Longitudes are periodic when they span the + globe (or when ``periodic=True``). Values at the poles are set to NaN. + """ + u = np.asarray(u, dtype=np.float64) + v = np.asarray(v, dtype=np.float64) + lat = np.asarray(lat, dtype=np.float64) + lon = np.asarray(lon, dtype=np.float64) + if u.shape != v.shape or u.shape[-2:] != (lat.size, lon.size): + raise ValueError(f"u and v must be shaped (..., {lat.size}, {lon.size}), got {u.shape} and {v.shape}") + a = EARTH_RADIUS_KM * 1000.0 + phi = np.deg2rad(lat)[:, None] + lam = np.deg2rad(lon) + if periodic is None: + step = np.median(np.abs(np.diff(lon))) if lon.size > 1 else 0.0 + periodic = lon.size > 2 and abs(lon.size * step - 360.0) < 1e-6 + if periodic: + dlam = np.deg2rad(np.median(np.diff(lon))) + dv_dlam = (np.roll(v, -1, axis=-1) - np.roll(v, 1, axis=-1)) / (2 * dlam) + else: + dv_dlam = np.gradient(v, lam, axis=-1) + du_dphi = np.gradient(u, np.deg2rad(lat), axis=-2) + with np.errstate(divide="ignore", invalid="ignore"): + zeta = dv_dlam / (a * np.cos(phi)) - du_dphi / a + u * np.tan(phi) / a + poles = np.isclose(np.abs(lat), 90.0) + zeta[..., poles, :] = np.nan + return zeta + + +def _level_name(prefix: str, level) -> str: + value = float(level) + if value.is_integer(): + value = int(value) + return f"{prefix}{value}" + + +def standardize_fields( + dataset, + variables: Optional[Iterable[str]] = None, + rename: Optional[Mapping[str, str]] = None, + time_dim: Optional[str] = None, +): + """Return an ``xarray.Dataset`` in the tracker conventions (see the module docstring). + + Accepts WeatherBench 2 (``latitude`` / ``longitude``, ``mean_sea_level_pressure``, + ``u_component_of_wind`` with a ``level`` dimension), earth2studio (``u10m``, ``u850``) and ECMWF / + TCBench short names (``msl``, ``u10``, ``z`` with ``level``). ``rename`` adds explicit + source-to-canonical mappings, ``variables`` keeps only the listed canonical variables and + ``time_dim`` names the valid-time dimension when it is not ``time`` / ``valid_time``. + """ + import xarray as xr + + ds = dataset + coord_names = {"latitude": "lat", "longitude": "lon"} + ds = ds.rename({k: v for k, v in coord_names.items() if k in ds.dims or k in ds.coords}) + if time_dim is not None and time_dim != "time": + ds = ds.rename({time_dim: "time"}) + elif "time" not in ds.dims and "valid_time" in ds.dims: + ds = ds.rename({"valid_time": "time"}) + if "lat" not in ds.dims or "lon" not in ds.dims: + raise ValueError(f"dataset needs lat/lon (or latitude/longitude) dimensions, has {dict(ds.sizes)}") + explicit = dict(rename or {}) + wanted = set(variables) if variables is not None else None + out: Dict[str, "xr.DataArray"] = {} + for name, array in ds.data_vars.items(): + if name in explicit: + out[explicit[name]] = array + continue + level_dim = next((d for d in ("level", "pressure_level", "isobaricInhPa", "plev") if d in array.dims), None) + if level_dim is not None and name in LEVEL_ALIASES: + prefix = LEVEL_ALIASES[name] + levels = array[level_dim].values + if level_dim == "plev" and np.nanmax(levels) > 2000: # Pa + levels = levels / 100.0 + for k, level in enumerate(levels): + key = _level_name(prefix, level) + if wanted is None or key in wanted: + out[key] = array.isel({level_dim: k}).drop_vars(level_dim, errors="ignore") + continue + key = SURFACE_ALIASES.get(name, name) + out[key] = array + if wanted is not None: + missing = sorted(wanted - set(out)) + if missing: + raise KeyError(f"dataset lacks variables {missing} (found {sorted(out)})") + out = {k: out[k] for k in sorted(wanted)} + result = xr.Dataset(out) + order = [d for d in ("time", "lat", "lon") if d in result.dims] + return result.transpose(*order, ...) diff --git a/pyhazards/forecasts/following.py b/pyhazards/forecasts/following.py new file mode 100644 index 00000000..48b7cb7d --- /dev/null +++ b/pyhazards/forecasts/following.py @@ -0,0 +1,380 @@ +"""ECMWF-style "following" cyclone tracker, as described in the Pangu-Weather and GraphCast papers. + +Both papers track a known cyclone through a deterministic forecast, starting from its observed +position at the initial time, with the rules of ECMWF's tracker (White 2005, ECMWF Newsletter 102; +van der Grijn 2002, ECMWF Tech. Memo. 386). Neither paper released its tracker code, and ECMWF's +operational tracker is not public, so this is a re-implementation of the published descriptions: + +* Bi et al., "Pangu-Weather: A 3D High-Resolution Model for Fast and Accurate Global Weather + Forecast", arXiv:2211.02556, Sec. 4.2.2 (the Nature paper, doi:10.1038/s41586-023-06185-3, cites it + for the details): from the cyclone's position, look 6 h later for a local minimum of mean sea-level + pressure (MSLP) within 445 km such that (1) there is a maximum of 850 hPa relative vorticity larger + than 5e-5 s-1 within 278 km (a minimum smaller than -5e-5 s-1 in the Southern Hemisphere; the + report prints "smaller than 5e-5", a dropped minus sign), (2) there is a maximum of the 850-200 hPa + thickness within 278 km when the cyclone is extratropical, (3) the maximum 10 m wind speed within + 278 km exceeds 8 m/s when the cyclone is on land. Tracking stops when no minimum qualifies. +* Lam et al., "Learning skillful medium-range global weather forecasting", Science 382:1416 (2023), + supplementary Sec. 8.1.4: the same three checks (radii 278 km), candidates are all MSLP local minima + within 445 km of a first guess, the closest qualifying candidate is taken, and the first guess moves + the current position by the average of the last displacement (linear extrapolation) and the wind + steering (u, v averaged over 200, 500, 700 and 850 hPa at the current position). GraphCast's + modified tracker, chosen by a hyper-parameter search (selected values printed in bold in the + supplement): candidate radius 445 x 0.5 = 222.5 km, check radius 278 x 0.75 = 208.5 km, steering + weight 0.5, candidates must not turn the track by 90 degrees or more, no clipping of the first-guess + displacement. When a cyclone disappears the track stops (ECMWF's brief-disappearance rule is not + used). + +Presets: :data:`PANGU_TRACKER` (search around the current position, no first guess), +:data:`ECMWF_TRACKER` (GraphCast's description of the unmodified ECMWF rules) and +:data:`GRAPHCAST_TRACKER` (GraphCast's modified tracker). + +What the papers leave open, and what this module does (each is a parameter): + +* "Extratropical" is not defined: the thickness check is applied only when + ``extratropical_latitude`` is set, poleward of that absolute latitude (default: never). Thickness + is ``z200 - z850`` (GraphCast's text writes ``z850 - z200``, whose maximum would be a cold core) and + "a maximum" means a grid-point local maximum (3 x 3 neighbourhood) inside the radius. +* "On land" needs a land-sea mask: pass an ``lsm`` field (land where ``lsm >= 0.5``); without it every + candidate is treated as over sea. +* MSLP local minima are grid points not larger than any of their 8 neighbours; positions are grid + points (no sub-grid interpolation); steering winds are read from the fields at the current time, at + the grid point nearest the current position (for the first step from a start time that is not in + the fields, from the first forecast step); vorticity uses centred differences on the sphere + (:func:`~pyhazards.forecasts.fields.relative_vorticity`). Among the candidates, the one closest to + the first guess (Pangu-Weather: to the current position) that passes the checks is taken. +* The first step has no previous displacement unless ``previous_position`` is given (e.g. the + best-track position 6 h before the initial time); the first guess then uses the steering alone. +* If the fields include the initial time, ``relocate_start`` moves the start to the qualifying + minimum nearest the observed position (ECMWF verifies the cyclone in the analysis); Pangu's + description starts from the observed position itself. + +Intensity outputs, which neither paper scores, are the MSLP at the centre and the maximum 10 m wind +speed within ``intensity_radius_km`` (default: the check radius). +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, replace +from typing import Dict, List, Optional, Sequence, Tuple + +import numpy as np + +from .fields import EARTH_RADIUS_KM, great_circle_km, relative_vorticity + +__all__ = [ + "ECMWF_TRACKER", + "FollowingTrackerConfig", + "GRAPHCAST_TRACKER", + "PANGU_TRACKER", + "follow_cyclone", + "required_variables", + "with_overrides", +] + +KM_PER_DEGREE = math.pi * EARTH_RADIUS_KM / 180.0 + + +@dataclass(frozen=True) +class FollowingTrackerConfig: + """Parameters of :func:`follow_cyclone` (distances in km, vorticity in s-1, winds in m/s).""" + + name: str = "ecmwf" + search_radius_km: float = 445.0 + check_radius_km: float = 278.0 + vorticity_threshold: float = 5e-5 + vorticity_level: int = 850 + land_wind_threshold: float = 8.0 + use_first_guess: bool = True + steering_weight: float = 0.5 + steering_levels: Tuple[int, ...] = (200, 500, 700, 850) + max_turn_deg: Optional[float] = None + max_first_guess_km: Optional[float] = None + extratropical_latitude: Optional[float] = None + thickness_levels: Tuple[int, int] = (200, 850) + relocate_start: bool = True + intensity_radius_km: Optional[float] = None + + def __post_init__(self) -> None: + if self.search_radius_km <= 0 or self.check_radius_km <= 0: + raise ValueError("search and check radii must be positive") + if not 0.0 <= self.steering_weight <= 1.0: + raise ValueError("steering_weight must be in [0, 1]") + if self.max_turn_deg is not None and not 0 < self.max_turn_deg <= 180: + raise ValueError("max_turn_deg must be in (0, 180]") + + +PANGU_TRACKER = FollowingTrackerConfig( + name="pangu", use_first_guess=False, steering_weight=0.0, steering_levels=(), relocate_start=False +) +"""Bi et al. (2022) Sec. 4.2.2: minima within 445 km of the current position, checks within 278 km.""" + +ECMWF_TRACKER = FollowingTrackerConfig(name="ecmwf") +"""ECMWF rules as summarised in the GraphCast supplement (445 / 278 km, 50-50 first guess).""" + +GRAPHCAST_TRACKER = FollowingTrackerConfig( + name="graphcast", search_radius_km=445.0 * 0.5, check_radius_km=278.0 * 0.75, steering_weight=0.5, max_turn_deg=90.0 +) +"""GraphCast's modified ECMWF tracker (Science 2023 supplement, Sec. 8.1.4, bold values).""" + + +def required_variables(config: FollowingTrackerConfig) -> Tuple[str, ...]: + """Fields :func:`follow_cyclone` reads for ``config`` (``lsm`` is optional and not listed).""" + names = ["msl", "u10", "v10", f"u{config.vorticity_level}", f"v{config.vorticity_level}"] + if config.use_first_guess and config.steering_weight > 0: + for level in config.steering_levels: + names += [f"u{level}", f"v{level}"] + if config.extratropical_latitude is not None: + names += [f"z{level}" for level in config.thickness_levels] + return tuple(dict.fromkeys(names)) + + +class _Frame: + """One time step of the fields with cached derived quantities.""" + + def __init__(self, ds, t: int, lat: np.ndarray, lon: np.ndarray, config: FollowingTrackerConfig, periodic: bool): + self.ds, self.t, self.lat, self.lon, self.config, self.periodic = ds, t, lat, lon, config, periodic + self._cache: Dict[str, np.ndarray] = {} + + def field(self, name: str) -> np.ndarray: + if name not in self._cache: + array = self.ds[name] + if "time" in array.dims: + array = array.isel(time=self.t) + self._cache[name] = np.asarray(array.values, dtype=np.float64) + return self._cache[name] + + def has(self, name: str) -> bool: + return name in self.ds.data_vars + + def vorticity(self) -> np.ndarray: + if "vort" not in self._cache: + level = self.config.vorticity_level + self._cache["vort"] = relative_vorticity(self.field(f"u{level}"), self.field(f"v{level}"), self.lat, self.lon, self.periodic) + return self._cache["vort"] + + def wind10(self) -> np.ndarray: + if "wind10" not in self._cache: + self._cache["wind10"] = np.hypot(self.field("u10"), self.field("v10")) + return self._cache["wind10"] + + def msl_minima(self) -> np.ndarray: + if "minima" not in self._cache: + self._cache["minima"] = _local_extrema(self.field("msl"), minimum=True, periodic=self.periodic) + return self._cache["minima"] + + def thickness_maxima(self) -> np.ndarray: + if "thick_max" not in self._cache: + top, bottom = self.config.thickness_levels + thickness = self.field(f"z{top}") - self.field(f"z{bottom}") + self._cache["thick_max"] = _local_extrema(thickness, minimum=False, periodic=self.periodic) + return self._cache["thick_max"] + + +def _local_extrema(values: np.ndarray, minimum: bool, periodic: bool) -> np.ndarray: + """Boolean mask of grid points not larger (smaller for maxima) than their 8 neighbours.""" + from scipy.ndimage import maximum_filter, minimum_filter + + data = np.where(np.isnan(values), np.inf if minimum else -np.inf, values) + mode = ("nearest", "wrap" if periodic else "nearest") + filtered = minimum_filter(data, size=3, mode=mode) if minimum else maximum_filter(data, size=3, mode=mode) + return (data == filtered) & ~np.isnan(values) + + +def _disk(lat: np.ndarray, lon: np.ndarray, lat0: float, lon0: float, radius_km: float): + """Row indices, column indices and distances (km) of grid points within ``radius_km``.""" + band = np.flatnonzero(np.abs(lat - lat0) <= radius_km / KM_PER_DEGREE + 1e-9) + if band.size == 0: + return band, band, np.empty(0) + dist = great_circle_km(lat[band][:, None], lon[None, :], lat0, lon0) + rows, cols = np.nonzero(dist <= radius_km) + return band[rows], cols, dist[rows, cols] + + +def _move(lat: float, lon: float, east_km: float, north_km: float) -> Tuple[float, float]: + new_lat = lat + north_km / KM_PER_DEGREE + new_lat = max(-89.999, min(89.999, new_lat)) + coslat = max(math.cos(math.radians(lat)), 1e-6) + return new_lat, lon + east_km / (KM_PER_DEGREE * coslat) + + +def _displacement_km(lat0: float, lon0: float, lat1: float, lon1: float) -> Tuple[float, float]: + """East and north components (km) of the move from point 0 to point 1 (local tangent plane).""" + dlon = (lon1 - lon0 + 180.0) % 360.0 - 180.0 + mean_lat = math.radians(0.5 * (lat0 + lat1)) + return dlon * KM_PER_DEGREE * math.cos(mean_lat), (lat1 - lat0) * KM_PER_DEGREE + + +def _nearest_index(values: np.ndarray, target: float, periodic: bool = False) -> int: + diff = np.abs(values - target) + if periodic: + diff = np.minimum(diff, 360.0 - diff % 360.0) + return int(np.argmin(diff)) + + +def _checks(frame: _Frame, j: int, i: int, config: FollowingTrackerConfig) -> Optional[str]: + """None if the candidate passes the checks, else the name of the failed check.""" + lat0, lon0 = float(frame.lat[j]), float(frame.lon[i]) + rows, cols, _ = _disk(frame.lat, frame.lon, lat0, lon0, config.check_radius_km) + vort = frame.vorticity()[rows, cols] + vort = vort[~np.isnan(vort)] + if vort.size == 0: + return "vorticity" + if lat0 >= 0: + if not vort.max() > config.vorticity_threshold: + return "vorticity" + elif not vort.min() < -config.vorticity_threshold: + return "vorticity" + if frame.has("lsm") and float(frame.field("lsm")[j, i]) >= 0.5: + if not frame.wind10()[rows, cols].max() > config.land_wind_threshold: + return "land_wind" + if config.extratropical_latitude is not None and abs(lat0) > config.extratropical_latitude: + if not frame.thickness_maxima()[rows, cols].any(): + return "thickness" + return None + + +def _steering_km(frame: _Frame, lat0: float, lon0: float, levels: Sequence[int], hours: float) -> Optional[Tuple[float, float]]: + if not levels or not all(frame.has(f"u{l}") and frame.has(f"v{l}") for l in levels): + return None + j = _nearest_index(frame.lat, lat0) + i = _nearest_index(frame.lon % 360.0, lon0 % 360.0, periodic=True) + u = float(np.mean([frame.field(f"u{l}")[j, i] for l in levels])) + v = float(np.mean([frame.field(f"v{l}")[j, i] for l in levels])) + seconds = hours * 3600.0 + return u * seconds / 1000.0, v * seconds / 1000.0 + + +def _turn_angle(prev: Tuple[float, float], new: Tuple[float, float]) -> float: + norm = math.hypot(*prev) * math.hypot(*new) + if norm == 0.0: + return 0.0 + cosine = (prev[0] * new[0] + prev[1] * new[1]) / norm + return math.degrees(math.acos(max(-1.0, min(1.0, cosine)))) + + +def _select(frame: _Frame, guess: Tuple[float, float], current: Optional[Tuple[float, float]], prev_disp, config: FollowingTrackerConfig): + rows, cols, dist = _disk(frame.lat, frame.lon, guess[0], guess[1], config.search_radius_km) + minima = frame.msl_minima()[rows, cols] + rows, cols, dist = rows[minima], cols[minima], dist[minima] + order = np.argsort(dist, kind="stable") + for k in order: + j, i = int(rows[k]), int(cols[k]) + if config.max_turn_deg is not None and prev_disp is not None and current is not None: + new_disp = _displacement_km(current[0], current[1], float(frame.lat[j]), float(frame.lon[i])) + if math.hypot(*new_disp) > 0 and _turn_angle(prev_disp, new_disp) >= config.max_turn_deg: + continue + if _checks(frame, j, i, config) is None: + return j, i + return None + + +def _point(frame: _Frame, j: int, i: int, config: FollowingTrackerConfig) -> Dict[str, float]: + radius = config.intensity_radius_km or config.check_radius_km + lat0, lon0 = float(frame.lat[j]), float(frame.lon[i]) + rows, cols, _ = _disk(frame.lat, frame.lon, lat0, lon0, radius) + return { + "lat": lat0, + "lon": lon0, + "msl": float(frame.field("msl")[j, i]), + "wind_max": float(np.nanmax(frame.wind10()[rows, cols])), + } + + +def follow_cyclone( + fields, + start_lat: float, + start_lon: float, + start_time, + config: FollowingTrackerConfig = ECMWF_TRACKER, + previous_position: Optional[Tuple[float, float]] = None, + max_lead_hours: Optional[float] = None, +): + """Track one cyclone through forecast ``fields`` from its position at ``start_time``. + + ``fields`` is an ``xarray.Dataset`` in the conventions of :mod:`pyhazards.forecasts.fields` + (dimensions ``time``, ``lat``, ``lon``; valid times after ``start_time`` are tracked in order). + Returns a DataFrame with columns ``time``, ``lead_hours``, ``lat``, ``lon``, ``msl`` (Pa) and + ``wind_max`` (m/s); ``attrs['stop_reason']`` says why tracking ended. + """ + import pandas as pd + + missing = [name for name in required_variables(config) if name not in fields.data_vars] + if missing: + raise KeyError(f"fields lack {missing} needed by the {config.name} tracker") + if set(("time", "lat", "lon")) - set(fields.dims): + raise ValueError(f"fields must have dimensions time, lat, lon; got {dict(fields.sizes)}") + lat = np.asarray(fields["lat"].values, dtype=np.float64) + lon = np.asarray(fields["lon"].values, dtype=np.float64) + times = pd.to_datetime(fields["time"].values) + start = pd.Timestamp(start_time) + step = np.median(np.diff(lon)) if lon.size > 1 else 0.0 + periodic = lon.size > 2 and abs(lon.size * abs(step) - 360.0) < 1e-6 + + rows: List[Dict[str, object]] = [] + current = (float(start_lat), float(start_lon)) + current_time = start + prev_disp = None + if previous_position is not None: + prev_disp = _displacement_km(previous_position[0], previous_position[1], current[0], current[1]) + stop_reason = "end of forecast" + + start_index = np.flatnonzero(times == start) + if start_index.size and config.relocate_start: + frame = _Frame(fields, int(start_index[0]), lat, lon, config, periodic) + found = _select(frame, current, None, None, config) + if found is None: + out = pd.DataFrame(rows, columns=["time", "lead_hours", "lat", "lon", "msl", "wind_max"]) + out.attrs["stop_reason"] = "no qualifying minimum at the initial time" + return out + point = _point(frame, *found, config) + rows.append({"time": start, "lead_hours": 0.0, **point}) + lon_value = point["lon"] + current = (point["lat"], lon_value) + + future = [k for k, time in enumerate(times) if time > start] + if max_lead_hours is not None: + future = [k for k in future if (times[k] - start).total_seconds() / 3600.0 <= max_lead_hours + 1e-9] + previous_frame = _Frame(fields, int(start_index[0]), lat, lon, config, periodic) if start_index.size else None + for k in future: + frame = _Frame(fields, k, lat, lon, config, periodic) + hours = (times[k] - current_time).total_seconds() / 3600.0 + guess = current + if config.use_first_guess: + steering = None + if config.steering_weight > 0: + steering = _steering_km(previous_frame if previous_frame is not None else frame, current[0], current[1], config.steering_levels, hours) + weight = config.steering_weight + if prev_disp is None and steering is None: + east = north = 0.0 + elif prev_disp is None: + east, north = steering + elif steering is None: + east, north = prev_disp + else: + east = (1.0 - weight) * prev_disp[0] + weight * steering[0] + north = (1.0 - weight) * prev_disp[1] + weight * steering[1] + if config.max_first_guess_km is not None: + length = math.hypot(east, north) + if length > config.max_first_guess_km: + east, north = east * config.max_first_guess_km / length, north * config.max_first_guess_km / length + guess = _move(current[0], current[1], east, north) + found = _select(frame, guess, current, prev_disp, config) + if found is None: + stop_reason = f"no qualifying minimum at {times[k]}" + break + point = _point(frame, *found, config) + prev_disp = _displacement_km(current[0], current[1], point["lat"], point["lon"]) + rows.append({"time": times[k], "lead_hours": (times[k] - start).total_seconds() / 3600.0, **point}) + current = (point["lat"], point["lon"]) + current_time = times[k] + previous_frame = frame + out = pd.DataFrame(rows, columns=["time", "lead_hours", "lat", "lon", "msl", "wind_max"]) + out.attrs["stop_reason"] = stop_reason + out.attrs["tracker"] = config.name + return out + + +def with_overrides(config: FollowingTrackerConfig, **changes) -> FollowingTrackerConfig: + """Copy of ``config`` with some parameters changed (e.g. ``extratropical_latitude=35``).""" + return replace(config, **changes) diff --git a/pyhazards/forecasts/matching.py b/pyhazards/forecasts/matching.py new file mode 100644 index 00000000..b71c7a3b --- /dev/null +++ b/pyhazards/forecasts/matching.py @@ -0,0 +1,114 @@ +"""Assign best-track storm IDs to tracks detected in a forecast. + +TCBench matches the TempestExtremes tracks of each forecast to IBTrACS with HuracanPy's +``huracanpy.assess.match`` at its defaults (``dev/track_matcher.py``). :func:`match_tracks` implements +that rule (HuracanPy 1.4.0, ``assess/_match.py``, MIT; written from its documented behaviour, not +copied): a detected track and a best track match when, at one or more common times, their positions +are at most ``max_dist_km`` apart (haversine; HuracanPy's ``haversine`` package uses the mean Earth +radius 6371.0088 km). Every matching pair is kept, so one detected track can be assigned to several +storms and vice versa, as in TCBench. :func:`matched_forecast_tracks` then writes, for each pair, all +points of the detected track under the storm's ``SID`` (TCBench's ``matched_tracks`` layout). +""" + +from __future__ import annotations + +from typing import Optional + +import numpy as np + +from .fields import great_circle_km + +__all__ = ["HURACANPY_EARTH_RADIUS_KM", "match_tracks", "matched_forecast_tracks"] + +HURACANPY_EARTH_RADIUS_KM = 6371.0088 +"""Mean Earth radius of the ``haversine`` package used by HuracanPy's matcher.""" + + +def match_tracks( + tracks, + reference, + max_dist_km: float = 300.0, + min_overlap: int = 0, + radius_km: float = HURACANPY_EARTH_RADIUS_KM, +): + """Pairs of (best track, detected track) sharing a time with positions within ``max_dist_km``. + + ``tracks`` has columns ``track_id``, ``time``, ``lat``, ``lon``; ``reference`` (e.g. an IBTrACS table + from :func:`pyhazards.datasets.tc.read_ibtracs`) has ``SID``, ``ISO_TIME``, ``LAT``, ``LON``. + Returns a DataFrame with ``SID``, ``track_id``, ``overlap`` (number of close common times) and + ``mean_dist_km``. With ``min_overlap >= 2`` pairs need that many close common times (HuracanPy). + """ + import pandas as pd + + left = pd.DataFrame( + { + "SID": reference["SID"].astype(str).to_numpy(), + "time": pd.to_datetime(reference["ISO_TIME"]).to_numpy(), + "lat_ref": pd.to_numeric(reference["LAT"], errors="coerce").to_numpy(dtype=float), + "lon_ref": pd.to_numeric(reference["LON"], errors="coerce").to_numpy(dtype=float), + } + ) + right = pd.DataFrame( + { + "track_id": tracks["track_id"].to_numpy(), + "time": pd.to_datetime(tracks["time"]).to_numpy(), + "lat_det": tracks["lat"].to_numpy(dtype=float), + "lon_det": tracks["lon"].to_numpy(dtype=float), + } + ) + merged = left.merge(right, on="time").drop_duplicates() + columns = ["SID", "track_id", "overlap", "mean_dist_km"] + if merged.empty: + return pd.DataFrame(columns=columns) + merged["dist"] = great_circle_km(merged["lat_ref"], merged["lon_ref"], merged["lat_det"], merged["lon_det"], radius_km) + if max_dist_km is not None: + merged = merged[merged["dist"] <= max_dist_km] + grouped = merged.groupby(["SID", "track_id"], sort=True)["dist"] + result = pd.DataFrame({"overlap": grouped.count(), "mean_dist_km": grouped.mean()}).reset_index() + if min_overlap >= 2: + result = result[result["overlap"] >= min_overlap] + return result[columns].reset_index(drop=True) + + +def matched_forecast_tracks( + tracks, + reference, + init_time, + max_dist_km: float = 300.0, + min_overlap: int = 0, + wind_column: Optional[str] = "wind10", + pressure_column: Optional[str] = "slp", +): + """Forecast-track table (one row per storm and valid time) for the detected ``tracks`` of one forecast. + + Columns: ``SID``, ``init_time``, ``valid_time``, ``lead_hours``, ``lat``, ``lon``, ``wind_ms`` and + ``pres_pa`` (taken from ``wind_column`` / ``pressure_column`` of ``tracks``, NaN when absent) and + ``track_id``. This is the layout :func:`pyhazards.forecasts.scoring.score_forecast_tracks` scores. + """ + import pandas as pd + + init = pd.Timestamp(init_time) + pairs = match_tracks(tracks, reference, max_dist_km=max_dist_km, min_overlap=min_overlap) + frames = [] + for sid, track_id in zip(pairs["SID"], pairs["track_id"]): + points = tracks[tracks["track_id"] == track_id] + valid = pd.to_datetime(points["time"]) + frames.append( + pd.DataFrame( + { + "SID": sid, + "init_time": init, + "valid_time": valid.to_numpy(), + "lead_hours": ((valid - init).dt.total_seconds() / 3600.0).to_numpy(), + "lat": points["lat"].to_numpy(dtype=float), + "lon": points["lon"].to_numpy(dtype=float), + "wind_ms": points[wind_column].to_numpy(dtype=float) if wind_column in points else np.nan, + "pres_pa": points[pressure_column].to_numpy(dtype=float) if pressure_column in points else np.nan, + "track_id": track_id, + } + ) + ) + columns = ["SID", "init_time", "valid_time", "lead_hours", "lat", "lon", "wind_ms", "pres_pa", "track_id"] + if not frames: + return pd.DataFrame(columns=columns) + return pd.concat(frames, ignore_index=True)[columns] diff --git a/pyhazards/forecasts/pipeline.py b/pyhazards/forecasts/pipeline.py new file mode 100644 index 00000000..1de37e90 --- /dev/null +++ b/pyhazards/forecasts/pipeline.py @@ -0,0 +1,131 @@ +"""Forecast fields -> cyclone tracks -> forecast-track table matched to IBTrACS storms. + +Two routes, matching the two protocols in the literature: + +* :func:`tempest_forecast_tracks` (TCBench): detect and stitch every cyclone in the forecast with the + TempestExtremes rules (:mod:`.tempest`), then assign IBTrACS storm IDs with HuracanPy's matching + rule (:mod:`.matching`). +* :func:`follow_forecast_tracks` (Pangu-Weather, GraphCast papers): for each IBTrACS storm present at + the initial time, follow it from its observed position with the ECMWF-style tracker + (:mod:`.following`). + +Both return the forecast-track table scored by :func:`pyhazards.forecasts.scoring.score_forecast_tracks`. +""" + +from __future__ import annotations + +from typing import Iterable, Optional + +import numpy as np + +from .following import ECMWF_TRACKER, FollowingTrackerConfig, follow_cyclone +from .matching import matched_forecast_tracks +from .tempest import TCBENCH_DETECT_NODES, TCBENCH_STITCH_NODES, DetectNodesConfig, StitchNodesConfig, tempest_tracks + +__all__ = ["follow_forecast_tracks", "storms_at", "tempest_forecast_tracks"] + +_COLUMNS = ["SID", "init_time", "valid_time", "lead_hours", "lat", "lon", "wind_ms", "pres_pa"] + + +def tempest_forecast_tracks( + fields, + ibtracs, + init_time, + detect: DetectNodesConfig = TCBENCH_DETECT_NODES, + stitch: StitchNodesConfig = TCBENCH_STITCH_NODES, + max_dist_km: float = 300.0, + return_tracks: bool = False, +): + """TCBench route: TempestExtremes-style tracks of one forecast, matched to IBTrACS storms. + + ``fields`` is an ``xarray.Dataset`` with ``msl``, ``u10``, ``v10``, ``z300``, ``z500`` (for the + default configuration) on ``(time, lat, lon)``. ``wind_ms`` / ``pres_pa`` come from the + ``wind10`` / ``slp`` outputs (maximum 10 m wind within 2 degrees, MSLP at the node). + With ``return_tracks`` the unmatched StitchNodes table is returned as well. + """ + names = {detect.search_by_min} + for criterion in detect.closed_contours + detect.no_closed_contours: + names.update(_fields_in(criterion.variable)) + for output in detect.outputs: + names.update(_fields_in(output.variable)) + arrays = {name: fields[name].transpose("time", "lat", "lon").values for name in sorted(names)} + tracks = tempest_tracks(arrays, fields["lat"].values, fields["lon"].values, fields["time"].values, detect, stitch) + columns = set(stitch.columns) + table = matched_forecast_tracks( + tracks, + ibtracs, + init_time, + max_dist_km=max_dist_km, + wind_column="wind10" if "wind10" in columns else None, + pressure_column="slp" if "slp" in columns else None, + ) + return (table, tracks) if return_tracks else table + + +def _fields_in(expression: str): + import re + + return {token for token in re.split(r"[(),\s]+", expression) if token and not token.startswith("_")} + + +def storms_at(ibtracs, time, include_spur: bool = False): + """IBTrACS storms with a record at ``time``: DataFrame of ``SID``, ``LAT``, ``LON`` (one row per storm).""" + import pandas as pd + + stamp = pd.Timestamp(time) + rows = ibtracs[pd.to_datetime(ibtracs["ISO_TIME"]) == stamp] + if not include_spur and "TRACK_TYPE" in rows.columns: + rows = rows[~rows["TRACK_TYPE"].astype(str).str.contains("spur", case=False, na=False)] + rows = rows.dropna(subset=["LAT", "LON"]) + return rows.drop_duplicates(subset=["SID"])[["SID", "LAT", "LON"]].reset_index(drop=True) + + +def follow_forecast_tracks( + fields, + ibtracs, + init_time, + config: FollowingTrackerConfig = ECMWF_TRACKER, + sids: Optional[Iterable[str]] = None, + use_previous_position: bool = True, + max_lead_hours: Optional[float] = None, +): + """Paper route: follow each IBTrACS storm present at ``init_time`` through the forecast ``fields``. + + The start is the IBTrACS position at ``init_time``; with ``use_previous_position`` the position 6 h + earlier gives the first displacement for the first guess. ``wind_ms`` is the maximum 10 m wind + within the intensity radius and ``pres_pa`` the MSLP at the centre. + """ + import pandas as pd + + init = pd.Timestamp(init_time) + storms = storms_at(ibtracs, init) + if sids is not None: + wanted = {str(s) for s in sids} + storms = storms[storms["SID"].astype(str).isin(wanted)] + before = storms_at(ibtracs, init - pd.Timedelta(hours=6)).set_index("SID") if use_previous_position else None + frames = [] + for sid, lat, lon in zip(storms["SID"], storms["LAT"], storms["LON"]): + previous = None + if before is not None and sid in before.index: + previous = (float(before.loc[sid, "LAT"]), float(before.loc[sid, "LON"])) + track = follow_cyclone(fields, float(lat), float(lon), init, config, previous_position=previous, max_lead_hours=max_lead_hours) + track = track[track["lead_hours"] > 0] + if track.empty: + continue + frames.append( + pd.DataFrame( + { + "SID": str(sid), + "init_time": init, + "valid_time": pd.to_datetime(track["time"]).to_numpy(), + "lead_hours": track["lead_hours"].to_numpy(dtype=float), + "lat": track["lat"].to_numpy(dtype=float), + "lon": track["lon"].to_numpy(dtype=float), + "wind_ms": track["wind_max"].to_numpy(dtype=float), + "pres_pa": track["msl"].to_numpy(dtype=float), + } + ) + ) + if not frames: + return pd.DataFrame(columns=_COLUMNS) + return pd.concat(frames, ignore_index=True)[_COLUMNS] diff --git a/pyhazards/forecasts/scoring.py b/pyhazards/forecasts/scoring.py new file mode 100644 index 00000000..df600b14 --- /dev/null +++ b/pyhazards/forecasts/scoring.py @@ -0,0 +1,228 @@ +"""Score forecast cyclone tracks against IBTrACS best tracks. + +A *forecast-track table* has one row per storm, forecast and valid time, with columns ``SID``, +``init_time``, ``valid_time``, ``lead_hours``, ``lat``, ``lon`` (degrees), ``wind_ms`` (maximum 10 m +wind, m/s) and ``pres_pa`` (minimum sea-level pressure, Pa). The trackers' pipeline +(:mod:`pyhazards.forecasts.pipeline`) and the TCBench reader (:mod:`pyhazards.forecasts.tcbench`) +produce it. + +Each row is compared with the IBTrACS record of the same storm at exactly the valid time (rows +without one are not scored). :func:`score_forecast_tracks` reports, per lead time and averaged over +leads, the great-circle track error in km (the ``tc`` benchmark's +:func:`~pyhazards.benchmarks.tc.track_intensity_metrics`, sphere of radius 6371 km), the maximum-wind +error in knots against an IBTrACS wind column (default ``USA_WIND``, 1-minute sustained) and the +central-pressure error in hPa (default ``USA_PRES``), plus the number of scored rows and the median +track error per lead (GraphCast reports medians). + +``protocol="tcbench"`` reproduces TCBench's ``dev/evaluate_tracks.py`` and ``dev/metrics_test.py`` +(TCBench_Alpha 93924483): forecasts initialised at 00 and 12 UTC only, duplicate (storm, initial +time, valid time) rows dropped keeping the first, wind converted with TCBench's factor 1.94384 kt per +m/s, and the direct position error computed as TCBench computes it, including a quirk that changes +its values by up to several km: TCBench reads IBTrACS ``LAT`` and ``LON`` as ``float16`` +(``dev/utils/constants.py``), shifts negative longitudes by 360 in double precision, and evaluates +the haversine formula with the reference latitude still in ``float16`` (so ``np.radians`` and +``np.cos`` of it are half precision). :func:`tcbench_position_error_km` emulates this exactly; it +reproduces the ``DPE_GCD`` values printed in TCBench's ``dev/Getting_Started.ipynb``. +""" + +from __future__ import annotations + +from typing import Dict, Iterable, Optional, Sequence + +import numpy as np + +__all__ = [ + "KT_PER_MS", + "TCBENCH_KT_PER_MS", + "forecast_track_errors", + "score_forecast_tracks", + "tcbench_position_error_km", +] + +KT_PER_MS = 1.0 / 0.514444 +"""Knots per m/s (1 kt = 1852 m / 3600 s = 0.514444 m/s).""" + +TCBENCH_KT_PER_MS = 1.94384 +"""Conversion factor used by TCBench's ``track_matcher.py``.""" + +_TRACK_COLUMNS = ("SID", "init_time", "valid_time", "lat", "lon") + + +def tcbench_position_error_km(ref_lat, ref_lon, pred_lat, pred_lon) -> np.ndarray: + """TCBench's ``toolbox.haversine`` on IBTrACS positions read as ``float16`` (see module docstring). + + ``ref_lat`` / ``ref_lon`` are the IBTrACS values in degrees as written in the CSV (longitudes in + either convention); predictions are double precision. Radius 6371 km. + """ + lat16 = np.asarray(ref_lat, dtype=np.float64).astype(np.float16) + lon16 = np.asarray(ref_lon, dtype=np.float64).astype(np.float16) + lon = np.where(lon16 < 0, lon16.astype(np.float64) + 360.0, lon16.astype(np.float64)) + latp = np.radians(lat16) # float16, as in TCBench + lonp = np.radians(lon) + lat_list = np.radians(np.asarray(pred_lat, dtype=np.float64)) + lon_list = np.radians(np.asarray(pred_lon, dtype=np.float64)) + dlon = lonp - lon_list + dlat = latp - lat_list + a = np.power(np.sin(dlat / 2), 2) + np.cos(lat_list) * np.cos(latp) * np.power(np.sin(dlon / 2), 2) + a = np.where(np.sqrt(a) <= 1, a, np.sign(a)) + return 2 * 6371 * np.arcsin(np.sqrt(a)) + + +def _reference_table(ibtracs, wind_column: Optional[str], pres_column: Optional[str]): + import pandas as pd + + ref = pd.DataFrame( + { + "SID": ibtracs["SID"].astype(str).to_numpy(), + "valid_time": pd.to_datetime(ibtracs["ISO_TIME"]).to_numpy(), + "ref_lat": pd.to_numeric(ibtracs["LAT"], errors="coerce").to_numpy(dtype=float), + "ref_lon": pd.to_numeric(ibtracs["LON"], errors="coerce").to_numpy(dtype=float), + } + ) + ref["ref_wind_kt"] = pd.to_numeric(ibtracs[wind_column], errors="coerce").to_numpy(dtype=float) if wind_column in ibtracs else np.nan + ref["ref_pres_hpa"] = pd.to_numeric(ibtracs[pres_column], errors="coerce").to_numpy(dtype=float) if pres_column in ibtracs else np.nan + return ref.drop_duplicates(subset=["SID", "valid_time"], keep="first") + + +def forecast_track_errors( + tracks, + ibtracs, + protocol: str = "pyhazards", + wind_column: Optional[str] = "USA_WIND", + pres_column: Optional[str] = "USA_PRES", + init_hours: Optional[Iterable[int]] = None, +): + """Row-level errors of a forecast-track table against IBTrACS. + + Adds ``ref_lat``, ``ref_lon``, ``ref_wind_kt``, ``ref_pres_hpa``, ``wind_kt``, ``pres_hpa``, + ``track_error_km``, ``wind_error_kt`` and ``pres_error_hpa`` (forecast minus best track). See the + module docstring for ``protocol``; ``init_hours`` restricts initial times (TCBench: 0 and 12). + """ + import pandas as pd + + if protocol not in {"pyhazards", "tcbench"}: + raise ValueError("protocol must be 'pyhazards' or 'tcbench'") + missing = [c for c in _TRACK_COLUMNS if c not in tracks.columns] + if missing: + raise ValueError(f"forecast-track table lacks columns {missing}") + table = tracks.copy() + table["init_time"] = pd.to_datetime(table["init_time"]) + table["valid_time"] = pd.to_datetime(table["valid_time"]) + table["SID"] = table["SID"].astype(str) + if "lead_hours" not in table: + table["lead_hours"] = (table["valid_time"] - table["init_time"]).dt.total_seconds() / 3600.0 + if protocol == "tcbench" and init_hours is None: + init_hours = (0, 12) + if init_hours is not None: + table = table[table["init_time"].dt.hour.isin(list(init_hours))] + ref = _reference_table(ibtracs, wind_column, pres_column) + table = table[table["SID"].isin(set(ref["SID"]))] + if "member" not in table.columns: + table = table.drop_duplicates(subset=["init_time", "valid_time", "SID"], keep="first") + table = table.merge(ref, on=["SID", "valid_time"], how="left") + factor = TCBENCH_KT_PER_MS if protocol == "tcbench" else KT_PER_MS + table["wind_kt"] = table["wind_ms"].astype(float) * factor if "wind_ms" in table else np.nan + table["pres_hpa"] = table["pres_pa"].astype(float) / 100.0 if "pres_pa" in table else np.nan + if protocol == "tcbench": + distance = tcbench_position_error_km(table["ref_lat"], table["ref_lon"], table["lat"], table["lon"]) + else: + from .fields import great_circle_km + + distance = great_circle_km(table["ref_lat"], table["ref_lon"], table["lat"], table["lon"]) + table["track_error_km"] = distance + table["wind_error_kt"] = table["wind_kt"] - table["ref_wind_kt"] + table["pres_error_hpa"] = table["pres_hpa"] - table["ref_pres_hpa"] + return table.reset_index(drop=True) + + +def _lead_label(hours: float) -> str: + return f"{int(hours)}h" if float(hours).is_integer() else f"{hours:g}h".replace(".", "p") + + +def score_forecast_tracks( + tracks, + ibtracs, + lead_hours: Optional[Sequence[float]] = None, + protocol: str = "pyhazards", + wind_column: Optional[str] = "USA_WIND", + pres_column: Optional[str] = "USA_PRES", + init_hours: Optional[Iterable[int]] = None, + source: Optional[str] = None, +): + """Track and intensity errors per lead time as a :class:`~pyhazards.benchmarks.BenchmarkResult`. + + Metrics (``tc`` benchmark names): ``track_error_km``, ``intensity_mae`` (kt), ``pressure_mae`` + (hPa), each with ``_h`` per lead, plus ``track_error_km_median_h`` and ``count_h``. + ``lead_hours`` defaults to the multiples of 6 h present in the table. The sample is heterogeneous: + each lead averages the rows that exist at that lead. + """ + import pandas as pd + import torch + + from ..benchmarks.schemas import BenchmarkResult + from ..benchmarks.tc import track_intensity_metrics + + errors = forecast_track_errors(tracks, ibtracs, protocol, wind_column, pres_column, init_hours) + errors = errors[np.isfinite(errors["ref_lat"].to_numpy(dtype=float))] + if lead_hours is None: + leads = sorted({float(h) for h in errors["lead_hours"] if float(h) > 0 and float(h) % 6 == 0}) + else: + leads = [float(h) for h in lead_hours] + if not leads: + raise ValueError("no forecast rows match IBTrACS records at the requested lead times") + errors = errors[errors["lead_hours"].isin(leads)] + cases = errors[["SID", "init_time"]].drop_duplicates().reset_index(drop=True) + case_index = {key: k for k, key in enumerate(zip(cases["SID"], cases["init_time"]))} + lead_index = {h: k for k, h in enumerate(leads)} + shape = (len(cases), len(leads)) + + def grid(column: str) -> np.ndarray: + out = np.full(shape, np.nan) + for sid, init, lead, value in zip(errors["SID"], errors["init_time"], errors["lead_hours"], errors[column]): + out[case_index[(sid, init)], lead_index[float(lead)]] = value + return out + + metrics: Dict[str, float] + if protocol == "tcbench": + # TCBench's own distance (float16 quirk); averaged the same way as the tc benchmark. + values = {"track_error_km": grid("track_error_km")} + values["intensity_mae"] = np.abs(grid("wind_error_kt")) + values["pressure_mae"] = np.abs(grid("pres_error_hpa")) + metrics = {} + for name, array in values.items(): + finite = array[np.isfinite(array)] + metrics[name] = float(finite.mean()) if finite.size else float("nan") + for k, hours in enumerate(leads): + column = array[:, k] + column = column[np.isfinite(column)] + metrics[f"{name}_{_lead_label(hours)}"] = float(column.mean()) if column.size else float("nan") + else: + forecast = {"lat": torch.as_tensor(grid("lat")), "lon": torch.as_tensor(grid("lon"))} + target = {"lat": torch.as_tensor(grid("ref_lat")), "lon": torch.as_tensor(grid("ref_lon"))} + if errors["wind_kt"].notna().any(): + forecast["wind"], target["wind"] = torch.as_tensor(grid("wind_kt")), torch.as_tensor(grid("ref_wind_kt")) + if errors["pres_hpa"].notna().any(): + forecast["pres"], target["pres"] = torch.as_tensor(grid("pres_hpa")), torch.as_tensor(grid("ref_pres_hpa")) + metrics = track_intensity_metrics(forecast, target, leads) + track = grid("track_error_km") + for k, hours in enumerate(leads): + column = track[:, k] + column = column[np.isfinite(column)] + metrics[f"count_{_lead_label(hours)}"] = float(column.size) + metrics[f"track_error_km_median_{_lead_label(hours)}"] = float(np.median(column)) if column.size else float("nan") + return BenchmarkResult( + benchmark_name="tc", + hazard_task="tc.track_intensity", + metrics={key: value for key, value in metrics.items() if not (isinstance(value, float) and np.isnan(value))}, + metadata={ + "source": source, + "protocol": protocol, + "lead_hours": leads, + "units": {"track_error_km": "km", "intensity_mae": "kt", "pressure_mae": "hPa"}, + "reference": {"wind": wind_column, "pressure": pres_column}, + "num_cases": len(cases), + "num_storms": int(cases["SID"].nunique()), + "sample": "heterogeneous (each lead averages the rows available at that lead)", + "synthetic": False, + }, + ) diff --git a/pyhazards/forecasts/synthetic.py b/pyhazards/forecasts/synthetic.py new file mode 100644 index 00000000..2d40b7d8 --- /dev/null +++ b/pyhazards/forecasts/synthetic.py @@ -0,0 +1,132 @@ +"""Synthetic global fields with idealised cyclones on known tracks (for tests and examples only). + +Nothing here describes real weather. Each vortex has a Gaussian sea-level-pressure deficit, a +cyclonic (counter-clockwise in the Northern Hemisphere, clockwise in the Southern) tangential wind +of the form ``v(r) = vmax (r / rmax) exp((1 - (r / rmax)^2) / 2)`` at 10 m and 850 hPa, a warm core +(a Gaussian bump of the 300-500 hPa and 200-850 hPa thicknesses) and moves at a constant velocity, +which is also the uniform steering wind at 200-850 hPa. The background pressure varies smoothly so +that it has no flat plateaus. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import List, Sequence, Tuple + +import numpy as np + +from .fields import EARTH_RADIUS_KM, great_circle_km + +__all__ = ["SyntheticVortex", "synthetic_cyclone_fields", "vortex_track"] + +_KM_PER_DEG = math.pi * EARTH_RADIUS_KM / 180.0 + + +@dataclass(frozen=True) +class SyntheticVortex: + """An idealised cyclone; ``u`` / ``v`` (m/s) is its motion and the steering flow around it.""" + + lat: float + lon: float + u: float = -5.0 + v: float = 2.0 + pressure_drop: float = 3000.0 # Pa + radius_km: float = 250.0 # e-folding radius of the pressure deficit + vmax: float = 30.0 # m/s + rmax_km: float = 100.0 + warm_core: float = 300.0 # m2 s-2, amplitude of the thickness anomaly + warm_core_radius_km: float = 300.0 + cyclonic: bool = True + + +def vortex_track(vortex: SyntheticVortex, hours: Sequence[float]) -> List[Tuple[float, float]]: + """Centre positions (lat, lon in degrees) after ``hours`` of constant-velocity motion.""" + out = [] + for h in hours: + north = vortex.v * h * 3.6 + east = vortex.u * h * 3.6 + lat = vortex.lat + north / _KM_PER_DEG + mean_lat = math.radians(0.5 * (vortex.lat + lat)) + lon = vortex.lon + east / (_KM_PER_DEG * math.cos(mean_lat)) + out.append((lat, lon % 360.0)) + return out + + +def _local_offsets(lat, lon, lat0, lon0): + """East / north offsets (km) of grid points from a centre on the local tangent plane.""" + dlon = (lon - lon0 + 180.0) % 360.0 - 180.0 + east = dlon * _KM_PER_DEG * np.cos(np.deg2rad(lat)) + north = (lat - lat0) * _KM_PER_DEG + return east, north + + +def synthetic_cyclone_fields( + vortices: Sequence[SyntheticVortex], + hours: Sequence[float] = tuple(range(0, 121, 6)), + resolution: float = 0.5, + init_time="2020-01-01T00:00", + lat_descending: bool = True, + land_mask: bool = False, +): + """Global fields (``xarray.Dataset`` in the tracker conventions) with the given vortices. + + Variables: ``msl``, ``u10``, ``v10``, ``u/v`` at 200, 500, 700 and 850 hPa, ``z200``, ``z300``, + ``z500``, ``z850`` and, with ``land_mask``, an ``lsm`` that is land east of 160 W and west of 20 W + in the Northern Hemisphere poleward of 20 N. ``attrs['tracks']`` holds each vortex's true centres. + """ + import pandas as pd + import xarray as xr + + lat = np.arange(-90.0, 90.0 + resolution / 2, resolution) + if lat_descending: + lat = lat[::-1] + lon = np.arange(0.0, 360.0, resolution) + lat2, lon2 = np.meshgrid(lat, lon, indexing="ij") + phi, lam = np.deg2rad(lat2), np.deg2rad(lon2) + background = 101325.0 + 900.0 * np.sin(phi) ** 2 + 250.0 * np.cos(phi) * np.cos(2 * lam + 0.3) + 120.0 * np.sin(3 * phi + 0.2) * np.sin(lam) + nt = len(hours) + shape = (nt,) + lat2.shape + fields = {name: np.zeros(shape) for name in ("msl", "u10", "v10", "z200", "z300", "z500", "z850")} + for level in (200, 500, 700, 850): + fields[f"u{level}"] = np.zeros(shape) + fields[f"v{level}"] = np.zeros(shape) + fields["msl"][:] = background + fields["z850"][:] = 14000.0 + 300.0 * np.cos(phi) ** 2 + fields["z500"][:] = 55000.0 + 1500.0 * np.cos(phi) ** 2 + fields["z300"][:] = 90000.0 + 2500.0 * np.cos(phi) ** 2 + fields["z200"][:] = 115000.0 + 3500.0 * np.cos(phi) ** 2 + tracks = [] + for vortex in vortices: + centres = vortex_track(vortex, hours) + tracks.append(centres) + for t, (clat, clon) in enumerate(centres): + r = great_circle_km(lat2, lon2, clat, clon) + east, north = _local_offsets(lat2, lon2, clat, clon) + fields["msl"][t] -= vortex.pressure_drop * np.exp(-((r / vortex.radius_km) ** 2)) + x = r / vortex.rmax_km + speed = vortex.vmax * x * np.exp(0.5 * (1.0 - x**2)) + with np.errstate(invalid="ignore", divide="ignore"): + sense = (1.0 if clat >= 0 else -1.0) * (1.0 if vortex.cyclonic else -1.0) + tu = np.where(r > 0, -sense * speed * north / r, 0.0) + tv = np.where(r > 0, sense * speed * east / r, 0.0) + near = np.exp(-((r / (8 * vortex.radius_km)) ** 2)) # confine the steering flow to the storm area + fields["u10"][t] += 0.9 * tu + vortex.u * near + fields["v10"][t] += 0.9 * tv + vortex.v * near + fields["u850"][t] += 0.8 * tu + fields["v850"][t] += 0.8 * tv + for level in (200, 500, 700, 850): + fields[f"u{level}"][t] += vortex.u * near + fields[f"v{level}"][t] += vortex.v * near + bump = vortex.warm_core * np.exp(-((r / vortex.warm_core_radius_km) ** 2)) + fields["z300"][t] += bump + fields["z200"][t] += 2.0 * bump + times = [pd.Timestamp(init_time) + pd.Timedelta(hours=float(h)) for h in hours] + data = {name: (("time", "lat", "lon"), value.astype(np.float32)) for name, value in fields.items()} + if land_mask: + land = ((lon2 > 200.0) & (lon2 < 340.0) & (lat2 > 20.0)).astype(np.float32) + data["lsm"] = (("lat", "lon"), land) + ds = xr.Dataset(data, coords={"time": times, "lat": lat, "lon": lon}) + ds.attrs["tracks"] = repr(tracks) + ds.attrs["synthetic"] = 1 + return ds diff --git a/pyhazards/forecasts/tcbench.py b/pyhazards/forecasts/tcbench.py new file mode 100644 index 00000000..55333efd --- /dev/null +++ b/pyhazards/forecasts/tcbench.py @@ -0,0 +1,338 @@ +"""Readers for TCBench's released weather-model cyclone tracks and forecast fields. + +TCBench (Gomez et al., "TCBench: A Benchmark for Tropical Cyclone Track and Intensity Forecasting at +the Global Scale", arXiv:2601.23268, 2026; code https://github.com/msgomez06/TCBench_Alpha, MIT) ran +Pangu-Weather, FourCastNet v2 (SFNO, "small") and AIFS for 2023, tracked cyclones in their outputs +with TempestExtremes and matched the tracks to IBTrACS. The Hugging Face dataset ``TCBench/TCBench`` +(MIT) holds, per model: + +* ``matched_tracks/2023_.csv``: tracks matched to IBTrACS storms (``SID``, ``Initial Time``, + ``Valid Time``, ``wind max`` in m/s, ``pressure min`` in Pa, ``lat``, ``lon``), a few MB; +* ``unmatched_tracks/

/.csv``: TempestExtremes StitchNodes output per initial time; +* ``neural_weather_models//.nc``: the raw forecast fields (about 3 GB per initial time, + 1.1-2.7 TB per model). :func:`read_tcbench_fields` reads only the variables a tracker needs with + HTTP range requests (about 200 MB for the TempestExtremes variables), never the whole file. + +Everything is read at run time from revision :data:`TCBENCH_REVISION`; nothing is redistributed. +The Pangu-Weather forecasts derive from weights licensed CC BY-NC-SA 4.0 (non-commercial); TCBench's +FourCastNet v2 is NVIDIA's ``sfno_73ch_small``, not the FourCastNet (AFNO) model of Pathak et al. 2022. +""" + +from __future__ import annotations + +import hashlib +import io +import urllib.request +from pathlib import Path +from typing import Dict, Iterable, Optional, Sequence, Union + +import numpy as np + +__all__ = [ + "TCBENCH_FILES", + "TCBENCH_MODELS", + "TCBENCH_REPO", + "TCBENCH_REVISION", + "HTTPRangeFile", + "download_tcbench_file", + "read_tcbench_fields", + "read_tcbench_matched_tracks", + "read_tcbench_unmatched_tracks", + "tcbench_ibtracs", + "tcbench_path", + "tcbench_url", +] + +TCBENCH_REPO = "TCBench/TCBench" +TCBENCH_REVISION = "0124d14d7f1f468096f46aec1e79696ab9c880c1" + +TCBENCH_FILES: Dict[str, str] = { + "matched_tracks/2023_PANGU.csv": "0b5f7a51531a34c70b190a9e9bbec10bae3a7a009badfd9995d61b882e34e348", + "matched_tracks/2023_fcnet.csv": "fe4197793b072ce94de6ad0bce4abefa512ba89784f38eb9068e6475fed47323", + "matched_tracks/2023_aifs.csv": "ec93a38582f970043ddf497d73bba836d3ccb6c1f8dc7483f0f00494461056f9", +} +"""sha256 of the pinned small files (checked on download).""" + +TCBENCH_MODELS: Dict[str, Dict[str, str]] = { + "pangu": { + "label": "Pangu-Weather", + "matched": "matched_tracks/2023_PANGU.csv", + "unmatched_dir": "unmatched_tracks/2023_pangu", + "fields_dir": "neural_weather_models/panguweather", + "stem": "panguweather_{init:%Y.%m.%d-%Hh%M}_maxltd-120_timeres-6", + }, + "fourcastnet_v2": { + "label": "FourCastNet v2 (SFNO small)", + "matched": "matched_tracks/2023_fcnet.csv", + "unmatched_dir": "unmatched_tracks/2023_fcnet", + "fields_dir": "neural_weather_models/fourcastnetv2_small", + "stem": "fcnet_{init:%Y.%m.%d-%Hh%Mm}_maxltd-120_timeres-6", + }, + "aifs": { + "label": "AIFS v1.0", + "matched": "matched_tracks/2023_aifs.csv", + "unmatched_dir": "unmatched_tracks/2023_aifs", + "fields_dir": "neural_weather_models/AIFS", + "stem": "AIFS_init-{init:%Y.%m.%d-%Hh%M}_max-lead-120", + }, +} + + +def tcbench_url(path: str, revision: str = TCBENCH_REVISION) -> str: + return f"https://huggingface.co/datasets/{TCBENCH_REPO}/resolve/{revision}/{path}" + + +def _model(model: str) -> Dict[str, str]: + if model not in TCBENCH_MODELS: + raise ValueError(f"unknown TCBench model {model!r}; choose from {sorted(TCBENCH_MODELS)}") + return TCBENCH_MODELS[model] + + +def tcbench_path(model: str, kind: str, init_time=None) -> str: + """Repository path of a model's ``matched`` file, or of its ``unmatched`` / ``fields`` file for ``init_time``.""" + import pandas as pd + + spec = _model(model) + if kind == "matched": + return spec["matched"] + if init_time is None: + raise ValueError(f"kind={kind!r} needs init_time") + stem = spec["stem"].format(init=pd.Timestamp(init_time)) + if kind == "unmatched": + return f"{spec['unmatched_dir']}/{stem}.csv" + if kind == "fields": + return f"{spec['fields_dir']}/{stem}.nc" + raise ValueError("kind must be 'matched', 'unmatched' or 'fields'") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def download_tcbench_file(path: str, cache_dir: Union[str, Path], overwrite: bool = False) -> Path: + """Download a (small) TCBench file at the pinned revision into ``cache_dir``. + + Files listed in :data:`TCBENCH_FILES` are checked against their sha256. Raw forecast files are + refused (use :func:`read_tcbench_fields`, which reads only the needed variables). + """ + if path.startswith("neural_weather_models/"): + raise ValueError("raw forecast files are ~3 GB each; read slices with read_tcbench_fields()") + target = Path(cache_dir).expanduser() / TCBENCH_REVISION / path + if overwrite or not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_suffix(target.suffix + ".part") + urllib.request.urlretrieve(tcbench_url(path), partial) + partial.replace(target) + expected = TCBENCH_FILES.get(path) + if expected is not None: + found = _sha256(target) + if found != expected: + raise ValueError(f"{target} has sha256 {found}, expected {expected}") + return target + + +def read_tcbench_matched_tracks(path: Union[str, Path], units: str = "si"): + """Read a TCBench ``matched_tracks`` CSV into a forecast-track table (see :mod:`.scoring`). + + The released files hold winds in m/s and pressures in Pa (``units="si"``); TCBench's own + ``track_matcher.py`` writes knots and hPa (``units="kt_hpa"``), which are converted back with its + factors. Ensemble files keep their ``ensemble_idx`` column as ``member``. + """ + import pandas as pd + + from .scoring import TCBENCH_KT_PER_MS + + frame = pd.read_csv(path) + required = ["SID", "Initial Time", "Valid Time", "wind max", "pressure min", "lat", "lon"] + missing = [c for c in required if c not in frame.columns] + if missing: + raise ValueError(f"{path} is not a TCBench matched-tracks file: missing {missing}") + if units not in {"si", "kt_hpa"}: + raise ValueError("units must be 'si' or 'kt_hpa'") + init = pd.to_datetime(frame["Initial Time"]) + valid = pd.to_datetime(frame["Valid Time"]) + wind = frame["wind max"].astype(float) + pres = frame["pressure min"].astype(float) + if units == "kt_hpa": + wind, pres = wind / TCBENCH_KT_PER_MS, pres * 100.0 + out = pd.DataFrame( + { + "SID": frame["SID"].astype(str), + "init_time": init, + "valid_time": valid, + "lead_hours": (valid - init).dt.total_seconds() / 3600.0, + "lat": frame["lat"].astype(float), + "lon": frame["lon"].astype(float), + "wind_ms": wind, + "pres_pa": pres, + } + ) + ensemble = next((c for c in frame.columns if "ensemble" in str(c).lower()), None) + if ensemble is not None: + out["member"] = frame[ensemble] + return out + + +def read_tcbench_unmatched_tracks(path: Union[str, Path]): + """Read a TCBench ``unmatched_tracks`` CSV (TempestExtremes StitchNodes output).""" + from .tempest import read_stitchnodes_csv + + return read_stitchnodes_csv(path) + + +def tcbench_ibtracs(table, year: int = 2023): + """IBTrACS rows TCBench evaluates against: records whose ``ISO_TIME`` falls in ``year``.""" + import pandas as pd + + return table[pd.to_datetime(table["ISO_TIME"]).dt.year == year].reset_index(drop=True) + + +class HTTPRangeFile(io.RawIOBase): + """Read-only, seekable file over HTTP range requests (for opening remote HDF5 files with h5py).""" + + def __init__(self, url: str, block_size: int = 1 << 22, max_blocks: int = 256, session=None): + import requests + + self._session = session or requests.Session() + response = self._session.head(url, allow_redirects=True, timeout=60) + response.raise_for_status() + self.url = url + self.size = int(response.headers["Content-Length"]) + self.block_size = int(block_size) + self.max_blocks = int(max_blocks) + self._blocks: Dict[int, bytes] = {} + self._pos = 0 + self.bytes_read = 0 + + def readable(self) -> bool: + return True + + def seekable(self) -> bool: + return True + + def tell(self) -> int: + return self._pos + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + if whence == io.SEEK_SET: + self._pos = offset + elif whence == io.SEEK_CUR: + self._pos += offset + else: + self._pos = self.size + offset + return self._pos + + def _block(self, index: int) -> bytes: + if index not in self._blocks: + start = index * self.block_size + end = min(self.size, start + self.block_size) - 1 + response = self._session.get(self.url, headers={"Range": f"bytes={start}-{end}"}, allow_redirects=True, timeout=300) + response.raise_for_status() + data = response.content + if len(data) != end - start + 1: + raise IOError(f"range request returned {len(data)} bytes, expected {end - start + 1}") + self._blocks[index] = data + self.bytes_read += len(data) + while len(self._blocks) > self.max_blocks: + self._blocks.pop(next(iter(self._blocks))) + return self._blocks[index] + + def readinto(self, buffer) -> int: + end = min(self.size, self._pos + len(buffer)) + out = bytearray() + position = self._pos + while position < end: + index = position // self.block_size + block = self._block(index) + offset = position - index * self.block_size + take = min(len(block) - offset, end - position) + out += block[offset : offset + take] + position += take + buffer[: len(out)] = out + self._pos = end + return len(out) + + +_SURFACE = {"msl": "msl", "u10": "u10", "v10": "v10", "t2m": "t2m"} +_LEVEL_PREFIX = ("u", "v", "z", "t", "q", "r") + + +def _split_variable(name: str): + if name in _SURFACE: + return _SURFACE[name], None + for prefix in _LEVEL_PREFIX: + rest = name[len(prefix):] + if name.startswith(prefix) and rest.isdigit(): + return prefix, int(rest) + raise ValueError(f"cannot map variable {name!r} to a TCBench field (use msl, u10, v10, t2m or u/v/z/t/q/r)") + + +def read_tcbench_fields( + model: str, + init_time, + variables: Sequence[str] = ("msl", "u10", "v10", "z300", "z500"), + path: Optional[Union[str, Path]] = None, + url: Optional[str] = None, +): + """Read selected variables of a TCBench raw forecast as an ``xarray.Dataset`` (tracker conventions). + + Reads ``path`` (a local copy) or, by default, the pinned file on the Hugging Face Hub with HTTP + range requests, fetching only the requested variables and pressure levels. Values are unpacked + from int16 with the files' ``scale_factor`` / ``add_offset`` in double precision and returned as + float32 (this is the input that reproduces TCBench's TempestExtremes tracks exactly). ``time`` + holds the valid times (lead times 6-120 h). + """ + import h5py + import pandas as pd + import xarray as xr + + init = pd.Timestamp(init_time) + if path is not None: + handle = h5py.File(Path(path), "r") + source = str(path) + else: + source = url or tcbench_url(tcbench_path(model, "fields", init)) + handle = h5py.File(HTTPRangeFile(source), "r") + try: + lat = handle["latitude"][...].astype(np.float64) + lon = handle["longitude"][...].astype(np.float64) + leads = handle["leadtime_hours"][...].astype(np.int64) + levels = list(handle["level"][...].astype(int)) if "level" in handle else [] + data = {} + for name in variables: + source_name, level = _split_variable(name) + if source_name not in handle: + raise KeyError(f"{source} has no variable {source_name!r}") + dataset = handle[source_name] + dims = [dim[0].name.rsplit("/", 1)[-1] if len(dim) else "" for dim in dataset.dims] + index = [] + for dim in dims: + if dim == "time": + index.append(0) + elif dim == "level": + if level not in levels: + raise KeyError(f"level {level} hPa not in {levels}") + index.append(levels.index(level)) + else: + index.append(slice(None)) + raw = dataset[tuple(index)] + kept = [dim for dim, idx in zip(dims, index) if isinstance(idx, slice)] + order = [kept.index(d) for d in ("leadtime_hours", "latitude", "longitude")] + raw = np.transpose(raw, order) + scale = float(np.asarray(dataset.attrs.get("scale_factor", 1.0)).ravel()[0]) + offset = float(np.asarray(dataset.attrs.get("add_offset", 0.0)).ravel()[0]) + fill = dataset.attrs.get("_FillValue") + values = raw.astype(np.float64) * scale + offset + if fill is not None: + values[raw == np.asarray(fill).ravel()[0]] = np.nan + data[name] = (("time", "lat", "lon"), values.astype(np.float32)) + finally: + handle.close() + times = [init + pd.Timedelta(hours=int(h)) for h in leads] + ds = xr.Dataset(data, coords={"time": times, "lat": lat, "lon": lon}) + ds.attrs.update({"source": source, "model": model, "init_time": str(init), "tcbench_revision": TCBENCH_REVISION}) + return ds diff --git a/pyhazards/forecasts/tempest.py b/pyhazards/forecasts/tempest.py new file mode 100644 index 00000000..3da29f8d --- /dev/null +++ b/pyhazards/forecasts/tempest.py @@ -0,0 +1,769 @@ +"""TempestExtremes-compatible cyclone detection (DetectNodes) and stitching (StitchNodes) in Python. + +TCBench (Gomez et al. 2026, https://github.com/msgomez06/TCBench_Alpha) extracts the cyclone tracks +of Pangu-Weather, FourCastNet v2 and AIFS from their global forecast fields with TempestExtremes +(Ullrich and Zarzycki, GMD 10:1069-1090, 2017, doi:10.5194/gmd-10-1069-2017; Ullrich et al., GMD +14:5023-5048, 2021, doi:10.5194/gmd-14-5023-2021), using the commands of +``dev/TempestExtremes_example.sh``:: + + DetectNodes --searchbymin msl --mergedist 6.0 + --closedcontourcmd "msl,200.0,5.5,0;_DIFF(z300,z500),-58.8,6.5,1.0" + --outputcmd "msl,min,0;_VECMAG(u10,v10),max,2" + StitchNodes --in_fmt "lon,lat,slp,wind10" --range 8.0 --mintime 12h + --threshold "wind10,>=,10.0,2;lat,<=,50.0,1;lat,>=,-50.0,1" + +This module implements the subset of DetectNodes and StitchNodes those commands use, on regular +latitude-longitude grids, following the published algorithm descriptions and the TempestExtremes +user guide. TempestExtremes itself (C++, BSD-2-Clause per its repository LICENSE; some source files +still carry an older GPL header) is not copied, linked or required: the official binaries are used +only as the test oracle. ``tests/oracle/test_tempest_oracle.py`` checks that on synthetic fields and +on TCBench's released Pangu-Weather forecast fields this module writes the same tracks, byte for +byte, as DetectNodes and StitchNodes v2.4.2 (and as TCBench's released ``unmatched_tracks`` file). + +Algorithm (DetectNodes, per time step) +-------------------------------------- +1. Candidates: grid points where the search variable is a local minimum (no 4-connected neighbour + strictly smaller; 8-connected with ``diagonal_connectivity``). Longitude wraps around unless + ``regional``; rows at the poles are not connected across the pole. +2. Merge: a candidate is dropped when another candidate within ``merge_dist`` degrees (great-circle, + compared as chord length) has a strictly smaller value. +3. Closed contours, in order: starting from the candidate (or from the extremum of the field within + ``minmax_dist`` degrees of it), a flood fill over connected grid points stops at points whose value + has risen by ``delta`` (fallen, for negative ``delta``) relative to the start value; the criterion + fails when the fill reaches any point farther than ``distance`` degrees from the start point. +4. Outputs: for each surviving node, the minimum or maximum of a field within a great-circle radius. + +Algorithm (StitchNodes) +----------------------- +Each node is linked to its nearest node at the next time (``max_gap`` extra steps allowed) when that +node lies within ``range_deg``; paths are assembled first-come-first-served in time and grid order, +then filtered by duration (``min_time``) and threshold counts. Thresholds and output columns use the +node values as printed by DetectNodes (``%3.6e``), exactly like the C++ tools, which pass them through +a text file. + +Numerics follow the C++ code paths that affect results: fields are single precision, differences of +field values are formed in single precision, great-circle distances use the spherical law of cosines +in double precision, and coordinates are converted with ``deg * (pi / 180)``. + +Only operators used by common cyclone configurations are supported in variable expressions: a field +name, ``_DIFF(a,b)`` and ``_VECMAG(a,b)``. Threshold commands (``--thresholdcmd``), ``--searchbymax`` +and unstructured grids raise ``NotImplementedError``. +""" + +from __future__ import annotations + +import math +import re +from collections import deque +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np + +__all__ = [ + "ClosedContourCriterion", + "DetectNodesConfig", + "NodeOutput", + "StitchNodesConfig", + "StitchThreshold", + "TCBENCH_DETECT_NODES", + "TCBENCH_STITCH_NODES", + "detect_nodes", + "read_stitchnodes_csv", + "stitch_nodes", + "tempest_tracks", + "write_stitchnodes_csv", +] + +# -------------------------------------------------------------------------------------------------- +# Configuration + + +@dataclass(frozen=True) +class ClosedContourCriterion: + """``--closedcontourcmd var,delta,distance,minmaxdist`` (distances in great-circle degrees).""" + + variable: str + delta: float + distance: float + minmax_distance: float = 0.0 + + def __post_init__(self) -> None: + if self.delta == 0.0: + raise ValueError("closed contour delta must be non-zero") + if self.distance <= 0.0: + raise ValueError("closed contour distance must be positive") + if self.minmax_distance < 0.0: + raise ValueError("closed contour min/max distance must be non-negative") + + +@dataclass(frozen=True) +class NodeOutput: + """``--outputcmd var,op,distance`` with ``op`` in ``min`` / ``max``.""" + + variable: str + op: str + distance: float + name: Optional[str] = None + + def __post_init__(self) -> None: + if self.op not in {"min", "max"}: + raise NotImplementedError(f"output operation {self.op!r} is not supported (use 'min' or 'max')") + if self.distance < 0.0: + raise ValueError("output distance must be non-negative") + + +@dataclass(frozen=True) +class DetectNodesConfig: + """Options of ``DetectNodes`` (``search_by_min`` is the variable searched for minima).""" + + search_by_min: str = "msl" + closed_contours: Tuple[ClosedContourCriterion, ...] = () + no_closed_contours: Tuple[ClosedContourCriterion, ...] = () + merge_dist: float = 0.0 + outputs: Tuple[NodeOutput, ...] = () + min_lat: float = 0.0 + max_lat: float = 0.0 + min_abs_lat: float = 0.0 + regional: bool = False + diagonal_connectivity: bool = False + + +@dataclass(frozen=True) +class StitchThreshold: + """``--threshold column,op,value,count``; ``count`` is an integer or ``all`` / ``first`` / ``last``.""" + + column: str + op: str + value: float + count: Union[int, str] = 1 + + _OPS = (">", "<", ">=", "<=", "=", "!=", "|>=", "|<=") + + def __post_init__(self) -> None: + if self.op not in self._OPS: + raise ValueError(f"threshold operation {self.op!r} not in {self._OPS}") + if isinstance(self.count, str) and self.count not in {"all", "first", "last"}: + raise ValueError("threshold count must be an integer or 'all', 'first', 'last'") + + def satisfied(self, value: float) -> bool: + op, ref = self.op, self.value + if op == ">": + return value > ref + if op == "<": + return value < ref + if op == ">=": + return value >= ref + if op == "<=": + return value <= ref + if op == "=": + return value == ref + if op == "!=": + return value != ref + if op == "|>=": + return abs(value) >= ref + return abs(value) <= ref + + +@dataclass(frozen=True) +class StitchNodesConfig: + """Options of ``StitchNodes``. + + ``min_time`` is a number of time steps (int) or a duration in hours (``"12h"`` / float hours); + ``max_gap`` is the number of missing time steps allowed inside a path. + """ + + columns: Tuple[str, ...] = ("lon", "lat") + range_deg: float = 5.0 + min_time: Union[int, str] = 3 + max_gap: int = 0 + thresholds: Tuple[StitchThreshold, ...] = () + min_endpoint_dist: float = 0.0 + min_path_dist: float = 0.0 + + def __post_init__(self) -> None: + if "lat" not in self.columns or "lon" not in self.columns: + raise ValueError("columns must contain 'lat' and 'lon'") + if int(self.max_gap) < 0: + raise ValueError("max_gap must be non-negative") + for threshold in self.thresholds: + if threshold.column not in self.columns: + raise ValueError(f"threshold column {threshold.column!r} not in columns {self.columns}") + + +TCBENCH_DETECT_NODES = DetectNodesConfig( + search_by_min="msl", + closed_contours=( + ClosedContourCriterion("msl", 200.0, 5.5, 0.0), + ClosedContourCriterion("_DIFF(z300,z500)", -58.8, 6.5, 1.0), + ), + merge_dist=6.0, + outputs=(NodeOutput("msl", "min", 0.0, "slp"), NodeOutput("_VECMAG(u10,v10)", "max", 2.0, "wind10")), +) +"""DetectNodes options of TCBench's ``dev/TempestExtremes_example.sh`` (msl in Pa, z in m2 s-2).""" + +TCBENCH_STITCH_NODES = StitchNodesConfig( + columns=("lon", "lat", "slp", "wind10"), + range_deg=8.0, + min_time="12h", + max_gap=0, + thresholds=( + StitchThreshold("wind10", ">=", 10.0, 2), + StitchThreshold("lat", "<=", 50.0, 1), + StitchThreshold("lat", ">=", -50.0, 1), + ), +) +"""StitchNodes options of TCBench's ``dev/TempestExtremes_example.sh``.""" + + +# -------------------------------------------------------------------------------------------------- +# Grid and fields + + +class _Grid: + """Regular lat-lon grid in TempestExtremes' flattened (lat-major) order.""" + + def __init__(self, lat: np.ndarray, lon: np.ndarray, regional: bool, diagonal: bool): + lat = np.asarray(lat, dtype=np.float64) + lon = np.asarray(lon, dtype=np.float64) + if lat.ndim != 1 or lon.ndim != 1 or lat.size < 2 or lon.size < 2: + raise ValueError("lat and lon must be 1-D coordinate vectors with at least two values") + if not regional and np.abs(lat).max() > 90.0 + 1e-10: + raise ValueError("latitudes must lie in [-90, 90] (use regional=True otherwise)") + self.nlat, self.nlon = lat.size, lon.size + self.regional = regional + self.diagonal = diagonal + # TempestExtremes: vecLat[j] *= M_PI / 180.0 + self.lat_rad = lat * (math.pi / 180.0) + self.lon_rad = lon * (math.pi / 180.0) + self._lat = [float(v) for v in self.lat_rad] + self._lon = [float(v) for v in self.lon_rad] + self._sin_lat = [math.sin(v) for v in self._lat] + self._cos_lat = [math.cos(v) for v in self._lat] + + def neighbours(self, ix: int) -> List[int]: + nlat, nlon = self.nlat, self.nlon + j, i = divmod(ix, nlon) + out: List[int] = [] + if self.diagonal: + for di in (-1, 0, 1): + for dj in (-1, 0, 1): + if di == 0 and dj == 0: + continue + inew, jnew = i + di, j + dj + if jnew < 0 or jnew >= nlat: + continue + if self.regional: + if inew < 0 or inew >= nlon: + continue + else: + inew %= nlon + out.append(jnew * nlon + inew) + return out + if j != 0: + out.append((j - 1) * nlon + i) + if j != nlat - 1: + out.append((j + 1) * nlon + i) + if (not self.regional) or (i != 0 and i != nlon - 1): + out.append(j * nlon + (i + 1) % nlon) + out.append(j * nlon + (i + nlon - 1) % nlon) + return out + + def latlon(self, ix: int) -> Tuple[float, float]: + j, i = divmod(ix, self.nlon) + return self._lat[j], self._lon[i] + + def distance_deg(self, ix1: int, ix2: int) -> float: + """GreatCircleDistance_Deg(point 1, point 2) (law of cosines, ``RadToDeg``), same operation order.""" + j1, i1 = divmod(ix1, self.nlon) + j2, i2 = divmod(ix2, self.nlon) + r = self._sin_lat[j1] * self._sin_lat[j2] + self._cos_lat[j1] * self._cos_lat[j2] * math.cos(self._lon[i2] - self._lon[i1]) + if r >= 1.0: + r = 0.0 + elif r <= -1.0: + r = math.pi + else: + r = math.acos(r) + return r * 180.0 / math.pi + + def contour_distance_deg(self, ix0: int, ix: int) -> float: + """Distance as written in HasClosedContour (``180 / pi * acos``; 180 when antipodal).""" + j0, i0 = divmod(ix0, self.nlon) + j, i = divmod(ix, self.nlon) + r = math.sin(self._lat[j0]) * math.sin(self._lat[j]) + math.cos(self._lat[j0]) * math.cos(self._lat[j]) * math.cos(self._lon[i] - self._lon[i0]) + if r >= 1.0: + return 0.0 + if r <= -1.0: + return 180.0 + return 180.0 / math.pi * math.acos(r) + + +_EXPR = re.compile(r"^\s*(_[A-Z]+)\((.*)\)\s*$") + + +def _evaluate(expression: str, fields: Mapping[str, np.ndarray], cache: Dict[str, np.ndarray]) -> np.ndarray: + """Single-precision field for a variable name or a supported TempestExtremes operator.""" + expression = expression.strip() + if expression in cache: + return cache[expression] + match = _EXPR.match(expression) + if match is None: + if expression not in fields: + raise KeyError(f"field {expression!r} not provided (have {sorted(fields)})") + value = np.asarray(fields[expression], dtype=np.float32) + else: + op, inner = match.groups() + if op not in {"_DIFF", "_VECMAG"}: + raise NotImplementedError(f"operator {op} is not supported (only _DIFF and _VECMAG)") + args = _split_args(inner) + if len(args) != 2: + raise ValueError(f"{op} expects two arguments, got {args}") + left, right = (_evaluate(arg, fields, cache) for arg in args) + if op == "_DIFF": + value = (left - right).astype(np.float32) + else: + value = np.sqrt(left * left + right * right).astype(np.float32) + cache[expression] = value + return value + + +def _split_args(inner: str) -> List[str]: + args, depth, start = [], 0, 0 + for k, ch in enumerate(inner): + if ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + elif ch == "," and depth == 0: + args.append(inner[start:k]) + start = k + 1 + args.append(inner[start:]) + return [arg.strip() for arg in args] + + +# -------------------------------------------------------------------------------------------------- +# DetectNodes + + +def _local_minima(grid: _Grid, data: np.ndarray) -> np.ndarray: + """Flat indices of points with no connected neighbour strictly smaller (NaN = fill, ignored).""" + values = data.reshape(grid.nlat, grid.nlon) + valid = ~np.isnan(values) + is_min = valid.copy() + + def shifted(dj: int, di: int): + out = np.full_like(values, np.nan) + rows_src = slice(max(0, dj), grid.nlat + min(0, dj)) + rows_dst = slice(max(0, -dj), grid.nlat + min(0, -dj)) + moved = np.roll(values, -di, axis=1) if di else values + out[rows_dst] = moved[rows_src] + if grid.regional and di: + if di > 0: + out[:, grid.nlon - di :] = np.nan + else: + out[:, : -di] = np.nan + return out + + if grid.diagonal: + offsets = [(dj, di) for dj in (-1, 0, 1) for di in (-1, 0, 1) if (dj, di) != (0, 0)] + else: + offsets = [(-1, 0), (1, 0), (0, 1), (0, -1)] + for dj, di in offsets: + neighbour = shifted(dj, di) + if grid.regional and not grid.diagonal and di: + # 4-connected regional grids drop both zonal links at the first and last column. + neighbour[:, 0] = np.nan + neighbour[:, -1] = np.nan + with np.errstate(invalid="ignore"): + is_min &= ~(neighbour < values) + return np.flatnonzero(is_min) + + +def _xyz(lat: float, lon: float) -> Tuple[float, float, float]: + return math.cos(lon) * math.cos(lat), math.sin(lon) * math.cos(lat), math.sin(lat) + + +def _merge(grid: _Grid, data: np.ndarray, candidates: Sequence[int], merge_dist: float) -> List[int]: + if not candidates: + return [] + chord = 2.0 * math.sin(0.5 * merge_dist / 180.0 * math.pi) + chord_sq = chord * chord + points = np.array([_xyz(*grid.latlon(ix)) for ix in candidates]) + values = data[np.asarray(candidates)] + from scipy.spatial import cKDTree + + tree = cKDTree(points) + neighbours = tree.query_ball_point(points, r=chord * (1.0 + 1e-9) + 1e-15) + kept = [] + for k, ix in enumerate(candidates): + x0, y0, z0 = points[k] + value = float(values[k]) + extremum = True + for m in neighbours[k]: + x, y, z = points[m] + dist_sq = 0.0 + dist_sq += (x - x0) * (x - x0) + dist_sq += (y - y0) * (y - y0) + dist_sq += (z - z0) * (z - z0) + if dist_sq <= chord_sq and float(values[m]) < value: + extremum = False + break + if extremum: + kept.append(ix) + return kept + + +def _find_local_minmax(grid: _Grid, data: np.ndarray, minimum: bool, ix0: int, max_dist: float) -> Tuple[int, float]: + """FindLocalMinMax: extremum (first found on ties) over the connected points within ``max_dist``.""" + best_ix = ix0 + best = data[ix0] + best_is_fill = bool(np.isnan(best)) + seen = set() + queue = deque([ix0]) + while queue: + ix = queue.popleft() + if ix in seen: + continue + seen.add(ix) + if grid.distance_deg(ix, ix0) > max_dist: + continue + value = data[ix] + if not np.isnan(value): + if best_is_fill or (value < best if minimum else value > best): + best_ix, best, best_is_fill = ix, value, False + queue.extend(grid.neighbours(ix)) + return best_ix, float(best) + + +def _has_closed_contour(grid: _Grid, data: np.ndarray, ix0: int, criterion: ClosedContourCriterion) -> bool: + delta = float(criterion.delta) + origin = ix0 + if criterion.minmax_distance != 0.0: + origin, _ = _find_local_minmax(grid, data, delta > 0.0, ix0, criterion.minmax_distance) + ref = data[origin] + seen = set() + queue = deque([origin]) + while queue: + ix = queue.popleft() + if ix in seen: + continue + seen.add(ix) + if grid.contour_distance_deg(origin, ix) > criterion.distance: + return False + value = data[ix] + # Single-precision difference compared with the double-precision delta, as in the C++ code. + if delta > 0.0: + if float(value - ref) >= delta: + continue + elif float(ref - value) >= -delta: + continue + queue.extend(grid.neighbours(ix)) + return True + + +def _output_value(grid: _Grid, data: np.ndarray, ix: int, output: NodeOutput) -> float: + _, value = _find_local_minmax(grid, data, output.op == "min", ix, output.distance) + return value + + +def _format_e(value: float) -> str: + return "%3.6e" % value + + +def _format_f(value: float) -> str: + return "%3.6f" % value + + +def detect_nodes( + fields: Mapping[str, np.ndarray], + lat: Sequence[float], + lon: Sequence[float], + times: Sequence, + config: DetectNodesConfig = TCBENCH_DETECT_NODES, +): + """Run DetectNodes on fields shaped ``(time, lat, lon)``. + + ``fields`` maps variable names to arrays (cast to float32 like TempestExtremes). NaN marks missing + values: such points are never candidates, but inside closed-contour tests they never stop the + flood fill (TempestExtremes compares its numeric fill value instead), so fill gaps before tracking + fields that have them. Returns a DataFrame with one row per node: ``time``, ``i`` (longitude index), ``j`` + (latitude index), ``lon``, ``lat`` (degrees, as printed by DetectNodes), one float column per output + (named ``output.name`` or ``out``) and ``text_`` columns holding the printed strings. + """ + import pandas as pd + + grid = _Grid(np.asarray(lat), np.asarray(lon), config.regional, config.diagonal_connectivity) + times = pd.to_datetime(list(times)) + arrays = {name: np.asarray(value) for name, value in fields.items()} + for name, value in arrays.items(): + if value.ndim != 3 or value.shape[1:] != (grid.nlat, grid.nlon) or value.shape[0] != len(times): + raise ValueError( + f"field {name!r} must be shaped (time={len(times)}, lat={grid.nlat}, lon={grid.nlon}), got {value.shape}" + ) + if config.min_lat > config.max_lat: + raise ValueError("min_lat must not exceed max_lat") + names = [out.name or f"out{k}" for k, out in enumerate(config.outputs)] + rows: List[Dict[str, object]] = [] + for t, time in enumerate(times): + step = {name: value[t] for name, value in arrays.items()} + cache: Dict[str, np.ndarray] = {} + search = _evaluate(config.search_by_min, step, cache).reshape(-1) + candidates = [int(ix) for ix in _local_minima(grid, search)] + if config.min_lat != config.max_lat or config.min_abs_lat != 0.0: + kept = [] + # TempestExtremes: dMinLatitude *= M_PI / 180.0 + lo, hi, absmin = (value * (math.pi / 180.0) for value in (config.min_lat, config.max_lat, config.min_abs_lat)) + for ix in candidates: + la, _ = grid.latlon(ix) + if config.min_lat != config.max_lat and (la < lo or la > hi): + continue + if config.min_abs_lat != 0.0 and abs(la) < absmin: + continue + kept.append(ix) + candidates = kept + if config.merge_dist != 0.0: + candidates = _merge(grid, search, candidates, config.merge_dist) + for criterion in config.closed_contours: + data = _evaluate(criterion.variable, step, cache).reshape(-1) + candidates = [ix for ix in candidates if _has_closed_contour(grid, data, ix, criterion)] + for criterion in config.no_closed_contours: + data = _evaluate(criterion.variable, step, cache).reshape(-1) + candidates = [ix for ix in candidates if not _has_closed_contour(grid, data, ix, criterion)] + output_data = [_evaluate(out.variable, step, cache).reshape(-1) for out in config.outputs] + for ix in sorted(candidates): + j, i = divmod(ix, grid.nlon) + row: Dict[str, object] = { + "time": time, + "i": i, + "j": j, + "text_lon": _format_f(grid._lon[i] * 180.0 / math.pi), + "text_lat": _format_f(grid._lat[j] * 180.0 / math.pi), + } + for name, out, data in zip(names, config.outputs, output_data): + row["text_" + name] = _format_e(_output_value(grid, data, ix, out)) + rows.append(row) + columns = ["time", "i", "j", "text_lon", "text_lat"] + ["text_" + name for name in names] + frame = pd.DataFrame(rows, columns=columns) + frame["lon"] = frame["text_lon"].astype(float) + frame["lat"] = frame["text_lat"].astype(float) + for name in names: + frame[name] = frame["text_" + name].astype(float) + return frame + + + +# -------------------------------------------------------------------------------------------------- +# StitchNodes + + +def _min_time_seconds(min_time: Union[int, str, float]) -> Tuple[int, float]: + """(minimum number of steps, minimum duration in seconds).""" + if isinstance(min_time, (int, np.integer)) and not isinstance(min_time, bool): + if int(min_time) < 1: + raise ValueError("min_time as a step count must be positive") + return int(min_time), 0.0 + if isinstance(min_time, float): + hours = min_time + else: + text = str(min_time).strip() + if text.isdigit(): + return _min_time_seconds(int(text)) + match = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([hd])", text) + if match is None: + raise ValueError(f"min_time must be a step count, 'h' or 'd', got {min_time!r}") + hours = float(match.group(1)) * (24.0 if match.group(2) == "d" else 1.0) + if hours <= 0: + raise ValueError("min_time must be positive") + return 1, hours * 3600.0 + + +def stitch_nodes(nodes, config: StitchNodesConfig = TCBENCH_STITCH_NODES): + """Run StitchNodes on the output of :func:`detect_nodes` (or a table with the same columns). + + Returns a DataFrame with one row per track point: ``track_id`` (0-based, in path order), + ``time``, ``i``, ``j`` and the configured columns as floats, plus ``text_`` strings. + The time steps are the distinct node times together with ``nodes.attrs['times']`` (set by + :func:`tempest_tracks`, so that a time without any node still counts as a step, as in a + DetectNodes file). Nodes of one time are taken in table order (DetectNodes: ascending grid index). + """ + import pandas as pd + + min_steps, min_seconds = _min_time_seconds(config.min_time) + times = sorted(set(pd.to_datetime(nodes["time"]).tolist()) | set(pd.to_datetime(nodes.attrs.get("times", [])).tolist())) + if not times: + raise ValueError("no candidate nodes to stitch") + text_cols = [] + for column in config.columns: + name = "text_" + column + if name not in nodes.columns: + if column not in nodes.columns: + raise KeyError(f"nodes have no column {column!r}") + nodes = nodes.assign(**{name: nodes[column].map(_format_e if column not in {"lon", "lat"} else _format_f)}) + text_cols.append(name) + by_time: List[List[Dict[str, object]]] = [] + stamps = pd.to_datetime(nodes["time"]) + for time in times: + rows = nodes[stamps == time] + # Candidates keep the DetectNodes order (ascending flat grid index). + by_time.append(rows.to_dict("records")) + lon_col = text_cols[config.columns.index("lon")] + lat_col = text_cols[config.columns.index("lat")] + geo: List[List[Tuple[float, float, float, float, float]]] = [] + for rows in by_time: + level = [] + for row in rows: + lon_r = float(row[lon_col]) * math.pi / 180.0 + lat_r = float(row[lat_col]) * math.pi / 180.0 + level.append((lon_r, lat_r) + _xyz(lat_r, lon_r)) + geo.append(level) + + def gc_deg(a, b) -> float: + r = math.sin(a[1]) * math.sin(b[1]) + math.cos(a[1]) * math.cos(b[1]) * math.cos(b[0] - a[0]) + if r >= 1.0: + r = 0.0 + elif r <= -1.0: + r = math.pi + else: + r = math.acos(r) + return r * 180.0 / math.pi + + n_times = len(times) + segments: List[Dict[int, Tuple[int, int]]] = [dict() for _ in range(max(n_times - 1, 0))] + for t in range(n_times - 1): + for i, node in enumerate(geo[t]): + for g in range(1, int(config.max_gap) + 2): + if t + g >= n_times: + break + if not geo[t + g]: + continue + best, best_d = None, None + for k, other in enumerate(geo[t + g]): + d = (other[2] - node[2]) ** 2 + (other[3] - node[3]) ** 2 + (other[4] - node[4]) ** 2 + if best_d is None or d < best_d: + best, best_d = k, d + if gc_deg(node, geo[t + g][best]) <= config.range_deg: + segments[t][i] = (t + g, best) + break + + paths: List[List[Tuple[int, int]]] = [] + for t in range(n_times - 1): + while segments[t]: + start = min(segments[t]) + path = [(t, start)] + tx, cand = t, start + while True: + nxt = segments[tx].pop(cand) + path.append(nxt) + tnext, cnext = nxt + if tnext >= n_times - 1 or cnext not in segments[tnext]: + break + tx, cand = tnext, cnext + paths.append(path) + + kept_paths = [] + for path in paths: + if len(path) < min_steps: + continue + if min_seconds > 0.0: + duration = (times[path[-1][0]] - times[path[0][0]]).total_seconds() + if duration < min_seconds: + continue + if config.min_endpoint_dist > 0.0: + if gc_deg(geo[path[0][0]][path[0][1]], geo[path[-1][0]][path[-1][1]]) < config.min_endpoint_dist: + continue + if config.min_path_dist > 0.0: + total = sum(gc_deg(geo[a[0]][a[1]], geo[b[0]][b[1]]) for a, b in zip(path[:-1], path[1:])) + if total < config.min_path_dist: + continue + ok = True + for threshold in config.thresholds: + col = text_cols[config.columns.index(threshold.column)] + points = path + if threshold.count == "first": + points = path[:1] + elif threshold.count == "last": + points = path[-1:] + count = sum(threshold.satisfied(float(by_time[t][c][col])) for t, c in points) + if threshold.count == "all": + ok = count == len(path) + elif threshold.count in {"first", "last"}: + ok = count == 1 + else: + ok = count >= int(threshold.count) + if not ok: + break + if ok: + kept_paths.append(path) + + rows = [] + for track_id, path in enumerate(kept_paths): + for t, c in path: + node = by_time[t][c] + row = {"track_id": track_id, "time": times[t], "i": int(node["i"]), "j": int(node["j"])} + for column, text in zip(config.columns, text_cols): + row["text_" + column] = node[text] + row[column] = float(node[text]) + rows.append(row) + columns = ["track_id", "time", "i", "j"] + list(config.columns) + ["text_" + c for c in config.columns] + return pd.DataFrame(rows, columns=columns) + + +def tempest_tracks( + fields: Mapping[str, np.ndarray], + lat: Sequence[float], + lon: Sequence[float], + times: Sequence, + detect: DetectNodesConfig = TCBENCH_DETECT_NODES, + stitch: StitchNodesConfig = TCBENCH_STITCH_NODES, +): + """DetectNodes followed by StitchNodes (defaults: the TCBench configuration).""" + nodes = detect_nodes(fields, lat, lon, times, detect) + nodes.attrs["times"] = list(times) + return stitch_nodes(nodes, stitch) + + +def write_stitchnodes_csv(tracks, path) -> None: + """Write tracks in StitchNodes' ``--out_file_format csv`` layout (the TCBench ``unmatched_tracks`` files).""" + import pandas as pd + + columns = [c[len("text_"):] for c in tracks.columns if c.startswith("text_")] + lines = ["track_id, year, month, day, hour, i, j" + "".join(f", {c}" for c in columns)] + for row in tracks.itertuples(index=False): + record = row._asdict() + stamp = pd.Timestamp(record["time"]) + seconds = stamp.hour * 3600 + stamp.minute * 60 + stamp.second + values = [str(record["track_id"]), str(stamp.year), str(stamp.month), str(stamp.day), str(seconds // 3600), str(record["i"]), str(record["j"])] + values += [str(record["text_" + c]) for c in columns] + lines.append(", ".join(values)) + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write("\n".join(lines) + "\n") + + +def read_stitchnodes_csv(path, columns: Optional[Iterable[str]] = None): + """Read a StitchNodes CSV (e.g. a TCBench ``unmatched_tracks`` file) into the :func:`stitch_nodes` layout.""" + import pandas as pd + + frame = pd.read_csv(path, skipinitialspace=True, dtype=str) + frame.columns = [c.strip() for c in frame.columns] + required = ["track_id", "year", "month", "day", "hour", "i", "j", "lon", "lat"] + missing = [c for c in required if c not in frame.columns] + if missing: + raise ValueError(f"{path} is not a StitchNodes CSV: missing columns {missing}") + value_cols = [c for c in frame.columns if c not in {"track_id", "year", "month", "day", "hour", "i", "j"}] + if columns is not None: + value_cols = [c for c in value_cols if c in set(columns) | {"lon", "lat"}] + out = pd.DataFrame( + { + "track_id": frame["track_id"].astype(int), + "time": pd.to_datetime( + {"year": frame["year"].astype(int), "month": frame["month"].astype(int), "day": frame["day"].astype(int), "hour": frame["hour"].astype(int)} + ), + "i": frame["i"].astype(int), + "j": frame["j"].astype(int), + } + ) + for column in value_cols: + out[column] = frame[column].astype(float) + for column in value_cols: + out["text_" + column] = frame[column].str.strip() + return out diff --git a/pyhazards/forecasts/weatherbench2.py b/pyhazards/forecasts/weatherbench2.py new file mode 100644 index 00000000..c9fa0716 --- /dev/null +++ b/pyhazards/forecasts/weatherbench2.py @@ -0,0 +1,169 @@ +"""Reader for the GraphCast and Pangu-Weather forecasts published by WeatherBench 2. + +WeatherBench 2 (Rasp et al., JAMES 2024, doi:10.1029/2023MS004019) hosts global 0.25-degree +forecasts on Google Cloud Storage (public bucket ``gs://weatherbench2``, zarr v2): + +* GraphCast (Lam et al. 2023), ERA5 initial conditions at 00/12 UTC: 2018 forecasts from the model + trained on 1979-2017 (the paper's test-year model) and 2020 forecasts (trained to 2019); + ``graphcast_hres_init`` holds GraphCast-operational 2020 forecasts from HRES analyses. +* Pangu-Weather (Bi et al. 2023), run by the WeatherBench 2 team with the official code and weights: + 2018-2022 from ERA5 (``pangu``) and 2020-2022 from HRES (``pangu_hres_init``). + +Lead times are 0-234 h every 6 h. WeatherBench 2 does not host FourCastNet forecasts. The WeatherBench +2 data guide asks users to check each dataset's licence ("some datasets allow commercial use, others +only permit research use"); no licence file was found next to these forecasts, and the Pangu-Weather +forecasts derive from weights licensed CC BY-NC-SA 4.0, so treat them as non-commercial. PyHazards +reads them at run time and never redistributes them. + +Each zarr chunk holds one initial time, one lead time and the whole globe (all pressure levels for +upper-air variables), so a pressure-level variable costs one full chunk per lead time even when only +one level is used (about 54 MB uncompressed for Pangu's 13 levels, 154 MB for GraphCast's 37). Reading +needs the optional packages ``zarr`` and ``gcsfs`` (``pip install pyhazards[weather]``). +""" + +from __future__ import annotations + +from typing import Dict, Iterable, Optional, Sequence, Tuple, Union + +import numpy as np + +__all__ = ["WEATHERBENCH2_FORECASTS", "read_weatherbench2_forecast", "weatherbench2_url"] + +_BUCKET = "gs://weatherbench2/datasets" + +WEATHERBENCH2_FORECASTS: Dict[str, Dict[Union[int, str], str]] = { + "graphcast": { + 2018: f"{_BUCKET}/graphcast/2018/date_range_2017-11-16_2019-02-01_12_hours.zarr", + 2020: f"{_BUCKET}/graphcast/2020/date_range_2019-11-16_2021-02-01_12_hours.zarr", + }, + "graphcast_hres_init": { + 2020: f"{_BUCKET}/graphcast_hres_init/2020/date_range_2019-11-16_2021-02-01_12_hours.zarr", + }, + "pangu": {"all": f"{_BUCKET}/pangu/2018-2022_0012_0p25.zarr"}, + "pangu_hres_init": {year: f"{_BUCKET}/pangu_hres_init/{year}_0012_0p25.zarr" for year in (2020, 2021, 2022)}, +} +"""0.25-degree forecast stores by model and year (``all`` = one store for every year).""" + +_SURFACE = { + "msl": "mean_sea_level_pressure", + "u10": "10m_u_component_of_wind", + "v10": "10m_v_component_of_wind", + "t2m": "2m_temperature", +} +_LEVEL = {"u": "u_component_of_wind", "v": "v_component_of_wind", "z": "geopotential", "t": "temperature", "q": "specific_humidity"} + + +def weatherbench2_url(model: str, init_time) -> str: + """Store holding ``model``'s forecast initialised at ``init_time``.""" + import pandas as pd + + if model not in WEATHERBENCH2_FORECASTS: + raise ValueError(f"unknown WeatherBench 2 model {model!r}; choose from {sorted(WEATHERBENCH2_FORECASTS)}") + stores = WEATHERBENCH2_FORECASTS[model] + if "all" in stores: + return stores["all"] + stamp = pd.Timestamp(init_time) + # The GraphCast stores span mid-November of the previous year to the end of January of the next. + for year in (stamp.year, stamp.year + 1, stamp.year - 1): + if year in stores: + url = stores[year] + if "date_range_" in url: + start, end = url.split("date_range_")[1].split("_")[:2] + if pd.Timestamp(start) <= stamp <= pd.Timestamp(end): + return url + elif year == stamp.year: + return url + raise ValueError(f"no WeatherBench 2 {model} store covers {stamp}") + + +def _source_name(name: str) -> Tuple[str, Optional[int]]: + if name in _SURFACE: + return _SURFACE[name], None + for prefix, long_name in _LEVEL.items(): + rest = name[len(prefix):] + if name.startswith(prefix) and rest.isdigit(): + return long_name, int(rest) + raise ValueError(f"cannot map {name!r} to a WeatherBench 2 variable (msl, u10, v10, t2m, u/v/z/t/q)") + + +def _lead_hours(coord) -> list: + """Lead times in hours whether or not xarray decoded ``prediction_timedelta`` (units: hours).""" + values = np.asarray(coord.values) + if np.issubdtype(values.dtype, np.timedelta64): + return [int(v) for v in values / np.timedelta64(1, "h")] + units = str(coord.attrs.get("units", "hours")) + if units != "hours": + raise ValueError(f"unexpected prediction_timedelta units {units!r}") + return [int(v) for v in values] + + +def read_weatherbench2_forecast( + model: str, + init_time, + variables: Sequence[str] = ("msl", "u10", "v10", "z300", "z500"), + lead_hours: Optional[Iterable[int]] = None, + lat_bounds: Optional[Tuple[float, float]] = None, + lon_bounds: Optional[Tuple[float, float]] = None, + url: Optional[str] = None, + storage_options: Optional[dict] = None, +): + """One forecast as an ``xarray.Dataset`` in the tracker conventions (``time`` = valid times). + + ``lead_hours`` defaults to the available 6-hourly leads up to 120 h (the Pangu-Weather stores start + at 6 h, the GraphCast stores at 0 h). ``lat_bounds`` / ``lon_bounds`` (degrees, longitudes + 0-360 and possibly wrapping, e.g. ``(300, 30)``) crop the result after reading; they do not reduce + the download (see the module docstring). ``url`` overrides the store (any path xarray's zarr + backend opens, e.g. a local copy); ``gs://`` stores are read anonymously. + """ + import pandas as pd + import xarray as xr + + try: + import zarr # noqa: F401 + except ImportError as exc: # pragma: no cover - depends on the environment + raise ImportError("reading WeatherBench 2 needs zarr (and gcsfs for gs:// stores): pip install pyhazards[weather]") from exc + init = pd.Timestamp(init_time) + store = url or weatherbench2_url(model, init) + options = storage_options + if options is None and str(store).startswith("gs://"): + options = {"token": "anon"} + ds = xr.open_zarr(store, consolidated=True, chunks=None, storage_options=options) + ds = ds.rename({k: v for k, v in {"latitude": "lat", "longitude": "lon"}.items() if k in ds.dims}) + if init not in pd.to_datetime(ds["time"].values): + raise KeyError(f"{store} has no forecast initialised at {init}") + available = _lead_hours(ds["prediction_timedelta"]) + if lead_hours is None: + leads = [h for h in available if 0 <= h <= 120 and h % 6 == 0] + else: + leads = [int(h) for h in lead_hours] + absent = sorted(set(leads) - set(available)) + if absent: + raise KeyError(f"{store} has no lead times {absent} h (available: {available[:3]}...{available[-1]})") + ds = ds.sel(time=init.to_datetime64()).isel(prediction_timedelta=[available.index(h) for h in leads]) + lat_sel = slice(None) + lat = ds["lat"].values + if lat_bounds is not None: + lo, hi = sorted(lat_bounds) + lat_sel = np.flatnonzero((lat >= lo) & (lat <= hi)) + lon_sel = slice(None) + lon = ds["lon"].values % 360.0 + if lon_bounds is not None: + west, east = (b % 360.0 for b in lon_bounds) + mask = (lon >= west) & (lon <= east) if west <= east else (lon >= west) | (lon <= east) + lon_sel = np.flatnonzero(mask) + data = {} + for name in variables: + source, level = _source_name(name) + if source not in ds: + raise KeyError(f"{store} has no variable {source!r}") + array = ds[source] + if level is not None: + array = array.sel(level=level) + array = array.transpose("prediction_timedelta", "lat", "lon").isel(lat=lat_sel, lon=lon_sel) + data[name] = (("time", "lat", "lon"), np.asarray(array.values, dtype=np.float32)) + out_lat = lat if isinstance(lat_sel, slice) else lat[lat_sel] + out_lon = ds["lon"].values if isinstance(lon_sel, slice) else ds["lon"].values[lon_sel] + times = [init + pd.Timedelta(hours=h) for h in leads] + result = xr.Dataset(data, coords={"time": times, "lat": out_lat.astype(np.float64), "lon": out_lon.astype(np.float64)}) + result.attrs.update({"source": str(store), "model": model, "init_time": str(init)}) + return result diff --git a/pyhazards/metrics/hydrology.py b/pyhazards/metrics/hydrology.py new file mode 100644 index 00000000..03993eee --- /dev/null +++ b/pyhazards/metrics/hydrology.py @@ -0,0 +1,395 @@ +"""Hydrological evaluation metrics, defined as in NeuralHydrology. + +Ported from NeuralHydrology, ``neuralhydrology/evaluation/metrics.py`` at commit ea94a40 +(https://github.com/neuralhydrology/neuralhydrology, BSD-3-Clause, Copyright (c) 2021, NeuralHydrology). +The reference works on xarray DataArrays; this port works on 1-D NumPy arrays (plus an optional array of +dates for the peak-timing metrics) and keeps every definition, default and edge case of the reference: + +- observations and simulations are masked to the time steps where both are finite; +- standard deviations are population standard deviations (``ddof=0``, as ``DataArray.std()``); +- the flow-duration-curve metrics set zero observations and non-positive simulations to 1e-6 before + taking logarithms, and use ``np.round`` (round half to even) for the curve indices; +- the peak metrics find observed peaks with ``scipy.signal.find_peaks`` and skip peaks whose window + runs past the series or across a gap in the dates. + +``calculate_metrics`` returns NeuralHydrology's deterministic metric set for one basin under +snake-case names (``NSE`` -> ``nse``, ``Alpha-NSE`` -> ``alpha_nse``, ``Peak-Timing`` -> ``peak_timing``, ...). +``aggregate_basin_metrics`` summarises per-basin values the way Kratzert et al. (HESS 2019, Table 2) +report them: the median and the mean over basins, and the number of basins with NSE <= 0. +""" + +from __future__ import annotations + +from typing import Callable, Dict, Iterable, Mapping, Optional, Sequence, Tuple + +import numpy as np +import pandas as pd +from scipy import signal, stats + +# NeuralHydrology name -> PyHazards key, in the order of ``calculate_all_metrics``. +NEURALHYDROLOGY_METRIC_NAMES: Dict[str, str] = { + "NSE": "nse", + "MSE": "mse", + "RMSE": "rmse", + "KGE": "kge", + "Alpha-NSE": "alpha_nse", + "Beta-KGE": "beta_kge", + "Beta-NSE": "beta_nse", + "Pearson-r": "pearson_r", + "FHV": "fhv", + "FMS": "fms", + "FLV": "flv", + "Peak-Timing": "peak_timing", + "Missed-Peaks": "missed_peaks", + "Peak-MAPE": "peak_mape", +} +STREAMFLOW_METRICS: Tuple[str, ...] = tuple(NEURALHYDROLOGY_METRIC_NAMES.values()) + + +def _as_series(obs, sim) -> Tuple[np.ndarray, np.ndarray]: + obs = np.asarray(obs, dtype=np.float64) + sim = np.asarray(sim, dtype=np.float64) + if obs.shape != sim.shape: + raise ValueError(f"Shapes of observations {obs.shape} and simulations {sim.shape} must match.") + if obs.ndim != 1: + raise ValueError(f"Metrics are only defined for 1-D time series, got ndim={obs.ndim}.") + return obs, sim + + +def _mask_valid(obs: np.ndarray, sim: np.ndarray, dates: Optional[np.ndarray] = None): + """Keep the time steps where neither series is NaN (``_mask_valid`` of the reference).""" + idx = ~np.isnan(sim) & ~np.isnan(obs) + if dates is None: + return obs[idx], sim[idx] + return obs[idx], sim[idx], dates[idx] + + +def _fdc(values: np.ndarray) -> np.ndarray: + """Flow duration curve: values sorted in descending order.""" + return np.sort(values)[::-1].copy() + + +def nse(obs, sim) -> float: + """Nash-Sutcliffe efficiency: 1 - sum((sim - obs)^2) / sum((obs - mean(obs))^2).""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + denominator = ((obs - obs.mean()) ** 2).sum() + numerator = ((sim - obs) ** 2).sum() + with np.errstate(divide="ignore", invalid="ignore"): + return float(1 - numerator / denominator) + + +def mse(obs, sim) -> float: + obs, sim = _mask_valid(*_as_series(obs, sim)) + with np.errstate(invalid="ignore"): + return float(((sim - obs) ** 2).mean()) if obs.size else float("nan") + + +def rmse(obs, sim) -> float: + return float(np.sqrt(mse(obs, sim))) + + +def alpha_nse(obs, sim) -> float: + """Ratio of the standard deviations, sigma_sim / sigma_obs (Gupta et al. 2009).""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + with np.errstate(divide="ignore", invalid="ignore"): + return float(sim.std() / obs.std()) if obs.size else float("nan") + + +def beta_nse(obs, sim) -> float: + """(mean(sim) - mean(obs)) / sigma_obs (Gupta et al. 2009).""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + with np.errstate(divide="ignore", invalid="ignore"): + return float((sim.mean() - obs.mean()) / obs.std()) if obs.size else float("nan") + + +def beta_kge(obs, sim) -> float: + """mean(sim) / mean(obs), the bias term of the KGE.""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + with np.errstate(divide="ignore", invalid="ignore"): + return float(sim.mean() / obs.mean()) if obs.size else float("nan") + + +def kge(obs, sim, weights: Sequence[float] = (1.0, 1.0, 1.0)) -> float: + """Kling-Gupta efficiency 1 - sqrt((s_r (r-1))^2 + (s_a (alpha-1))^2 + (s_b (beta-1))^2). + + As in the reference, the weights multiply the squared terms. + """ + if len(weights) != 3: + raise ValueError("Weights of the KGE must be a list of three values") + obs, sim = _mask_valid(*_as_series(obs, sim)) + if len(obs) < 2: + return float("nan") + r, _ = stats.pearsonr(obs, sim) + with np.errstate(divide="ignore", invalid="ignore"): + alpha = sim.std() / obs.std() + beta = sim.mean() / obs.mean() + value = weights[0] * (r - 1) ** 2 + weights[1] * (alpha - 1) ** 2 + weights[2] * (beta - 1) ** 2 + return float(1 - np.sqrt(float(value))) + + +def pearson_r(obs, sim) -> float: + obs, sim = _mask_valid(*_as_series(obs, sim)) + if len(obs) < 2: + return float("nan") + r, _ = stats.pearsonr(obs, sim) + return float(r) + + +def fdc_fms(obs, sim, lower: float = 0.2, upper: float = 0.7) -> float: + """Bias of the slope of the middle section of the flow duration curve, in percent (Yilmaz et al. 2008).""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + if len(obs) < 1: + return float("nan") + if any((x <= 0) or (x >= 1) for x in (upper, lower)): + raise ValueError("upper and lower have to be in range ]0,1[") + if lower >= upper: + raise ValueError("The lower threshold has to be smaller than the upper.") + obs, sim = _fdc(obs), _fdc(sim) + sim[sim <= 0] = 1e-6 + obs[obs == 0] = 1e-6 + with np.errstate(divide="ignore", invalid="ignore"): + qsm_lower = np.log(sim[np.round(lower * len(sim)).astype(int)]) + qsm_upper = np.log(sim[np.round(upper * len(sim)).astype(int)]) + qom_lower = np.log(obs[np.round(lower * len(obs)).astype(int)]) + qom_upper = np.log(obs[np.round(upper * len(obs)).astype(int)]) + fms = ((qsm_lower - qsm_upper) - (qom_lower - qom_upper)) / (qom_lower - qom_upper + 1e-6) + return float(fms * 100) + + +def fdc_fhv(obs, sim, h: float = 0.02) -> float: + """Peak-flow bias of the top ``h`` fraction of the flow duration curve, in percent.""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + if len(obs) < 1: + return float("nan") + if (h <= 0) or (h >= 1): + raise ValueError("h has to be in range ]0,1[. Consider small values, e.g. 0.02 for 2% peak flows") + obs, sim = _fdc(obs), _fdc(sim) + obs = obs[: np.round(h * len(obs)).astype(int)] + sim = sim[: np.round(h * len(sim)).astype(int)] + with np.errstate(divide="ignore", invalid="ignore"): + fhv = np.sum(sim - obs) / np.sum(obs) + return float(fhv * 100) + + +def fdc_flv(obs, sim, l: float = 0.3) -> float: # noqa: E741 (reference argument name) + """Low-flow bias of the bottom ``l`` fraction of the flow duration curve (log space), in percent. + + As in the reference, a fraction that rounds to zero elements selects the whole curve + (``array[-0:]``). + """ + obs, sim = _mask_valid(*_as_series(obs, sim)) + if len(obs) < 1: + return float("nan") + if (l <= 0) or (l >= 1): + raise ValueError("l has to be in range ]0,1[. Consider small values, e.g. 0.3 for 30% low flows") + obs, sim = _fdc(obs), _fdc(sim) + sim[sim <= 0] = 1e-6 + obs[obs == 0] = 1e-6 + obs = obs[-np.round(l * len(obs)).astype(int):] + sim = sim[-np.round(l * len(sim)).astype(int):] + with np.errstate(divide="ignore", invalid="ignore"): + obs = np.log(obs) + sim = np.log(sim) + qsl = np.sum(sim - sim.min()) + qol = np.sum(obs - obs.min()) + flv = -1 * (qsl - qol) / (qol + 1e-6) + return float(flv * 100) + + +def _resolution(resolution: str) -> pd.Timedelta: + return pd.to_timedelta(resolution if resolution[0].isdigit() else "1" + resolution) + + +def _default_window(minimum: int, resolution: str) -> int: + # NeuralHydrology: max(int(get_frequency_factor('12h', resolution)), minimum). + return max(int(pd.Timedelta("12h") / _resolution(resolution)), minimum) + + +def _dates_or_index(dates, n: int, resolution: str) -> np.ndarray: + if dates is None: + return (np.datetime64("2000-01-01") + np.arange(n) * _resolution(resolution).to_timedelta64()) + dates = np.asarray(dates, dtype="datetime64[ns]") + if dates.shape != (n,): + raise ValueError(f"dates must have shape ({n},), got {dates.shape}.") + return dates + + +def _window_has_gap(dates: np.ndarray, idx: int, window: int, step: pd.Timedelta) -> bool: + # pd.date_range(dates[idx - window], dates[idx + window], freq=step).size != 2 * window + 1 + span = pd.Timedelta(dates[idx + window] - dates[idx - window]) + size = int(span // step) + 1 if span >= pd.Timedelta(0) else 0 + return size != 2 * window + 1 + + +def mean_peak_timing(obs, sim, dates=None, window: Optional[int] = None, resolution: str = "1D") -> float: + """Mean absolute timing error (in time steps) of the observed peaks (Kratzert et al. 2021, appendix). + + Observed peaks: ``find_peaks(obs, distance=100, prominence=std(obs))``. The simulated peak is the + value at the observed peak when it is a local maximum, else the maximum within ``window`` steps + on either side (default 3 for daily data). ``dates`` (one per time step) are needed to skip + windows across gaps; without them the series is taken as gap-free. + """ + obs, sim = _as_series(obs, sim) + dates = _dates_or_index(dates, len(obs), resolution) + obs, sim, dates = _mask_valid(obs, sim, dates) + step = _resolution(resolution) + peaks, _ = signal.find_peaks(obs, distance=100, prominence=np.std(obs)) + if window is None: + window = _default_window(3, resolution) + timing_errors = [] + for idx in peaks: + if (idx - window < 0) or (idx + window >= len(obs)) or _window_has_gap(dates, idx, window, step): + continue + if (sim[idx] > sim[idx - 1]) and (sim[idx] > sim[idx + 1]): + peak_sim = idx + else: + peak_sim = idx - window + int(np.argmax(sim[idx - window: idx + window + 1])) + delta = pd.Timedelta(dates[idx] - dates[peak_sim]) + timing_errors.append(abs(delta / step)) + return float(np.mean(timing_errors)) if timing_errors else float("nan") + + +def missed_peaks( + obs, sim, dates=None, window: Optional[int] = None, resolution: str = "1D", percentile: float = 80 +) -> float: + """Fraction of observed peaks above the ``percentile`` flow without a simulated peak nearby. + + Peaks of both series: ``find_peaks(distance=30, height=percentile)``; a simulated peak within + ``window`` steps (default 1 for daily data) counts as a hit. As in the reference, the denominator + counts all observed peaks, including those skipped at the edges or next to gaps. + """ + obs, sim = _as_series(obs, sim) + dates = _dates_or_index(dates, len(obs), resolution) + obs, sim, dates = _mask_valid(obs, sim, dates) + step = _resolution(resolution) + min_obs_height = np.percentile(obs, percentile) + min_sim_height = np.percentile(sim, percentile) + peaks_obs_times, _ = signal.find_peaks(obs, distance=30, height=min_obs_height) + peaks_sim_times, _ = signal.find_peaks(sim, distance=30, height=min_sim_height) + if len(peaks_obs_times) == 0: + return 0.0 + if window is None: + window = _default_window(1, resolution) + missed_events = 0 + for idx in peaks_obs_times: + if (idx - window < 0) or (idx + window >= len(obs)) or _window_has_gap(dates, idx, window, step): + continue + if len(np.where(np.abs(peaks_sim_times - idx) <= window)[0]) == 0: + missed_events += 1 + return missed_events / len(peaks_obs_times) + + +def mean_absolute_percentage_peak_error(obs, sim) -> float: + """Mean absolute percentage error of the simulation at the observed peaks (``distance=100``, + ``prominence=std(obs)``).""" + obs, sim = _mask_valid(*_as_series(obs, sim)) + if obs.size == 0 or sim.size == 0: + return float("nan") + peaks, _ = signal.find_peaks(obs, distance=100, prominence=np.std(obs)) + if peaks.size == 0: + return float("nan") + obs, sim = obs[peaks], sim[peaks] + with np.errstate(divide="ignore", invalid="ignore"): + return float(np.sum(np.abs((sim - obs) / obs)) / peaks.size * 100) + + +_METRIC_FUNCTIONS: Dict[str, Callable[..., float]] = { + "nse": nse, + "mse": mse, + "rmse": rmse, + "kge": kge, + "alpha_nse": alpha_nse, + "beta_kge": beta_kge, + "beta_nse": beta_nse, + "pearson_r": pearson_r, + "fhv": fdc_fhv, + "fms": fdc_fms, + "flv": fdc_flv, + "peak_timing": mean_peak_timing, + "missed_peaks": missed_peaks, + "peak_mape": mean_absolute_percentage_peak_error, +} +_DATED_METRICS = {"peak_timing", "missed_peaks"} + + +def calculate_metrics( + obs, + sim, + dates=None, + metrics: Optional[Iterable[str]] = None, + resolution: str = "1D", +) -> Dict[str, float]: + """Metrics of one basin's series; ``metrics`` defaults to all of ``STREAMFLOW_METRICS``. + + Like the NeuralHydrology tester, a basin whose observations or simulations are all NaN gets NaN + for every metric (the reference raises ``AllNaNError`` and the tester then stores NaN). + """ + obs, sim = _as_series(obs, sim) + names = list(STREAMFLOW_METRICS if metrics is None else metrics) + unknown = [name for name in names if name not in _METRIC_FUNCTIONS] + if unknown: + raise ValueError(f"Unknown streamflow metric(s) {unknown}; known: {list(STREAMFLOW_METRICS)}") + if np.isnan(obs).all() or np.isnan(sim).all(): + return {name: float("nan") for name in names} + values: Dict[str, float] = {} + for name in names: + if name in _DATED_METRICS: + values[name] = float(_METRIC_FUNCTIONS[name](obs, sim, dates=dates, resolution=resolution)) + else: + values[name] = float(_METRIC_FUNCTIONS[name](obs, sim)) + return values + + +def aggregate_basin_metrics(per_basin: Mapping[str, Mapping[str, float]]) -> Dict[str, float]: + """Median (````) and mean (``_mean``) over basins, ignoring NaN, plus counts. + + ``n_basins`` is the number of basins scored and ``n_basins_nse_le_0`` the number with NSE <= 0 + (Kratzert et al. 2019, Table 2). + """ + names = [] + for values in per_basin.values(): + for name in values: + if name not in names: + names.append(name) + summary: Dict[str, float] = {} + for name in names: + column = np.array([float(values.get(name, np.nan)) for values in per_basin.values()], dtype=np.float64) + finite = column[~np.isnan(column)] + summary[name] = float(np.median(finite)) if finite.size else float("nan") + summary[f"{name}_mean"] = float(np.mean(finite)) if finite.size else float("nan") + summary["n_basins"] = float(len(per_basin)) + if "nse" in names: + nse_values = np.array([float(values.get("nse", np.nan)) for values in per_basin.values()]) + summary["n_basins_nse_le_0"] = float(np.sum(nse_values <= 0)) + return summary + + +def streamflow_metric_names() -> list: + """Every key ``aggregate_basin_metrics`` reports for the full metric set.""" + names = [] + for name in STREAMFLOW_METRICS: + names.extend([name, f"{name}_mean"]) + return names + ["n_basins", "n_basins_nse_le_0"] + + +__all__ = [ + "NEURALHYDROLOGY_METRIC_NAMES", + "STREAMFLOW_METRICS", + "aggregate_basin_metrics", + "alpha_nse", + "beta_kge", + "beta_nse", + "calculate_metrics", + "fdc_fhv", + "fdc_flv", + "fdc_fms", + "kge", + "mean_absolute_percentage_peak_error", + "mean_peak_timing", + "missed_peaks", + "mse", + "nse", + "pearson_r", + "rmse", + "streamflow_metric_names", +] diff --git a/pyhazards/metrics/inundation.py b/pyhazards/metrics/inundation.py new file mode 100644 index 00000000..0407e952 --- /dev/null +++ b/pyhazards/metrics/inundation.py @@ -0,0 +1,146 @@ +"""Flood inundation metrics: depth errors, wet-area overlap and the scores of the flood neural-operator papers. + +``relative_l2``, ``nash_sutcliffe``, ``pearson_correlation`` and ``critical_success_index`` are defined as +in the UrbanFloodCast evaluation (Xu et al., J. Hydrology 2025; ``DNO/utils25.py`` of +HydroPML/UrbanFloodCast): per sample (one event), the relative L2 error of every variable over all +cells and time steps averaged over the variables (FNO's relative ``LpLoss``), and NSE / Pearson r over all +values of the sample; Pearson r divides the (population) covariance by the product of the sample +standard deviations, as the reference does. The CSI counts cells where both depths exceed the threshold +(hits) against misses and false alarms, ``hits / (hits + misses + false_alarms + 1e-8)``. The definitions +were written from the formulas and are checked against the reference (``tests/oracle``). + +:func:`inundation_metrics` reports, for a set of samples: + +- ``pixel_mae`` and ``rmse``: mean absolute / root mean squared depth error over every cell of every + sample (PyHazards); +- ``iou`` and ``f1``: overlap of the predicted (depth >= 0.5) and observed (depth > 0) wet cells over + all samples (PyHazards' earlier inundation score, kept for comparability); +- ``csi_1cm``, ``csi_10cm``, ``csi_50cm``: depth CSI at 0.01 / 0.1 / 0.5 m, averaged over samples; +- ``relative_l2``, ``nse``, ``pearson_r``: per sample over all predicted variables, averaged over samples. +""" + +from __future__ import annotations + +from typing import Dict, Optional + +import torch + +CSI_THRESHOLDS = {"csi_1cm": 0.01, "csi_10cm": 0.1, "csi_50cm": 0.5} +INUNDATION_METRICS = ("pixel_mae", "rmse", "iou", "f1", *CSI_THRESHOLDS, "relative_l2", "nse", "pearson_r") + + +def relative_l2(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Relative L2 error per sample: ``mean_v ||pred[:, :, v] - target[:, :, v]|| / ||target[:, :, v]||``. + + Inputs are ``(batch, points, variables)``; returns ``(batch,)``. + """ + if pred.shape != target.shape or pred.ndim != 3: + raise ValueError( + f"relative_l2 expects pred and target of the same shape (batch, points, variables); got " + f"{tuple(pred.shape)} and {tuple(target.shape)}." + ) + diff_norms = torch.norm(pred - target, 2, 1) + target_norms = torch.norm(target, 2, 1) + return (diff_norms / target_norms).mean(-1) + + +def nash_sutcliffe(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """NSE over all values: ``1 - sum((target - pred)^2) / sum((target - mean(target))^2)``.""" + numerator = torch.sum((target - pred) ** 2) + denominator = torch.sum((target - torch.mean(target)) ** 2) + return 1.0 - numerator / denominator + + +def pearson_correlation(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """``mean((t - mean t)(p - mean p)) / (std(t) std(p))`` over all values (std with Bessel's correction).""" + mean_true = torch.mean(target) + mean_pred = torch.mean(pred) + cov = torch.mean((target - mean_true) * (pred - mean_pred)) + return cov / (torch.std(target) * torch.std(pred)) + + +def critical_success_index(pred: torch.Tensor, target: torch.Tensor, threshold: float) -> torch.Tensor: + """CSI of the cells deeper than ``threshold``: ``hits / (hits + misses + false_alarms + 1e-8)``.""" + hits = torch.sum(torch.logical_and(target > threshold, pred > threshold)) + misses = torch.sum(torch.logical_and(target > threshold, pred <= threshold)) + false_alarms = torch.sum(torch.logical_and(target <= threshold, pred > threshold)) + return hits / (hits + misses + false_alarms + 1e-8) + + +def inundation_metrics( + preds: torch.Tensor, + targets: torch.Tensor, + mask: Optional[torch.Tensor] = None, + depth_index: Optional[int] = None, +) -> Dict[str, float]: + """Inundation metrics of ``n_samples`` predictions (first dimension = samples). + + With ``depth_index`` the last dimension holds several variables (e.g. depth and the two unit + discharges of UrbanFloodCast) and depth is ``[..., depth_index]``; without it every value is a depth. + ``mask`` (same shape, True = valid) multiplies predictions and targets before scoring, as the + UrbanFloodCast evaluation does with its NaN mask. + """ + pred = preds.detach().float().cpu() + target = targets.detach().float().cpu() + if tuple(pred.shape) != tuple(target.shape): + raise ValueError(f"flood.inundation predictions {tuple(pred.shape)} must match targets {tuple(target.shape)}.") + if pred.ndim < 2: + raise ValueError(f"flood.inundation expects a leading sample dimension, got shape {tuple(pred.shape)}.") + if mask is not None: + mask = mask.detach().cpu() + if tuple(mask.shape) != tuple(pred.shape): + raise ValueError(f"mask {tuple(mask.shape)} must match predictions {tuple(pred.shape)}.") + pred = pred * mask + target = target * mask + n_samples = pred.shape[0] + if depth_index is None: + pred_vars = pred.reshape(n_samples, -1, 1) + target_vars = target.reshape(n_samples, -1, 1) + pred_depth, target_depth = pred, target + else: + n_vars = pred.shape[-1] + pred_vars = pred.reshape(n_samples, -1, n_vars) + target_vars = target.reshape(n_samples, -1, n_vars) + pred_depth, target_depth = pred[..., depth_index], target[..., depth_index] + + pred_mask = (pred_depth >= 0.5).float() + target_mask = (target_depth > 0).float() + intersection = (pred_mask * target_mask).sum() + union = pred_mask.sum() + target_mask.sum() - intersection + metrics = { + "pixel_mae": float(torch.mean(torch.abs(pred_depth - target_depth))), + "rmse": float(torch.sqrt(torch.mean((pred_depth - target_depth) ** 2))), + "iou": float(intersection / union.clamp(min=1.0)), + "f1": float(2 * intersection / (pred_mask.sum() + target_mask.sum()).clamp(min=1.0)), + } + per_sample: Dict[str, list] = {name: [] for name in (*CSI_THRESHOLDS, "relative_l2", "nse", "pearson_r")} + for i in range(n_samples): + depth_p = pred_depth[i].reshape(1, -1, 1) + depth_t = target_depth[i].reshape(1, -1, 1) + for name, threshold in CSI_THRESHOLDS.items(): + per_sample[name].append(float(critical_success_index(depth_p, depth_t, threshold))) + per_sample["relative_l2"].append(float(relative_l2(pred_vars[i : i + 1], target_vars[i : i + 1]).sum())) + per_sample["nse"].append(float(nash_sutcliffe(pred_vars[i : i + 1], target_vars[i : i + 1]))) + per_sample["pearson_r"].append(float(pearson_correlation(pred_vars[i : i + 1], target_vars[i : i + 1]))) + for name, values in per_sample.items(): + metrics[name] = float(sum(values) / len(values)) if values else float("nan") + return metrics + + +def rollout_rmse(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """RMSE over nodes at every rollout step: ``(steps, nodes)`` -> ``(steps,)`` (HydroGraphNet ``inference.py``).""" + if pred.shape != target.shape or pred.ndim != 2: + raise ValueError(f"rollout_rmse expects (steps, nodes) tensors of equal shape, got {tuple(pred.shape)} and {tuple(target.shape)}.") + return torch.sqrt(torch.mean((pred - target) ** 2, dim=1)) + + +__all__ = [ + "CSI_THRESHOLDS", + "INUNDATION_METRICS", + "critical_success_index", + "inundation_metrics", + "nash_sutcliffe", + "pearson_correlation", + "relative_l2", + "rollout_rmse", +] diff --git a/pyhazards/metrics/picking.py b/pyhazards/metrics/picking.py new file mode 100644 index 00000000..48637b3b --- /dev/null +++ b/pyhazards/metrics/picking.py @@ -0,0 +1,228 @@ +"""Seismic phase-pick extraction and pick metrics (earthquake.picking). + +Pick extraction + :func:`detect_peaks` is a port of ``detect_peaks`` by Marcos Duarte (version 1.0.6, MIT License, + https://github.com/demotu/BMC), the copy that ships with PhaseNet (``phasenet/detect_peaks.py``) and, + slightly modified, with EQTransformer (``EqT_utils._detect_peaks``). It returns peak indices only. + :func:`trigger_onset` reimplements the documented behaviour of ObsPy's ``trigger_onset`` (ObsPy is + LGPL; no code was copied). It was checked against ObsPy 1.5.1 on random inputs + (``tests/oracle/test_picking_metrics_oracle.py``). + +Scoring (:func:`score_picks`) + Follows the official PhaseNet evaluation (``correct_picks`` and ``metrics`` in ``phasenet/util.py``, + AI4EPS/PhaseNet, MIT License, Copyright (c) 2021 Weiqiang Zhu), which produced Table 1 of Zhu & + Beroza (2019): every pair (predicted pick, manual pick) of the same phase whose residual is within + ``tolerance`` counts as a true positive; precision = TP / number of predicted picks; recall = + TP / number of manual picks; F1 = 2PR / (P + R). Residual statistics are taken over the pairs with + ``|residual| < residual_window``. Residuals are ``predicted - manual`` and reported in seconds. + + Protocols (:data:`PICKING_PROTOCOLS`): + + - ``"phasenet"``: Zhu & Beroza (2019), GJI 216:261-273: a pick is correct when ``|dt| < 0.1 s``; + mean and standard deviation of residuals over ``|dt| < 0.5 s``. + - ``"eqtransformer"``: Mousavi et al. (2020), Nat. Commun. 11:3952: a pick is a true positive when + its absolute distance from the ground truth is less than 0.5 s; mean, standard deviation and mean + absolute error over the true positives. + + Undefined ratios (no predicted or no manual picks) are reported as 0; residual statistics without + any residual are NaN. EQTransformer's MAPE is not computed: the paper does not define its + denominator. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + +import numpy as np + +PICKING_PROTOCOLS: Dict[str, Dict[str, float]] = { + "phasenet": {"tolerance_s": 0.1, "residual_window_s": 0.5}, + "eqtransformer": {"tolerance_s": 0.5, "residual_window_s": 0.5}, +} + +# One trace's picks: phase name -> list of (sample index, probability). +TracePicks = Dict[str, List[Tuple[float, float]]] + + +def detect_peaks( + x: Sequence[float], + mph: Optional[float] = None, + mpd: int = 1, + threshold: float = 0.0, + edge: Optional[str] = "rising", + kpsh: bool = False, + valley: bool = False, +) -> np.ndarray: + """Indices of the peaks of ``x`` (port of Duarte's ``detect_peaks`` 1.0.6, MIT). + + ``mph``: minimum peak height; ``mpd``: minimum peak distance in samples (smaller peaks within + ``mpd`` of a higher one are removed); ``threshold``: minimum height above both neighbours; + ``edge``: which edge of a flat peak to keep (``"rising"``, ``"falling"``, ``"both"`` or ``None``); + ``kpsh``: keep peaks of the same height even when closer than ``mpd``; ``valley``: detect minima. + """ + x = np.atleast_1d(np.asarray(x, dtype="float64")).copy() + if x.size < 3: + return np.array([], dtype=int) + if valley: + x = -x + if mph is not None: + mph = -mph + # find indices of all peaks + dx = x[1:] - x[:-1] + # handle NaN's + indnan = np.where(np.isnan(x))[0] + if indnan.size: + x[indnan] = np.inf + dx[np.where(np.isnan(dx))[0]] = np.inf + ine, ire, ife = np.array([[], [], []], dtype=int) + if not edge: + ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0] + else: + if edge.lower() in ["rising", "both"]: + ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0] + if edge.lower() in ["falling", "both"]: + ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0] + ind = np.unique(np.hstack((ine, ire, ife))) + # NaN's and values next to NaN's cannot be peaks + if ind.size and indnan.size: + ind = ind[np.isin(ind, np.unique(np.hstack((indnan, indnan - 1, indnan + 1))), invert=True)] + # first and last values of x cannot be peaks + if ind.size and ind[0] == 0: + ind = ind[1:] + if ind.size and ind[-1] == x.size - 1: + ind = ind[:-1] + # remove peaks < minimum peak height + if ind.size and mph is not None: + ind = ind[x[ind] >= mph] + # remove peaks - neighbours < threshold + if ind.size and threshold > 0: + dx = np.min(np.vstack([x[ind] - x[ind - 1], x[ind] - x[ind + 1]]), axis=0) + ind = np.delete(ind, np.where(dx < threshold)[0]) + # remove small peaks closer than the minimum peak distance + if ind.size and mpd > 1: + ind = ind[np.argsort(x[ind])][::-1] # sort by peak height + idel = np.zeros(ind.size, dtype=bool) + for i in range(ind.size): + if not idel[i]: + # keep peaks with the same height if kpsh is True + idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) & (x[ind[i]] > x[ind] if kpsh else True) + idel[i] = 0 # keep the current peak + ind = np.sort(ind[~idel]) + return ind + + +def trigger_onset(charfct: Sequence[float], thres1: float, thres2: float) -> np.ndarray: + """``(n, 2)`` array of ``[on, off]`` sample pairs of a two-threshold trigger. + + A trigger switches on at the first sample with ``charfct >= thres1`` and stays on while + ``charfct >= thres2``; ``off`` is the last sample of that run (the last sample of ``charfct`` when + the trigger is still on at the end). Same results as ObsPy's ``trigger_onset`` (without its + ``max_len`` options) for ``thres2 <= thres1``. + """ + if thres2 > thres1: + raise ValueError(f"trigger_onset needs thres2 <= thres1, got thres1={thres1}, thres2={thres2}.") + x = np.asarray(charfct, dtype="float64").ravel() + on_mask, stay_mask = x >= thres1, x >= thres2 + triggers: List[Tuple[int, int]] = [] + start = 0 + while start < x.size: + candidates = np.flatnonzero(on_mask[start:]) + if not candidates.size: + break + on = start + int(candidates[0]) + below = np.flatnonzero(~stay_mask[on:]) + off = on + int(below[0]) - 1 if below.size else x.size - 1 + triggers.append((on, off)) + start = off + 1 + return np.array(triggers, dtype=int).reshape(-1, 2) + + +def peak_picks(probability: Sequence[float], threshold: float, min_distance: int) -> List[Tuple[float, float]]: + """``(sample, probability)`` of the peaks of a probability trace above ``threshold``. + + The PhaseNet rule (``detect_peaks(prob, mph=threshold, mpd=min_distance)``). + """ + trace = np.asarray(probability, dtype="float64") + indices = detect_peaks(trace, mph=threshold, mpd=int(min_distance)) + return [(float(i), float(trace[i])) for i in indices] + + +@dataclass +class PhaseScore: + """Pick counts and residuals (in samples, ``predicted - manual``) of one phase.""" + + n_true: int = 0 + n_pred: int = 0 + n_tp: int = 0 + residuals: List[float] = field(default_factory=list) + + def metrics(self, sampling_rate: float) -> Dict[str, float]: + precision = self.n_tp / self.n_pred if self.n_pred else 0.0 + recall = self.n_tp / self.n_true if self.n_true else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else 0.0 + seconds = np.asarray(self.residuals, dtype="float64") / float(sampling_rate) + if seconds.size: + mean, std, mae = float(seconds.mean()), float(seconds.std()), float(np.abs(seconds).mean()) + else: + mean = std = mae = math.nan + return { + "precision": precision, + "recall": recall, + "f1": f1, + "residual_mean": mean, + "residual_std": std, + "mae": mae, + } + + +def score_picks( + predicted: Iterable[Sequence[float]], + manual: Iterable[Sequence[float]], + tolerance: float, + residual_window: float, +) -> PhaseScore: + """Score one phase over traces (sample units). + + ``predicted[i]`` and ``manual[i]`` are the predicted and the manual pick samples of trace ``i`` + (NaN entries are ignored). Counting follows the official PhaseNet evaluation: TP = number of + (prediction, manual pick) pairs with ``|residual| < tolerance``; residuals are kept for pairs + with ``|residual| < residual_window``. + """ + score = PhaseScore() + for pred, true in zip(predicted, manual): + pred = np.asarray([p for p in pred if not math.isnan(float(p))], dtype="float64") + true = np.asarray([t for t in true if not math.isnan(float(t))], dtype="float64") + score.n_true += int(true.size) + score.n_pred += int(pred.size) + if not pred.size or not true.size: + continue + diff = pred[None, :] - true[:, None] + score.n_tp += int(np.sum(np.abs(diff) < tolerance)) + score.residuals.extend(diff[np.abs(diff) < residual_window].tolist()) + return score + + +def detection_scores(detected: Sequence[bool], is_event: Sequence[bool]) -> Dict[str, float]: + """Trace-level detection precision, recall and F1 (EQTransformer Table 1).""" + detected = np.asarray(detected, dtype=bool) + is_event = np.asarray(is_event, dtype=bool) + tp = int(np.sum(detected & is_event)) + n_pred, n_true = int(detected.sum()), int(is_event.sum()) + precision = tp / n_pred if n_pred else 0.0 + recall = tp / n_true if n_true else 0.0 + f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else 0.0 + return {"precision": precision, "recall": recall, "f1": f1} + + +__all__ = [ + "PICKING_PROTOCOLS", + "PhaseScore", + "TracePicks", + "detect_peaks", + "detection_scores", + "peak_picks", + "score_picks", + "trigger_onset", +] diff --git a/pyhazards/metrics/wavefield.py b/pyhazards/metrics/wavefield.py new file mode 100644 index 00000000..587657a8 --- /dev/null +++ b/pyhazards/metrics/wavefield.py @@ -0,0 +1,76 @@ +"""Wavefield-forecast metrics of WaveCastNet (earthquake.forecasting). + +Ports of ``validation_acc``, ``validation_rfne`` and ``validation_rmse`` in +``src/models_earthquake/Validation_pixel.py`` of dwlyu/WaveCastNet at commit +``c859e04c85acd6657306f08bce8c6f9129ba1480`` (MIT License, Copyright (c) 2023 dwlyu), which compute +equations (17) and (18) of Lyu et al., "Rapid wavefield forecasting for earthquake early warning via deep +sequence to sequence learning", Nature Communications 16:10622 (2025): + +- ACC = sum_{t,h,w} pred * target / sqrt(sum_{t,h,w} target^2 * sum_{t,h,w} pred^2) +- RFNE = ||pred - target||_F / ||target||_F +- RMSE = sqrt(mean_{t,h,w} (pred - target)^2) + +Each value is computed for every (sample, channel) pair over the time and space axes of +``(batch, channels, time, height, width)`` tensors; the official validation then averages all pairs +(:func:`wavefield_metrics` returns that mean and the per-channel means). Like the official code, nothing +guards against a zero norm: an all-zero target channel gives NaN or infinity. +""" + +from __future__ import annotations + +from typing import Dict, Optional, Sequence + +import torch + + +def _check(pred: torch.Tensor, target: torch.Tensor) -> None: + if pred.shape != target.shape or target.ndim != 5: + raise ValueError( + "Wavefield metrics expect pred and target shaped (batch, channels, time, height, width); " + f"got shapes {tuple(pred.shape)} and {tuple(target.shape)}." + ) + + +def wavefield_acc(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """ACC (eq. 17) of every (sample, channel) pair: a ``(batch, channels)`` tensor.""" + _check(pred, target) + pred, target = pred.flatten(2), target.flatten(2) + sum1 = (pred * target).sum(dim=-1) + sum2 = (target * target).sum(dim=-1) + sum3 = (pred * pred).sum(dim=-1) + return sum1 / torch.sqrt(sum2 * sum3) + + +def wavefield_rfne(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """RFNE (eq. 18) of every (sample, channel) pair: a ``(batch, channels)`` tensor.""" + _check(pred, target) + return torch.linalg.vector_norm((target - pred).flatten(2), dim=-1) / torch.linalg.vector_norm( + target.flatten(2), dim=-1 + ) + + +def wavefield_rmse(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """RMSE of every (sample, channel) pair: a ``(batch, channels)`` tensor.""" + _check(pred, target) + return torch.sqrt(((pred - target) ** 2).flatten(2).mean(dim=-1)) + + +def wavefield_metrics( + pred: torch.Tensor, + target: torch.Tensor, + channel_names: Optional[Sequence[str]] = None, +) -> Dict[str, float]: + """ACC, RFNE and RMSE averaged over all (sample, channel) pairs, as the official validation does, + plus ``acc_`` and ``rfne_`` averaged over the samples of each channel.""" + acc, rfne, rmse = (fn(pred, target).double() for fn in (wavefield_acc, wavefield_rfne, wavefield_rmse)) + names = list(channel_names) if channel_names is not None else [f"c{i}" for i in range(acc.shape[1])] + if len(names) != acc.shape[1]: + raise ValueError(f"Got {len(names)} channel names for {acc.shape[1]} channels.") + metrics = {"acc": float(acc.mean()), "rfne": float(rfne.mean()), "rmse": float(rmse.mean())} + for index, name in enumerate(names): + metrics[f"acc_{name}"] = float(acc[:, index].mean()) + metrics[f"rfne_{name}"] = float(rfne[:, index].mean()) + return metrics + + +__all__ = ["wavefield_acc", "wavefield_metrics", "wavefield_rfne", "wavefield_rmse"] diff --git a/pyhazards/model_cards/asufm.yaml b/pyhazards/model_cards/asufm.yaml index 7a2d8a0a..37df9902 100644 --- a/pyhazards/model_cards/asufm.yaml +++ b/pyhazards/model_cards/asufm.yaml @@ -5,47 +5,89 @@ catalog_status: core source_file: pyhazards/models/asufm.py builder_name: asufm_builder summary: > - A temporal convolution baseline for weekly wildfire activity forecasting. + Attention Swin U-Net with Focal Modulation for next-day wildfire spread (fire-mask + segmentation of 64x64 Next Day Wildfire Spread tiles). description: - > - ``asufm`` is a compact temporal convolution baseline for next-window wildfire - activity prediction. + ``asufm`` is a Swin U-Net (patch 4, embedding 96, depths (2, 2, 2, 2), heads + (3, 6, 12, 24), window 8) whose encoder blocks apply focal modulation before window + attention, with patch-expanding decoder stages and skip connections. It maps one day of + Next Day Wildfire Spread (NDWS) features, 64x64 at 1 km, to logits for the next day's fire + mask (Li & Rad, IEEE CAI 2024). - > - PyHazards exposes it through the shared wildfire benchmark and config workflow. + The implementation reproduces the official fire-asufm code (``get_asfum_6_configs`` with six + features by default, ``get_asufm_12_configs`` with all twelve) with the same parameter names + and initialisation, so official checkpoints load with ``strict=True``. It is assembled from + MIT-licensed Swin Transformer and FocalNet blocks rather than copied, because the official + model package derives from the unlicensed Attention Swin U-Net code. paper: title: Wildfire Spread Prediction in North America Using Satellite Imagery and Vision Transformer - url: https://doi.ieeecomputersociety.org/10.1109/CAI59869.2024.00278 + url: https://doi.org/10.1109/CAI59869.2024.00278 repo_url: https://github.com/bronteee/fire-asufm +references: + - title: "Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data" + url: https://doi.org/10.1109/TGRS.2022.3192974 + repo_url: https://github.com/google-research/google-research/tree/master/simulation_research/next_day_wildfire_spread + note: > + Dataset used by ASUFM (64x64 tiles, 12 input features). The official training script uses + six features (elevation, th, sph, pr, NDVI, PrevFireMask), BCE with pos_weight 3, AdamW (amsgrad) + lr 1e-4 with cosine annealing and linear warm-up, batch 16 and mixed precision; the authors also release a + 2012-2023 North America extension on Kaggle. The paper reports, on NDWS (Table I), PR-AUC + 0.3728, precision 0.4301, recall 0.4050 and Dice 0.4109, and on the extended dataset + (Table IV, 35M parameters) PR-AUC 0.3974 and Dice 0.4066, trained with weighted BCE + (positive weight 3.0), Adam with weight decay 0.05, cosine annealing with warm-up and batch 16. + - title: "Focal Modulation Networks" + url: https://arxiv.org/abs/2203.11926 + repo_url: https://github.com/microsoft/FocalNet + note: Focal modulation in the encoder blocks (focal level 1, window 3). + - title: "Swin Transformer: Hierarchical Vision Transformer using Shifted Windows" + url: https://arxiv.org/abs/2103.14030 + repo_url: https://github.com/microsoft/Swin-Transformer + note: Window-attention blocks, patch merging and patch embedding. +reproduction: + reference_code: https://github.com/bronteee/fire-asufm + reference_commit: 688dda94dec9e3b22f149f2b9335d3b38fd2277f + reference_license: Apache-2.0 + reference_config: > + ASUFM(get_asfum_6_configs(), num_classes=1) and ASUFM(get_asufm_12_configs(), num_classes=1) + from configs/asufm.py (35,047,840 and 35,057,056 parameters), plus the focal=False variant + get_swin_unet_attention_configs, on (batch, 6 or 12, 64, 64) inputs. + parameter_count: 35047840 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_swin_oracle.py + deviations: + - > + The official blocks return their window-attention maps and the decoder adds the encoder's + maps to them ("spatial attention"), but the sums are discarded and never reach the output. + They are not computed here; outputs are identical. + - > + The configuration's cross-contextual-attention mode (CrossViT skips) is not part of ASUFM + and is not implemented. tasks: - - forecasting - - regression + - segmentation example: | import torch from pyhazards.models import build_model - model = build_model( - name="asufm", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) - preds = model(torch.randn(2, 12, 7)) - print(preds.shape) + # Six NDWS features: elevation, th, sph, pr, NDVI, PrevFireMask. + model = build_model(name="asufm", task="segmentation", in_channels=6) + logits = model(torch.randn(2, 6, 64, 64)) + print(logits.shape) # (2, 1, 64, 64) notes: - - "The smoke path uses weekly wildfire count windows with seasonal time features." + - "Inputs must be 64x64 (img_size); the architecture is tied to the token grid it was built for." + - "Decoder stages fuse each skip connection twice through the same concat_back_dim layer, because the configured spatial-attention branch concatenates and projects again. This is the official behaviour and is kept." + - "Decoder blocks contain focal-modulation weights that the official code never applies; the top-level patch_embed (4 input channels) and decoder.norm are also unused. All are kept so official state dicts load." + - "The official model ignores the config's drop_path_rate, attn_drop_rate, ape and patch_size (fixed at 0.1, 0, False and 4)." + - "The paper (Section III-A) describes spatial attention carried along the skip connections; in the official code those maps never reach the output (see the first deviation), so the released network is a Swin U-Net with focal modulation. The paper's 35M parameter count (Table IV) matches." + - "The authors' Kaggle checkpoint link (bronteli/attention-swin-u-net-with-focal-modulation-asufm) returned HTTP 404 on 2026-10-07, so no trained weights are checked." smoke_test: - task: forecasting + task: segmentation build_kwargs: - input_dim: 7 - hidden_dim: 32 - output_dim: 5 - lookback: 12 - dropout: 0.0 + in_channels: 6 input: kind: tensor tensor: - shape: [2, 12, 7] + shape: [2, 6, 64, 64] expected_output: kind: tensor - shape: [2, 5] + shape: [2, 1, 64, 64] diff --git a/pyhazards/model_cards/attention_unet.yaml b/pyhazards/model_cards/attention_unet.yaml new file mode 100644 index 00000000..6653c0c3 --- /dev/null +++ b/pyhazards/model_cards/attention_unet.yaml @@ -0,0 +1,120 @@ +model_name: attention_unet +display_name: Attention U-Net +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/attention_unet.py +builder_name: attention_unet_builder +summary: > + U-Net with additive attention gates on its skip connections, in MONAI's implementation, + configured by default as the TS-SatFire spatio-temporal (3D) baseline. +description: + - > + ``attention_unet`` is an encoder-decoder with strided-convolution down-sampling and + transposed-convolution up-sampling in which every skip connection is multiplied by an + attention map before it is merged with the decoder feature, following the additive attention + gate of Oktay et al. (2018). + - > + The implementation reproduced is MONAI's ``AttentionUnet`` (MONAI 1.3.2, Apache-2.0), because + that is what the wildfire paper used, ported to plain PyTorch with MONAI's module names so + MONAI state dicts load with ``strict=True``. It is not Oktay et al.'s official network: MONAI + computes the gate at the skip resolution from the already up-sampled decoder feature, with no + grid sub-sampling of the gating signal, a single gate per level and no deep supervision. + - > + With the defaults (``spatial_dims=3``) the model is TS-SatFire's Attention-U-Net-3D: input + ``(batch, time, channels, H, W)``, 3D convolutions over (time, H, W) with stride (1, 2, 2) at + every level so time is never down-sampled, widths 64-1024, and two-class logits averaged over + time to ``(batch, 2, H, W)``. ``spatial_dims=2`` gives TS-SatFire's single-image 2D baseline + (stride 2 at every level, input ``(batch, channels, H, W)``). +paper: + title: "Attention U-Net: Learning Where to Look for the Pancreas" + url: https://arxiv.org/abs/1804.03999 + repo_url: https://github.com/ozan-oktay/Attention-Gated-Networks +references: + - title: "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction" + url: https://doi.org/10.1038/s41597-025-06271-3 + repo_url: https://github.com/zhaoyutim/TS-SatFire + note: > + Attention-U-Net-3D from the repository's modified MONAI copy (channels 64-1024, stride + (1, 2, 2) at every level) on 256x256 tiles of daily VIIRS and auxiliary data, 43 channels + after the land-cover one-hot for next-day progression prediction, T in {2, 4, 6}, logits + averaged over time; Dice loss, Adam lr 0.0012, batch 8, 100 epochs. Paper Table 3 (6 input + days; arXiv 2412.11555): 94.5M parameters, F1 0.770 / 0.712 / 0.354 and IoU + 0.654 / 0.607 / 0.312 on active fire / burned area / prediction. The 2D Attention-U-Net + (stock MONAI, stride 2) has 31.7M parameters and F1 0.763 / 0.793 on active fire / burned area. +reproduction: + reference_code: https://github.com/Project-MONAI/MONAI + reference_commit: "1.3.2" + reference_license: Apache-2.0 + reference_config: > + TS-SatFire's AttentionUnet(spatial_dims=3, in_channels=43, out_channels=2, + channels=(64, 128, 256, 512, 1024), strides=(1, 2, 2)) from spatial_models/attentionunet.py at + da75732 (MONAI 1.2/1.3.0 code with shared strides; the repository has no license and is used + only as a test oracle) on monai 1.3.2, with its outputs averaged over time; MONAI 1.3.2 + AttentionUnet(spatial_dims=2, in_channels=8, out_channels=2, same channels, strides=(2, 2, 2, 2)) + for the 2D baseline (31,743,282 parameters); and 1D/2D/3D MONAI configurations with + non-uniform per-level strides, kernel size 5 and dropout. Forward passes use 32x32 (3D, T=2) + and 64x64 (2D) inputs instead of 256x256 to keep the CPU test fast. + parameter_count: 94555506 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_attention_unet_oracle.py + deviations: + - > + Architecture is MONAI's, not the official Attention-Gated-Networks code (eee4881, MIT), + which is not ported. Its 3D segmentation networks (unet_grid_attention_3D, + unet_CT_single/multi_att_dsv_3D) down-sample with max pooling at widths + [64, 128, 256, 512, 1024] / feature_scale (4 by default), take the gating signal from a + coarser level, sub-sample the skip feature with a strided theta convolution + (attention_dsample (2, 2, 2)) before the additive gate, up-sample the attention map + trilinearly and pass the gated feature through a 1x1 convolution and BatchNorm; the CT + models add deep supervision (and two gates per level in the multi-attention model), and all + use Kaiming initialisation. MONAI gates at the skip resolution with the up-convolved decoder + feature, has one gate per level, no deep supervision and PyTorch's default initialisation. + - > + TS-SatFire's copy was taken from MONAI 1.2/1.3.0 and ignores ``kernel_size`` (its blocks are + always 3x3x3); this port honours ``kernel_size`` as MONAI 1.3.2 does. The two are identical + at the kernel size 3 that TS-SatFire uses. + - > + TS-SatFire averages the 3D logits over time in its training script + (``outputs.mean(2)``); here that read-out is part of the model (``time_reduction="mean"``), + which also takes PyHazards' ``(batch, time, channels, H, W)`` layout instead of + ``(batch, channels, time, H, W)``. + - > + Configurations the reference rejects with IndexError or NotImplementedError (too few + strides, even kernel sizes) or a size-mismatch RuntimeError (spatial sizes not divisible by + the stride product) raise ValueError instead. + - > + The paper reports 94.5M parameters for Attention-U-Net-3D across all three tasks; the + prediction configuration with 43 input channels has 94,555,506 (94,495,026 with the + 8-channel active-fire / burned-area input). +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # TS-SatFire prediction model: 43 channels, logits averaged over the input days. + model = build_model(name="attention_unet", task="segmentation", in_channels=43) + logits = model(torch.randn(1, 4, 43, 64, 64)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 64, 64) + + # TS-SatFire's single-image 2D baseline. + model_2d = build_model(name="attention_unet", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 64, 64)).shape) # (1, 2, 64, 64) +notes: + - "Every spatial size must be divisible by the product of the strides along that dimension: 16 for height and width with the default four levels; time is never down-sampled." + - "The default two output channels follow TS-SatFire, which applied a sigmoid Dice loss to both; use out_channels=1 for a single-logit binary head." + - "time_reduction='none' returns per-date maps (batch, classes, time, H, W), as TS-SatFire uses for its active-fire and burned-area tasks." + - "strides follow MONAI (one entry per level, each an int or one value per dimension); stride_mode='shared' takes TS-SatFire's single strides=(1, 2, 2) literally and builds the same network as strides=[(1, 2, 2)] * 4." + - "MONAI quirks are kept: the merge convolution after each gate uses instance norm and PReLU, and dropout is applied in the convolution blocks and merges but never in the gates or up-convolutions." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 4 + channels: [8, 16, 32] + input: + kind: tensor + tensor: + shape: [2, 3, 4, 16, 16] + expected_output: + kind: tensor + shape: [2, 2, 16, 16] diff --git a/pyhazards/model_cards/convgru.yaml b/pyhazards/model_cards/convgru.yaml new file mode 100644 index 00000000..0f9a4ec5 --- /dev/null +++ b/pyhazards/model_cards/convgru.yaml @@ -0,0 +1,117 @@ +model_name: convgru +display_name: ConvGRU +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/convgru.py +builder_name: convgru_builder +summary: > + Convolutional GRU (Ballas et al., ICLR 2016) with a convolutional head on the last hidden state: + the Conv-GRU baseline that FireCastNet trained for seasonal burned-area prediction. +description: + - > + ``convgru`` runs a stack of convolutional GRU cells over a ``(batch, time, channels, height, + width)`` sequence and maps the hidden state of the last time step to per-pixel logits with a + ``Conv2d`` head. Each cell follows Ballas et al.: one convolution over ``[x_t, h_{t-1}]`` + gives the update and reset gates, a second convolution over ``[x_t, r * h_{t-1}]`` gives the + candidate, and ``h_t = (1 - z) * h_{t-1} + z * tanh(candidate)``. + - > + The default is the Conv-GRU baseline of FireCastNet (Michail et al., Scientific Reports 2025), + as in its ``configs/conv-gru-config.yaml``: 11 SeasFire variables, one layer of 128 hidden + channels, 5x5 kernels, a dense 64x64 logit map trained with BCE on every pixel. FireCastNet's + code has no license, so the module is written from the equations; it is checked against + FireCastNet's ``ConvGRUSeg``, whose state dicts load with ``strict=True``, and gives identical + outputs and seeded initial weights. +paper: + title: "Delving Deeper into Convolutional Networks for Learning Video Representations" + url: https://arxiv.org/abs/1511.06432 +references: + - title: "FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction" + url: https://doi.org/10.1038/s41598-025-30645-7 + repo_url: https://github.com/SeasFire/firecastnet + note: > + Conv-GRU baseline (arXiv:2502.01550). SeasFire datacube (0.25 degree, 8-day steps), 11 + inputs (mslp, tp, vpd, sst, t2m_mean, ssrd, swvl1, lst_day, ndvi, pop_dens and the land-sea + mask), binary burned area (gwis_ba) h periods ahead, years 2002-2017 / 2018 / 2019 for + training / validation / testing, BCE, AdamW lr 1e-3. Global test AUPRC with 24 input steps + (Table 2): 0.593 / 0.579 / 0.556 / 0.551 / 0.545 / 0.569 for h = 1 / 2 / 4 / 8 / 16 / 24; + with 12 steps (Figure 3) 0.624 / 0.614 / 0.604 / 0.593 / 0.582 / 0.579, the best Conv-GRU + setting, and with 6 steps 0.604 / 0.597 / 0.586 / 0.571 / 0.560 / 0.557. FireCastNet scores + 0.641 at h = 1 with 24 steps. + - title: "A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA)" + url: https://arxiv.org/abs/2606.15529 + repo_url: https://github.com/LabRAI/WildfireIA + note: > + Same cell, different model. WildfireIA's ConvGRU baseline (train.py ConvGRUClassifier at + aba9be9, MIT) is one cell with 64 channels and 3x3 kernels on 29x29 event patches, read out + by global pooling and an MLP to one score. Initial-attack failure prediction: AUPRC 41.2 +/- + 1.6, AUROC 84.1 +/- 0.6 (Table 3); containment duration: MAE 36.4 h (Table 6). +reproduction: + reference_code: https://github.com/SeasFire/firecastnet + reference_commit: dc0d131be7f0638e3a84c16817e7bc9be454e53e + reference_license: none (no LICENSE file; seasfire/backbones/conv_gru.py is used only as the test oracle, not copied) + reference_config: > + configs/conv-gru-config.yaml: ConvGRULit(input_dim_grid_nodes 11, hidden_layers 1, hidden_dim + 128, kernel_size [5, 5]) -> ConvGRUSeg(..., num_classes=1), 64x64 patches, checked on + (batch, 12, 11, 64, 64) inputs, also with all-zero (padding) steps; the paper's 64 hidden + channels (361,793 parameters); a three-layer model with two classes (outputs and input + gradients). + parameter_count: 1337985 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_convgru_oracle.py + deviations: + - > + The reference looks for all-zero (padding) time steps and, if there are any, re-indexes the + per-step outputs passed to the next layer with a batch-sized index (giving a + ``(batch, batch, ...)`` tensor). This never changes the output of the one-layer model and + breaks deeper ones. The port does not look for padding: padded steps update the state, as + they do in the one-layer reference. + - > + The head's padding is ``(kernel - 1) // 2`` per dimension; the reference uses the first + kernel dimension for both, which only differs for non-square kernels. + - > + Only ``task="segmentation"`` exists: the reference maps a sequence to one map of logits and + has no frames-to-frames form. The ConvGRU baseline of Shi et al. (2017), a frame forecaster + with a different cell (reset gate after the state convolution, leaky ReLU), is + ``build_model("trajgru", task="forecasting", layer_type="ConvGRU")``. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # FireCastNet's Conv-GRU: 12 eight-day steps of 11 standardised SeasFire variables on 64x64 patches. + model = build_model(name="convgru", task="segmentation") # 1,337,985 parameters + x = torch.randn(2, 12, 11, 64, 64) # (batch, time, variables, lat, lon) + logits = model(x) # (2, 1, 64, 64); train with BCEWithLogitsLoss on every pixel + print(logits.shape) + + # The paper's size: one hidden layer of 64 channels. + small = build_model(name="convgru", task="segmentation", hidden_dim=64) # 361,793 parameters +notes: + - > + Paper and code differ, and the code is followed. Hidden size: the paper (Sec. 5.1) gives the + Conv-GRU "a single hidden layer with 64 hidden units" (also ConvGRULit's default), the + configuration file 128 (the default here; ``hidden_dim=64`` gives the paper's size). Equations: + the paper writes the candidate as ``tanh(W_xh * x + r . (W_hh * h) + b)``, reset gate after the + state convolution, while the code, like Ballas et al. (Eq. 7), applies it before: + ``tanh(W * [x, r . h])``. Read-out: the paper describes a (2r+1)x(2r+1) grid around each + location and MLP layers that reduce it to one prediction; the code predicts a dense 64x64 map + with a 5x5 convolution and BCE over all pixels. Training: the paper uses AdamW, lr 1e-3, SGDR + (cycles of 10 and 40 epochs) and weight decay 1e-7; the configuration file lr 1e-3, weight + decay 1e-8, gradient clipping 0.5, 50 epochs, 12 input steps and a target shift of 16. + - > + Input layout and preprocessing: ConvGRULit permutes SeasFire batches from ``(B, C, T, H, W)`` + to ``(B, T, C, H, W)``, the layout used here. Variables are prepared by FireCastNet's data + module (log1p for tp and pop_dens, standardisation; see the ``firecastnet`` card). +smoke_test: + task: segmentation + build_kwargs: + in_channels: 4 + hidden_dim: 8 + input: + kind: tensor + tensor: + shape: [2, 3, 4, 16, 16] + expected_output: + kind: tensor + shape: [2, 1, 16, 16] diff --git a/pyhazards/model_cards/convlstm.yaml b/pyhazards/model_cards/convlstm.yaml new file mode 100644 index 00000000..366f4750 --- /dev/null +++ b/pyhazards/model_cards/convlstm.yaml @@ -0,0 +1,72 @@ +model_name: convlstm +display_name: ConvLSTM +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/convlstm.py +builder_name: convlstm_builder +summary: > + Convolutional LSTM over daily raster sequences with a convolutional head on the + final cell state, as used by the WildfireSpreadTS benchmark. +description: + - > + ``convlstm`` runs a stack of ConvLSTM cells (Shi et al., 2015) over a + ``(batch, time, channels, height, width)`` sequence and maps the cell state of the last + time step to per-pixel logits with a ``Conv2d`` head. + - > + The implementation is a port of the ConvLSTM that WildfireSpreadTS vendors from + utae-paps (originally TUM-LMF/MTLCC-pytorch): gates come from one convolution over the + concatenated input and hidden state, there are no peephole connections, and the head reads + the cell state rather than the hidden state. Parameter names match the reference, so its + state dicts load with ``strict=True``. +paper: + title: "Convolutional LSTM Network: A Machine Learning Approach for Precipitation Nowcasting" + url: https://arxiv.org/abs/1506.04214 + repo_url: https://github.com/VSainteuf/utae-paps +references: + - title: "WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction" + url: https://openreview.net/forum?id=RgdGkPRQ03 + repo_url: https://github.com/SebastianGer/WildfireSpreadTS + note: > + One layer, 64 hidden channels, 3x3 kernels, 5 days x 40 channels, 128x128 crops with tiled + inference, Jaccard loss, AdamW lr 0.01; test AP 0.292-0.310 (paper Table 5). +reproduction: + reference_code: https://github.com/VSainteuf/utae-paps + reference_commit: 987874e27a98bb399277f2d55eb010744d26f881 + reference_license: MIT + reference_config: > + ConvLSTM_Seg(num_classes=1, input_dim=40, hidden_dim=64, kernel_size=(3, 3)), the + WildfireSpreadTS configuration; WildfireSpreadTS vendors this file unchanged. + parameter_count: 240449 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_wildfirespreadts_oracle.py + deviations: + - > + The reference fixes the spatial size at construction; this port reads it from the input. + Outputs are identical at the reference size. + - > + The reference head uses ``padding=1`` for every kernel size; this port uses + ``kernel_size // 2``, which only differs for kernels other than 3x3. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + model = build_model(name="convlstm", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 5, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) +notes: + - "Multi-layer stacks are supported; WildfireSpreadTS uses one layer." + - "Set readout='hidden' to read the last hidden state instead of the cell state." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 6 + hidden_dim: 16 + input: + kind: tensor + tensor: + shape: [2, 4, 6, 16, 16] + expected_output: + kind: tensor + shape: [2, 1, 16, 16] diff --git a/pyhazards/model_cards/deep_ensemble.yaml b/pyhazards/model_cards/deep_ensemble.yaml new file mode 100644 index 00000000..8c86189c --- /dev/null +++ b/pyhazards/model_cards/deep_ensemble.yaml @@ -0,0 +1,159 @@ +model_name: deep_ensemble +display_name: Deep Ensemble +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/deep_ensemble.py +builder_name: deep_ensemble_builder +summary: > + Deep ensembles (Lakshminarayanan et al., 2017) of any registered PyHazards model, with the + uncertainty terms of the ten-LSTM wildfire-danger ensemble of Kondylatos et al. (2025). +description: + - > + ``deep_ensemble`` builds ``num_members`` (default 5) copies of a registered model + (``base_model``, ``base_kwargs``), member ``m`` initialised right after + ``torch.manual_seed(seeds[m])`` (default seeds ``0 .. M-1``), and predicts with their uniform + mixture: classification and segmentation average the member probabilities (softmax over the + channel dimension, or a sigmoid for one-channel binary logits), regression moment-matches the + Gaussian mixture of mean/variance members. + - > + ``forward`` returns the log of the mixture probability for multi-class outputs (``(batch, + 2)`` for ``wildfire_forecasting`` members), the logit of the mixture probability for + one-channel binary outputs, and a ``(mean, variance)`` tuple for regression. + ``predict_uncertainty`` adds the epistemic variance, aleatoric term, predictive entropy and + mutual information of Kondylatos et al. (2025), or the epistemic and aleatoric variances of + the Gaussian mixture. + - > + Members are trained independently (Algorithm 1): ``ensemble.fit`` trains each with its own + optimizer and its own data order, optionally with fast-gradient-sign adversarial examples + (``fgsm_example``, step ``input_range_epsilon`` = 1% of each input dimension's range). + ``mc_dropout_passes`` keeps the members' dropout active at prediction and pools several + passes per member, as in Chakravarty (2025). +paper: + title: "Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles" + url: https://arxiv.org/abs/1612.01474 +references: + - title: "Uncertainty-Aware Deep Learning for Wildfire Danger Forecasting" + url: https://arxiv.org/abs/2509.25017 + repo_url: https://github.com/Orion-AI-Lab/uncertainty-wildfires + note: > + Kondylatos, Papadopoulos, Camps-Valls & Papoutsis (arXiv 2509.25017). Next-day danger on + Mesogeos (1 km, Mediterranean; train 2006-2019, validation 2020, test 2021-2022; two + negatives per ignition): deep ensemble of 10 LSTMs (LayerNorm, LSTM 128, linear 128 and 64 + with ReLU and dropout 0.5, two outputs) on 45-day windows of 25 features (13 dynamic, 12 + static), each trained from its own seed (1, 12, 17, 123, 1234, 2222, 12345, 54321, 77777, + 87877 in the released checkpoints) with Adam (lr 0.004, weight decay 0.0063), + StepLR(15, 0.1), 30 epochs, batch 256 and an NLL loss scaled by the log burned area. + Table 1: precision 0.794, recall 0.760, F1 0.777, AUPRC 0.852, ECE 0.019 (with the + aleatoric head: 0.787, 0.768, 0.777, 0.854, 0.022), against F1 0.762, AUPRC 0.840 and ECE + 0.031 for one deterministic LSTM. In PyHazards: ``base_model="wildfire_forecasting"``, + ``base_kwargs={"hidden_size": 128}``, ``num_members=10``. + - title: "Spatial Uncertainty Quantification in Wildfire Forecasting for Climate-Resilient Emergency Planning" + url: https://arxiv.org/abs/2510.09666 + note: > + Chakravarty, NeurIPS 2025 workshop Tackling Climate Change with Machine Learning. Deep + ensemble of U-TAE models (about 1.1M parameters, dropout 0.1 after the temporal attention) + trained with distinct random seeds, each run with MC dropout (20 forward passes) at + inference, on WildfireSpreadTS (5-day inputs, vegetation and active-fire features, 128 x 128 + crops, AdamW lr 0.01 and weight decay 0.01, weighted BCE, 10,000 steps, batch 32, 12-fold + cross-validation). The ensemble size is not stated and no code was released. Calibration, + 12-fold mean (Table 2): ECE 0.512 +- 0.018, Brier score 0.265 +- 0.009, NLL 0.731 +- 0.023 + (MC dropout 0.536 / 0.294 / 0.805, BNN 0.525 / 0.283 / 0.794). In PyHazards: + ``base_model="utae"``, ``task="segmentation"``, ``mc_dropout_passes=20``. +reproduction: + reference_code: https://github.com/Orion-AI-Lab/uncertainty-wildfires + reference_commit: fcfbfb894926d173e2f4cafc95b08f02cefe6e00 + reference_license: MIT + reference_config: > + The deep ensemble of Kondylatos et al. (2025): ten SimpleLSTM members (models/model.py, + output_lstm 128, dropout 0.5, 25 features; configs/config_det.json) seeded as in the released + checkpoints trained_models/ensembles/no-noisy/ensembles--checkpoint.pth, aggregated by + utils/train_functions.py ``uncertainties`` as in test.py (configs_test/config_des.json, + num_models 10), also with test-time dropout and several passes per member. PyHazards members + are ``wildfire_forecasting`` LSTMs with hidden_size 128 (104,308 parameters each). + parameter_count: 1043080 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_deep_ensemble_oracle.py + deviations: + - > + Lakshminarayanan et al. released no code. The mean/variance regression path (softplus + variance plus 1e-6, Gaussian NLL, moment-matched mixture) and the FGSM adversarial training + are rebuilt from the paper's Section 2 and Algorithm 1 and covered by plain tests only; + Kondylatos et al. (2025) use neither. + - > + ``DeepEnsemble.fit`` is a generic independent-training loop (any loss, an optimizer per + member, member-seeded shuffling). It does not reproduce the reference training script + (StepLR schedule, burned-area loss scaling, validation monitoring); train the members with + that recipe to reproduce the paper. + - > + The reference members return logits and ``wildfire_forecasting`` returns log-probabilities; + the ensemble applies a softmax to either, so the probabilities are the same (checked). + - > + The epistemic term is computed as a population variance (``var(unbiased=False)``) instead of + the reference's ``E[p^2] - E[p]^2``: the same quantity without cancellation error, equal + within 1e-6 in the oracle test. + - > + The aleatoric-noise heads (Collier et al.), Bayes-by-Backprop and MC-dropout-only models of + Kondylatos et al. (2025) are not part of this entry. +tasks: + - classification + - segmentation + - regression +example: | + import torch + from pyhazards.models import build_model + from pyhazards.models.deep_ensemble import input_range_epsilon + + # Kondylatos et al. (2025): ten next-day danger LSTMs + ensemble = build_model( + name="deep_ensemble", + task="classification", + base_model="wildfire_forecasting", + base_kwargs={"hidden_size": 128}, + num_members=10, + ) + x = torch.randn(4, 45, 25) + log_probs = ensemble(x) # log of the mean member probability, (4, 2) + terms = ensemble.predict_uncertainty(x) + print(terms["probs"].shape, terms["epistemic"].shape, terms["mutual_information"].shape) + + # Algorithm 1: train each member on its own, optionally with FGSM adversarial examples + x_train, y_train = torch.randn(64, 45, 25), torch.randint(0, 2, (64,)) + ensemble.fit( + x_train, + y_train, + loss_fn=torch.nn.NLLLoss(), + optimizer_factory=lambda params: torch.optim.Adam(params, lr=1e-3), + epochs=1, + adversarial_epsilon=input_range_epsilon(x_train), + ) +notes: + - > + Outputs per task: multi-class classification / segmentation give ``log`` of the mixture + probability (``exp`` for probabilities; ``nn.NLLLoss`` applies); one-channel binary outputs + give the logit of the mixture probability (``sigmoid`` for probabilities); regression gives + ``(mean, variance)``. With ``regression_output="gaussian"`` (default, the paper) members must + output ``2K`` channels along dim 1, K means then K raw variances; ``regression_output="point"`` + uses point-prediction members and their spread as the variance. + - > + ``Trainer.fit`` refuses the ensemble (training the averaged output as one network would not + be a deep ensemble). Use ``ensemble.fit`` or train each of ``ensemble.members`` separately; + ``Trainer.evaluate`` and ``Trainer.predict`` work on the ensemble. + - > + The builder restores the global random state after seeding the members, so building an + ensemble does not change later random draws. Member ``m`` equals ``build_model(base_model, + ...)`` called right after ``torch.manual_seed(seeds[m])``. + - > + Cost scales with the number of members (and MC-dropout passes): ten 104k-parameter LSTMs for + the Kondylatos configuration, about 11M parameters for ten U-TAE members. +smoke_test: + task: classification + build_kwargs: + base_model: wildfire_forecasting + num_members: 2 + input: + kind: tensor + tensor: + shape: [2, 10, 25] + expected_output: + kind: tensor + shape: [2, 2] diff --git a/pyhazards/model_cards/deeplabv3.yaml b/pyhazards/model_cards/deeplabv3.yaml new file mode 100644 index 00000000..6708f1e2 --- /dev/null +++ b/pyhazards/model_cards/deeplabv3.yaml @@ -0,0 +1,115 @@ +model_name: deeplabv3 +display_name: DeepLabV3 +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/deeplabv3.py +builder_name: deeplabv3_builder +summary: > + DeepLabV3 (Chen et al., 2017) as implemented by segmentation_models_pytorch: a dilated ResNet + encoder, atrous spatial pyramid pooling with image-level features, and bilinear up-sampling, + configured as the DeepLabV3 baseline of Shadrin et al. (2024) for multi-day wildfire spread. +description: + - > + ``deeplabv3`` runs a ResNet encoder at output stride 8 (the strides of ``layer3`` and + ``layer4`` replaced by dilation 2 and 4) and applies atrous spatial pyramid pooling to its + deepest feature: a 1x1 branch, three 3x3 atrous branches at rates 12, 24 and 36 and an + image-pooling branch, each with 256 filters, batch normalisation and ReLU, concatenated and + projected by a 1x1 convolution with dropout 0.5. A 3x3 convolution, a 1x1 classifier and + bilinear up-sampling by 8 return logits at the input resolution. + - > + The implementation reproduced is ``segmentation_models_pytorch.DeepLabV3`` (smp 0.3.2; the + code path is identical from 0.2.0 to 0.3.4), because Shadrin et al. describe their models + in smp's terms ("encoder backbone ResNet18, number of stages used in encoder equals to 3 ... + default values for the other hyperparameters") and report smp's ``micro-imagewise`` metric + reduction. It is ported to plain PyTorch with smp's parameter names, creation order and + initialisation, so smp state dicts load with ``strict=True``; ``encoder_weights="imagenet"`` + loads the ImageNet ResNet and adapts the stem to the input channels the way smp does. + - > + The builder defaults are Shadrin et al.'s configuration: ResNet-18 with three encoder stages + and 58 input channels (the 3-day horizon), on 32 x 32 tiles. With three stages the ASPP runs on + the 128-channel, stride-8 output of ``layer2``; smp still builds (and dilates) ``layer3`` and + ``layer4``, whose 10,493,440 parameters are kept for state-dict compatibility although the + forward pass never uses them. The ``DeepLabV3`` class itself defaults to smp's ResNet-34 with + five stages. +paper: + title: "Rethinking Atrous Convolution for Semantic Image Segmentation" + url: https://arxiv.org/abs/1706.05587 + repo_url: https://github.com/tensorflow/models/tree/master/research/deeplab +references: + - title: "Wildfire spreading prediction using multimodal data and deep neural network approach" + url: https://doi.org/10.1038/s41598-024-52821-x + note: > + Shadrin et al., Scientific Reports 14:2606 (2024). DeepLabV3 with "encoder backbone ResNet18, + number of stages used in encoder equals to 3 ... default values for the other hyperparameters" + (smp defaults: 256 ASPP channels, output stride 8, rates 12/24/36, ImageNet encoder weights), + compared with U-Net, U-Net++ and MA-Net. 947 fires of 2021-2022 in Krasnoyarsk, Irkutsk and + Sakha, split 4:1. Input: 32 x 32 tiles (21 x 21 km at 650 m around the ignition point; the + data are first resampled to 128 x 128 at 0.0059435 degrees) with one ignition layer, 21 static + layers (17 land-cover masks, elevation, aspect, slope, population), 6 MODIS vegetation layers + and 10 ERA5-Land/MODIS weather layers per forecast day: 58 channels for 3 days, 78 for 5. + Target: burned-area mask. F1 for the day-3 forecast (micro-imagewise, Table 3) with BCE 0.64, + Dice 0.66, focal 0.63, Dice + focal 0.65, generalized Dice 0.66 and Tversky 0.66 (+- 0.004 to + 0.006); the selected MA-Net reaches 0.67. Only MA-Net's training setup is given (Adam, lr 3e-3, + L2 1e-5, OneCycleLR, 35 epochs, batch 32). No code was released; data on request. +reproduction: + reference_code: https://github.com/qubvel-org/segmentation_models.pytorch + reference_commit: v0.3.2 + reference_license: MIT (the ASPP/decoder file is from torchvision, BSD-3-Clause) + reference_config: > + smp.DeepLabV3(encoder_name="resnet18", encoder_depth=3, encoder_weights=None, in_channels=58, + classes=1) on 2 x 58 x 32 x 32 inputs (Shadrin et al.), plus smp's defaults (ResNet-34, five + stages, 26,007,105 parameters), ResNet-18 with four and five stages, and the ImageNet-initialised + 58-channel stem. The decoder and 1x1 classifier are also checked against torchvision's DeepLabHead. + parameter_count: 13220609 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_deeplabv3_oracle.py + deviations: + - > + ``encoder_weights`` defaults to None, so building the model downloads nothing; smp's default + (which Shadrin et al. kept) is "imagenet". Pass ``encoder_weights="imagenet"`` to match it. + - > + Inputs whose height or width is not divisible by the output stride raise ValueError instead + of smp's RuntimeError, and ``encoder_depth`` outside smp's documented range [3, 5] raises + ValueError (smp builds such a model, but its fixed x8 up-sampling then no longer restores the + input size). +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # Shadrin et al. (2024): ResNet-18, three encoder stages, 58 channels for a 3-day horizon. + model = build_model(name="deeplabv3", task="segmentation", in_channels=58) + logits = model(torch.randn(2, 58, 32, 32)) + print(logits.shape) # (2, 1, 32, 32) + + # smp's own defaults (ResNet-34, five stages); encoder_weights="imagenet" downloads ImageNet weights. + smp_default = build_model(name="deeplabv3", task="segmentation", in_channels=3, + encoder_name="resnet34", encoder_depth=5) +notes: + - > + smp's DeepLabV3 differs from the paper's network: it keeps output stride 8 throughout (the + paper trains at 16 with rates 6/12/18 and evaluates at 8 with 12/24/36), has no multi-grid, + dilates every convolution of the dilated stages including the first block's (torchvision keeps + the previous dilation there), adds a 3x3 convolution after the ASPP and dropout 0.5 in the + projection (both from torchvision), uses ResNet-18/34 rather than ResNet-50/101, and up-samples + the logits with align_corners=True. + - > + On Shadrin et al.'s 32 x 32 tiles with three encoder stages the ASPP sees 4 x 4 features, so the + rate-12/24/36 branches reach only padding outside their centre tap and act as 1x1 convolutions + (the degenerate case discussed in the DeepLabV3 paper). + - "smp 0.3.x never calls its initialize() for DeepLabV3, so the decoder and head keep PyTorch's default initialisation; the port does the same." + - "The image-pooling branch has batch normalisation on a 1 x 1 map, so training needs a batch size above 1, as in smp and torchvision." + - "Height and width must be divisible by 8. Encoders: resnet18 and resnet34. smp's auxiliary classification head (aux_params) and output activation are not ported." + - "This is DeepLabV3, not DeepLabV3+; no wildfire paper in the PyHazards inventory used V3+." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 6 + input: + kind: tensor + tensor: + shape: [2, 6, 32, 32] + expected_output: + kind: tensor + shape: [2, 1, 32, 32] diff --git a/pyhazards/model_cards/earthfarseer.yaml b/pyhazards/model_cards/earthfarseer.yaml new file mode 100644 index 00000000..16d129c2 --- /dev/null +++ b/pyhazards/model_cards/earthfarseer.yaml @@ -0,0 +1,127 @@ +model_name: earthfarseer +display_name: Earthfarseer +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/earthfarseer.py +builder_name: earthfarseer_builder +summary: > + Spatio-temporal forecaster that combines a local CNN branch with a global Fourier transformer + (FoTF) and a SimVP-style temporal block with Fourier mixing (TeDev); a Sim2Real-Fire + fire-forecasting baseline. +description: + - > + ``earthfarseer`` maps ``T`` input frames ``(batch, T, C, H, W)`` to the next ``T`` frames + (Wu et al., AAAI 2024). The spatial block FoTF runs a global Fourier transformer (16x16 + patches, 12 blocks of width 768 whose token mixing is an adaptive Fourier neural operator, + then three transposed convolutions back to pixels) next to a local convolution branch, and + lets the two exchange features three times. A strided convolutional encoder (``hid_S`` + channels, ``N_S`` layers) compresses each frame; TeDev stacks the frames as channels and + runs a U-shaped stack of multi-kernel Inception blocks (``N_T`` down, ``N_T`` up, ``hid_T`` + channels) with 12 Fourier blocks at its bottleneck; a mirrored decoder returns to pixels, + and the output of a complete SimVP network on the raw input is added. + - > + The default is the official ``Earthfarseer_model(shape_in=(10, 1, 64, 64))`` (the paper's + Moving MNIST setting, 10 -> 10 frames): hid_S 512, hid_T 256, N_S 4, N_T 8, Inception kernels + 3/5/7/11 with 8 groups, 157,518,863 parameters. The official code has no license, so the + model is written from the paper and permissively licensed parts (OpenSTL's SimVP Inception + block, Apache-2.0); parameter names and creation order follow the official code, so its + state dicts load with ``strict=True`` and the same seed gives the same weights. + - > + ``task="forecasting"`` returns the frame forecast. ``task="segmentation"`` is a PyHazards + adaptation for next-step fire masks: a 1x1 convolution (``segmentation_head``) maps the + channels of the first predicted frame to ``out_channels`` logits ``(batch, 1, H, W)``; the + Earthfarseer parameters keep their official names at the top level of the state dict. +paper: + title: "Earthfarseer: Versatile Spatio-Temporal Dynamical Systems Modeling in One Model" + url: https://arxiv.org/abs/2312.08403 + repo_url: https://github.com/easylearningscores/EarthFarseer +references: + - title: "Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire" + url: https://github.com/TJU-IDVLab/Sim2Real-Fire + repo_url: https://github.com/TJU-IDVLab/Sim2Real-Fire + note: > + Li et al., NeurIPS 2024 Datasets and Benchmarks. Listed as "Earthfarsser" among the AI + baselines of Table 2, trained on simulated wildfire scenarios and tested on simulated and + real-world fires (binary fire-area sequences with satellite, topography, vegetation, fuel + and weather inputs). Forecast AUPRC / F1 / IoU: 73.4 / 70.6 / 63.5 (simulation) and + 62.4 / 60.5 / 49.2 (real world); backtracking: 69.3 / 68.5 / 50.9 and 51.6 / 49.4 / 37.5. + Configuration not published: the paper only calls the baselines "commonly used AI models + that can be easily adapted", and its repository contains only S2R-FireTr (3 input frames + at 256x256), so the input stacking, model size, loss and output head of this baseline are + unknown. These numbers are not reproduced by PyHazards. +reproduction: + reference_code: https://github.com/Alexander-wu/EarthFarseer + reference_commit: 258d4bb56497a6fb4022a5c37dec1e05ab1bedb1 + reference_license: >- + none (no LICENSE file; the README's Apache-2.0 badge links to OpenSTL's licence and does not + license this repository); used only as a test oracle, not copied + reference_config: > + Earthfarseer_model(shape_in=(10, 1, 64, 64)) with its defaults hid_S=512, hid_T=256, N_S=4, + N_T=8, incep_ker=[3, 5, 7, 11], groups=8 (timm 0.9.16 as in the official requirements): + 157,518,863 parameters, seeded initialisation and outputs compared locally with + PYHAZARDS_ORACLE_LARGE=1 (bit-identical in eval and train mode). CI compares three reduced + models (other frame counts, channels, sizes, N_S 2/4/6, N_T 2/3, kernels and groups) in which + only the hard-coded FoTF transformer width and depth (768, 12) are overridden in the official + GF_Block call, plus official state dicts loaded into the builder's forecasting and + segmentation models. + parameter_count: 157518863 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_earthfarseer_oracle.py + deviations: + - > + task="segmentation" (first predicted frame, 1x1 convolution to out_channels logits) is a + PyHazards adaptation, not from Sim2Real-Fire, whose baseline heads are unpublished. + - > + The official model sizes the TeDev Fourier token grid as int(H / 2 ** (N_S / 2)), plus 1 + when H is divisible by 3. Because H must be a multiple of 16, this disagrees with the real + latent size, and the official forward fails, whenever H is divisible by 3 (48, 96, ..., 384) + or N_S is odd. PyHazards uses the real latent size, which equals the official value + wherever the official model runs. + - > + The official FoTF builds its transformer for H x H (img_size=H), so non-square inputs fail + its patch-embedding assertion; PyHazards builds it for H x W. + - > + gf_embed_dim, gf_depth and num_interactions are hard-coded in the official model (768, 12, + 3); PyHazards exposes them only to build smaller models (smoke tests). Their defaults give + the official network. +tasks: + - forecasting + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # Official default: 10 frames of 1 x 64 x 64 -> the next 10 frames (157.5M parameters). + model = build_model(name="earthfarseer", task="forecasting") + x = torch.randn(2, 10, 1, 64, 64) # (batch, time, channels, height, width) + print(model(x).shape) # (2, 10, 1, 64, 64) + + # PyHazards next-step fire-mask adaptation on 3 frames of 4 channels at 128 x 128. + seg = build_model(name="earthfarseer", task="segmentation", in_channels=4, history=3, img_size=128) + print(seg(torch.randn(2, 3, 4, 128, 128)).shape) # (2, 1, 128, 128) +notes: + - "The output has as many frames as the input. The paper's temporal projection to other lengths (10 -> 30, 50 -> 50 frames) is not in the released code, so it is not provided." + - "Height and width must be multiples of 16 (FoTF patches and its 16x transposed-convolution head) and of the encoder stride; the parameter count depends on the frame count and size (for example 145,121,999 for 3 frames of 1 x 256 x 256)." + - "Kept from the official code because they change outputs or parameter counts: the same global transformer and local branch are applied seven times inside FoTF; the transformer MLP replaces fc2 by an average pool over groups of four hidden features (fc2 is built but unused); the Fourier operator's second layer computes its imaginary part from the already updated real part; a second encoder (enc) is built but unused; the added SimVP branch (skip_conneciton, spelling kept) has fixed sizes 16 / 256 / 4 / 8." + - "Where the paper and the released code differ, PyHazards follows the code: the local branch is one 1x1 transposed convolution (the paper describes 3x3 ConvNormReLU units), the FoTF up-exchange is a transposed convolution and the down-exchange a convolution (the paper states the reverse), and the TeDev kernels are 3/5/7/11 (the paper lists 1/3/7/11)." + - "Every dropout and stochastic-depth rate is 0 in the official model, so training and evaluation mode give the same outputs (GroupNorm and LayerNorm only)." + - "No official pretrained weights were found." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 2 + history: 2 + img_size: 32 + hid_S: 8 + hid_T: 16 + N_S: 4 + N_T: 2 + gf_embed_dim: 32 + gf_depth: 1 + input: + kind: tensor + tensor: + shape: [1, 2, 2, 32, 32] + expected_output: + kind: tensor + shape: [1, 1, 32, 32] diff --git a/pyhazards/model_cards/earthformer.yaml b/pyhazards/model_cards/earthformer.yaml new file mode 100644 index 00000000..f236bd11 --- /dev/null +++ b/pyhazards/model_cards/earthformer.yaml @@ -0,0 +1,166 @@ +model_name: earthformer +display_name: Earthformer +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/earthformer.py +builder_name: earthformer_builder +summary: > + Space-time Transformer built from cuboid attention with global vectors, a hierarchical + encoder-decoder for frame sequences; one of the Sim2Real-Fire forecasting baselines. +description: + - > + ``earthformer`` forecasts a sequence of future frames from past frames (Gao et al., NeurIPS + 2022). Cuboid attention splits the (time, height, width) tensor into cuboids and attends inside + each; the "axial" pattern used for all released models stacks three of them, (T, 1, 1), + (1, H, 1) and (1, 1, W), each with a pre-LN feed-forward layer, and optional global vectors + exchange information between cuboids. Convolutions with patch merging first reduce the + frames (12x for SEVIR), a two-level encoder follows (patch merging between levels), and a + non-autoregressive decoder starts from learned query frames (the projected positional + embedding), alternates self-attention with cross-attention to the encoder memory of each + level and upsamples back to the input resolution. + - > + The module is a port of the official ``CuboidTransformerModel`` (Apache-2.0) with its + parameter names, creation order and initialisation, so the official state dicts load with + ``strict=True`` and the same seed gives the same weights. ``config`` selects an official + configuration file: ``sevir`` (earthformer_sevir_v1.yaml, the released SEVIR checkpoint, + default), ``sevir_lr``, ``moving_mnist`` / ``nbody`` and ``enso`` (the released ICAR-ENSO + checkpoint); any constructor argument can be overridden. ``pretrained="sevir"`` or + ``"icarenso2021"`` loads the official weights. + - > + ``task="forecasting"`` maps ``(batch, history, in_channels, H, W)`` to ``(batch, horizon, + out_channels, H, W)``; ``task="segmentation"`` is the same network predicting one frame with one + channel and returns next-fire-mask logits ``(batch, 1, H, W)``. The official code works in + ``(batch, T, H, W, C)``; ``CuboidTransformerModel`` keeps that layout. +paper: + title: "Earthformer: Exploring Space-Time Transformers for Earth System Forecasting" + url: https://arxiv.org/abs/2207.05833 + repo_url: https://github.com/amazon-science/earth-forecasting-transformer +references: + - title: "Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire" + url: https://github.com/TJU-IDVLab/Sim2Real-Fire + repo_url: https://github.com/TJU-IDVLab/Sim2Real-Fire + note: > + Li et al., NeurIPS 2024 Datasets and Benchmarks. Models are trained on about 1M simulated + wildfire scenarios (FARSITE, WFDS, WRF-SFIRE) and tested on simulated and about 1K real + scenarios; the input is the source sequence of binary fire-area masks with satellite image + sequences, topography, vegetation, fuel maps and weather, and the target is the future + (forecast) or past (backtracking) mask sequence. Earthformer is one of the "commonly used AI + models that can be easily adapted" (Sec. 4.1). Table 2 (AUPRC / F1 / IoU, %): forecast + 77.2 / 73.5 / 59.7 on simulated and 65.4 / 61.7 / 50.1 on real-world data; backtracking + 71.4 / 63.0 / 48.1 and 53.4 / 51.3 / 41.7. Tables 4 and 6 report the AUPRC without each + modality. Configuration not published: the paper and the repository (which contains only + S2R-FireTr) give no Earthformer hyperparameters, input stacking, resolution, loss or output + head; S2R-FireTr itself uses 3 input frames at 256 x 256. +reproduction: + reference_code: https://github.com/amazon-science/earth-forecasting-transformer/blob/7732b03bdb366110563516c3502315deab4c2026/src/earthformer/cuboid_transformer/cuboid_transformer.py + reference_commit: 7732b03bdb366110563516c3502315deab4c2026 + reference_license: Apache-2.0 (Copyright Amazon.com, Inc. or its affiliates) + reference_config: > + CuboidTransformerModel built as the official training scripts build it from the model section + of scripts/cuboid_transformer/sevir/earthformer_sevir_v1.yaml (13 x 384 x 384 -> 12 frames, + base 128 channels, stack-conv down-sampling 3-2-2 to 32 x 32, one axial block per level, + 8 global vectors with separate projections and global self-attention, 8,659,677 + parameters) and moving_mnist/cfg.yaml (10 x 64 x 64 -> 10, base 64, four blocks per level, no + global vectors, 6,702,109), plus sevir/cfg_sevirlr.yaml (1,505,069), enso/earthformer_enso_v1.yaml + (1,394,325), six configurations with other patterns and options, and the official + earthformer_sevir.pt and earthformer_icarenso2021.pt checkpoints (sha256-pinned Internet + Archive copies). Seeded initialisation, eval and train-mode outputs and gradients are + compared; architecture checks run at 13 x 48 x 48 and 13 x 50 x 50 (SEVIR) and 10 x 32 x 32 + (Moving-MNIST), the checkpoints at 13 x 384 x 384 and 12 x 24 x 48. + parameter_count: 8659677 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_earthformer_oracle.py + deviations: + - > + task="segmentation" is a PyHazards adaptation, not from Sim2Real-Fire (whose Earthformer + setup is unpublished): the network is built with target_shape (1, H, W, 1) and its single + predicted frame is returned as (batch, 1, H, W) logits. Parameter names are those of + CuboidTransformerModel (no prefix). + - > + Earthformer and EarthformerSegmenter take (batch, time, channels, H, W) and permute to the + official (batch, time, H, W, channels) layout; CuboidTransformerModel keeps the official + layout. Inputs must have exactly the configured shape (ValueError otherwise); the official + code also accepts sizes that pad to the same token grid and then returns the configured + output size. + - > + Three paths that only raise errors in the official code work here: PatchMerging3D pads when + only the time axis needs padding (the official test reads "pad_h or pad_h or pad_w"), the + CTHW layout of Upsample3DLayer (official: undefined self.output_size), and cuboid + cross-attention with padding_type "zeros" or "nearest" when padding is needed (official: + undefined mask; here padded entries count as tokens, as in the self-attention mask). None + of them is reached by the official configurations. + - > + Only CuboidTransformerModel is ported. CuboidTransformerAuxModel and the U-Net decoder + (cuboid_transformer_unet_dec.py, used for EarthNet2021 with auxiliary inputs and + the earthformer_earthnet2021.pt checkpoint) and the unused DownSampling3D layer are not. +tasks: + - forecasting + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # Released SEVIR configuration: 13 frames of 384 x 384 VIL (scaled to [0, 1]) -> 12 frames. + model = build_model(name="earthformer", task="forecasting") # 8,659,677 parameters + # Official SEVIR weights (Apache-2.0, downloaded and sha256-checked on first use): + # model = build_model(name="earthformer", task="forecasting", pretrained="sevir") + model.eval() + with torch.no_grad(): + frames = model(torch.rand(1, 13, 1, 384, 384)) # (batch, time, channels, H, W) + print(frames.shape) # (1, 12, 1, 384, 384) + + # Next-fire-mask adaptation (PyHazards): 3 days of 8 channels at 256 x 256 -> one mask logit map. + fire = build_model(name="earthformer", task="segmentation", history=3, in_channels=8, img_size=256) + print(fire(torch.randn(2, 3, 8, 256, 256)).shape) # (2, 1, 256, 256) +notes: + - > + Parameter counts in the paper. The released configurations are smaller than the models in + the paper's tables (15.1M on SEVIR, 7.6M on Moving-MNIST, N-body MNIST and ICAR-ENSO), and the + official class reproduces the paper's numbers exactly when built from them as follows + (checked against the official code): SEVIR with enc_depth = dec_depth = [2, 2], two cuboid + attention blocks per level as listed in the paper's Table 9 (the released v1 file has one), + gives 13,075,029 without global vectors (13.1M, "w/o global") and 15,082,069 (15.1M) with + eight global vectors that share the local q/k/v projections and have no FFN of their own; + Moving-MNIST cfg.yaml with "t+h+w" instead of "t+hw" positional embeddings (-90,112) gives + 6,611,997 (6.61M, "Axial" / "w/o global") and 7,610,781 (7.61M) with those global vectors; + ICAR-ENSO with four blocks per level (the Moving-MNIST architecture, paper Table 8) gives + 6,601,293 and 7,600,077 (6.6M / 7.6M). The counts also fix that the decoder self-attention + uses no global vectors (which would add parameters); whether the decoder cross-attention and + the global self-attention use them does not change the count. The appendix equations show a + global FFN, but with it the totals would not match. The released v1 files instead use one + block per level, and SEVIR v1 uses separate global projections with global self-attention. + - > + Official weights: earthformer_sevir.pt (SEVIR, 34.8 MB) and earthformer_icarenso2021.pt + (ICAR-ENSO, 5.7 MB) are plain CuboidTransformerModel state dicts for the sevir and enso + presets. The S3 bucket of the README (earthformer.s3.amazonaws.com) answered HTTP 403 on 2026-10-07; + pretrained= tries it first and then the Internet Archive capture of 2025-05-17, whose SHA-1 + equals the archived original (S3 Last-Modified 2023-07-14), and checks the pinned sha256. The + SEVIR model expects VIL divided by 255 in (batch, 13, 1, 384, 384) and was trained with MSE. + No Moving-MNIST or N-body weights were released. + - > + Behaviour of the official code that is kept because it changes outputs: cuboid patterns are + computed from the encoder memory shapes, so the decoder's temporal cuboids hold T_in frames; + with T_out < T_in they shrink and the relative-position bias table is sliced as a flattened + index (exact when only the outermost non-unit cuboid axis shrinks, as with the axial + pattern), and with T_out > T_in (ICAR-ENSO, 12 -> 14) the decoder frames are padded to a + multiple of T_in. With padding_type "zeros" (all official files) padded positions take part + in attention as zero vectors. z_init_method "zeros" makes the decoder queries the projected + positional embedding, independent of the input. + - > + Sizes that the initial down-sampling does not divide (for example 256 with the 12x SEVIR + stack) are zero-padded inside the patch merging, and the final upsampling returns the + configured size. Gradient checkpointing (checkpoint_level 1 or 2) uses the reentrant variant + as the official code does; all official configuration files set checkpoint_level 0. +smoke_test: + task: segmentation + build_kwargs: + history: 3 + in_channels: 4 + img_size: 48 + input: + kind: tensor + tensor: + shape: [2, 3, 4, 48, 48] + expected_output: + kind: tensor + shape: [2, 1, 48, 48] diff --git a/pyhazards/model_cards/eqnet.yaml b/pyhazards/model_cards/eqnet.yaml index 0e00baf2..1fedf7ad 100644 --- a/pyhazards/model_cards/eqnet.yaml +++ b/pyhazards/model_cards/eqnet.yaml @@ -1,41 +1,132 @@ model_name: eqnet display_name: EQNet hazard: Earthquake +catalog_status: variant source_file: pyhazards/models/eqnet.py builder_name: eqnet_builder summary: > - A transformer-style earthquake phase-picking baseline for modern sequence - modeling comparisons. + End-to-end multi-station earthquake detector (Zhu et al., JGR Solid Earth 2022): a 1-D ResNet feature + extractor, P and S picking heads, and a shift-and-stack module that aligns station features on candidate + hypocentres before an event detection network. Rebuilt from the paper. description: - > - ``eqnet`` extends the PyHazards earthquake benchmark stack with a - lightweight attention-based picking model. + ``eqnet`` takes station gathers ``(batch, stations, 3, samples)`` (E, N, Z at 100 Hz) and, for + detection, travel times ``(batch, stations, candidates, 2)`` (P and S, seconds) from every station to + every candidate hypocentre; ``eqnet_travel_times`` computes them for a uniform velocity model (the + paper's 6 km/s and 3.4 km/s) from station and candidate coordinates in km (``eqnet_candidate_grid``: + the paper's ~4 km grid), any travel-time table can be passed instead, and ``station_mask`` marks + padded stations. It returns ``{"phase": (batch, stations, 2, samples / 2), "event": (batch, + candidates, samples / 32)}`` probabilities (logits with ``logits=True``). - > - The implementation keeps the shared waveform input and two-pick output - contract so it can be evaluated alongside ``phasenet`` and ``eqtransformer``. + Feature extraction (Figure 3a, 996,960 parameters): a 1-D ResNet-18 with 32 / 64 / 128 / 256 channels + and a final 1x1 convolution to 128 features at 1/32 of the sampling rate, applied to every station. + Phase picking (Figure 3b): one sub-network for P on feature channels 0-63 and one for S on 64-127, + each two convolution / batch-norm / ReLU layers with x4 upsampling and an output convolution. The + shift-and-stack module reads the P features ``t_P`` and the S features ``t_S`` later at every station, + so that an event's features align on its origin time at its true location, and averages over + stations; the event detection network (Figure 3c) turns the aligned features into an activation over + origin time for every candidate. ``extract_picks`` keeps activation peaks above 0.5, + ``extract_events`` takes origin times from the peaks of the maximum over candidates and the location + as the geometric median of the 20 most activated candidates (Section 2.2). ``EQNetLoss`` is the sum + of the three binary cross-entropies (equation 1). + - > + For single-station picking (the paper's STEAD evaluation) ``annotate`` takes ``(n, 3, samples)`` + windows and the ``earthquake.picking`` benchmark scores the P / S picks. There is no multi-station + detection benchmark task yet, and no weights exist: EQNet must be trained before use. paper: - title: An End-To-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning - url: https://www.osti.gov/biblio/1978539 + title: "An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning" + url: https://doi.org/10.1029/2021JB023283 repo_url: https://github.com/AI4EPS/EQNet +references: + - title: "An End-to-End Earthquake Detection Method for Joint Phase Picking and Association Using Deep Learning (Zhu, Tai, Mousavi, Bailis & Beroza, JGR Solid Earth 127(3), e2021JB023283, 2022; arXiv:2109.09911)" + url: https://doi.org/10.1029/2021JB023283 + note: > + Trained on 99,465 NCEDC events with manual picks at more than 3 stations (AdamW, learning rate 3e-4, + weight decay 1e-4, cosine decay; Gaussian targets 1 s wide for picks, 2 s for origin times; + negative sampling of candidate locations). Table 1, STEAD test set (~120,000 waveforms, the + EQTransformer split), picks = peaks above 0.5, true positive within 0.5 s (protocol + "eqtransformer"): P precision 0.96, recall 0.95, F1 0.95, residual mean -0.01 s, std 0.08 s, MAE + 0.04 s; S 0.92 / 0.92 / 0.92, 0.01 / 0.11 / 0.07 s. Table 2, Ridgecrest 4-8 July 2019 (stations within 1 degree + of the sequence, 6 / 3.4 km/s, 4 km grid): 11,765 events at threshold 0.5; with the SCSN catalogue + (8,044 events) as benchmark, precision 0.55, recall 0.83, F1 0.66. +reproduction: + source: paper + reference_code: https://github.com/AI4EPS/EQNet + reference_commit: af94a08a85de4b2c917a1b9429b044e7f38e4c28 + reference_license: >- + Academic and Commercial License (Copyright (c) 2023 Weiqiang Zhu, Zhongwen Zhan): academic and + non-commercial use only; no licence before 2023-10-26. Not ported; used only as a test oracle. No + EQNet weights were released. + reference_config: > + Paper Figure 3 and Sections 2.1-2.2 (arXiv 2109.09911): 1,043,619 parameters (feature extractor + 996,960, two picking heads of 7,825, event detector 31,009). Verified against code: the feature + extractor equals ``ResNet(BasicBlock, [2, 2, 2, 2])`` of ``eqnet/models/resnet1d.py`` at af94a08 + (996,960 parameters, same names, same seeded initialisation, equal outputs in evaluation and training + mode, batch-norm statistics, gradients); the picking and detection heads equal the author's first + ``PhasePicker`` / ``EventDetector`` (``eqnet/models/eqnet.py`` at a9df49a, 2022-07-27, unlicensed) + instantiated at the paper's widths ``[64, 32, 16]`` and ``[128, 64, 32]`` (equal outputs with copied + weights, same seeded convolution weights). Not verifiable against code: the shift-and-stack module, + the P / S feature split and the end-to-end model (tested from the paper's description: synthetic + arrivals from a known hypocentre peak at the true candidate and origin time); no numbers of the paper + are reproduced (no weights, retraining needed). + parameter_count: 1043619 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_eqnet_oracle.py + deviations: + - > + Choices the paper leaves open, taken from the author's code: reflect padding, bias-free + convolutions before batch normalisation and a biased output convolution, linear x4 interpolation + (``align_corners=False``), Kaiming-normal initialisation of the extractor, and no ReLU after its last + batch normalisation (the figure caption puts batch normalisation and ReLU after every convolution). + - > + PyHazards choices (paper silent, not in any code): the shift-and-stack averages over stations + (``station_mask`` excludes padded ones), reads fractional shifts by linear interpolation and treats + features outside the window as zero; output sample ``j`` of the picking heads is input sample + ``2 j`` and feature sample ``t`` is input sample ``32 t``; peaks of one phase must be 0.5 s apart + and events 2 s apart; candidate chunks of ``candidate_chunk`` in evaluation mode bound memory. + - > + ``annotate`` standardises each station's window per channel (mean removed, divided by the standard + deviation), as the official data reader does; the paper does not describe its normalisation. The + component order (E, N, Z) and the 100 Hz rate are assumptions (NCEDC data). + - > + The loss sums binary cross-entropies over time as in equations (2)-(4) and averages over stations, + candidates and the batch; target generation (Gaussian labels, negative sampling) is not part of the + module. tasks: - - regression + - picking + - detection example: | import torch from pyhazards.models import build_model + from pyhazards.models.eqnet import eqnet_candidate_grid, eqnet_travel_times + + model = build_model(name="eqnet", task="detection").eval() # no released weights: train first - model = build_model(name="eqnet", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + waveforms = torch.randn(1, 6, 3, 3072) # (batch, stations, E/N/Z, samples) at 100 Hz + stations = torch.rand(6, 3) * torch.tensor([40.0, 40.0, 0.0]) # station x, y, z in km + candidates = eqnet_candidate_grid((0.0, 40.0), (0.0, 40.0), spacing=4.0, depth=8.0) + travel_times = eqnet_travel_times(stations, candidates) # (1, 6, 121, 2), 6 and 3.4 km/s + with torch.no_grad(): + out = model(waveforms, travel_times) # phase: (1, 6, 2, 1536), event: (1, 121, 96) + events = model.extract_events(out["event"], candidates) + picks = model.extract_picks(out["phase"][0]) # one dict of P / S picks per station notes: - - "Outputs are P- and S-arrival sample indices." + - "Zhu, Tai, Mousavi, Bailis & Beroza, J. Geophys. Res. Solid Earth 127(3), e2021JB023283 (2022), arXiv:2109.09911. Not the GaMMA association paper (doi:10.1029/2021JB023249) that earlier versions of this card linked." + - "The AI4EPS/EQNet repository is now a toolbox of PhaseNet+ / PhaseNet-DAS models; its current picking and detection heads are different networks from the paper's, and it has no shift-and-stack module." + - "Breaking change: ``eqnet`` used to be a small transformer regressor returning one (P, S) pair per trace (task ``regression``, arguments ``hidden_dim``, ``num_heads``, ``num_layers``, ``dropout``); it now takes ``task='picking'`` or ``'detection'`` and returns the paper's activation sequences." smoke_test: - task: regression + task: detection build_kwargs: in_channels: 3 input: - kind: tensor - tensor: - shape: [4, 3, 256] + kind: kwargs + kwargs: + waveforms: + shape: [1, 4, 3, 1024] + travel_times: + shape: [1, 4, 6, 2] expected_output: - kind: tensor - shape: [4, 2] + kind: mapping + mapping: + phase: [1, 4, 2, 512] + event: [1, 6, 32] diff --git a/pyhazards/model_cards/eqtransformer.yaml b/pyhazards/model_cards/eqtransformer.yaml index 02bb1cf8..5a609726 100644 --- a/pyhazards/model_cards/eqtransformer.yaml +++ b/pyhazards/model_cards/eqtransformer.yaml @@ -1,41 +1,135 @@ model_name: eqtransformer display_name: EQTransformer hazard: Earthquake +catalog_status: core source_file: pyhazards/models/eqtransformer.py builder_name: eqtransformer_builder summary: > - A bidirectional sequence encoder for joint earthquake phase picking with - attention pooling over waveform windows. + Earthquake Transformer (Mousavi et al., Nature Communications 2020): a multi-task network that turns + a 60-s three-component seismogram into per-sample earthquake-detection, P-arrival and S-arrival + probabilities, ported from the official Keras code with its two released models. description: - > - ``eqtransformer`` is the second earthquake picking baseline in the staged - roadmap and shares the synthetic waveform contract used by ``phasenet``. + A deep encoder (seven convolution + max-pooling layers, seven residual CNN blocks, bidirectional + LSTM blocks and two transformer blocks with additive self-attention) compresses 6000 samples to 47 + time steps. Three decoders read the encoding: the detection decoder directly, the P and S decoders + after an LSTM and a local self-attention of width 3; each upsamples back to 6000 samples and ends + with a sigmoid. ``forward`` returns ``(batch, 3, 6000)`` probabilities in the order detection, P, S. - > - The PyHazards adapter focuses on the shared picking interface rather than a - full reproduction of the original multitask training pipeline. + ``variant="original"`` (default) is the paper model ``EqT_original_model.h5`` (two BiLSTM blocks, + 371,639 parameters); ``variant="conservative"`` is ``EqT_model_conservative.h5`` (three BiLSTM blocks, + 376,423 parameters), which the authors released later for fewer false positives. Both load with + ``pretrained=True`` (downloaded from the official repository at a pinned commit and checked by + sha256; MIT-licensed weights) and reproduce the official Keras outputs. + - > + ``annotate`` applies the official per-trace normalisation (remove the mean, divide by the standard + deviation of each component); ``extract_picks`` and ``extract_detections`` port the official + tester's ``picker`` (detection triggers of at least 10 samples, the earliest S peak and the most + probable P peak associated with each event), which the ``earthquake.picking`` benchmark uses. paper: - title: Earthquake Transformer-An attentive deep-learning model for simultaneous earthquake detection and phase picking + title: "Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking" url: https://doi.org/10.1038/s41467-020-17591-w repo_url: https://github.com/smousavi05/EQTransformer +references: + - title: "Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking" + url: https://doi.org/10.1038/s41467-020-17591-w + repo_url: https://github.com/smousavi05/EQTransformer + note: > + STEAD test set (10% random split, trace names in ModelsAndSampleData/test.npy), paper model, a pick + is a true positive when |error| < 0.5 s. Table 1 detection: precision 1.0, recall 1.0, F1 1.0 + (detection threshold 0.5). Table 2 P picks: mean error 0.00 s, std 0.03 s, precision 0.99, recall + 0.99, F1 0.99, MAE 0.01 s, MAPE 0.00. Table 3 S picks: mean 0.00 s, std 0.11 s, precision 0.99, + recall 0.96, F1 0.98, MAE 0.01 s, MAPE 0.00. + - title: "Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers" + url: https://doi.org/10.1029/2021JB023499 + repo_url: https://github.com/seisbench/pick-benchmark + note: > + Münchmeyer et al., J. Geophys. Res. Solid Earth 127, e2021JB023499 (2022). Retrains SeisBench's + PyTorch EQTransformer (the conservative three-BiLSTM architecture, 376,935 parameters because + PyTorch LSTMs carry two bias vectors) on each dataset; in-domain phase identification MCC + (Table 2): STEAD 1.00, INSTANCE 0.97, ETHZ 0.97, SCEDC 0.96, Iquique 0.99, NEIC 0.96, GEOFON 0.82. + These are retrained models, not the released weights. +reproduction: + reference_code: https://github.com/smousavi05/EQTransformer + reference_commit: a589da6504b11df8341fe1dc859a025f49955409 + reference_license: MIT (code and released models) + reference_config: > + The two released Keras models, EqT_original_model.h5 (paper model, Keras 2.3.0) and + EqT_model_conservative.h5 (Keras 2.2.4), loaded with tf.keras.models.load_model and the official + custom layers of EQTransformer/core/EqT_utils.py on TensorFlow 2.11, on random input and on the + repository's 100 STEAD sample traces (100samples.hdf5); the official ``picker`` on the same + probabilities; and SeisBench 0.12.6's EQTransformer with its conversions of both models (GPL-3.0, + used only as a second oracle). + parameter_count: 371639 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_eqtransformer_oracle.py + deviations: + - > + The released graphs call SpatialDropout1D (rate 0.2 in the paper model, 0.1 in the conservative + one) with ``training=True``, so the official models are random at inference (Monte Carlo + dropout; the paper uses dropout "at training and test time"). The port applies it in train mode + and, in eval mode, only with ``mc_dropout=True``: by default ``eval()`` outputs are deterministic + and equal the official model with that dropout switched off. ``annotate(x, mc_samples=n)`` + averages ``n`` passes with it on, as the official tester does with ``estimate_uncertainty=True``. + - > + Initial weights cannot match the reference for a seed (TensorFlow and PyTorch draw different + random numbers). The port uses the Keras initialisers of every layer (Glorot-uniform kernels, + Glorot-normal truncated at two standard deviations for the attention and feed-forward weights, + orthogonal recurrent kernels, unit forget bias), which the oracle test compares by distribution. + - > + Layout: input ``(batch, 3, 6000)`` and one stacked output ``(batch, 3, 6000)`` instead of Keras' + ``(batch, 6000, 3)`` input and three ``(batch, 6000, 1)`` outputs. Other input lengths raise a + ``ValueError``; the reference decoder cannot restore them either. + - > + Train-mode dropout masks follow Keras (one mask per sequence for the LSTM inputs and recurrent + state, per gate in the conservative model's ``implementation=1``), but cannot reproduce Keras' + random draws; train-mode outputs were compared with every dropout switched off. + - > + The official tester also reports MC-dropout uncertainties (standard deviations over passes); + ``extract_picks`` reports probabilities only. tasks: - - regression + - picking example: | import torch from pyhazards.models import build_model - model = build_model(name="eqtransformer", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + # The paper model with its released weights (MIT), downloaded on first use. + model = build_model(name="eqtransformer", task="picking", pretrained=True).eval() + + waveforms = torch.randn(4, 3, 6000) # 60 s at 100 Hz, components E, N, Z, band-passed 1-45 Hz + with torch.no_grad(): + probabilities = model.annotate(waveforms) # (4, 3, 6000): detection, P, S + picks = model.extract_picks(probabilities) # [{"P": [(sample, prob)], "S": [...]}, ...] + events = model.extract_detections(probabilities) # [[(on, off, prob)], ...] + + conservative = build_model(name="eqtransformer", task="picking", variant="conservative") notes: - - "Outputs are P- and S-arrival sample indices." + - > + Inputs follow the training data (STEAD): 60-s windows at 100 Hz with components in the order E, N, + Z, band-pass filtered between 1 and 45 Hz. ``annotate`` only normalises; filter real data first. + - > + The released models differ from the defaults of ``cred2`` at the pinned commit (e.g. 96/128 + filters there). The port follows the graphs stored in the .h5 files. The paper text gives a dropout + rate of 0.1; the stored paper model uses 0.2 (the conservative model 0.1). The paper also names a + Xavier-normal initialiser; the stored configurations use Glorot-uniform kernels for convolutions + and LSTMs and Glorot-normal ones only for the attention and feed-forward weights. + - > + The conservative model was saved by Keras 2.2.4, whose LSTMs use ``hard_sigmoid`` gates and + ``implementation=1``; the paper model (Keras 2.3.0) uses ``sigmoid`` and ``implementation=2``. The + two Keras versions also update BatchNorm's running statistics differently (zero-debiased moving + averages in 2.2.4); the port keeps each model's behaviour. + - > + Default pick thresholds are those of the official ``tester()`` (detection 0.2, P 0.1, S 0.1). As in + the tester's output table, ``extract_picks`` reports the first detected event of each window unless + ``all_events=True``. smoke_test: - task: regression + task: picking build_kwargs: in_channels: 3 input: kind: tensor tensor: - shape: [4, 3, 256] + shape: [1, 3, 6000] expected_output: kind: tensor - shape: [4, 2] + shape: [1, 3, 6000] diff --git a/pyhazards/model_cards/firecastnet.yaml b/pyhazards/model_cards/firecastnet.yaml index 34e2a281..b2d235d9 100644 --- a/pyhazards/model_cards/firecastnet.yaml +++ b/pyhazards/model_cards/firecastnet.yaml @@ -5,18 +5,85 @@ catalog_status: core source_file: pyhazards/models/firecastnet.py builder_name: firecastnet_builder summary: > - A compact encoder-decoder baseline for wildfire spread mask prediction. + GraphCast on an icosahedral multi-mesh for global seasonal burned-area forecasting on the + SeasFire datacube, with the official pretrained weights. description: - > - ``firecastnet`` is a raster wildfire spread baseline that uses a shallow - encoder-decoder architecture. + ``firecastnet`` predicts whether fire will burn in each 0.25-degree cell during a future + 8-day period (horizon 1 to 24 periods) from a time series of Earth-system variables + (Michail et al., Scientific Reports 2025). A cube embedding (``Conv3d`` with kernel and + stride ``T x 4 x 4`` plus LayerNorm) maps ``T = 24`` steps of the global 720 x 1440 grid + (10 SeasFire variables, land-sea mask and cos/sin coordinates) to 64 features on a + 1-degree grid. A GraphCast encoder-processor-decoder passes messages between that grid and + a multi-mesh made of icosphere levels 0-6 (40,962 nodes, 12 processor layers, hidden size + 64). A sub-pixel shuffle turns 16 outputs per 1-degree cell into one logit per 0.25-degree + cell. - > - The PyHazards implementation is optimized for the shared smoke benchmark - rather than the full upstream training stack. + This is a pure PyTorch port of the official code (no DGL). The icosphere multi-mesh and the + grid/mesh graphs are generated when the model is built and match the official graphs bit for + bit. Parameter names follow the official network, so the released checkpoints load with + ``strict=True`` through ``build_model(..., checkpoint=path)``: global ``ts24`` models for + horizons 1, 2, 4, 8, 16 and 24 (classification and regression) and per-GFED-region + local-area models, which also need their mesh file from the official repository + (``icospheres_graph_path``). paper: title: "FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction" url: https://doi.org/10.1038/s41598-025-30645-7 repo_url: https://github.com/SeasFire/firecastnet +references: + - title: "FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction (arXiv:2502.01550)" + url: https://arxiv.org/abs/2502.01550 + repo_url: https://github.com/SeasFire/firecastnet + note: > + SeasFire datacube (0.25 degree, 8-day steps), years 2002-2017 / 2018 / 2019 for + train / validation / test, binary burned area (gwis_ba) at horizon h, one model per + horizon, BCE, AdamW lr 1e-3, 50 epochs, batch 1. Global test AUPRC with 24 input steps + (Table 2): 0.641 / 0.636 / 0.631 / 0.631 / 0.628 / 0.633 for h = 1 / 2 / 4 / 8 / 16 / 24, + ahead of GRU, Conv-GRU, Conv-LSTM, U-TAE and TeleViT; local-area models per GFED region in + Table 4 (for example AUST 0.25 at h = 1, against 0.31 for the global model). +reproduction: + reference_code: https://github.com/SeasFire/firecastnet + reference_commit: dc0d131be7f0638e3a84c16817e7bc9be454e53e + reference_license: >- + none at repository level (test oracle only); the ported GraphCast layers are Apache-2.0 + (NVIDIA), as is NVIDIA Modulus v0.5.0, which the graph construction follows; checkpoints + Apache-2.0 (Hugging Face d-michail/firecastnet-artifacts) + reference_config: > + Released global classifier firecastnet-cls-ts24-h1.ckpt: 24 steps x 11 inputs (+3 static + channels) on the 720 x 1440 grid, Conv3d 24x4x4 to 64 channels with LayerNorm, 1-degree graph + grid (180 x 360), icosphere levels 0-6 (40,962 mesh nodes; 327,660 mesh, 100,160 grid-to-mesh + and 64,800 mesh-to-grid edges), 12 processor layers, hidden 64, sum aggregation, 16 outputs + and PixelShuffle(4); likewise firecastnet-regr-ts24-h1.ckpt and the AUST local-area + checkpoint firecastnet-cls-AUST-ts24-h1.ckpt (2,002-node mesh), plus small global + configurations with seeded initialisation. All 94 released checkpoint configurations use + this network configuration. + parameter_count: 9087568 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_firecastnet_oracle.py + deviations: + - > + Only the configuration FireCastNet uses is ported: a cube embedding whose temporal patch + spans the whole input (embed_cube_time == timeseries_len). The reference's other options + (no cube embedding, ViT and L-TAE cube embedders, the recurrent processor used when the + embedded cube keeps a time axis, do_concat_trick) appear neither in the paper nor in the + released checkpoints and raise an error here. + - > + The reference LightningModule accepts a batch size of 1. Here the cube embedding is batched + and the graph network runs once per sample, which gives the same per-sample outputs. + - > + The reference sizes its DGL bipartite graphs by the largest mesh vertex a grid node links + to, so it fails unless the grid reaches the last mesh vertex (in practice, only global + grids work). The port counts all mesh vertices, so regional windows also run; outputs on + global grids are unchanged. + - > + The reference also lists GraphNorm, InstanceNorm, BatchNorm and MessageNorm as norm_type + but looks them up in torch.nn, where none exists; only LayerNorm (or none) is accepted + here. Non-square patches switch the reference to a ConvTranspose3d up-sampling that fails + on its 4-D input; the port requires square patches. + - > + Nearest neighbours for the grid/mesh graphs come from a SciPy KD-tree with exact float64 + re-ranking instead of scikit-learn; the oracle checks that every graph (edge order and + features) is bitwise identical for the global and the local-area meshes. tasks: - segmentation - regression @@ -24,22 +91,63 @@ example: | import torch from pyhazards.models import build_model - model = build_model(name="firecastnet", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) + # Released configuration: 24 eight-day steps of 11 variables on the global 0.25-degree grid. + model = build_model(name="firecastnet", task="segmentation") # 9,087,568 parameters + # Official weights (huggingface.co/datasets/d-michail/firecastnet-artifacts, Apache-2.0): + # model = build_model(name="firecastnet", task="segmentation", checkpoint="firecastnet-cls-ts24-h1.ckpt") + model.eval() + x = torch.randn(1, 24, 11, 720, 1440) # (batch, time, variables, lat, lon), standardised + with torch.no_grad(): + probability = torch.sigmoid(model(x)) # (1, 1, 720, 1440) + print(probability.shape) notes: - - "The smoke configuration uses the single-frame wildfire spread raster fixture." + - > + Input channels, in order: mslp, tp, vpd, sst, t2m_mean, ssrd, swvl1, lst_day, ndvi, pop_dens, + lsm. Preprocessing is done outside the model, as in the official inference script: log(1 + x) + for tp and pop_dens, standardisation of the 10 dynamic variables with SeasFire statistics + (lsm stays raw), missing values set to -1, and a window of 24 steps ending h periods before the + target period. The official inference sets predictions to 0 where lsm < 0.1. + - > + The cube LayerNorm normalises over the whole embedded cube (64 x 1 x 180 x 360) with an + elementwise affine of that shape: 8,294,400 of the 9,087,568 parameters. A model therefore only + runs on the grid it was built for; the default is the global 0.25-degree grid. + - > + Kept from the reference because they change outputs: mesh-node features are cos/sin of + latitude and longitude in degrees passed to cos/sin without conversion to radians (as in + NVIDIA Modulus), and icosphere vertices come from midpoint subdivision of the flat icosahedron + with one projection onto the sphere at the end, not a projection after every refinement step + as the paper describes. + - > + The cos(lat), sin(lon) and cos(lon) channels are appended inside the model + (``lat_lon_static_data``). Any latitude/longitude window and resolution can be configured; + the smoke test uses a tiny 2.5-degree global grid with icosphere levels 0-2. + - > + Local-area checkpoints for BONA and SHSA point to mesh files that are not in the official + repository (final_icospheres/icosphere_s3_BONA_6u.json and + icospheres-lam/icospheres/icosphere_s3_SHSA_7u_SHAF_2n.json), + so they cannot be run as released; their weights still load, since no weight depends on + the mesh. + - > + A global forward pass on CPU needs about 5 GB of memory (the float32 input alone is 1.1 GB). + The paper's AUPRC was not re-evaluated here: that needs the 44 GB SeasFire datacube. smoke_test: task: segmentation build_kwargs: - in_channels: 12 - hidden_dim: 24 - out_channels: 1 - dropout: 0.0 + in_channels: 3 + timeseries_len: 2 + mesh_levels: [0, 1, 2] + sp_res: 2.5 + max_lat: 88.75 + min_lat: -88.75 + max_lon: 178.75 + min_lon: -178.75 + hidden_dim: 16 + embed_cube_dim: 16 + processor_layers: 3 input: kind: tensor tensor: - shape: [2, 12, 16, 16] + shape: [2, 2, 3, 72, 144] expected_output: kind: tensor - shape: [2, 1, 16, 16] + shape: [2, 1, 72, 144] diff --git a/pyhazards/model_cards/floodcast.yaml b/pyhazards/model_cards/floodcast.yaml index afd5fecb..f5f22367 100644 --- a/pyhazards/model_cards/floodcast.yaml +++ b/pyhazards/model_cards/floodcast.yaml @@ -1,21 +1,62 @@ model_name: floodcast display_name: FloodCast hazard: Flood +catalog_status: experimental source_file: pyhazards/models/floodcast.py builder_name: floodcast_builder summary: > - A compact spatiotemporal flood-inundation baseline for raster forecast experiments. + A small convolutional inundation baseline under the FloodCast name; not the published model, whose + flood-model code was never released and whose network widths the paper does not report (experimental). description: - > - ``floodcast`` is the first public inundation model in the staged PyHazards - flood roadmap. + ``floodcast`` is a compact PyHazards spatiotemporal network that maps ``(batch, history, channels, H, + W)`` rasters to a next-step depth raster ``(batch, 1, H, W)``. It is not FloodCast. FloodCast's + hydrodynamic module is the sequence-to-sequence GeoPINS: a physics-informed Fourier neural operator + solving the 2-D shallow-water equations without training labels, trained per 16-step sequence and + marched in time, with hard-encoded inflow boundaries. - > - The adapter uses shared raster tensors so it can be benchmarked through the - ``flood.inundation`` evaluator without dataset-specific glue code. + Why it is not rebuilt from the paper (arXiv 2403.12226v1, the only open version; read in full): the + paper gives the GeoPINS layout (MLP lift, FNO layers, MLP projection; GELU and a layer normalisation + after each FNO layer in its PDE experiments), four space-time FNO layers with spatial modes 32 and + temporal modes 4 for the flood model, the GeoPC loss (continuity and + momentum residuals with Manning friction, initial-condition weight 10, finite differences) and the + training schedule, but not the channel widths of the flood model (only the toy PDE experiments list + widths 16 / 24 / 24 / 32 / 32), not the lifting / projection widths, and only "3 input channels: + coordinate x, time t and initial condition" for a 2-D problem with three state variables. The + released repository holds toy PDE examples and empty placeholders for the flood model and has no + licence. A rebuild would therefore guess its size; it would be neither the paper's model nor + checkable. + - > + FloodCastBench's supervised FNO baseline (Xu et al., Scientific Data 12:431, 2025: 4 Fourier layers, + the 12 lowest modes, width 20, one-shot over 19 steps from the initial depth plus coordinates and + time; FNO+ adds terrain and rainfall) is not added either: FloodCastBench released only its + data-generation code (no model code, no licence), so there is nothing to verify a port against, and + the paper leaves the temporal modes open. The smoke configuration scores this stand-in on + ``flood_inundation_synthetic`` (random rasters). paper: - title: Large-scale flood modeling and forecasting with FloodCast - url: https://doi.org/10.1038/s41586-024-08028-8 + title: "Large-scale flood modeling and forecasting with FloodCast" + url: https://doi.org/10.1016/j.watres.2024.122162 repo_url: https://github.com/HydroPML/FloodCast +references: + - title: "Large-scale flood modeling and forecasting with FloodCast" + url: https://doi.org/10.1016/j.watres.2024.122162 + repo_url: https://github.com/HydroPML/FloodCast + note: > + Xu, Shi, Bamber, Ouyang and Zhu, Water Research 264:122162 (2024); arXiv 2403.12226. 2022 Pakistan + flood (85,616.5 km2, 18-31 August), 480 m grid, 300 s steps, 14-day simulation against a + finite-difference hydrodynamic benchmark: average MAPE 14.93% and MAE 0.0610 m (depth >= 0 m), + MAE 0.0589 m (>= 0.1 m), 0.0452 m (>= 0.5 m) (Table 5); MAE 0.3615 m against SAR-derived depths + on 30 August (hydrodynamics 0.4203 m). The repository has no licence and does not contain the flood + model. + - title: "FloodCastBench: A Large-Scale Dataset and Foundation Models for Flood Modeling and Forecasting" + url: https://doi.org/10.1038/s41597-025-04725-2 + repo_url: https://github.com/HydroPML/FloodCastBench + note: > + Xu, Shi, Zhao and Zhu, Scientific Data 12:431 (2025); data Zenodo 10.5281/zenodo.14017092 (21.6 GB, + CC BY 4.0). Table 4 (RMSE / NSE), low-fidelity 480 m (Pakistan): U-Net 0.079399 / 0.991705, FNO + 0.002232 / 0.999993, FNO+ 0.002107 / 0.999994; high-fidelity 60 m (Australia): U-Net 0.566626 / + 0.560984, FNO 0.004258 / 0.999975, FNO+ 0.003941 / 0.999979. Only the data-generation code is + released. tasks: - regression - segmentation @@ -28,6 +69,9 @@ example: | print(preds.shape) notes: - "Outputs are next-horizon inundation depth rasters." + - > + Experimental: kept under its published name only as a placeholder; do not report its results as + FloodCast's. A faithful entry needs the flood-model code (or the widths) from the authors. smoke_test: task: regression build_kwargs: diff --git a/pyhazards/model_cards/forefire.yaml b/pyhazards/model_cards/forefire.yaml deleted file mode 100644 index 455d34e8..00000000 --- a/pyhazards/model_cards/forefire.yaml +++ /dev/null @@ -1,43 +0,0 @@ -model_name: forefire -display_name: ForeFire Adapter -hazard: Wildfire -catalog_status: core -source_file: pyhazards/models/forefire.py -builder_name: forefire_builder -summary: > - A lightweight simulator-style wildfire spread adapter inspired by front-propagation systems. -description: - - > - ``forefire`` is a deterministic raster adapter that approximates simulator-style - front propagation through fixed diffusion kernels. - - > - PyHazards exposes it as a benchmarkable baseline through the standard model registry. -paper: - title: "ForeFire: A Modular, Scriptable C++ Simulation Engine and Library for Wildland-Fire Spread" - url: https://doi.org/10.21105/joss.08680 - repo_url: https://github.com/forefireAPI/forefire -tasks: - - segmentation - - regression -example: | - import torch - from pyhazards.models import build_model - - model = build_model(name="forefire", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) -notes: - - "This adapter is deterministic and does not learn parameters during the smoke test." -smoke_test: - task: segmentation - build_kwargs: - in_channels: 12 - out_channels: 1 - diffusion_steps: 2 - input: - kind: tensor - tensor: - shape: [2, 12, 16, 16] - expected_output: - kind: tensor - shape: [2, 1, 16, 16] diff --git a/pyhazards/model_cards/fourcastnet_tc.yaml b/pyhazards/model_cards/fourcastnet_tc.yaml deleted file mode 100644 index c76f4cbf..00000000 --- a/pyhazards/model_cards/fourcastnet_tc.yaml +++ /dev/null @@ -1,44 +0,0 @@ -model_name: fourcastnet_tc -display_name: FourCastNet TC Adapter -hazard: Tropical Cyclone -catalog_status: experimental -source_file: pyhazards/models/fourcastnet_tc.py -builder_name: fourcastnet_tc_builder -summary: > - An experimental wrapper-style storm adapter inspired by FourCastNet forecast fields. -description: - - > - ``fourcastnet_tc`` completes the first wave of experimental - foundation-weather storm adapters in the staged roadmap. - - > - The PyHazards version is intentionally lightweight and uses the same - trajectory output contract as the other storm baselines. -paper: - title: "FourCastNet: A Global Data-driven High-resolution Weather Model using Adaptive Fourier Neural Operators" - url: https://arxiv.org/abs/2202.11214 - repo_url: https://github.com/NVlabs/FourCastNet -tasks: - - regression -example: | - import torch - from pyhazards.models import build_model - - model = build_model(name="fourcastnet_tc", task="regression", input_dim=8, history=6, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) -notes: - - "Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity." -smoke_test: - task: regression - build_kwargs: - input_dim: 8 - history: 6 - horizon: 5 - output_dim: 3 - input: - kind: tensor - tensor: - shape: [2, 6, 8] - expected_output: - kind: tensor - shape: [2, 5, 3] diff --git a/pyhazards/model_cards/google_flood_forecasting.yaml b/pyhazards/model_cards/google_flood_forecasting.yaml index f4d81c43..be498d65 100644 --- a/pyhazards/model_cards/google_flood_forecasting.yaml +++ b/pyhazards/model_cards/google_flood_forecasting.yaml @@ -5,48 +5,123 @@ catalog_status: core source_file: pyhazards/models/google_flood_forecasting.py builder_name: google_flood_forecasting_builder summary: > - A transformer-style sequence baseline for nodewise streamflow forecasting. + Google's operational streamflow model (FloodHub): hindcast and forecast LSTMs over masked-mean + embeddings of several weather products, with a probabilistic CMAL head; released weights load. description: - > - ``google_flood_forecasting`` is a compact sequence-to-node forecasting baseline - for flood streamflow prediction. + ``google_flood_forecasting`` is a port of ``MeanEmbeddingForecastLSTM`` from google-research/flood-forecasting + (googlehydrology). Static attributes are embedded by an FC network; each weather product (input group) + is embedded with the static embedding by its own FC network, and the group embeddings are averaged + with a NaN-aware mean so that a product that is missing on a day is skipped. A hindcast LSTM runs + over the averaged hindcast embeddings, and a forecast LSTM over the averaged forecast embeddings and + the hindcast LSTM's outputs. The CMAL head returns, for every day, a mixture of three asymmetric + Laplace distributions (``mu``, ``b``, ``tau``, ``pi``); ``point_prediction`` gives the mixture mean. - > - The PyHazards implementation uses a transformer encoder over per-node history - windows and returns one forecast value per node. + ``config="floodhub"`` (default) is the released FloodHub model (Gauch et al. 2025 architecture): 84 + Caravan / HydroATLAS attributes, hindcast products HRES, GraphCast, IMERG and CPC over 365 days, + forecast products HRES and GraphCast over the 365 days plus 7 lead days, hidden size 512 (3,402,832 + parameters). ``pretrained=True`` downloads and loads the released weights (13.6 MB, Apache-2.0 + repository). Inputs are ``x_s`` (batch, 84), ``x_d_hindcast`` (batch, 365, 9) and ``x_d_forecast`` + (batch, 372, 7), as tensors in the configured feature order or as googlehydrology's per-feature dicts. + - > + ``config="streamflow"`` keeps the architecture but uses one input group of ``n_dynamic`` daily + forcings, ``n_static`` attributes and no lead time, so that the model reads the PyHazards streamflow + layout ``{"x_d", "x_s"}`` (``camels_us_streamflow``, ``caravan_streamflow``) and is scored by the flood + benchmark from the mixture mean. This is a PyHazards adaptation, not a Google configuration. paper: - title: Global Flood Forecasting at a Fine Catchment Resolution using Machine Learning - url: https://research.google/pubs/global-flood-forecasting-at-a-fine-catchment-resolution-using-machine-learning/ + title: "How to deal w___ missing input data" + url: https://doi.org/10.5194/hess-29-6221-2025 repo_url: https://github.com/google-research/flood-forecasting +references: + - title: "Global prediction of extreme floods in ungauged watersheds" + url: https://doi.org/10.1038/s41586-024-07145-1 + repo_url: https://github.com/google-research-datasets/global_streamflow_model_paper + note: > + Nearing, Cohen, Dube, Gauch, Gilon, Harrigan, Hassidim, Klotz, Kratzert, Metzger, Nevo, + Pappenberger, Prudhomme, Shalev, Shenzis, Tekalign, Weitzner and Matias, Nature 627:559-563 (2024). + The earlier FloodHub model, a hindcast/forecast LSTM with a state handoff (hidden size 256, one + asymmetric Laplacian output, 0-7 day lead times, ensemble of 3) trained on 5,680 gauges. Forecasts + for extreme events (1- to 10-year return periods) at up to 5 days lead time in ungauged basins had + precision and recall similar to or better than GloFAS nowcasts; medians are given in figures only. + That handoff model is not ported here. + - title: "How to deal w___ missing input data" + url: https://doi.org/10.5194/hess-29-6221-2025 + note: > + Gauch, Kratzert, Klotz, Nearing, Cohen and Gilon, HESS 29:6221-6235 (2025). Introduces the + masked-mean input embedding of this model and compares it with input replacing and attention on + 531 CAMELS-US basins (three forcing products, hidden size 256, 365-day inputs, NSE* loss); the + masked mean performs best by a small margin. Results are reported as figures (median NSE and KGE + versus the fraction of missing inputs). + - title: "google-research/flood-forecasting: released FloodHub model" + url: https://github.com/google-research/flood-forecasting/tree/cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1/pretrained-models/google-floodhub-settings-110-epochs + note: > + The released run was trained on 1982-2023 for all 15,955 listed Caravan + MultiMet basins (no + temporal hold-out). Its test_metrics.csv (median NSE 0.688, median KGE 0.659 over 10,137 basins) + is therefore in-sample, and Google states it must not be used as a benchmark. +reproduction: + reference_code: https://github.com/google-research/flood-forecasting + reference_commit: cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1 + reference_license: Apache-2.0 + reference_config: > + googlehydrology/modelzoo/mean_embedding_forecast_lstm.py built from + pretrained-models/google-floodhub-settings-110-epochs/config.yml (84 statics; hindcast groups + hres, graphcast, imerg, cpc; forecast groups hres, graphcast; seq_length 365, lead_time 7, + hidden_size 512, CMAL with 3 components, output_dropout 0.4, initial_forget_bias 3, Xavier / + orthogonal initialisation; 3,402,832 parameters) and the released model_epoch110.pt + (sha256 90280f06...3fdba, strict load after removing the ``_orig_mod.`` prefix). + parameter_count: 3402832 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_google_flood_forecasting_oracle.py + deviations: + - > + Constructor arguments replace the googlehydrology Config; group order follows the configuration, + as in the reference. + - > + Not ported: the data-assimilation hooks of ``forward`` (``assimilation_overrides``, + ``assimilation_slice``, ``return_embeddings``) and the hot-start state files (``save_state``, + ``load_state_from_disk``). Without them the forward pass is the reference's. + - > + The release normalises inputs with its scaler.zarr, which PyHazards does not read; the + googlehydrology tester also reduces 7,500 samples of the mixture to their median, whereas the + PyHazards flood benchmark scores the closed-form mixture mean (``point_prediction``). + - > + ``config="streamflow"`` (one shared input group, ``lead_time=0``) is a PyHazards adaptation for the + streamflow layout; the oracle test checks that it equals googlehydrology with the same settings. tasks: - regression example: | import torch from pyhazards.models import build_model - model = build_model( - name="google_flood_forecasting", - task="regression", - input_dim=2, - out_dim=1, - history=4, - ) - preds = model({"x": torch.randn(2, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="google_flood_forecasting", task="regression", pretrained=False) + out = model({ + "x_s": torch.randn(2, 84), + "x_d_hindcast": torch.randn(2, 365, 9), # hres (5), graphcast (2), imerg, cpc + "x_d_forecast": torch.randn(2, 372, 7), # hres (5), graphcast (2) incl. 7 lead days + }) + print(out["mu"].shape, model.point_prediction(out).shape) # (2, 372, 3) (2, 372, 1) notes: - - "The smoke path uses the same streamflow-style graph fixture as the other flood baselines." + - > + Missing data: a NaN anywhere in a product's features on a day removes that product from the mean of + that day; a day where all products are missing makes every later output NaN (the LSTM state is + undefined), exactly as in the reference. + - The smoke configuration runs ``config="streamflow"`` on ``flood_streamflow_synthetic``. smoke_test: task: regression - build_kwargs: - input_dim: 2 - hidden_dim: 32 - out_dim: 1 - history: 4 - dropout: 0.0 + build_kwargs: {} input: kind: mapping mapping: - x: - shape: [2, 4, 6, 2] + x_s: + shape: [2, 84] + x_d_hindcast: + shape: [2, 365, 9] + x_d_forecast: + shape: [2, 372, 7] expected_output: - kind: tensor - shape: [2, 6, 1] + kind: mapping + mapping: + mu: [2, 372, 3] + b: [2, 372, 3] + tau: [2, 372, 3] + pi: [2, 372, 3] diff --git a/pyhazards/model_cards/gpd.yaml b/pyhazards/model_cards/gpd.yaml index 84032f7b..71b135eb 100644 --- a/pyhazards/model_cards/gpd.yaml +++ b/pyhazards/model_cards/gpd.yaml @@ -1,41 +1,105 @@ model_name: gpd display_name: GPD hazard: Earthquake +catalog_status: core source_file: pyhazards/models/gpd.py builder_name: gpd_builder summary: > - A compact CNN baseline for generalized phase detection and historical - earthquake picking comparisons. + Generalized Phase Detection (Ross et al., BSSA 2018): a convolutional classifier that labels 4-s + three-component windows as P, S or noise, and picks continuous data with a sliding window. Ported from + the official Keras release, whose weights load and reproduce the official picks. description: - > - ``gpd`` provides a lightweight earthquake picking adapter with the same - waveform-to-pick interface used across the PyHazards earthquake benchmarks. + ``gpd`` classifies a 400-sample window (4 s at 100 Hz, channels N, E, Z, scaled by its maximum + absolute amplitude) into P, S and noise. The network has four blocks of convolution (32 / 64 / 128 / + 256 filters, kernels 21 / 15 / 11 / 9), batch normalisation, ReLU and 2x max pooling, followed by two + 200-unit dense layers with batch normalisation and a three-way softmax (1,741,003 parameters). - > - This adapter is intended as a reproducible low-cost baseline rather than an - exact port of every original training detail. + ``annotate`` slides the classifier over longer traces in steps of 10 samples, as ``gpd_predict.py`` + does, and ``extract_picks`` turns the P and S probability sequences into picks: a trigger starts when + a probability reaches 0.95 and ends when it falls below 0.1, and the window with the highest + probability in the trigger gives the pick at its centre. Module names are the Keras layer names, and + the released weights (``model_pol_best.hdf5``, MIT) load with ``pretrained=True``. paper: - title: Generalized Seismic Phase Detection with Deep Learning + title: "Generalized Seismic Phase Detection with Deep Learning" url: https://doi.org/10.1785/0120180080 repo_url: https://github.com/interseismic/generalized-phase-detection +references: + - title: "Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking" + url: https://doi.org/10.1038/s41467-020-17591-w + repo_url: https://github.com/smousavi05/EQTransformer + note: > + Applies the pretrained GPD (trained on 4.5M Southern California windows) to the STEAD test set; a + pick counts as a true positive within 0.5 s of the manual pick. Table 2 (P): mean 0.03 s, std + 0.10 s, precision 0.81, recall 0.80, F1 0.81, MAE 0.08 s, MAPE 0.01. Table 3 (S): mean 0.03 s, std + 0.14 s, precision 0.81, recall 0.83, F1 0.82, MAE 0.10 s, MAPE 0.01. + - title: "Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers" + url: https://doi.org/10.1029/2021JB023499 + repo_url: https://github.com/seisbench/pick-benchmark + note: > + Muenchmeyer et al., JGR Solid Earth 127:e2021JB023499 (2022). GPD (SeisBench's port, same 1,741,003 + parameters) retrained on each dataset; in-domain phase identification MCC (Table 2): ETHZ 0.92, + INSTANCE 0.95, Iquique 0.98, SCEDC 0.93, STEAD 0.99, GEOFON 0.67, NEIC 0.84. +reproduction: + reference_code: https://github.com/interseismic/generalized-phase-detection + reference_commit: ea81ef17d204797de6a99d277fd2b9407fc77df7 + reference_license: MIT (code and released weights, Copyright (c) 2018 Zachary E. Ross) + reference_config: > + The Keras 2.2.2 network of model_pol.json with the released weights model_pol_best.hdf5, run on + TensorFlow 2.11 (tf.keras) from the JSON's inner Sequential config, and the gpd_predict.py pipeline + (ObsPy linear detrend and 3-20 Hz band-pass, 400-sample windows every 10 samples, per-window max + normalisation, trigger_onset(0.95, 0.1), argmax pick) on the shipped Anza 2016 station AZ.TRO data; + SeisBench 0.12.6's GPD with its conversion of the same weights as a second reference. + parameter_count: 1741003 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_gpd_oracle.py + deviations: + - > + The release wraps the network in Keras multi-GPU Lambda / Concatenate layers (stored as Python 3.6 + bytecode). They only split the batch across GPUs and are not ported; the oracle is the inner + Sequential network, unchanged. + - > + An all-zero window, which gpd_predict.py divides by zero (NaN probabilities), is left at zero by + ``annotate`` and classified normally. + - > + Filtering is not part of ``annotate``: gpd_predict.py band-passes whole traces at 3-20 Hz (and + the training data were high-passed at 2 Hz), so callers must filter their traces the same way. + - > + Inputs are ``(batch, channels, samples)`` instead of Keras' ``(batch, samples, channels)``; the + feature map is transposed before flattening so that the Keras dense_1 kernel loads unchanged. + - > + Initial weights follow the Keras scheme (Glorot-uniform kernels, zero biases) but cannot match + TensorFlow's random draws; the oracle compares their bounds and spread. tasks: - - regression + - classification + - picking example: | import torch from pyhazards.models import build_model - model = build_model(name="gpd", task="regression", in_channels=3) - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + # Window classifier: 4-s windows at 100 Hz, channels N, E, Z -> P / S / noise probabilities. + model = build_model(name="gpd", task="classification") # pretrained=True loads model_pol_best.hdf5 + model.eval() + windows = torch.randn(8, 3, 400) + windows = windows / windows.abs().amax(dim=(1, 2), keepdim=True) + probabilities = model(windows) # (8, 3) + + # Picking a 60-s band-passed (3-20 Hz) trace with the official sliding window. + with torch.no_grad(): + annotations = model.annotate(torch.randn(1, 3, 6000), stride=10) # (1, 3, 561) + picks = model.extract_picks(annotations) # [{"P": [(sample, prob), ...], "S": [...]}] notes: - - "The adapter keeps a simple two-output pick interface for shared evaluation." + - "Channel order N, E, Z (gpd_predict.py stacks the N, E and Z files in that order). SeisBench's conversion of the same weights takes Z, N, E: it permuted the first convolution's input channels, which the oracle test confirms." + - "Class order P, S, noise. The repository's picker uses a 0.95 trigger threshold (``min_proba``); the paper reports detections above 0.98." + - "Batch normalisation reproduces Keras 2.2.2, which trained the released weights: the moving variance is updated with the factor n / (n - 1 - eps) and a zero-debiased moving average (decay 0.99), checked against TensorFlow's assign_moving_average." + - "On 18 minutes of the shipped Anza 2016 data (08:02-08:20 UTC), the port's picks are identical to the official Keras pipeline and, inside the slice, to the shipped anza2016.out (33 P and 96 S picks)." smoke_test: - task: regression - build_kwargs: - in_channels: 3 + task: classification + build_kwargs: {} input: kind: tensor tensor: - shape: [4, 3, 256] + shape: [2, 3, 400] expected_output: kind: tensor - shape: [4, 2] + shape: [2, 3] diff --git a/pyhazards/model_cards/graphcast_tc.yaml b/pyhazards/model_cards/graphcast_tc.yaml deleted file mode 100644 index 3d6c83d4..00000000 --- a/pyhazards/model_cards/graphcast_tc.yaml +++ /dev/null @@ -1,43 +0,0 @@ -model_name: graphcast_tc -display_name: GraphCast TC Adapter -hazard: Tropical Cyclone -catalog_status: experimental -source_file: pyhazards/models/graphcast_tc.py -builder_name: graphcast_tc_builder -summary: > - An experimental wrapper-style storm adapter inspired by GraphCast/GenCast forecast fields. -description: - - > - ``graphcast_tc`` is an experimental foundation-weather adapter that keeps - the shared storm trajectory interface while remaining lightweight enough for CI. - - > - The PyHazards version is intentionally wrapper-style and should be treated as - an adapter contract rather than a full reproduction of the original weather model. -paper: - title: "GraphCast: Learning skillful medium-range global weather forecasting" - url: https://www.science.org/doi/10.1126/science.adi2336 - repo_url: https://github.com/google-deepmind/graphcast -tasks: - - regression -example: | - import torch - from pyhazards.models import build_model - - model = build_model(name="graphcast_tc", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) -notes: - - "Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity." -smoke_test: - task: regression - build_kwargs: - input_dim: 8 - horizon: 5 - output_dim: 3 - input: - kind: tensor - tensor: - shape: [2, 6, 8] - expected_output: - kind: tensor - shape: [2, 5, 3] diff --git a/pyhazards/model_cards/hurricast.yaml b/pyhazards/model_cards/hurricast.yaml index c27d34a3..110be9c8 100644 --- a/pyhazards/model_cards/hurricast.yaml +++ b/pyhazards/model_cards/hurricast.yaml @@ -1,49 +1,134 @@ model_name: hurricast display_name: Hurricast hazard: Tropical Cyclone +catalog_status: core source_file: pyhazards/models/hurricast.py builder_name: hurricast_builder summary: > - A compact multimodal storm baseline for hurricane track and intensity forecasting. + Hurricast (HUML) of Boussioux et al. (2022): ERA5 maps encoded by a CNN and IBTrACS statistics pass a + Transformer encoder-decoder, whose embeddings feed XGBoost for the 24-hour intensity or track. description: - > - ``hurricast`` is the first basin-specific storm baseline in the staged PyHazards - roadmap and operates on storm-history sequences. + ``hurricast`` forecasts one lead time, 24 hours, from the last 8 three-hourly steps (t-21 h ... t) of a + storm: ``target="intensity"`` the maximum sustained wind (1-minute, kt) and ``target="displacement"`` the + latitude / longitude change (degrees; ``forecast()`` adds it to the current position). Inputs are a + mapping with ``x_stat`` ``(batch, 8, 30)``, the 30 statistical features per step of the official feature + tables (``HURRICAST_STAT_FEATURES``), ``x_viz`` ``(batch, 8, 9, 25, 25)``, ERA5 u, v and geopotential at + 225, 500 and 700 hPa on 25 x 25 one-degree maps around the storm, and ``position`` for track forecasts. + ``hurricast_ibtracs_era5`` builds them from IBTrACS and the user's ERA5 data. - > - This initial adapter focuses on the shared tropical-cyclone forecasting interface - and is intended as a reproducible starting point before broader storm-model breadth. + Stage 1 (the official ``ExperimentalHurricast``, written from the paper): per step a CNN (three 3 x 3 + convolutions with BatchNorm and ReLU, two max poolings, dense layers 4096-576-256-128) embeds the maps; + the first 14 statistical features are prepended and a Transformer decoder (2 layers, 2 heads, width 142, + feed-forward 128, sinusoidal positions, mean pooling, tanh) reads the sequence; a linear layer predicts the + standardised target. 2,969,771 parameters for intensity, 2,969,914 for displacement; the released code's + other presets (``transformer_config_4`` / ``_68`` / ``_noviz``, recurrent ``lstm_config*``, + ``split_encoder_config``) are available through ``decoder_config`` / ``encoder_config``. + - > + Stage 2: XGBoost (one regressor per target) on the flattened statistics (every numerical feature of the 8 + steps and the categorical ones of the first step, 128 values) followed by the 142-d decoder output of the + frozen network, with the defaults of the official ``train_xgb_*`` functions (depth 8, 140 trees, learning + rate 0.15, subsample 0.7, minimum child weight 5). ``Hurricast.fit`` standardises the targets, trains the + network (MSE + L2, Adam, batch 64) and then XGBoost; ``predictor="network"`` predicts with the network's + head instead, ``use_embeddings=False`` is HUML-(stat, xgb). paper: title: "Hurricane Forecasting: A Novel Multimodal Machine Learning Framework" - url: https://arxiv.org/abs/2102.01204 + url: https://doi.org/10.1175/WAF-D-21-0091.1 repo_url: https://github.com/leobix/hurricast +references: + - title: "Boussioux, Zeng, Guenais and Bertsimas, Weather and Forecasting 37(6), 817-831 (2022); preprint arXiv 2011.06125v4" + url: https://arxiv.org/abs/2011.06125 + repo_url: https://github.com/leobix/hurricast + note: > + 24-hour forecasts on 2016-2019 North Atlantic (NA) and Eastern Pacific (EP) cases with concurrent ATCF + operational forecasts, models trained on all basins 1980-2011 (validation 2012-2015). Track MAE + (Table 5, EP 837 / NA 899 cases): HUML-(stat/viz, xgb/cnn/transfo) 72 / 109 km, HUML-(stat/viz, + xgb/cnn/gru) 72 / 111 km, HUML-(stat, xgb) 81 / 144 km; HWRF 67 / 75 km, CLP5 121 / 201 km. Intensity + MAE (Table 6, EP 877 / NA 899 cases): 10.3 / 10.4 kt (cnn/transfo), 10.3 / 10.8 kt (cnn/gru), + 10.6 / 10.7 kt (stat, xgb); Decay-SHIPS 11.7 / 10.2 kt, HWRF 10.6 / 9.7 kt. Not reproduced by PyHazards + (the ERA5 maps of the ~134,000 training cases are not part of the tests). +reproduction: + source: paper + reference_code: https://github.com/leobix/hurricast + reference_commit: b1b303a7a62eea89ddfd357fc99cd0787016a3bc + reference_license: none (no LICENSE file; the README claims MIT and links a LICENSE that does not exist). Used only as a test oracle, never copied. + reference_config: > + ExperimentalHurricast(encoder full_encoder_config, decoder ExpTRANSFORMER transformer_config) from + src/models/experimental_models.py and scripts/config.py: 2,969,771 (intensity) / 2,969,914 (displacement) + parameters; for every preset of scripts/config.py (8 decoders x full / split encoders, both targets) the + same state-dict keys, identical initial weights for the same seed, equal outputs and embeddings in eval and + train mode (BatchNorm statistics, dropout) and equal gradients; official state dicts load with strict=True + into Hurricast.network. The L2 term equals src/utils/run.py compute_l2 and a training step of fit_network + equals src/run.py train_epoch (displacement target); the XGBoost feature columns equal the + rule of notebooks/Compute_results_*_Round2.ipynb, its defaults those of scripts/run_embeddings.py, and the + XGBoost stage predicts exactly as XGBRegressor (xgboost 3.2.0) fitted the official way. The storm cut, + interpolated WMO wind / pressure, wind category and displacements of hurricast_ibtracs_era5 equal + src/utils/data_processing.py on real IBTrACS rows. + parameter_count: 2969771 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_hurricast_oracle.py + deviations: + - > + Paper and released code differ; the code is followed where it is the executable reference: the CNN's + dense layers are 4096-576-256-128 (paper Fig. A1: 576-128), the decoder input is [statistics, embedding] + (paper text: [embedding, statistics]), and the network reads 14 statistical features (the paper's text + says 31; its d_model = 142 = 128 + 14 agrees with the code). + - > + The paper's GRU decoder (two unidirectional GRU layers, all 8 hidden states concatenated, dense + 1024-512-128-c, embedding = second dense output) is not in the released code and is not provided (the + activations of its dense layers are not specified). The released recurrent presets (bidirectional LSTM / + GRU / RNN reading the last hidden state: lstm_config, lstm_config_4layers, lstm_config_best_dis, + lstm_config_test_dis) are. + - > + Training is reimplemented from the paper and src/run.py: MSE plus 2 / batch * 0.01 * sum of squared + weights, Adam (1e-3 intensity, 4e-4 track), batch 64, 30 epochs, the epoch with the lowest validation MSE + kept. The official loop compared (batch, 1) intensity outputs with (batch,) targets, which nn.MSELoss + broadcasts to all (batch x batch) pairs; PyHazards compares matching shapes. + - > + The XGBoost hyperparameters are given in the paper only as ranges (depth 6-9, 100-300 trees, learning + rate 0.03-0.15, subsample 0.6-0.9, column sampling 0.7-1, minimum child weight 1-5) and varied per task + and basin in the Round2 notebooks; the defaults of the official train_xgb_* functions are used. Library + defaults of xgboost >= 2 (histogram trees, estimated base score) differ from the 2020-21 xgboost 1.x. + - > + Not provided: the tensor-decomposition embeddings (HUML-(stat/viz, xgb/td)), the ElasticNet ensemble and + the consensus with operational forecasts (HUML-ensemble, HUML/OP-average), and the code's intensity-category + classifier. The official ExpTRANSFORMER's "unroll" pooling (unused by every preset) gives the predictor the + wrong width; here it gets n_out_unroll. Official forward(..., xgb=True) fails (a tuple reaches the + predictor); here only get_embeddings takes xgb. tasks: - regression example: | import torch from pyhazards.models import build_model - model = build_model( - name="hurricast", - task="regression", - input_dim=8, - horizon=5, - output_dim=3, - ) + # The paper's best model: CNN + Transformer embeddings, then XGBoost (needs pyhazards[xgboost]). + model = build_model(name="hurricast", task="regression", target="intensity") + inputs = { + "x_stat": torch.randn(64, 8, 30), # 8 three-hourly steps x 30 IBTrACS features + "x_viz": torch.randn(64, 8, 9, 25, 25), # u, v, z at 225 / 500 / 700 hPa, 25 x 25 degrees + } + model.fit(inputs, 60 + 20 * torch.randn(64), epochs=1) # network, then XGBoost on its embeddings + print(model(inputs).shape) # (64, 1): wind 24 h ahead - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # Real data: IBTrACS + ERA5 maps around the storms (user-provided netCDF / zarr). + # from pyhazards.datasets import load_dataset + # data = load_dataset("hurricast_ibtracs_era5", path="ibtracs.ALL.list.v04r01.csv", era5="era5_pl.nc").load() notes: - - "Outputs are lead-time sequences of latitude, longitude, and intensity targets." + - "The official repository has no LICENSE file; nothing is copied from it. Its released configuration values (scripts/config.py presets, XGBoost defaults) are used as data." + - "Inputs must be standardised as for training: hurricast_ibtracs_era5 standardises LAT, LON, WMO wind and pressure, distance to land, speed and the displacements with training statistics (paper Table 2) and leaves cyclic encodings and categories as they are, so the network's 14 features are standardised as in the official run_embeddings.py; each map channel is standardised over samples, steps and pixels." + - "The XGBoost stage is not in state_dict(); use Hurricast.save / Hurricast.load (joblib). Embeddings are always computed with the network in eval mode." + - "No trained weights were released, and the ERA5 tensors (> 30 GB) are not hosted." smoke_test: task: regression build_kwargs: - input_dim: 8 - horizon: 5 - output_dim: 3 + predictor: network input: - kind: tensor - tensor: - shape: [2, 6, 8] + kind: mapping + mapping: + x_stat: + shape: [2, 8, 30] + x_viz: + shape: [2, 8, 9, 25, 25] expected_output: kind: tensor - shape: [2, 5, 3] + shape: [2, 1] diff --git a/pyhazards/model_cards/hydrographnet.yaml b/pyhazards/model_cards/hydrographnet.yaml index d6656b64..fcca57d5 100644 --- a/pyhazards/model_cards/hydrographnet.yaml +++ b/pyhazards/model_cards/hydrographnet.yaml @@ -1,60 +1,120 @@ model_name: hydrographnet display_name: HydroGraphNet hazard: Flood -catalog_status: variant +catalog_status: core source_file: pyhazards/models/hydrographnet.py builder_name: hydrographnet_builder summary: > - A physics-informed graph neural network for flood forecasting with interpretable - KAN-style components, residual message passing, and delta-state decoding. + The physics-informed graph network of Taghizadeh et al. (CACIE 2025) as released in NVIDIA PhysicsNeMo + (MeshGraphKAN): water depth and volume changes on an unstructured flood mesh, rolled out step by step. description: - > - ``hydrographnet`` is the PyHazards entrypoint for flood forecasting on irregular - meshes with graph-structured hydrologic state updates. + ``hydrographnet`` is a port of PhysicsNeMo's ``MeshGraphKAN``, the HydroGraphNet model: a Fourier + Kolmogorov-Arnold network encodes the 16 node features, an MLP encodes the 3 edge features, 15 + residual message-passing blocks update edges (MLP on edge, source and destination) and nodes (MLP on + the sum of incoming messages and the node), and an MLP decodes the normalised changes of water depth + and volume over one 20-minute step. Every MLP has two hidden layers of 128 and ReLU, and all but the + decoder end in LayerNorm (2,318,722 parameters). It takes ``(node_features (N, 16), edge_features + (E, 3), edge_index (2, E))`` (or a PyTorch Geometric graph, or a mesh batch mapping) and returns + ``(N, 2)``; ``rollout`` runs the example's autoregressive inference, feeding ``last + change`` back into + the depth / volume windows and the next inflow and precipitation into the forcing columns. - > - In PyHazards, this model is typically paired with the ERA5-based hydrograph - adapter ``load_hydrograph_data`` for end-to-end smoke validation. + ``HydroGraphNetLoss`` / ``hydrographnet_physics_loss`` port the example's training loss: MSE plus a + volume-continuity penalty on the total predicted volume against inflow, effective precipitation and + the next step's volume (delta_t 1200 s, weight 1). Parameter names, initialisation, outputs, the + physics loss and the rollout equal PhysicsNeMo's. + - > + Data: ``hydrographnet_white_river`` reads a local copy of the official White River dataset (HEC-RAS + simulations on a 4,787-cell mesh near Muncie, Indiana, Zenodo 14969507, CC BY 4.0) exactly like + PhysicsNeMo's ``HydroGraphDataset`` (node features, k=4 nearest-neighbour graph, normalisation, physics + data, rollout targets); ``flood_mesh_synthetic`` produces random data in the same layout. The flood + benchmark (``flood.inundation``) rolls every test hydrograph out and scores depths in metres. paper: - title: Interpretable physics-informed graph neural networks for flood forecasting - url: https://onlinelibrary.wiley.com/doi/10.1111/mice.13484 + title: "Interpretable physics-informed graph neural networks for flood forecasting" + url: https://doi.org/10.1111/mice.13484 + repo_url: https://github.com/NVIDIA/physicsnemo/tree/main/examples/weather/flood_modeling/hydrographnet +references: + - title: "Interpretable physics-informed graph neural networks for flood forecasting" + url: https://doi.org/10.1111/mice.13484 + repo_url: https://github.com/NVIDIA/physicsnemo/tree/main/examples/weather/flood_modeling/hydrographnet + note: > + Taghizadeh, Zandsalimi, Nabian, Shafiee-Jood and Alemazkoor, Computer-Aided Civil and + Infrastructure Engineering 40(18):2629-2649 (2025). White River near Muncie, Indiana: 4,787-cell + HEC-RAS mesh, boundary inflow hydrographs and rainfall; 30-step (10-hour) rollouts. The abstract + reports a 67% lower prediction error than a baseline GNN, near-zero mass-balance error and a 58% + higher critical success index for major floods; the full text (and its absolute numbers) could not + be accessed, so no paper numbers are reproduced here. The official code is the PhysicsNeMo example, + contributed by the first author. +reproduction: + reference_code: https://github.com/NVIDIA/physicsnemo + reference_commit: eb7a329c246a48b6fb5acd569eaabeac53f915f7 + reference_license: Apache-2.0 + reference_config: > + examples/weather/flood_modeling/hydrographnet (conf/config.yaml, train.py, inference.py, utils.py): + MeshGraphKAN(16, 3, 2) with the PhysicsNeMo defaults (processor_size 15, hidden 128, 2 hidden layers + per MLP, ReLU, LayerNorm, sum aggregation, 5 harmonics, do_concat_trick False), 2,318,722 parameters; + HydroGraphDataset(prefix M80, n_time_steps 2, k 4, noise_type none, return_physics True); physics + loss weight 1, delta_t 1200 s; rollout length 30. Oracle: physicsnemo/models/meshgraphnet/meshgraphkan.py + (last changed in dcad4372dc166d3d57e7572943a9c5934684c885), torch_geometric + torch_scatter. + parameter_count: 2318722 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_hydrographnet_oracle.py + deviations: + - > + Graphs are an ``edge_index`` tensor (PyTorch Geometric graphs are accepted) and messages are + summed with ``index_add_`` instead of ``torch_scatter``; outputs agree to float precision. Batching several meshes is ``hydrograph_collate`` (PyG ``Batch`` layout). + - > + Not ported (unused by the HydroGraphNet configuration): ``do_concat_trick`` (MeshGraphEdgeMLPSum), + ``recompute_activation`` (nvFuser SiLU), gradient checkpointing of the processor, Transformer Engine + LayerNorm, and the dataset's training noise options (only ``noise_type: none``) including the + ``pushforward`` training branch. + - > + The White River release has no test list (the example reads ``Test/test.txt``, which is not + published, and ``train.txt`` lists all 500 hydrographs), so ``hydrographnet_white_river`` needs the + test hydrographs as ``test_ids`` and drops them from the training list. It does not overwrite the + release's normalisation-statistics files as the example's training run does, and does not + subsample hydrographs (the example samples 500 at random only when more are listed). + - > + No official weights were released, so no pretrained checkpoint is checked. tasks: - regression example: | import torch + from pyhazards.datasets import load_dataset from pyhazards.models import build_model - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, - ) + data = load_dataset("flood_mesh_synthetic", micro=True).load() # or hydrographnet_white_river + model = build_model(name="hydrographnet", task="regression") # PhysicsNeMo MeshGraphKAN(16, 3, 2) + inputs, target = data.get_split("train").inputs[0] + delta = model(inputs["node_features"], inputs["edge_features"], inputs["edge_index"]) + print(delta.shape) # (nodes, 2): change of normalised depth and volume - batch = { - "x": torch.randn(1, 3, 6, 2), - "adj": torch.eye(6).unsqueeze(0), - "coords": torch.randn(6, 2), - } - preds = model(batch) - print(preds.shape) + start, truth = data.get_split("test").inputs[0] + out = model.rollout(start["node_features"], start["edge_features"], start["edge_index"], start["inflow"], start["precipitation"]) + print(out["water_depth"].shape) # (rollout steps, nodes) notes: - - "The smoke test uses a synthetic graph batch so it stays CPU-safe in CI." + - > + Training recipe of the example (``scripts/train_hydrographnet.py``): batch 1, Adam with learning rate + 1e-4 (the configured weight decay 1e-4 is not passed to the optimizer), the learning rate multiplied by + 0.9999979 after every batch, 100 epochs, MSE + physics loss. + - > + Rollout quirk kept from inference.py: after the first step the forcing columns hold the inflow and + precipitation of the step being predicted, while training windows hold those of the first window step. + The example prints the rollout RMSE of normalised depth; the flood benchmark reports it in metres + (``rollout_rmse``) and keeps both per-step curves in the report metadata. smoke_test: task: regression - build_kwargs: - node_in_dim: 2 - edge_in_dim: 3 - out_dim: 1 input: - kind: mapping - mapping: - x: - shape: [1, 3, 6, 2] - adj: - shape: [1, 6, 6] - coords: - shape: [6, 2] + kind: kwargs + kwargs: + node_features: + shape: [12, 16] + edge_features: + shape: [48, 3] + graph: + shape: [2, 48] + dtype: int64 + high: 12 expected_output: kind: tensor - shape: [1, 6, 1] + shape: [12, 2] diff --git a/pyhazards/model_cards/logistic_regression.yaml b/pyhazards/model_cards/logistic_regression.yaml new file mode 100644 index 00000000..1997d192 --- /dev/null +++ b/pyhazards/model_cards/logistic_regression.yaml @@ -0,0 +1,61 @@ +model_name: logistic_regression +display_name: Logistic Regression (pixel) +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/logistic_regression.py +builder_name: logistic_regression_builder +summary: > + Per-pixel logistic regression over a 3x3 neighbourhood, the linear baseline of + WildfireSpreadTS and Next Day Wildfire Spread. +description: + - > + ``logistic_regression`` scores every pixel with a linear function of the + ``kernel_size x kernel_size`` window of input features around it, implemented as one + ``Conv2d`` with ``kernel_size // 2`` padding; the sigmoid is applied by the loss. + - > + This is exactly the WildfireSpreadTS logistic-regression baseline + (``Conv2d(C, 1, kernel_size=3, padding=1)``, 361 parameters for 40 channels). Next Day + Wildfire Spread fits the same model on 3x3 neighbourhoods with scikit-learn instead of + gradient descent. Multi-day input ``(batch, time, channels, height, width)`` is flattened + to ``time * channels`` channels. +paper: + title: "WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction" + url: https://openreview.net/forum?id=RgdGkPRQ03 + repo_url: https://github.com/SebastianGer/WildfireSpreadTS +references: + - title: "Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data" + url: https://arxiv.org/abs/2112.02447 + repo_url: https://github.com/google-research/google-research/tree/master/simulation_research/next_day_wildfire_spread + note: > + Same model on 12 features x 3x3 neighbourhoods (109 parameters), fitted with scikit-learn + LogisticRegression and a no-fire class weight; reported test AUC-PR 19.8%. +reproduction: + reference_code: https://github.com/SebastianGer/WildfireSpreadTS + reference_commit: f62dc49f2c2a6d249c071533ae5340c0d01bfb95 + reference_license: MIT + reference_config: "src/models/LogisticRegression.py with n_channels=40 (all features, one day)." + parameter_count: 361 + checks: [parameter_count, state_dict, forward] + oracle_test: tests/oracle/test_wildfirespreadts_oracle.py +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + model = build_model(name="logistic_regression", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) +notes: + - "WildfireSpreadTS trains it with Dice loss and AdamW (lr 0.1)." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 12 + input: + kind: tensor + tensor: + shape: [2, 12, 32, 32] + expected_output: + kind: tensor + shape: [2, 1, 32, 32] diff --git a/pyhazards/model_cards/neuralhydrology_ealstm.yaml b/pyhazards/model_cards/neuralhydrology_ealstm.yaml index e38f3075..d10a121d 100644 --- a/pyhazards/model_cards/neuralhydrology_ealstm.yaml +++ b/pyhazards/model_cards/neuralhydrology_ealstm.yaml @@ -1,42 +1,105 @@ model_name: neuralhydrology_ealstm display_name: EA-LSTM hazard: Flood +catalog_status: core source_file: pyhazards/models/neuralhydrology_ealstm.py builder_name: neuralhydrology_ealstm_builder summary: > - An entity-aware hydrology baseline with static-feature gating over streamflow histories. + The Entity-Aware LSTM of Kratzert et al. (HESS 2019): static catchment attributes set the input gate, + daily forcings drive the other gates; ported from NeuralHydrology. description: - > - ``neuralhydrology_ealstm`` complements the plain LSTM adapter with a - lightweight static gating path inspired by EA-LSTM style hydrology models. + ``neuralhydrology_ealstm`` is a port of NeuralHydrology's ``EALSTM`` (the same network as the paper + code). The input gate ``i = sigmoid(W_s x_s + b_s)`` is computed once from the static attributes + and applied at every step; the forget, output and cell gates come from the dynamic inputs and the + previous hidden state. It reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}`` + and returns ``y_hat`` (batch, time, n_targets) and the per-step states ``h_n`` and ``c_n``. - > - It keeps the same graph-temporal input contract as the rest of the flood - streamflow roadmap. + Defaults are the paper's: 5 extended-Maurer forcings, 27 CAMELS attributes, hidden size 256, output + dropout 0.4, forget-gate bias 5, 270-day windows (208,641 parameters). The official 2019 EA-LSTM + checkpoints load through ``checkpoint=``. Data: ``camels_us_streamflow`` or ``caravan_streamflow``, + scored by the flood benchmark's per-basin NSE / KGE. paper: - title: Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets + title: "Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets" url: https://doi.org/10.5194/hess-23-5089-2019 - repo_url: https://github.com/neuralhydrology/neuralhydrology + repo_url: https://github.com/kratzert/ealstm_regional_modeling +references: + - title: "Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets" + url: https://doi.org/10.5194/hess-23-5089-2019 + repo_url: https://github.com/kratzert/ealstm_regional_modeling + note: > + Kratzert, Klotz, Shalev, Klambauer, Hochreiter and Nearing, HESS 23:5089-5110 (2019). 531 CAMELS-US + basins, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30, 8 seeds. Table 2, EA-LSTM, + NSE* loss: single model mean NSE 0.67 (+/-0.006), median 0.71 (+/-0.005), 3 (+/-1) basins with + NSE <= 0; ensemble of 8: mean 0.70, median 0.74, 2 basins. MSE loss: single median 0.71, + ensemble median 0.74. Table 3 (447 basins): single median 0.714, ensemble median 0.742. The + flood benchmark reproduces Table 2 from the official stored simulations (gated oracle test). + - title: "NeuralHydrology - A Python library for Deep Learning research in hydrology" + url: https://doi.org/10.21105/joss.04050 + repo_url: https://github.com/neuralhydrology/neuralhydrology + note: > + Kratzert, Gauch, Nearing and Klotz, Journal of Open Source Software 7(71):4050 (2022); the EALSTM + implementation that PyHazards ports. +reproduction: + reference_code: https://github.com/neuralhydrology/neuralhydrology + reference_commit: ea94a40d2f271994e33baa70f5ca1dd82e0e539d + reference_license: BSD-3-Clause + reference_config: > + neuralhydrology/modelzoo/ealstm.py (EALSTM) with a regression head: 5 dynamic inputs, 27 static + attributes, hidden_size 256, output_dropout 0.4, initial_forget_bias 5 (208,641 parameters, the + same as the 2019 code). Official weights: the 16 EA-LSTM runs of Kratzert et al. (2019) on HydroShare + (doi 10.4211/hs.83ea5312635e44dc824eeb99eda12f06, CC BY 4.0), written by papercode/ealstm.py of + kratzert/ealstm_regional_modeling @ d118158 (Apache-2.0). + parameter_count: 208641 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_neuralhydrology_oracle.py + deviations: + - > + Only the configuration of the paper is ported: NeuralHydrology's optional embedding networks, + basin one-hot encoding and probabilistic heads are not available on this model. + - > + Dynamic inputs are one tensor ``x_d`` (batch, time, n_dynamic) instead of a dict of per-feature + tensors (same network input). + - > + Initialisation follows NeuralHydrology: the input gate is a default ``nn.Linear``, whereas the 2019 + paper code initialises ``weight_sh`` orthogonally. Seeded weights therefore match NeuralHydrology, + not the 2019 code; trained 2019 checkpoints load exactly (``weight_sh`` transposed into + ``input_gate.weight``). tasks: - regression example: | import torch from pyhazards.models import build_model - model = build_model(name="neuralhydrology_ealstm", task="regression", input_dim=2, out_dim=1) - preds = model({"x": torch.randn(1, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="neuralhydrology_ealstm", task="regression") # Kratzert et al. (2019) + out = model({"x_d": torch.randn(2, 270, 5), "x_s": torch.randn(2, 27)}) + print(out["y_hat"].shape, out["h_n"].shape) # (2, 270, 1) (2, 270, 256) notes: - - "This adapter focuses on the entity-aware gating contract, not exact repo parity." + - > + Same training recipe as the paper's LSTM (Adam 1e-3 / 5e-4 / 1e-4, 30 epochs, batch 256, gradient + clipping 1, NSE* or MSE loss on the last time step); PyHazards does not ship the NSE* loss yet. + - > + To apply the official 2019 checkpoints to real data, permute ``x_s`` from PyHazards' alphabetical + attribute order to ``pyhazards.datasets.flood.KRATZERT2019_CHECKPOINT_STATIC_ORDER`` and normalise the + forcings with the 2019 code's fixed scaler (papercode/datautils.py). + - > + The recurrence is a Python loop over time steps, as in the reference, so it is slower than the + cuDNN-backed LSTM on long sequences. + - The smoke configuration runs on ``flood_streamflow_synthetic`` (random basins, 30-day windows). smoke_test: task: regression build_kwargs: - input_dim: 2 - out_dim: 1 + hidden_size: 256 input: kind: mapping mapping: - x: - shape: [1, 4, 6, 2] + x_d: + shape: [2, 30, 5] + x_s: + shape: [2, 27] expected_output: - kind: tensor - shape: [1, 6, 1] + kind: mapping + mapping: + h_n: [2, 30, 256] + c_n: [2, 30, 256] + y_hat: [2, 30, 1] diff --git a/pyhazards/model_cards/neuralhydrology_lstm.yaml b/pyhazards/model_cards/neuralhydrology_lstm.yaml index dd843815..03f6cccb 100644 --- a/pyhazards/model_cards/neuralhydrology_lstm.yaml +++ b/pyhazards/model_cards/neuralhydrology_lstm.yaml @@ -1,42 +1,127 @@ model_name: neuralhydrology_lstm display_name: NeuralHydrology LSTM hazard: Flood +catalog_status: core source_file: pyhazards/models/neuralhydrology_lstm.py builder_name: neuralhydrology_lstm_builder summary: > - An adapter-style LSTM baseline for nodewise streamflow forecasting on graph-temporal inputs. + The regional rainfall-runoff LSTM of Kratzert et al. (HESS 2019) as NeuralHydrology implements it + (CudaLSTM): daily forcings plus static catchment attributes to daily discharge. description: - > - ``neuralhydrology_lstm`` is the first community-style hydrology baseline in - the PyHazards flood roadmap. + ``neuralhydrology_lstm`` is a port of NeuralHydrology's ``CudaLSTM`` with its regression head. It + reads ``{"x_d": (batch, time, n_dynamic), "x_s": (batch, n_static)}``: the static attributes are + concatenated to the dynamic inputs at every day, a single-layer LSTM runs over the sequence, and + dropout plus a linear head give a discharge value for every day. Like the reference it returns a + dict with ``y_hat`` (batch, time, n_targets), ``lstm_output`` and the final states ``h_n`` and + ``c_n``; streamflow evaluation uses the last day of each window. - > - The adapter consumes the shared graph-temporal streamflow batch format and - produces next-step nodewise discharge predictions. + Defaults are the "LSTM with static inputs" of Kratzert et al. (2019): 5 extended-Maurer forcings, + 27 CAMELS attributes, hidden size 256, output dropout 0.4, forget-gate bias initialised to 5, used + on 270-day windows (297,217 parameters). ``n_static=0`` gives their "LSTM without static inputs". + Parameter names, initialisation and outputs equal NeuralHydrology's, and the official 2019 + checkpoints load through ``checkpoint=`` (converted from the paper code's single-bias layout). + - > + Data: ``camels_us_streamflow`` (the paper's setup, from a local CAMELS-US copy) or + ``caravan_streamflow``; both normalise inputs as NeuralHydrology does and are scored by the flood + benchmark's per-basin NSE / KGE. paper: - title: Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets - url: https://doi.org/10.5194/hess-23-5089-2019 + title: "Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks" + url: https://doi.org/10.5194/hess-22-6005-2018 repo_url: https://github.com/neuralhydrology/neuralhydrology +references: + - title: "Towards learning universal, regional, and local hydrological behaviors via machine learning applied to large-sample datasets" + url: https://doi.org/10.5194/hess-23-5089-2019 + repo_url: https://github.com/kratzert/ealstm_regional_modeling + note: > + Kratzert, Klotz, Shalev, Klambauer, Hochreiter and Nearing, HESS 23:5089-5110 (2019). One LSTM for + 531 CAMELS-US basins: 5 extended-Maurer forcings + 27 attributes, hidden 256, dropout 0.4, + 270-day windows, train 1999-10-01 to 2008-09-30, test 1989-10-01 to 1999-09-30, NSE* or MSE loss, + 8 seeds. Table 2, LSTM with static inputs, NSE* loss: single model mean NSE 0.69 (+/-0.013), + median 0.73 (+/-0.002), 2 (+/-1) basins with NSE <= 0; ensemble of 8: mean 0.72, median 0.76. + MSE loss: median 0.73 (single), 0.76 (ensemble). Without static inputs (NSE*): median 0.59 + (single), 0.64 (ensemble). The flood benchmark reproduces all of these from the official + stored simulations (gated oracle test). + - title: "NeuralHydrology - A Python library for Deep Learning research in hydrology" + url: https://doi.org/10.21105/joss.04050 + repo_url: https://github.com/neuralhydrology/neuralhydrology + note: > + Kratzert, Gauch, Nearing and Klotz, Journal of Open Source Software 7(71):4050 (2022). The + library whose CudaLSTM, regression head, CAMELS-US / Caravan readers and metrics PyHazards ports. + - title: "Rainfall-runoff modelling using Long Short-Term Memory (LSTM) networks" + url: https://doi.org/10.5194/hess-22-6005-2018 + note: > + Kratzert, Klotz, Brenner, Schulz and Herrnegger, HESS 22:6005-6022 (2018). The LSTM + rainfall-runoff model, there with 2 layers of 20 cells, 365-day windows and 5 Daymet forcings, + trained per basin (mean NSE 0.63 over 241 basins in experiment 1). That two-layer variant is not + a CudaLSTM configuration and is not provided. +reproduction: + reference_code: https://github.com/neuralhydrology/neuralhydrology + reference_commit: ea94a40d2f271994e33baa70f5ca1dd82e0e539d + reference_license: BSD-3-Clause + reference_config: > + neuralhydrology/modelzoo/cudalstm.py (CudaLSTM) with a regression head, built from a Config with + 5 dynamic inputs, the 27 static attributes, hidden_size 256, output_dropout 0.4 and + initial_forget_bias 5 (297,217 parameters; 269,569 without static inputs). Official weights: the + 16 LSTM runs of Kratzert et al. (2019) on HydroShare (doi 10.4211/hs.83ea5312635e44dc824eeb99eda12f06, + CC BY 4.0), written by papercode/lstm.py of kratzert/ealstm_regional_modeling @ d118158. + parameter_count: 297217 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_neuralhydrology_oracle.py + deviations: + - > + Only the configuration of the paper is ported: NeuralHydrology's optional static / dynamic + embedding networks, basin one-hot encoding, evolving attributes, autoregressive inputs and the + GMM / CMAL / UMAL heads are not available on this model. + - > + Dynamic inputs are one tensor ``x_d`` (batch, time, n_dynamic) instead of a dict of per-feature + tensors; NeuralHydrology concatenates the dict in configuration order, so the network input is + the same. + - > + The 2019 checkpoints have one bias per gate (gate order f, i, o, g); the conversion puts it into + ``bias_ih_l0`` with a zero ``bias_hh_l0``, which gives the same outputs (checked to 1e-6 on all + three model types). The port therefore has 1,024 more parameters than the 2019 LSTM (296,193), + as NeuralHydrology's CudaLSTM does. + - > + The default ``initial_forget_bias`` is 5 (the 2019 code); NeuralHydrology's default is None + (no special initialisation) and its example configurations use 3. tasks: - regression example: | import torch from pyhazards.models import build_model - model = build_model(name="neuralhydrology_lstm", task="regression", input_dim=2, out_dim=1) - preds = model({"x": torch.randn(1, 4, 6, 2)}) - print(preds.shape) + model = build_model(name="neuralhydrology_lstm", task="regression") # Kratzert et al. (2019) + out = model({"x_d": torch.randn(2, 270, 5), "x_s": torch.randn(2, 27)}) + print(out["y_hat"].shape) # (2, 270, 1): discharge for every day; the last day is the prediction notes: - - "The smoke test uses the shared synthetic streamflow dataset shape." + - > + Training recipe of the paper (not part of the model): Adam, learning rate 1e-3 (5e-4 after epoch 10, + 1e-4 after epoch 20), 30 epochs, batch 256, gradient clipping at norm 1, loss on the last time step, + NSE* (squared error weighted by 1 / (std of the basin's training discharge + 0.1)^2) or MSE. + PyHazards does not ship the NSE* loss yet. + - > + The 2019 checkpoints expect the 27 attributes in the column order of their ``attributes.db`` + (``pyhazards.datasets.flood.KRATZERT2019_CHECKPOINT_STATIC_ORDER``), while PyHazards (like + NeuralHydrology) sorts static attributes alphabetically; permute ``x_s`` accordingly, and normalise + the forcings with the 2019 code's fixed scaler (papercode/datautils.py), before applying them to real + data. + - The smoke configuration runs on ``flood_streamflow_synthetic`` (random basins, 30-day windows). smoke_test: task: regression build_kwargs: - input_dim: 2 - out_dim: 1 + hidden_size: 256 input: kind: mapping mapping: - x: - shape: [1, 4, 6, 2] + x_d: + shape: [2, 30, 5] + x_s: + shape: [2, 27] expected_output: - kind: tensor - shape: [1, 6, 1] + kind: mapping + mapping: + lstm_output: [2, 30, 256] + h_n: [2, 1, 256] + c_n: [2, 1, 256] + y_hat: [2, 30, 1] diff --git a/pyhazards/model_cards/pangu_tc.yaml b/pyhazards/model_cards/pangu_tc.yaml deleted file mode 100644 index d3896011..00000000 --- a/pyhazards/model_cards/pangu_tc.yaml +++ /dev/null @@ -1,43 +0,0 @@ -model_name: pangu_tc -display_name: Pangu TC Adapter -hazard: Tropical Cyclone -catalog_status: experimental -source_file: pyhazards/models/pangu_tc.py -builder_name: pangu_tc_builder -summary: > - An experimental wrapper-style storm adapter inspired by Pangu-Weather forecast fields. -description: - - > - ``pangu_tc`` adds a second foundation-weather reference path behind the - shared tropical-cyclone evaluator. - - > - The implementation is intentionally lightweight and should be interpreted as - an adapter contract for forecast-field driven storm evaluation. -paper: - title: Accurate medium-range global weather forecasting with 3D neural networks - url: https://www.nature.com/articles/s41586-023-06185-3 - repo_url: https://github.com/198808xc/Pangu-Weather -tasks: - - regression -example: | - import torch - from pyhazards.models import build_model - - model = build_model(name="pangu_tc", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) -notes: - - "Experimental adapter: intended for shared-evaluator prototyping rather than exact weather-model parity." -smoke_test: - task: regression - build_kwargs: - input_dim: 8 - horizon: 5 - output_dim: 3 - input: - kind: tensor - tensor: - shape: [2, 6, 8] - expected_output: - kind: tensor - shape: [2, 5, 3] diff --git a/pyhazards/model_cards/phasenet.yaml b/pyhazards/model_cards/phasenet.yaml index ea660566..ad768480 100644 --- a/pyhazards/model_cards/phasenet.yaml +++ b/pyhazards/model_cards/phasenet.yaml @@ -1,46 +1,111 @@ model_name: phasenet display_name: PhaseNet hazard: Earthquake +catalog_status: core source_file: pyhazards/models/phasenet.py builder_name: phasenet_builder summary: > - A lightweight phase-picking baseline that predicts P- and S-arrival indices from - multichannel waveform windows. + 1-D U-Net that turns three-component waveforms into per-sample probabilities of noise, P and S + arrivals (Zhu & Beroza, GJI 2019); picks are the peaks of the P and S traces. description: - > - ``phasenet`` is the first earthquake picking baseline in the staged PyHazards - roadmap and is paired with the synthetic waveform dataset for smoke validation. + ``phasenet`` maps waveforms ``(batch, 3, samples)`` (E, N, Z at 100 Hz, any length) to softmax + probabilities ``(batch, 3, samples)`` of noise, P and S. The network is a U-Net: an input + convolution and five depths (8, 16, 32, 64, 128 channels) of kernel-7 convolutions with batch + normalisation and ReLU, stride-4 convolutions on the way down, stride-4 transposed convolutions + with cropped skip connections on the way up, and a 1x1 output convolution. - > - This initial adapter focuses on the shared waveform-to-pick interface and does not - claim exact reproduction of the original PhaseNet training stack. + It is a port of the official TensorFlow code (``phasenet/model.py``) with the released + configuration, including TensorFlow's asymmetric "same" padding, so the official checkpoint + ``model/190703-214543`` loads with ``strict=True`` (``pretrained="original"``, read without + TensorFlow) and reproduces the official outputs. ``annotate`` applies the official per-window + normalisation and ``extract_picks`` the official peak picking (probability above 0.5, peaks at + least 0.5 s apart). paper: - title: "PhaseNet: A Deep-Neural-Network-Based Seismic Arrival Time Picking Method" - url: https://arxiv.org/abs/1803.03211 + title: "PhaseNet: a deep-neural-network-based seismic arrival-time picking method" + url: https://doi.org/10.1093/gji/ggy423 repo_url: https://github.com/AI4EPS/PhaseNet +references: + - title: "PhaseNet: a deep-neural-network-based seismic arrival-time picking method (Zhu & Beroza, GJI 216(1):261-273, 2019)" + url: https://doi.org/10.1093/gji/ggy423 + repo_url: https://github.com/AI4EPS/PhaseNet + note: > + Table 1, NCEDC test set (78,592 three-component 30-s recordings, 100 Hz), picks = probability + peaks above 0.5, true positive if |dt| < 0.1 s: P precision 0.939, recall 0.857, F1 0.896; S + precision 0.853, recall 0.755, F1 0.801; residual mean / standard deviation over |dt| < 0.5 s: + P 2.068 / 51.530 ms, S 3.311 / 82.858 ms. Reproduce the scoring with protocol "phasenet". + - title: "Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking (Mousavi et al., Nat. Commun. 11:3952, 2020)" + url: https://doi.org/10.1038/s41467-020-17591-w + repo_url: https://github.com/smousavi05/EQTransformer + note: > + Tables 2-3, STEAD test set, the released PhaseNet, true positive if |dt| < 0.5 s: P precision + 0.96, recall 0.96, F1 0.96, MAE 0.07 s; S precision 0.96, recall 0.93, F1 0.94, MAE 0.09 s + (protocol "eqtransformer"). + - title: "Which Picker Fits My Data? A Quantitative Evaluation of Deep Learning Based Seismic Pickers (Münchmeyer et al., JGR Solid Earth 127, e2021JB023499, 2022)" + url: https://doi.org/10.1029/2021JB023499 + repo_url: https://github.com/seisbench/pick-benchmark + note: > + In-domain phase-identification MCC (Table 2): STEAD 0.99, INSTANCE 0.94, ETHZ 0.91, SCEDC 0.91, + Iquique 0.96, NEIC 0.81, GEOFON 0.51. These were obtained with SeisBench's earlier 23,305-parameter + PhaseNet variant retrained per dataset, not with this architecture or the original weights, and + with pick-benchmark's own tasks, which PyHazards does not implement. +reproduction: + reference_code: https://github.com/AI4EPS/PhaseNet + reference_commit: 62005c6195638f88d077f8870ea895971062715a + reference_license: MIT (code and released checkpoint; Copyright (c) 2021 Weiqiang Zhu) + reference_config: > + ``UNet(ModelConfig(), mode="pred")`` from ``phasenet/model.py`` (depths 5, filters_root 8, kernel + 7, pool 4, 3 classes; the graph-building fields of ``model/190703-214543/config.log``) on + TensorFlow 2.11 (the release in the repository's env.yaml), restored from + ``model/190703-214543/model_95.ckpt`` as ``phasenet/predict.py`` does; also SeisBench 0.12.6's + PhaseNet with its conversion of the same checkpoint (second oracle). + parameter_count: 268443 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_phasenet_oracle.py + deviations: + - > + The paper's Figure 5 shows channel widths 8, 11, 16, 22, 32 and no batch normalisation; the + released code and checkpoint use 8, 16, 32, 64, 128 with batch normalisation (268,443 + parameters). The port follows the code and the checkpoint; the figure's variant is not provided. + - > + Layout ``(batch, channels, samples)`` instead of TensorFlow's ``(batch, samples, 1, channels)``; + TensorFlow variable ``Scope/layer/kernel`` is the PyTorch parameter ``Scope.layer.weight`` + (kernels transposed). The checkpoint is read by a pure-Python TensorBundle reader, checked + against ``tf.train.load_checkpoint``. + - > + Initial values follow the reference scheme (Glorot-uniform kernels, zero biases) but cannot equal + TensorFlow's random draws; the oracle compares bounds and spread. + - > + Not ported: the training pipeline (data readers, label generation, augmentation) and the + continuous-data predictor (``normalize_long`` sliding normalisation, overlapping windows, + amplitude extraction). ``annotate`` normalises each window as a whole, as the reader does for + 30-s training and test windows. tasks: - - regression + - picking example: | import torch from pyhazards.models import build_model - model = build_model( - name="phasenet", - task="regression", - in_channels=3, - ) + # Official weights (MIT), downloaded from the pinned repository commit on first use: + # model = build_model(name="phasenet", task="picking", pretrained="original") + model = build_model(name="phasenet", task="picking").eval() - picks = model(torch.randn(4, 3, 256)) - print(picks.shape) + waveforms = torch.randn(4, 3, 3000) # 30 s at 100 Hz, channels E, N, Z + with torch.no_grad(): + probabilities = model.annotate(waveforms) # (4, 3, 3000): noise, P, S + picks = model.extract_picks(probabilities) # [{"P": [(sample, prob), ...], "S": [...]}, ...] notes: - - "Outputs are P- and S-arrival sample indices in the current smoke-test adapter." + - "Inputs are three components in E, N, Z order at 100 Hz; ``forward`` expects normalised windows, ``annotate`` normalises raw ones (mean removed, divided by the standard deviation per channel)." + - "``forward(x, logits=True)`` returns the pre-softmax output used by the official cross-entropy loss." + - "The released checkpoint (trained 2019-07-03) post-dates the paper; whether it is the model behind GJI Table 1, and which data it was trained on, is not documented." smoke_test: - task: regression + task: picking build_kwargs: in_channels: 3 input: kind: tensor tensor: - shape: [4, 3, 256] + shape: [2, 3, 3000] expected_output: kind: tensor - shape: [4, 2] + shape: [2, 3, 3000] diff --git a/pyhazards/model_cards/prithvi_burnscars.yaml b/pyhazards/model_cards/prithvi_burnscars.yaml new file mode 100644 index 00000000..6cd38c5f --- /dev/null +++ b/pyhazards/model_cards/prithvi_burnscars.yaml @@ -0,0 +1,134 @@ +model_name: prithvi_burnscars +display_name: Prithvi-EO-2.0 BurnScars +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/prithvi_burnscars.py +builder_name: prithvi_burnscars_builder +summary: > + The IBM/NASA Prithvi-EO-2.0-300M foundation model fine-tuned to segment burn scars in single HLS + scenes (post-fire burned-area mapping), with the official weights. +description: + - > + ``prithvi_burnscars`` is the released Prithvi-EO-2.0-300M-BurnScars model. Its encoder is the + Prithvi-EO-2.0-300M masked-autoencoder ViT (ViT-L/16 with a 3D patch embedding and fixed 3D + sin/cos positions, pretrained on 4.2M multi-temporal HLS samples). The outputs of encoder blocks + 6, 12, 18 and 24 are reshaped to maps, turned into a four-level pyramid (learned transposed + convolutions up, max pooling down) and decoded by a U-Net decoder (512, 256, 128, 64 channels) + into two classes: not burned and burn scar. + - > + The modules are a plain-PyTorch port of the official ``prithvi_mae.py`` and of TerraTorch 0.99.8 + with segmentation_models_pytorch 0.4.0, the stack the checkpoint was trained with, keeping + TerraTorch's parameter names. ``pretrained=True`` downloads the 1.3 GB checkpoint from Hugging Face + (pinned revision and sha256, cached in torch.hub's checkpoint directory) and loads it with + ``strict=True``; no weights ship with PyHazards. Without it the model is randomly initialised + exactly like TerraTorch's. +paper: + title: "Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications" + url: https://arxiv.org/abs/2412.02732 + repo_url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars +references: + - title: "Prithvi-EO-2.0-300M-BurnScars (model card)" + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars + repo_url: https://github.com/torchgeo/terratorch + note: > + The released checkpoint (Apache-2.0): TerraTorch fine-tune with a UNetDecoder instead of the + paper's UperNet, 512 x 512 chips, cross-entropy with ignore index -1, AdamW lr 1e-4, new + non-overlapping train/val/test splits published with the model, best of five runs by + validation loss. Test IoU (burn scar) 87.52, test mIoU 93.00; validation IoU 84.28, mIoU 90.95. + - title: "Prithvi 100M burn scar (Roy et al., Hugging Face 2023, doi:10.57967/hf/0953)" + url: https://doi.org/10.57967/hf/0953 + repo_url: https://github.com/NASA-IMPACT/hls-foundation-os + note: > + The first-generation burn-scar fine-tune (Prithvi-EO-1.0-100M, ViT-B, MMSegmentation, 50 + epochs): IoU 0.73 on the burn-scar class and 0.96 overall accuracy. A different architecture + and checkpoint; not the model built here. + - title: "Foundation Models for Generalist Geospatial Artificial Intelligence" + url: https://arxiv.org/abs/2310.18660 + repo_url: https://github.com/NASA-IMPACT/hls-foundation-os + note: > + Prithvi-100M (v1) paper, Table 3: wildfire scar mapping on HLS Burn Scars, IoU (fire scar) + 73.62, mIoU 84.84, against 71.01 / 83.55 for a U-Net baseline. + - title: "HLS Burn Scars dataset" + url: https://huggingface.co/datasets/ibm-nasa-geospatial/hls_burn_scars + note: > + 805 HLS scenes of 512 x 512 pixels over the contiguous US (2018-2021) with MTBS burn-scar masks, + CC-BY-4.0; the fine-tuning and evaluation data of this model. +reproduction: + reference_code: https://github.com/torchgeo/terratorch + reference_commit: "0.99.8" + reference_license: Apache-2.0 + reference_config: > + EncoderDecoderFactory with the model_args of burn_scars_config.yaml (Hugging Face revision a3f2c41) + under TerraTorch 0.99.8, segmentation_models_pytorch 0.4.0 and timm 1.0.15, at random initialisation + and with the official Prithvi_EO_V2_300M_BurnScars.pt (sha256 0c5f9334...) loaded strictly after + removing the Lightning "model." prefix. On the Hugging Face example chip T10SEH.2018190 the + logits are identical (max absolute difference 0) and 79.5 % of the pixels are predicted burned. + parameter_count: 324204674 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_prithvi_oracle.py + deviations: + - > + Padding: TerraTorch 0.99.8 reflect-pads the bottom/right edge to a multiple of the patch size + (16) and then fails in the U-Net decoder whenever the token grid is odd; the port pads to a + multiple of 32 (as later TerraTorch releases do, but at the bottom/right), which gives + identical outputs for every size the reference accepts. + - > + Non-square inputs: TerraTorch 0.99.8 swaps height and width when resizing the position table and + reshapes tokens as a square grid, so non-square inputs fail or come out scrambled. The port + uses the true (H, W) token grid, as the official prithvi_mae.py does. Square inputs, including + the official 512 x 512 chips, are unaffected. + - > + With num_classes=1 TerraTorch squeezes the class dimension; the port keeps (B, 1, H, W). +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + from pyhazards.models.prithvi_burnscars import BURN_SCARS_MEAN, BURN_SCARS_STD + + # Official weights: about 1.3 GB, downloaded once from Hugging Face. + model = build_model(name="prithvi_burnscars", task="segmentation", pretrained=True).eval() + reflectance = torch.rand(1, 6, 512, 512) # HLS Blue, Green, Red, NIR narrow, SWIR 1, SWIR 2 in 0-1 + mean = torch.tensor(BURN_SCARS_MEAN)[:, None, None] + std = torch.tensor(BURN_SCARS_STD)[:, None, None] + with torch.no_grad(): + logits = model((reflectance - mean) / std) + burn_scar = logits.argmax(dim=1) # 1 = burn scar + print(logits.shape) # (1, 2, 512, 512) +notes: + - > + Post-fire mapping, not forecasting: the model maps burned area in one image taken after a fire. It + is not linked to the wildfire benchmark's danger or spread tasks, which it does not solve. + - > + Input: HLS surface reflectance in 0-1 (digital numbers / 10000) of Blue, Green, Red, NIR narrow, + SWIR 1 and SWIR 2, standardised per band with BURN_SCARS_MEAN and BURN_SCARS_STD; shape + (B, 6, H, W) or (B, 6, 1, H, W). The official chips are 512 x 512. Pixels labelled -1 (no data, + clouds) were ignored in training. + - > + Newer TerraTorch releases (checked: 1.2.13 with smp 0.5.0) resize the last U-Net block to the + skip resolution instead of upsampling it by two. With the same weights that changes the logits by + up to 1.6 and 0.37 % of the predicted pixels on the example chip. PyHazards keeps the training-time + behaviour: the official demo pins TerraTorch 0.99.8, and the checkpoint was written by Lightning + 2.5.0.post0, which 0.99.8 pins. + - > + The Prithvi-EO-2.0 paper (Table V) reports a different set-up: UperNet decoder, chips resized to + 448 and cropped to 224, mean of ten seeds; test mIoU 88.6 and burn-scar IoU 79.9 for the 300M + encoder. The test metrics were not re-evaluated in PyHazards. + - > + Weights are cached in torch.hub's checkpoint directory (cache_dir= overrides it); pass + weights_path= to load an existing copy offline, and set HF_ENDPOINT to use a Hugging Face mirror. +smoke_test: + task: segmentation + build_kwargs: + embed_dim: 64 + depth: 4 + num_heads: 2 + select_indices: [0, 1, 2, 3] + decoder_channels: [32, 16, 8, 4] + input: + kind: tensor + tensor: + shape: [2, 6, 64, 64] + expected_output: + kind: tensor + shape: [2, 2, 64, 64] diff --git a/pyhazards/model_cards/prithvi_eo_2_tl.yaml b/pyhazards/model_cards/prithvi_eo_2_tl.yaml new file mode 100644 index 00000000..551c6396 --- /dev/null +++ b/pyhazards/model_cards/prithvi_eo_2_tl.yaml @@ -0,0 +1,131 @@ +model_name: prithvi_eo_2_tl +display_name: Prithvi-EO-2.0-TL +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/prithvi_eo_2_tl.py +builder_name: prithvi_eo_2_tl_builder +summary: > + Prithvi-EO-2.0 Earth-observation foundation-model encoder with time and location embeddings + (300M or 600M, official pretrained weights), wrapped in the official burn-scar segmentation head + for fine-tuning. +description: + - > + Prithvi-EO-2.0 (IBM, NASA and Julich Supercomputing Centre) is a ViT masked autoencoder pretrained + on 4.2M Harmonized Landsat Sentinel-2 samples of four time steps. The TL variants add sin/cos + encodings of each frame's acquisition date (year, day of year) and of the scene's latitude and + longitude, each multiplied by a learned scale, to the patch tokens. ``prithvi_eo_2_tl`` ports the + official ``prithvi_mae.py`` encoder; ``pretrained=True`` loads the released 300M-TL (ViT-L/16) or + 600M-TL (ViT-H/14) weights, downloaded from Hugging Face on first use and never bundled. + - > + Because PyHazards builders return a task model, the encoder is wrapped in the segmentation recipe + of the official Prithvi-EO-2.0 burn-scar fine-tune (TerraTorch EncoderDecoderFactory: four encoder + blocks at the per-size indices of the official configs, a learned feature pyramid, a U-Net + decoder and a 1x1 head). Only the encoder is pretrained; the neck, decoder and head are randomly + initialised and need fine-tuning. Inputs are ``(B, C, T, H, W)`` with optional + ``temporal_coords`` ``(B, T, 2)`` and ``location_coords`` ``(B, 2)``; with ``num_frames`` T > 1 + the frames are stacked along channels as in the official multi-temporal configs. + ``model.encoder.forward_features`` returns the raw tokens of every block, and + ``pyhazards.models.PrithviMAE`` is the full autoencoder for reconstruction. +paper: + title: "Prithvi-EO-2.0: A Versatile Multi-Temporal Foundation Model for Earth Observation Applications" + url: https://arxiv.org/abs/2412.02732 + repo_url: https://github.com/NASA-IMPACT/Prithvi-EO-2.0 +references: + - title: "Prithvi-EO-2.0-300M-TL (model card)" + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL + note: > + The released 300M-TL pretraining checkpoint and prithvi_mae.py (Apache-2.0): 224 x 224 crops of + four frames, 6 HLS bands, patch 1x16x16, mask ratio 0.75, time and location encodings with + learned scales. The 600M-TL checkpoint is ibm-nasa-geospatial/Prithvi-EO-2.0-600M-TL. + - title: "Prithvi-EO-2.0-300M-BurnScars (model card)" + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars + note: > + Source of the segmentation head recipe (SelectIndices, ReshapeTokensToImage, + LearnedInterpolateToPyramidal, UNetDecoder [512, 256, 128, 64]); that checkpoint uses the + non-TL 300M encoder and is available as prithvi_burnscars. + - title: "Prithvi-EO-2.0-300M-TL-Sen1Floods11 (model card)" + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL-Sen1Floods11 + note: > + Official flood-mapping fine-tune of the 300M-TL encoder with a UperNet decoder (not ported). + The paper reports Sen1Floods11 test mIoU 90.0 and water IoU 82.6 for 300M-TL, 90.3 and 83.1 + for 600M-TL (Table IV). +reproduction: + reference_code: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL + reference_commit: 63adbd39c271da4c42f447e69b1a7c91a338cdc9 + reference_license: Apache-2.0 + reference_config: > + prithvi_mae.py PrithviMAE with the 300M-TL config.json (ViT-L 1024/24/16, decoder 512/8/16, 4 + frames) loaded strictly with the official Prithvi_EO_V2_300M_TL.pt (sha256 3629cedf...): + identical loss, reconstructions and masks with and without coordinates (330,419,716 parameters). + The registry model's encoder (303,886,338 parameters) loaded from the same file matches TerraTorch + 0.99.8's prithvi_eo_v2_300_tl backbone, and the full model matches TerraTorch's + EncoderDecoderFactory with the burn-scar recipe at random initialisation, for one and three + frames. The 600M-TL architecture is checked against TerraTorch at reduced depth. + parameter_count: 324204676 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_prithvi_oracle.py + deviations: + - > + When the position table has to be rebuilt for a different number of frames (more than one) and + resized, prithvi_mae.py fails on a ``view`` of a non-contiguous tensor; the port uses + ``reshape`` (as later TerraTorch releases do). + - > + Integer temporal or location coordinates are converted to float; the reference asserts a + float dtype. + - > + TerraTorch 0.99.8's PixelWiseModel cannot pad 5-D input, so multi-temporal segmentation is + checked module by module (encoder, necks, decoder, head) against the reference. Padding, + non-square inputs and num_classes=1 follow prithvi_burnscars (same deviations). + - > + The registry model loads the encoder part of the pretraining checkpoint and, like TerraTorch, + rebuilds the fixed sin/cos position table for its own frame count instead of copying the + checkpoint's; the stored table equals the rebuilt one up to float32 rounding (4.6e-7). +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # Pretrained 300M-TL encoder (about 1.3 GB, downloaded once) + burn-scar head to fine-tune. + model = build_model(name="prithvi_eo_2_tl", task="segmentation", num_frames=2, pretrained=True) + x = torch.randn(1, 6, 2, 224, 224) # (B, C, T, H, W), standardised HLS bands + temporal_coords = torch.tensor([[[2020.0, 150], [2020.0, 250]]]) # (year, day of year) per frame + location_coords = torch.tensor([[37.5, -120.0]]) # (latitude, longitude) + logits = model(x, temporal_coords=temporal_coords, location_coords=location_coords) + print(logits.shape) # (1, 2, 224, 224) +notes: + - > + Pretraining normalisation: HLS digital numbers standardised with PRITHVI_EO_V2_MEAN and + PRITHVI_EO_V2_STD (pyhazards.models.prithvi), bands Blue, Green, Red, NIR narrow, SWIR 1, SWIR 2. + Coordinates are optional; the encodings were randomly dropped during pretraining. + - > + variant="600m" selects the 600M-TL encoder (patch 14, blocks 8/16/24/32 feed the head). Its + weights are pinned by revision and sha256 but were not downloaded for the oracle comparison; + the 300M-TL weights were. + - > + The paper reports wildfire scar mapping (Table V, UperNet decoder, 224 x 224 crops, ten seeds) + test mIoU 89.3 and burn-scar IoU 81.1 for 300M-TL, 90.5 and 83.2 for 600M-TL. These are fine-tunes + that were not released; nothing here was re-trained. + - > + The burn-scar head maps burned area after a fire; it is not linked to the wildfire benchmark's + danger or spread tasks. +smoke_test: + task: segmentation + build_kwargs: + embed_dim: 64 + depth: 4 + num_heads: 2 + select_indices: [0, 1, 2, 3] + decoder_channels: [32, 16, 8, 4] + input: + kind: kwargs + kwargs: + x: + shape: [2, 6, 64, 64] + temporal_coords: + shape: [2, 1, 2] + location_coords: + shape: [2, 2] + expected_output: + kind: tensor + shape: [2, 2, 64, 64] diff --git a/pyhazards/model_cards/rainformer.yaml b/pyhazards/model_cards/rainformer.yaml new file mode 100644 index 00000000..0758cfe2 --- /dev/null +++ b/pyhazards/model_cards/rainformer.yaml @@ -0,0 +1,130 @@ +model_name: rainformer +display_name: Rainformer +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/rainformer.py +builder_name: rainformer_builder +summary: > + U-shaped radar-nowcasting network whose stages fuse shifted-window self-attention (global) and + CNN + CBAM attention (local) features through a gate; the strongest Sim2Real-Fire baseline, + with the official KNMI weights verified. +description: + - > + ``rainformer`` stacks the input frames as channels and maps them to as many future frames + (Bai et al., IEEE GRSL 2022). Four encoder stages (patch merging by 4, 2, 2, 2) and four + decoder stages (patch expanding, concatenation with the encoder skip) each contain a + feature-extraction balance module: a global unit of a window and a shifted-window + self-attention block (each followed by channel attention), a local unit of two + convolution-BatchNorm-ReLU layers and CBAM channel/spatial attention, and a gate fusion unit + that mixes them as ``Z * global + R * local`` with sigmoid gates computed from both. + - > + The default is the official KNMI model of ``train.py``: 9 -> 9 frames of 288 x 288, hidden + 96, heads 3/6/12/24, head dim 32, window 9, relative position bias; 187,661,990 parameters + (104,976 of them the fixed shifted-window masks). The official code has no license, so the + model is written from the paper and from the MIT-licensed Swin implementation the official + code builds on (berniwal/swin-transformer-pytorch). Parameter names and creation order follow + the official ``Net``, so the released KNMI checkpoint loads with ``strict=True`` and the same + seed gives the same weights. + - > + ``task="forecasting"`` takes ``(batch, T, C, H, W)`` (or the official ``(batch, T * C, H, + W)``) and returns the next ``T`` frames. ``task="segmentation"`` is a PyHazards adaptation + for next-step fire masks: a 1x1 convolution (``segmentation_head``) maps the channels of the + first predicted frame to ``out_channels`` logits ``(batch, 1, H, W)``; the Rainformer + parameters keep their official names at the top level of the state dict. +paper: + title: "Rainformer: Features Extraction Balanced Network for Radar-Based Precipitation Nowcasting" + url: https://doi.org/10.1109/LGRS.2022.3162882 + repo_url: https://github.com/Zjut-MultimediaPlus/Rainformer +references: + - title: "Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire" + url: https://github.com/TJU-IDVLab/Sim2Real-Fire + repo_url: https://github.com/TJU-IDVLab/Sim2Real-Fire + note: > + Li et al., NeurIPS 2024 Datasets and Benchmarks. The strongest AI baseline of Table 2, + trained on simulated wildfire scenarios and tested on simulated and real-world fires + (binary fire-area sequences with satellite, topography, vegetation, fuel and weather + inputs). Forecast AUPRC / F1 / IoU: 79.7 / 78.8 / 69.6 (simulation) and 67.2 / 65.5 / 52.0 + (real world); backtracking: 73.3 / 71.9 / 57.0 and 54.6 / 52.4 / 42.9 (S2R-FireTr: 87.3 / + 83.2 / 71.2 and 72.9 / 69.6 / 56.4 for forecasting). Configuration not published: the + paper only calls the baselines "commonly used AI models that can be easily adapted", and + its repository contains only S2R-FireTr (3 input frames at 256x256), so the input stacking, + window size, loss and output head of this baseline are unknown. These numbers are not + reproduced by PyHazards. +reproduction: + reference_code: https://github.com/Zjut-MultimediaPlus/Rainformer + reference_commit: c4e04e9011b7bbc1201a781fe5e0e56530126120 + reference_license: >- + none (no LICENSE file; used only as a test oracle, not copied); the KNMI checkpoint states no + licence and is used only as test data; the ported Swin parts are MIT + (berniwal/swin-transformer-pytorch c921ebf914c6ea9734bb260ada395e3746c85402) + reference_config: > + Net(input_channel=9, hidden_dim=96, downscaling_factors=(4, 2, 2, 2), layers=(2, 2, 2, 2), + heads=(3, 6, 12, 24), head_dim=32, window_size=9, relative_pos_embedding=True) from train.py + at 288 x 288 (einops 0.8.2): 187,661,990 parameters; seeded initialisation, eval/train + outputs, gradients and BatchNorm statistics compared locally with PYHAZARDS_ORACLE_LARGE=1, + and the released KNMI checkpoint (model1_1_100.pt from the repository's Google Drive link, + sha256-pinned, 751 MB) loaded with strict=True into both models with identical outputs (all + bit-identical). CI compares three narrow 288 x 288 models (hidden 8-16, windows 9 and 3, + with and without relative position bias, two FEBM groups in stage 1 or 3). + parameter_count: 187661990 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_rainformer_oracle.py + deviations: + - > + task="segmentation" (first predicted frame, 1x1 convolution to out_channels logits) is a + PyHazards adaptation, not from Sim2Real-Fire, whose baseline heads are unpublished. + - > + The official Net hard-codes the stage feature maps for 288 x 288 inputs (72/36/18/9 and + back), which fixes the shapes of the gate LayerNorms; it runs only at that size with + downscaling factors (4, 2, 2, 2). PyHazards derives the stage sizes from img_size and + raises ValueError unless every stage map is divisible by window_size. Sim2Real-Fire's + 256 x 256 frames give 64/32/16/8 maps, which window 9 does not divide, so Sim2Real-Fire + must have changed the window size or the input size; which one is not published + (unverified). Its own S2R-FireTr encoder uses the same Swin stage settings (hidden 96, + heads 3/6/12, head dim 32) with window 8 at 256 x 256, and window_size=8 works here + (181,876,886 parameters). + - > + Input in the PyHazards layout (batch, time, channels, H, W) is flattened time-major to the + official (batch, time * channels, H, W) and reshaped back; the official layout is also + accepted. The relative-position index is a non-persistent buffer (it moves with the + model's device) instead of a plain tensor attribute; the state dict is unchanged. +tasks: + - forecasting + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # Official KNMI configuration: 9 radar frames of 288 x 288 -> the next 9 frames. + model = build_model(name="rainformer", task="forecasting") + # model.load_state_dict(torch.load("model1_1_100.pt", map_location="cpu")) # official KNMI weights + x = torch.rand(1, 9, 1, 288, 288) # (batch, time, channels, height, width) + print(model(x).shape) # (1, 9, 1, 288, 288) + + # PyHazards next-step fire-mask adaptation on 256 x 256 frames (window 8 divides 64/32/16/8). + seg = build_model(name="rainformer", task="segmentation", in_channels=4, history=3, img_size=256, window_size=8) + print(seg(torch.randn(1, 3, 4, 256, 256)).shape) # (1, 1, 256, 256) +notes: + - "The gate LayerNorms normalise over (channels, height, width) with elementwise affine weights (27,371,520 of the default parameters), so a model only runs at the img_size it was built for and its parameter count depends on that size." + - "Kept from the official code because they change outputs or parameter counts: the gate fusion unit computes Z * g + R * l (the paper's Eq. 8 also convolves g and l; those convolutions, conv_2 and conv_3, are built but unused); every window attention is followed by a channel attention with separate average- and max-pool MLPs; the relative position bias is one table shared by all heads; decoder blocks use an MLP of only twice their width; the shifted-window masks are parameters without gradient." + - "With layers > 2 per stage, the official stage applies every FEBM group to the same stage input and keeps only the last group's output; PyHazards reproduces this. The official layers = (2, 2, 2, 2) has one group per stage." + - "The official KNMI checkpoint (Google Drive file 1LyLOJI9sf1sdZE1FwyTLPEGEcUuvXQc3, model1_1_100.pt, sha256 e3d5e4e59b32f13a74c7ffdc02ae65f9da3362c036b60e73e46dffe8721ae6b2) states no licence and is not redistributed by PyHazards. train.py feeds KNMI rain maps multiplied by 4783 / 100 * 12." + - "The official train.py uses Adam with learning rate 1e-3 and ReduceLROnPlateau, batch 24, and a balanced-MAE loss; the paper states 1e-4 and batch 16." + - "Earthformer (Gao et al., NeurIPS 2022) benchmarks re-sized Rainformer variants on SEVIR (184.0M parameters) and Moving MNIST (19.2M); those configurations are not in the official repository." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 2 + history: 2 + img_size: 64 + hidden_dim: 8 + heads: [1, 1, 1, 1] + head_dim: 4 + window_size: 2 + input: + kind: tensor + tensor: + shape: [1, 2, 2, 64, 64] + expected_output: + kind: tensor + shape: [1, 1, 64, 64] diff --git a/pyhazards/model_cards/random_forest.yaml b/pyhazards/model_cards/random_forest.yaml new file mode 100644 index 00000000..57df6792 --- /dev/null +++ b/pyhazards/model_cards/random_forest.yaml @@ -0,0 +1,141 @@ +model_name: random_forest +display_name: Random Forest +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/classical.py +builder_name: random_forest_builder +summary: > + The random-forest baseline of Kondylatos et al. (2022) for next-day wildfire danger: a + scikit-learn forest of 100 trees of depth 10 on 35 instance features built from ten days of + covariates. +description: + - > + ``random_forest`` is a scikit-learn ``RandomForestClassifier(n_estimators=100, max_depth=10, + min_samples_split=2, min_samples_leaf=1, random_state=123)`` (Breiman, 2001) with the + configuration of the official random-forest notebook of Kondylatos et al. (GRL 2022). It + takes the daily tensor ``(batch, 10, 25)`` of the ``wildfire_forecasting`` LSTM (10 dynamic, + 5 static and 10 land-cover columns per day) or ready-made features ``(batch, 35)``, and + returns ``(batch, 2)`` log-probabilities over (no fire, fire). + - > + Daily tensors are turned into the paper's instance features exactly as the notebook does: + the mean of the 10 dynamic variables over the ten days (ignoring missing values), the dynamic + variables on the last day (t-1), the 5 static variables and the 10 Corine Land Cover + fractions. ``kondylatos_instance_features`` exposes that construction. + - > + The model is an ``nn.Module`` wrapper (``EstimatorModule``) around the fitted forest, not a + neural network: fit it with ``model.fit(inputs, targets)``, after which ``forward`` returns + the log of ``predict_proba``. It has no parameters, its outputs carry no gradient, and + ``pyhazards.engine.Trainer.fit`` refuses it with an explanation; ``Trainer.evaluate`` and + ``Trainer.predict`` work on the fitted model. ``task="regression"`` builds the matching + ``RandomForestRegressor``. +paper: + title: "Random Forests" + url: https://doi.org/10.1023/A:1010933404324 + repo_url: https://github.com/scikit-learn/scikit-learn +references: + - title: "Wildfire Danger Prediction and Understanding With Deep Learning" + url: https://doi.org/10.1029/2022GL099368 + repo_url: https://github.com/Orion-AI-Lab/wildfire_forecasting + note: > + Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. Instance-based data + set of the daily 1 km Greek / Eastern Mediterranean datacube (dynamic inputs at day t-1, + their average over days t-1..t-10, static features); 40,554 training samples (2009-2018, + two negatives per positive), test years 2020 (3,684 samples) and 2021 (13,221). Random + forest test results (Table 1, 2020 / 2021): precision 0.843 / 0.880, recall 0.603 / 0.697, + F1 0.703 / 0.778 (TP 740 / 3,073, FP 138 / 418, TN 2,318 / 8,396, FN 488 / 1,334), below + XGBoost (F1 0.782 / 0.786) and the LSTM (0.804 / 0.879). + - title: "Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data" + url: https://arxiv.org/abs/2112.02447 + repo_url: https://github.com/google-research/google-research/tree/master/simulation_research/next_day_wildfire_spread + note: > + Huot et al., IEEE TGRS 2022. A per-pixel scikit-learn random forest on the 12 features of a + pixel and its 8 neighbours, maximum depth 15 (swept over 1-20 on validation AUC-PR), the + 'no fire' class weighted by (examples / 'no fire' examples) x 5, other hyperparameters at + the scikit-learn defaults: test AUC-PR 22.5%, precision 26.3%, recall 46.9% (Table II). Not + the configuration of this entry; pass ``max_depth``, ``random_state`` and ``class_weight`` + to the builder to approximate it. +reproduction: + reference_code: https://github.com/Orion-AI-Lab/wildfire_forecasting + reference_commit: 2b18bcf194284d56bd4e1774f7d5315db94cba34 + reference_license: MIT + reference_config: > + notebooks/RF.ipynb: RandomForestClassifier(n_estimators=100, max_depth=10, + min_samples_split=2, min_samples_leaf=1, random_state=123) fitted on the 35 instance features + the notebook builds from FireDataset_npy(access_mode='temporal', clc='vec') with the 10 + dynamic and 5 static variables of the paper. The oracle test runs the notebook's own cells on + synthetic data and requires identical features, predicted probabilities and labels; the + PyHazards input is the LSTM's daily tensor built by the reference + combine_dynamic_static_inputs. + checks: [forward] + oracle_test: tests/oracle/test_classical_oracle.py + deviations: + - > + The notebook reads (dynamic, static, land cover) separately from the dataset; PyHazards + reads the concatenated daily tensor of ``wildfire_forecasting`` (or ready-made features) and + takes the static and land-cover values from its last day. The values are the same because + that tensor repeats them over the ten days. + - > + The reference repository does not pin scikit-learn; the oracle compares the two under the + installed release (1.7.2 when checked). +tasks: + - classification + - regression +example: | + from pyhazards.datasets import load_dataset + from pyhazards.models import build_model + + data = load_dataset("wildfire_danger_synthetic", samples=120).load() + train, test = data.get_split("train"), data.get_split("test") + + model = build_model(name="random_forest", task="classification") + model.fit(train.inputs, train.targets) # (n, 10, 25) daily tensors -> 35 features + log_probs = model(test.inputs) + danger = log_probs.exp()[:, 1] # = model.predict_proba(test.inputs)[:, 1] + print(log_probs.shape) # (18, 2) + + model.save("random_forest.joblib") # EstimatorModule.load(path); joblib = pickle, trusted files only +notes: + - > + Not trained by gradient descent: ``Trainer.fit`` raises ``TypeError``; call + ``model.fit(inputs, targets)`` on the whole training split (the notebook fits on the + training set only and uses neither the validation split nor early stopping). Calling the + model before ``fit`` raises ``sklearn.exceptions.NotFittedError``. + - > + ``forward`` returns ``log(predict_proba)``; a forest often gives a class probability of + exactly 0, which becomes ``-inf``. ``predict_proba`` and ``predict`` return the scikit-learn + arrays; the notebook reports precision, recall and F1 of ``predict`` (threshold 0.5) and AUROC + / AUPRC of the fire probability. + - > + ``state_dict()`` is empty, so torch checkpoints do not contain the trees. Persist the fitted + model with ``model.save(path)`` and ``EstimatorModule.load(path)`` (joblib). Loading + unpickles the file and can execute code: only load files you trust. + - > + Features are computed in float64 like the notebook. The notebook uses the dataset's float64 + values while ``combine_dynamic_static_inputs`` casts the LSTM input to float32, so pass + float64 daily tensors to reproduce the notebook's features bit for bit. + - > + At the pinned commit the dataset class validates on 2020 and tests on 2021, so the + notebook's training split is 2009-2019; the paper trains on 2009-2018, validates on 2019 and + tests on 2020 and 2021. Its negatives are drawn with an unseeded ``random.sample`` and its + training loader shuffles, so the paper's forest cannot be rebuilt exactly; the same samples in + the same order give the same forest. + - > + The benchmark smoke configs evaluate models without training, so this entry has none: fit + the model first and pass it to ``BenchmarkRunner.run(model=...)``. With + ``task="regression"`` the same hyperparameters are used, which no paper prescribes. +smoke_test: + task: classification + fit: + inputs: + shape: [16, 10, 25] + targets: + shape: [16] + dtype: int64 + num_classes: 2 + input: + kind: tensor + tensor: + shape: [4, 10, 25] + expected_output: + kind: tensor + shape: [4, 2] diff --git a/pyhazards/model_cards/resnet18_unet.yaml b/pyhazards/model_cards/resnet18_unet.yaml new file mode 100644 index 00000000..ed62dc6e --- /dev/null +++ b/pyhazards/model_cards/resnet18_unet.yaml @@ -0,0 +1,73 @@ +model_name: resnet18_unet +display_name: ResNet-18 U-Net +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/resnet_unet.py +builder_name: resnet18_unet_builder +summary: > + U-Net with a ResNet-18 encoder, equivalent to segmentation_models_pytorch's Unet and used + as the U-Net baseline of WildfireSpreadTS. +description: + - > + ``resnet18_unet`` pairs a torchvision-style ResNet-18 encoder with the U-Net decoder of + segmentation_models_pytorch: five nearest-neighbour upsampling blocks with skip connections + and two Conv-BN-ReLU layers each, followed by a 3x3 segmentation head. + - > + The network is a plain-PyTorch re-implementation of ``smp.Unet("resnet18")`` from + segmentation_models_pytorch 0.3.2, the version WildfireSpreadTS pins, with the same + initialisation and parameter names. ``encoder_weights="imagenet"`` loads the ImageNet + ResNet-18 checkpoint and adapts the first convolution to the input channels the way smp + does. Multi-day input ``(batch, time, channels, height, width)`` is flattened to + ``time * channels`` channels. +paper: + title: "U-Net: Convolutional Networks for Biomedical Image Segmentation" + url: https://arxiv.org/abs/1505.04597 + repo_url: https://github.com/qubvel-org/segmentation_models.pytorch +references: + - title: "WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction" + url: https://openreview.net/forum?id=RgdGkPRQ03 + repo_url: https://github.com/SebastianGer/WildfireSpreadTS + note: > + smp.Unet("resnet18", encoder_weights=None) on 1 or 5 days of 40 channels, with static + features kept for the last day only (120 channels for 5 days), Dice loss, AdamW lr 1e-3; + 14.4M parameters for one day and 14.7M for five (paper Table 5). + - title: "Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark" + url: https://arxiv.org/abs/2502.12003 + note: > + Same network with ImageNet encoder weights and focal loss (WACV 2026); test AP 0.455-0.472. + - title: "Deep Residual Learning for Image Recognition" + url: https://arxiv.org/abs/1512.03385 + note: ResNet-18 encoder. +reproduction: + reference_code: https://github.com/qubvel-org/segmentation_models.pytorch + reference_commit: v0.3.2 + reference_license: MIT + reference_config: > + smp.Unet(encoder_name="resnet18", encoder_weights=None, in_channels=40, classes=1) as in + WildfireSpreadTS src/models/SMPModel.py, plus the ImageNet-initialised stem for 40 channels. + parameter_count: 14444241 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_wildfirespreadts_oracle.py +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + model = build_model(name="resnet18_unet", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) +notes: + - "Height and width must be divisible by 32." + - "encoder_name='resnet34' gives the ResNet-34 variant." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 6 + input: + kind: tensor + tensor: + shape: [2, 6, 64, 64] + expected_output: + kind: tensor + shape: [2, 1, 64, 64] diff --git a/pyhazards/model_cards/saf_net.yaml b/pyhazards/model_cards/saf_net.yaml index 4b991630..75de7e43 100644 --- a/pyhazards/model_cards/saf_net.yaml +++ b/pyhazards/model_cards/saf_net.yaml @@ -1,41 +1,100 @@ model_name: saf_net display_name: SAF-Net hazard: Tropical Cyclone +catalog_status: core source_file: pyhazards/models/saf_net.py builder_name: saf_net_builder summary: > - A spatiotemporal tropical-cyclone baseline with an intensity-focused head and shared trajectory output. + Wide-and-deep typhoon intensity network of Xu et al. (2022): 96 best-track predictors plus + 31x31 ERA-Interim u/v winds at four levels and four times, fused by spatial attention, predict + the maximum sustained wind 24 hours ahead. description: - > - ``saf_net`` adds an intensity-oriented storm baseline to the shared - ``tc.track_intensity`` evaluator. + ``saf_net`` predicts one number per storm and time: the (MinMax-scaled) maximum sustained wind + 24 hours ahead, in the Northwest Pacific (CMA best track). It does not forecast tracks. The wide + input is 96 CLIPER-style predictors from the best track (current and past positions, pressures and + winds, their changes and climatology factors); the deep input is ERA-Interim u and v wind on a 31 x + 31 storm-centred grid at 1000, 750, 500 and 250 hPa for t, t-6, t-12 and t-18 h, as a tensor + ``(batch, 2, 4, 31, 31, 4)``. - > - The adapter keeps full trajectory outputs so it can use the same report - format as the other PyHazards storm models. + For every time step, three convolution stages (64, 128, 256 channels, 2x2 max pooling), shared by a + u branch, a v branch and a fused branch, are each followed by a spatial-attention block; learnable + cross weights mix u and v and fuse weights merge the result into the fused branch. The four 128-d + time features and the 96 wide predictors go through two fully connected layers with ReLU. 880,233 + parameters. + - > + The official code has no license, so the module is written from the paper; the official notebook + network and checkpoint are used only as test oracle. Parameter names follow the official state dict, + so the released checkpoint (``model_saver/SAF_Net.pkl``) loads with ``strict=True``. ``forward(wide, + deep)`` also accepts ``{"wide": ..., "deep": ...}``; the benchmark scores it with ``tc.intensity``, + mapping the scaled output back to m/s with the dataset's ``prediction_transform``. paper: title: "SAF-Net: A spatio-temporal deep learning method for typhoon intensity prediction" - url: https://www.sciencedirect.com/science/article/pii/S1568494623003152 + url: https://doi.org/10.1016/j.patrec.2021.11.012 repo_url: https://github.com/xuguangning1218/TI_Prediction +references: + - title: "Official notebook outputs (SAF-Net.ipynb, released checkpoint)" + url: https://github.com/xuguangning1218/TI_Prediction/blob/651ccc4ec5d2139c758148778d617583052f2eea/SAF-Net.ipynb + repo_url: https://github.com/xuguangning1218/TI_Prediction + note: > + 24-hour intensity MAE on the CMA Northwest Pacific test years with the released weights: 2015 4.38, + 2016 4.90, 2017 3.91, 2018 4.02 m/s (mean of the years 4.30 m/s); trained on 2000-2014 (8,406 cases, + 2,747 test cases). The paper's own tables (Elsevier) were not read; not reproduced by PyHazards, + because the ERA-Interim crops are only on the authors' Google Drive. + - title: "Tropical cyclone intensity forecasting using model knowledge guided deep learning model (TCIF-fusion)" + url: https://doi.org/10.1088/1748-9326/ad1bde + repo_url: https://github.com/wangchong96/TCIF-fusion + note: > + Wang, Li and Zheng, Environmental Research Letters 19, 024006 (2024), Table 2: SAF-Net 24-hour + intensity MAE 4.30 m/s on 2015-2018 Northwest Pacific cases, as a comparison baseline. +reproduction: + source: paper + reference_code: https://github.com/xuguangning1218/TI_Prediction + reference_commit: 651ccc4ec5d2139c758148778d617583052f2eea + reference_license: none (no LICENSE file; the notebook network and checkpoint are used only as a test oracle, never copied) + reference_config: > + The Net class of SAF-Net.ipynb (ahead_times = [0, 1, 2, 3], 24-hour lead): 880,233 parameters; the same + seed gives identical initial weights; outputs equal in eval mode and in train mode (BatchNorm batch + statistics, updated running statistics, gradients); the released model_saver/SAF_Net.pkl loads with + strict=True into both and gives the same outputs on real 2015-2018 wide predictors from the + repository's CMA_test_24h.csv (with random deep inputs, since the ERA-Interim crops are not public). + parameter_count: 880233 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_saf_net_oracle.py + deviations: + - > + The official network reads the number of time steps from the notebook global ``ahead_times``; here + it is the ``num_times`` argument (default 4). ``wide_dim``, ``num_levels`` and ``grid_size`` are + arguments too; only the defaults are checked. + - > + Training is not part of the module: the notebook uses L1 loss, Adam (learning rate 7e-4), batch 128, + 128 epochs, a new random 10 % validation split every epoch and keeps the weights with the lowest + validation loss. tasks: - regression example: | import torch from pyhazards.models import build_model - model = build_model(name="saf_net", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + model = build_model(name="saf_net", task="regression") + wide = torch.rand(2, 96) # MinMax-scaled best-track predictors + deep = torch.rand(2, 2, 4, 31, 31, 4) # (batch, [u, v], level, lat, lon, time) + print(model(wide, deep).shape) # (2, 1): scaled 24-hour maximum wind + # model.load_state_dict(torch.load("SAF_Net.pkl", map_location="cpu")) # official checkpoint (no licence) notes: - - "Track channels are retained so the shared storm evaluator can score all baselines consistently." + - "Kept from the official network because it changes outputs: the fused stage-3 features pass through the stage-3 attention block twice; fc1 has no activation; the output ReLU keeps scaled predictions non-negative." + - "The notebook fits the MinMax scalers of the inputs and the target on the training and test years together (test-set information leaks into the scaling); a reproduction of its numbers has to do the same." + - "The official checkpoint and the CMA data in the repository have no licence; PyHazards does not redistribute them. ERA-Interim is a retired ECMWF product." + - "No PyHazards loader reads the official CMA / ERA-Interim preprocessed files yet; safnet_cma_era_interim_synthetic gives random inputs in their layout for smoke tests." smoke_test: task: regression - build_kwargs: - input_dim: 8 - horizon: 5 input: - kind: tensor - tensor: - shape: [2, 6, 8] + kind: kwargs + kwargs: + wide: + shape: [2, 96] + deep: + shape: [2, 2, 4, 31, 31, 4] expected_output: kind: tensor - shape: [2, 5, 3] + shape: [2, 1] diff --git a/pyhazards/model_cards/segformer.yaml b/pyhazards/model_cards/segformer.yaml new file mode 100644 index 00000000..629d5b10 --- /dev/null +++ b/pyhazards/model_cards/segformer.yaml @@ -0,0 +1,119 @@ +model_name: segformer +display_name: SegFormer +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/segformer.py +builder_name: segformer_builder +summary: > + Hierarchical Mix Transformer encoder with a lightweight all-MLP decoder (SegFormer-B0 to B5), + used as a Transformer baseline for next-day wildfire spread on WildfireSpreadTS. +description: + - > + ``segformer`` encodes the input with a four-stage Mix Transformer (MiT): overlapping patch + embeddings, efficient self-attention whose keys and values are spatially reduced, and Mix-FFN + layers whose depth-wise convolution replaces positional encodings, so any input size works. + An all-MLP head projects the four stages to a common width, upsamples them to 1/4 resolution, + fuses them and predicts per-pixel logits (Xie et al., NeurIPS 2021). + - > + The network is a plain-PyTorch port of Hugging Face transformers' SegFormer (4.57.6) with the + same module names, initialisation and outputs: ``SegformerForSemanticSegmentation`` state dicts + and the ``nvidia/mit-b*`` ImageNet encoders load with ``strict=True``. ``variant`` selects + MiT-B0 to B5 (decoder width 256 for B0/B1, 768 for B2-B5). The logits are resized to the + input size by default; ``raw_logits()`` returns the 1/4-resolution decoder output. +paper: + title: "SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers" + url: https://arxiv.org/abs/2105.15203 + repo_url: https://github.com/NVlabs/SegFormer +references: + - title: "Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark" + url: https://arxiv.org/abs/2502.12003 + note: > + Lahrichi, Bova, Johnson & Malof, WACV 2026. SegFormer-B2 trained on 128x128 WildfireSpreadTS + crops without padding, encoder initialised from nvidia/mit-b2 (ImageNet-1k), decoder from + scratch, focal loss (alpha = inverse positive-pixel frequency, gamma = 2), AdamW, batch 64, + 10k iterations, learning rate from a grid search on one fold. One day (Veg 7, Multi 33, + All 40 channels) or five days concatenated on channels with the WildfireSpreadTS layout + (static features only on the last day; 120 channels for All). Reported 27.5M (T=1) and 27.7M + (T=5) parameters, matching B2 with 40 and 120 input channels (27,463,425 and 27,714,305). + Mean test AP over 12 folds 0.433 / 0.436 / 0.423 (T=1, Veg / Multi / All) and 0.439 / 0.436 / + 0.430 (T=5), below the paper's ResNet-18 U-Net. The paper does not say how the 3-channel + mit-b2 patch embedding was adapted to the wildfire channels. +reproduction: + reference_code: https://github.com/huggingface/transformers/blob/v4.57.6/src/transformers/models/segformer/modeling_segformer.py + reference_commit: v4.57.6 + reference_license: Apache-2.0 + reference_config: > + SegformerForSemanticSegmentation with the MiT-B0 (3 channels, 150 classes) and MiT-B2 + (40 channels, 1 class, the WSTS+ setting) configurations of nvidia/mit-b*, SegformerModel + (B0, 5 channels), and the revision-pinned Hub checkpoints nvidia/mit-b0 (ImageNet-1k encoder, + also adapted to 1/7/40 channels and compared with smp 0.3.2 patch_first_conv) and + nvidia/segformer-b0-finetuned-ade-512-512 (ADE20K, compared with transformers' + post_process_semantic_segmentation). + parameter_count: 27463425 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_segformer_oracle.py + deviations: + - > + forward() resizes the logits from 1/4 resolution to the input size (bilinear, + align_corners=False), as transformers' post-processing and loss and mmseg's inference do + outside the network; SegformerForSemanticSegmentation itself returns the 1/4-resolution + logits, available here from raw_logits() or with upsample=False. + - > + With encoder_weights and in_channels other than 3, the first patch embedding is adapted the + way segmentation_models_pytorch adapts ImageNet encoders (RGB filters repeated over the + channels and scaled by 3 / in_channels; summed for one channel). transformers' + from_pretrained(..., ignore_mismatched_sizes=True) would re-initialise it instead; WSTS+ does + not say which it did. + - > + Only logits are returned: no loss from labels, attention maps or output dataclasses + (SegformerModel returns the four stage outputs as a list). transformers' deprecated + reshape_last_stage=False and head pruning are not supported. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # SegFormer-B2 as in WSTS+: 40 channels (one day, all features), one output. + model = build_model(name="segformer", task="segmentation", in_channels=40) + logits = model(torch.randn(2, 40, 128, 128)) + print(logits.shape) # (2, 1, 128, 128) + print(model.raw_logits(torch.randn(2, 40, 128, 128)).shape) # (2, 1, 32, 32) + + # ImageNet-1k MiT-B2 encoder (non-commercial NVIDIA weights, downloaded on request). + pretrained = build_model(name="segformer", task="segmentation", in_channels=40, encoder_weights="imagenet") +notes: + - > + NVIDIA licenses the SegFormer and MiT weights (``nvidia/mit-b*``, ``nvidia/segformer-*``) for + non-commercial use only (NVIDIA Source Code License for SegFormer). PyHazards does not bundle + them; encoder_weights="imagenet" downloads the revision-pinned nvidia/mit- checkpoint + from the Hugging Face Hub, and a local pytorch_model.bin or model.safetensors path also works. + - > + load_hf_state_dict() loads transformers state dicts: SegformerForSemanticSegmentation into the + whole model; SegformerForImageClassification (``nvidia/mit-b*``: the "segformer." prefix is removed + and the ImageNet classifier dropped) and SegformerModel into model.segformer. + - > + Like transformers, every LayerNorm uses eps=1e-5. The official MiT uses 1e-6 in the + Transformer blocks and stage norms; with the ADE20K B0 weights this changes logits by up to + about 6e-3 (99.99% argmax agreement on random input). + - > + Mix-FFN expansion is 4 in every stage, as in the released code and checkpoints; the paper's + Table 6 lists 8 for stages 1-2 of B0-B4. The decode-head dropout is element-wise as in + transformers, where mmseg uses channel-wise Dropout2d; this only matters in training. + - "Height and width must be at least 29; they need not be multiples of 32." + - > + Multi-day input (batch, time, channels, height, width) is flattened time-major to + time * channels. The deduplicated WildfireSpreadTS layout (120 channels for five days of all + features) is built by the data pipeline and passed as (batch, 120, height, width). +smoke_test: + task: segmentation + build_kwargs: + in_channels: 6 + variant: b0 + input: + kind: tensor + tensor: + shape: [2, 6, 64, 64] + expected_output: + kind: tensor + shape: [2, 1, 64, 64] diff --git a/pyhazards/model_cards/swin_unet.yaml b/pyhazards/model_cards/swin_unet.yaml new file mode 100644 index 00000000..4c073d51 --- /dev/null +++ b/pyhazards/model_cards/swin_unet.yaml @@ -0,0 +1,93 @@ +model_name: swin_unet +display_name: Swin-Unet +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/swin_unet.py +builder_name: swin_unet_builder +summary: > + U-shaped pure Swin Transformer (Swin-Unet-Tiny), the attention-based spread baseline of the + WSTS+ wildfire benchmark. +description: + - > + ``swin_unet`` encodes the input with four Swin Transformer stages joined by patch merging, + decodes it with mirrored Swin stages joined by patch-expanding layers and skip connections, + and upsamples the last decoder tokens 4x into per-pixel logits (Cao et al., ECCV Workshops + 2022). The default is Swin-Unet-Tiny: patch 4, embedding 96, depths (2, 2, 2, 2), heads + (3, 6, 12, 24), window 7, input 224x224, drop-path rate 0.2. + - > + The implementation is written from the paper and from the MIT-licensed Swin Transformer + code, because the official Swin-Unet repository has no license. Parameter names and creation + order match the official ``SwinTransformerSys``, so its state dicts load with + ``strict=True`` and seeded initialisation is identical. ``pretrained="imagenet"`` + reproduces the official initialisation: the Swin-T ImageNet-1k checkpoint fills the encoder + and, mirrored, the decoder. Multi-day input ``(batch, time, channels, height, width)`` is + flattened to ``time * channels`` channels, as WSTS+ does for its 5-day models. +paper: + title: "Swin-Unet: Unet-like Pure Transformer for Medical Image Segmentation" + url: https://arxiv.org/abs/2105.05537 + repo_url: https://github.com/HuCaoFighting/Swin-Unet +references: + - title: "Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark" + url: https://arxiv.org/abs/2502.12003 + note: > + Lahrichi, Bova, Johnson and Malof (WACV 2026). SwinUnet-Tiny with in_chans set to 7, 33 + or 40 (Veg, Multi, All feature sets; times 5 for 5-day input), 128x128 WildfireSpreadTS + tiles zero-padded to 224x224, Swin-T ImageNet initialisation (Hugging Face + swin-tiny-patch4-window7-224), focal loss, AdamW, batch 64, 10k iterations. Mean test AP + over 12 leave-one-year-out folds: 0.432 / 0.437 / 0.424 (1 day) and 0.447 / 0.453 / + 0.435 (5 days) for Veg / Multi / All; 27.2M parameters (1 day). + - title: "Swin Transformer: Hierarchical Vision Transformer using Shifted Windows" + url: https://arxiv.org/abs/2103.14030 + repo_url: https://github.com/microsoft/Swin-Transformer + note: Swin-T blocks and the ImageNet-1k checkpoint used for initialisation (MIT). +reproduction: + reference_code: https://github.com/HuCaoFighting/Swin-Unet + reference_commit: f48f623e226e25b6e395c37207915c50aaa9c776 + reference_license: none (no LICENSE file; used only as a test oracle, not copied) + reference_config: > + SwinUnet(config) from configs/swin_tiny_patch4_window7_224_lite.yaml with IN_CHANS 40 and one + class (the WSTS+ All-features setting) and with IN_CHANS 3 and nine classes (Synapse, + 27,168,900 parameters), plus SwinUnet.load_from with the Swin-T ImageNet-1k checkpoint + (swin_tiny_patch4_window7_224.pth, microsoft/Swin-Transformer release v1.0.0, MIT, sha256 + pinned) for 40 and 3 input channels. + parameter_count: 27224964 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_swin_oracle.py + deviations: + - > + The official wrapper repeats a one-channel input to three channels. Here that happens only + when the model has three input channels; for other channel counts the official code + would fail. + - > + Only the ImageNet branch of the official load_from is provided. Its other branch + (fine-tuning from a saved Swin-Unet checkpoint, dropping the output layer) is covered by + load_state_dict, since parameter names match. +tasks: + - segmentation +example: | + import torch + import torch.nn.functional as F + from pyhazards.models import build_model + + # WSTS+ "All" features (40 channels); pretrained="imagenet" loads the Swin-T initialisation. + model = build_model(name="swin_unet", task="segmentation", in_channels=40) + x = torch.randn(2, 40, 128, 128) + logits = model(F.pad(x, (0, 96, 0, 96)))[..., :128, :128] # zero-pad 128 -> 224 as WSTS+ + print(logits.shape) # (2, 1, 128, 128) +notes: + - "Inputs must be img_size x img_size (224 by default); WSTS+ zero-pads its 128x128 tiles. The padding layout is not stated in the paper." + - "The decoder mirrors the encoder depths. The official DECODER_DEPTHS option and the depths_decoder argument have no effect in the official code, so they are not exposed." + - "Decoder blocks reuse the stochastic-depth rates of the matching encoder stage, as in the official code." + - "With pretrained weights, tensors whose shape differs from Swin-T (the patch embedding when in_channels != 3) keep their random initialisation, as in the official load_from." + - "WSTS+ loaded the Hugging Face release of Swin-T (microsoft/swin-tiny-patch4-window7-224, a conversion of the ImageNet-1k model); PyHazards loads the original microsoft/Swin-Transformer checkpoint with the official Swin-Unet key mapping." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 7 + input: + kind: tensor + tensor: + shape: [1, 7, 224, 224] + expected_output: + kind: tensor + shape: [1, 1, 224, 224] diff --git a/pyhazards/model_cards/swin_unetr.yaml b/pyhazards/model_cards/swin_unetr.yaml new file mode 100644 index 00000000..65608a35 --- /dev/null +++ b/pyhazards/model_cards/swin_unetr.yaml @@ -0,0 +1,120 @@ +model_name: swin_unetr +display_name: SwinUNETR +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/swin_unetr.py +builder_name: swin_unetr_builder +summary: > + Swin-Transformer encoder with a convolutional U-Net decoder (MONAI's SwinUNETR), configured by + default as TS-SatFire's spatio-temporal (3D) reference model for next-day fire progression. +description: + - > + ``swin_unetr`` is SwinUNETR (Hatamizadeh et al., BrainLes 2021): a four-stage Swin Transformer + with shifted-window attention and patch merging encodes the input, and its five feature + levels feed a convolutional U-Net decoder of residual blocks. The implementation is MONAI's + (1.3.2, Apache-2.0; the authors' official code uses it), ported to plain PyTorch with MONAI's module + names, so MONAI state dicts load with ``strict=True``; MONAI's ``"merging"`` / + ``"mergingv2"`` patch merging and SwinUNETR-v2 blocks (``use_v2``) are included. + - > + With the defaults (``spatial_dims=3``) the model is TS-SatFire's SwinUNETR-3D, which modifies + MONAI's file: patches of (1, 2, 2) and attention windows of (T, 4, 4), so every window spans + the whole time series; patch merging that only merges even-sized dimensions (with T = 6 the + first stage halves time to 3 and later stages keep it); optional Swin-V2 attention + (``attn_version="v2"``); feature size 36, batch norm and two-class logits averaged over time. + ``spatial_dims=2`` gives TS-SatFire's SwinUNETR-2D, which is stock MONAI (patch 2, window 7, + feature size 48). +paper: + title: "Swin UNETR: Swin Transformers for Semantic Segmentation of Brain Tumors in MRI Images" + url: https://arxiv.org/abs/2201.01266 + repo_url: https://github.com/Project-MONAI/research-contributions +references: + - title: "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction" + url: https://doi.org/10.1038/s41597-025-06271-3 + repo_url: https://github.com/zhaoyutim/TS-SatFire + note: > + SwinUNETR-3D from the repository's modified MONAI copy (patch (1, 2, 2), window (T, 4, 4), + even-dimension patch merging, window attention "v1", feature size 36) on 256x256 tiles of + daily VIIRS and auxiliary data, 43 channels for next-day progression prediction, T in + {2, 4, 6}, logits averaged over time; prediction trained with Dice + weighted CE (1:1, class + weights [1, 446.78]), learning rate 0.001, batch 8 (paper text). The number of heads (a + command-line argument) is not published. Paper Table 3 (6 input days; arXiv 2412.11555): + 33.2M parameters, F1 0.797 / 0.855 / 0.374 and IoU 0.688 / 0.768 / 0.331 on active fire / + burned area / prediction; Table 4 (seeds 42-44): prediction F1 0.371 +/- 0.003, IoU + 0.332 +/- 0.003; Table 5 (prediction, T = 6 / 4 / 2): F1 0.374 / 0.354 / 0.366. SwinUNETR-2D + (stock MONAI, feature size 48) has 25.2M parameters and F1 0.774 / 0.829 on active fire / + burned area. +reproduction: + reference_code: https://github.com/Project-MONAI/MONAI + reference_commit: "1.3.2" + reference_license: Apache-2.0 + reference_config: > + TS-SatFire's SwinUNETR(image_size=(T, H, W), patch_size=(1, 2, 2), window_size=(T, 4, 4), + in_channels=43, out_channels=2, depths=(2, 2, 2, 2), num_heads=(3, 3, 3, 3), feature_size=36, + norm_name="batch", attn_version="v1") from spatial_models/swinunetr/ at da75732 (an adapted + MONAI SwinUNETR; the repository has no license and is used only as a test oracle), with its + outputs averaged over time, at T = 6 (and T = 2, 3, 4 for the other merging plans) on 32x32 + tiles, at (6, 256, 256) for the parameter count (33,191,942), and with attn_version="v2"; MONAI + 1.3.2 SwinUNETR(spatial_dims=2, in_channels=8, feature_size=48, norm_name="batch") for the 2D + baseline (25,151,996 parameters, forward at 64x64); and 2D/3D MONAI configurations with + "merging" and "mergingv2", use_v2, instance norm, dropout, attention dropout, stochastic + depth, gradient checkpointing and unnormalised features. + parameter_count: 33191942 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_swin_unetr_oracle.py + deviations: + - > + TS-SatFire's autoregressive attention (``attn_version="ar"``, AutoregressiveAttention.py, + a causal temporal mask on Swin-V2 attention) is not ported: the prediction script hard-codes + ``attn_version="v1"``. The temporal mask TS-SatFire computes in every 3D stage is only used + by that attention, so it is not computed here either. + - > + TS-SatFire's number of heads (``-nh``) is not published; the default 3 per stage is a + PyHazards choice. Table 3's 33.2M is consistent with any of 3, 4, 6 or 12 heads (33.19M to + 33.23M with 43 channels; 33.15M to 33.19M with 8). + - > + TS-SatFire averages the 3D logits over time in its training script; here that read-out is + part of the model (``time_reduction="mean"``), which also takes ``(batch, time, channels, + H, W)`` instead of ``(batch, channels, time, H, W)``. + - > + ``downsample`` takes ``"merging"``, ``"mergingv2"`` or ``"ts_satfire"`` but not a custom + module, and MONAI's ``load_from`` helper for its self-supervised Swin-ViT checkpoint is not + ported (state dicts load directly). + - > + Gradient checkpointing follows MONAI; TS-SatFire's copy calls its block with the wrong + number of arguments when ``use_checkpoint=True``. Swin-V2 attention with a window size of 1 + (division by zero in the reference) and inputs that do not fit the merging plan fixed by + ``img_size`` (a concatenation error in the reference) raise ValueError. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # TS-SatFire SwinUNETR-3D prediction model for 6 days of 43 channels on 256x256 tiles. + model = build_model(name="swin_unetr", task="segmentation", in_channels=43, history=6) + logits = model(torch.randn(1, 6, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) + + # TS-SatFire's single-image SwinUNETR-2D (stock MONAI). + model_2d = build_model(name="swin_unetr", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 256, 256)).shape) # (1, 2, 256, 256) +notes: + - "With downsample='ts_satfire' the merging plan is fixed by img_size = (history, image_size, image_size): a stage merges a dimension only if its size there is even (T = 6: time 6 -> 3 at the first stage; T = 4: 4 -> 2 -> 1; T = 2: 2 -> 1; odd T: never)." + - "Height and width must be multiples of 32 (patch 2 times four merges); MONAI's merging modes also halve time four times, so they need T divisible by 16." + - "TS-SatFire's Swin-V2 attention normalises its 3D relative coordinates with [:, :, :, i] indexing, which in 3D scales entries of the width axis rather than each coordinate; this is kept." + - "MONAI quirks are kept: the 3D 'merging' mode concatenates two of the eight neighbours twice and two never, and window attention indexes its bias table with [:n, :n] when a window is shrunk to the feature size." + - "num_heads may be one int for every stage, as in TS-SatFire's scripts." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 4 + history: 2 + image_size: 32 + feature_size: 12 + input: + kind: tensor + tensor: + shape: [2, 2, 4, 32, 32] + expected_output: + kind: tensor + shape: [2, 2, 32, 32] diff --git a/pyhazards/model_cards/swinlstm.yaml b/pyhazards/model_cards/swinlstm.yaml new file mode 100644 index 00000000..1deab794 --- /dev/null +++ b/pyhazards/model_cards/swinlstm.yaml @@ -0,0 +1,154 @@ +model_name: swinlstm +display_name: SwinLSTM +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/swinlstm.py +builder_name: swinlstm_builder +summary: > + Recurrent cell built from Swin Transformer blocks (Tang et al., ICCV 2023): a frames-to-frames + forecaster with the official Moving-MNIST weights, one of the forecasters Sim2Real-Fire compares + for fire-area forecasting. +description: + - > + ``swinlstm`` replaces the convolutions of ConvLSTM with Swin Transformer blocks. Each frame is + cut into 2x2 patches and embedded. In a SwinLSTM cell the patch tokens and the previous hidden + state are layer-normalised, concatenated and projected back to the token width, passed through + (shifted-)window attention blocks, and the result F updates a simplified LSTM: + ``C_t = sigmoid(F) * (tanh(F) + C_{t-1})``, ``H_t = sigmoid(F) * tanh(C_t)``. A 3x3 transposed + convolution with stride 2 and a sigmoid reconstruct the next frame. SwinLSTM-D + (``variant="d"``, the default) has four cells joined by patch merging and patch expanding + (embedding 128, window 4, heads 4 and 8); SwinLSTM-B (``variant="b"``) has cells at a single + resolution. + - > + ``forward`` runs the official rollout: a warm-up phase over the first ``T_in - 1`` frames, then + autoregressive prediction starting from the last input frame, each predicted frame being the + next input. ``include_warmup=True`` also returns the warm-up predictions, which the official + L2 loss compares with the shifted input frames; ``step`` is the official single-step forward. + The port matches the official code in eval and train mode (stochastic depth), and the released + Moving-MNIST SwinLSTM-D weights load with ``strict=True``. + - > + Sim2Real-Fire compares SwinLSTM with other forecasters for fire-area forecasting and + backtracking but published no configuration for it. ``task="segmentation"`` is a PyHazards + adaptation that predicts one next-step fire mask from a sequence of rasters. +paper: + title: "SwinLSTM: Improving Spatiotemporal Prediction Accuracy using Swin Transformer and LSTM" + url: https://arxiv.org/abs/2308.09891 + repo_url: https://github.com/SongTang-x/SwinLSTM +references: + - title: "Sim2Real-Fire: A Multi-modal Simulation Dataset for Forecast and Backtracking of Real-world Forest Fire" + url: https://proceedings.neurips.cc/paper_files/paper/2024/hash/02e978a2cc9a1d0d4376a7deb01db612-Abstract-Datasets_and_Benchmarks_Track.html + repo_url: https://github.com/TJU-IDVLab/Sim2Real-Fire + note: > + Configuration not published: the paper lists SwinLSTM among "commonly used AI models that can + be easily adapted" but gives no hyperparameters, input stacking, loss or output head, and the + repository contains only S2R-FireTr. Trained on 1M simulated scenarios and tested on simulated + and about 1K real fires (binary fire-area sequences with satellite, topography, vegetation, + fuel and weather inputs). Table 2, AUPRC / F1 / IoU (%): forecast 77.1 / 71.2 / 56.2 + (simulation) and 62.5 / 60.3 / 48.9 (real); backtracking 72.5 / 65.3 / 52.4 (simulation) and + 53.8 / 49.5 / 40.3 (real). Modality ablations in Tables 4 and 6. Not reproduced here. + - title: "A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA)" + url: https://arxiv.org/abs/2606.15529 + repo_url: https://github.com/LabRAI/WildfireIA + note: > + Not this model. WildfireIA's "SwinLSTM" baseline (train.py SwinLSTMClassifier at aba9be9, + MIT) is a ConvLSTM cell between two window-attention blocks (48 channels, a strided + convolutional stem with BatchNorm, ``nn.MultiheadAttention`` in 5x5 windows without shifts or + relative position bias) with global pooling and an MLP to one score, on 29x29 event patches. + Initial-attack failure prediction: AUPRC 51.7 +/- 1.2, AUROC 85.7 +/- 0.9 (Table 3); + containment duration: MAE 36.3 h (Table 6). +reproduction: + reference_code: https://github.com/SongTang-x/SwinLSTM + reference_commit: 4425bcfefbebfac85c9fc6c6659361b8154d5ca3 + reference_license: MIT (code and the released weights in Pretrained/) + reference_config: > + configs.py defaults, which are the Moving-MNIST setting of paper Table 1: SwinLSTM-D, 64x64x1 + frames, patch 2, embedding 128, depths_down [2, 6], depths_up [6, 2], heads [4, 8], window 4, + drop-path rate 0.1, 10 -> 10 frames. Checked with the released weights + Pretrained/trained_model_state_dict (functions.model_forward_multi_layer rollout, single steps + and the segmentation adaptation), with seeded initialisation and a train-mode rollout + (stochastic depth); SwinLSTM-B with the configs.py defaults (depths [12], 2,778,417 + parameters) and the Human3.6m setting (128x128x3, 2,781,747), a two-cell SwinLSTM-B and a + two-level SwinLSTM-D with two input channels, each with seeded initialisation and eval and + train rollouts (functions.model_forward_single_layer / model_forward_multi_layer). + parameter_count: 20191969 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_swinlstm_oracle.py + deviations: + - > + ``patch_size`` must be 2. The reference reconstruction layer (3x3 transposed convolution, + stride 2) restores the input size only for 2x2 patches, so the released code cannot run the + paper's patch-4 settings (KTH, TaxiBJ) either; other patch sizes raise ``ValueError``. + - > + The model's ``forward`` takes the whole sequence ``(batch, T_in, C, H, W)`` and runs the + rollout of the official ``functions.py`` (warm-up, then autoregressive prediction); the + reference model's ``forward`` is one time step, available here as ``step`` with the same + arguments and return values. + - > + The reference SwinLSTM-D constructor passes no dropout or drop-path arguments (dropout 0, + attention dropout 0 and drop-path rate 0.1 are fixed); here they are arguments with those + defaults. Zero initial states take the input's dtype (the reference creates float32 zeros). + - > + ``task="segmentation"`` (SwinLSTMSegmenter) is a PyHazards adaptation, not from + Sim2Real-Fire: the reconstruction layer has one output channel (``out_chans``; every other + parameter has the shape of the forecasting model), the input frames go through the reference + rollout with one prediction step, and that frame is returned before the final sigmoid, as + logits ``(batch, 1, H, W)``. Its state dict keys are those of the forecasting model (no + prefix). +tasks: + - forecasting + - segmentation +example: | + import torch + import torch.nn.functional as F + from pyhazards.models import build_model + + # Official Moving-MNIST SwinLSTM-D: 10 frames of 64x64x1 in [0, 1] -> the next 10 frames. + model = build_model(name="swinlstm", task="forecasting") # 20,191,969 parameters + # Released weights: model.load_state_dict(torch.load("Pretrained/trained_model_state_dict")) + inputs, targets = torch.rand(2, 10, 1, 64, 64), torch.rand(2, 10, 1, 64, 64) + future = model(inputs) # (2, 10, 1, 64, 64) + + # Official training objective: L2 over the 9 warm-up and 10 predicted frames. + outputs = model(inputs, include_warmup=True) # (2, 19, 1, 64, 64) + loss = F.mse_loss(outputs, torch.cat([inputs[:, 1:], targets], dim=1)) + + # PyHazards adaptation: next-day fire-mask logits from 3 daily rasters with 6 channels. + seg = build_model(name="swinlstm", task="segmentation", in_channels=6, img_size=64) + logits = seg(torch.randn(2, 3, 6, 64, 64)) # (2, 1, 64, 64) +notes: + - > + With the official ``depths_up`` [6, 2] the decoder runs 2 Swin blocks at the deepest level and + 6 at the next, because the reference indexes ``depths_up`` (and the head counts) from the + deepest level: the network has 2 + 6 blocks on the way down and 2 + 6 on the way up, where + paper Table 1 lists (2, 6, 6, 2). Decoder cells also take their level's stochastic-depth + rates in reverse block order. Both are kept, since the released weights follow them. + - > + ``Upsample.patch_embed`` is created by the reference but never used in its forward pass; it is + kept (896 parameters) so that the official checkpoint loads with ``strict=True``. + - > + Frames are expected in [0, 1] (pixels / 255 for Moving MNIST); predictions are sigmoid outputs. + Any frame size whose token grid (size / 2) can be halved once per level and split into whole + windows works; Sim2Real-Fire's 256x256 frames give 128, 64 and 32 tokens per side. + - > + Sanity check of the released weights through this port: MSE 18.8 per frame (squared error + summed over the 64x64 pixels, averaged over the 10 predicted frames) on 32 sequences generated + by the official Moving_MNIST class from MNIST digits 10000-13000. The paper reports 17.7 on the + standard Moving MNIST test set, which was not re-evaluated here. +smoke_test: + task: forecasting + build_kwargs: + in_channels: 2 + img_size: 16 + embed_dim: 16 + depths_downsample: [2, 2] + depths_upsample: [2, 2] + num_heads: [2, 4] + window_size: 2 + num_output_frames: 2 + input: + kind: tensor + tensor: + shape: [2, 3, 2, 16, 16] + expected_output: + kind: tensor + shape: [2, 2, 2, 16, 16] diff --git a/pyhazards/model_cards/tcif_fusion.yaml b/pyhazards/model_cards/tcif_fusion.yaml index 1c5a07cd..d979bc87 100644 --- a/pyhazards/model_cards/tcif_fusion.yaml +++ b/pyhazards/model_cards/tcif_fusion.yaml @@ -1,42 +1,139 @@ model_name: tcif_fusion display_name: TCIF-fusion hazard: Tropical Cyclone +catalog_status: core source_file: pyhazards/models/tcif_fusion.py builder_name: tcif_fusion_builder summary: > - A knowledge-guided fusion baseline for tropical cyclone track and intensity forecasting. + The model-knowledge-guided intensity network of Wang, Li and Zheng (2024): 3-D CNN branches with a fusion + branch over ERA5 winds and SST, a VGG-19 on infrared images and storm history give the 24-hour intensity. description: - > - ``tcif_fusion`` combines multiple feature streams behind the shared storm - forecasting interface used throughout the PyHazards cyclone roadmap. + ``tcif_fusion`` predicts one number per storm and time, the maximum sustained wind (2-minute, m/s) + 24 hours ahead, for Northwest Pacific typhoons; it does not forecast tracks. Inputs (a mapping, channels + last as in the official notebook): ERA5 ``u``, ``v``, ``w`` ``(batch, 25, 25, 5, 4)`` - 25 x 25 one-degree + grid, 5 six-hourly times, 200 / 500 / 850 / 1000 hPa - and ``sst`` ``(batch, 25, 25, 5, 1)``; ``all``, the + four fields concatenated to ``(batch, 25, 25, 65)`` (built by ``era5_all`` when absent); ``his``, 30 + history features; ``ir``, GridSat-B1 infrared images ``(batch, 224, 224, 5)``. - > - The adapter focuses on the fusion contract and evaluator compatibility - rather than full reproduction of the original training stack. + Each ERA5 field runs through three 3-D blocks (three 3 x 3 x 5 convolutions with 128 / 256 / 512 filters, + 2 x 2 x 2 max pooling with stride (2, 2, 1)); a fusion branch adds the four fields' features after every + block and runs blocks 2 and 3 on the sums; ALL runs through three 2-D blocks. The flattened maps (212,992 + values) go through Dense 256 and 15, the history through Dense 32 and 64, the IR images through a VGG-19 + (64-128-256-512-512 filters, Dense 1024-1024-15); two residual blocks of three dense layers (256, 128) and a + linear output follow. 299,588,223 parameters (``all_channels=85``, the notebook's graph: 299,611,263). + - > + The model-knowledge (MK) step of the paper is provided as functions: ``model_knowledge_heatmaps`` computes + Grad-CAM heatmaps of a trained model's inputs and ``apply_model_knowledge`` multiplies the inputs by their + absolute values; a second TCIF-fusion trained on the guided inputs is the MK-guided model the paper + evaluates. The benchmark scores the model with ``tc.intensity``. paper: title: Tropical cyclone intensity forecasting using model knowledge guided deep learning model - url: https://doi.org/10.5194/egusphere-2024-250 + url: https://doi.org/10.1088/1748-9326/ad1bde repo_url: https://github.com/wangchong96/TCIF-fusion +references: + - title: "Wang, Li and Zheng, Environmental Research Letters 19, 024006 (2024), open access (CC BY 4.0)" + url: https://doi.org/10.1088/1748-9326/ad1bde + repo_url: https://github.com/wangchong96/TCIF-fusion + note: > + Northwest Pacific, CMA/STI best track 1979-2019 (90 % training, 10 % validation; 20,533 samples + 1979-2021 with ERA5 and GridSat-B1), independent test 2020-2021, 24-hour intensity MAE: MK-guided + TCIF-fusion 3.56 m/s (2020 3.64, 2021 3.51). Input ablation (Table 1, MK-guided): HIS+U+V+W 3.87, + +SST 3.74, +IR 3.69, +IR+SST 3.56 m/s. Official forecasts 2020 / 2021 (Table 2): CMA 4.50 / 4.30, + JMA 4.50 / 4.30, JTWC 4.90 / 4.60, ECMWF-IFS 6.70 / 8.00, NCEP-GFS 4.70 / 5.90 m/s; landfalling TCs 2020 + 4.55 m/s. Not reproduced by PyHazards (no reader for the CMA / ERA5 / GridSat-B1 inputs yet). +reproduction: + source: paper + reference_code: https://github.com/wangchong96/TCIF-fusion + reference_commit: 4b5fafcd8accf288f796d0859f22a7d103f40c24 + reference_license: none (no LICENSE file; the notebooks are used only as a test oracle, never copied) + reference_config: > + TCIF_fusion() of TCIF-fusion.ipynb. The notebooks do not run as published (TensorFlow 1 session code, no + data loading, a validation list with one input too many); the graph functions (F3d, F2d, VGG192d, + TCIF_fusion) are executed unchanged with Keras 3.12.4 on the PyTorch backend. The parameter count of every + layer and the total, 299,611,263, equal the summary the authors' own run printed in + "obtain model knowledge.ipynb" (Keras 2 / TensorFlow 1.14); with the Keras weights copied (layer by layer, + names of that summary) the outputs equal the Keras graph for the notebook's 85-channel ALL input and for the + paper's 65 channels (299,588,223 parameters, the input shape substituted). The training settings equal the + notebook's compile / fit call, and the gradient the MK example starts from (forecast w.r.t. the SST input, + averaged over the batch and the horizontal axes) equals the Keras model's. + parameter_count: 299588223 + checks: [parameter_count, state_dict, forward] + oracle_test: tests/oracle/test_tcif_fusion_oracle.py + deviations: + - > + ALL channels: the notebook's graph has an 85-channel ALL input; the paper's Figure 1 draws it as 25 x 25 x + 65, exactly U, V, W (5 times x 4 levels each) and SST (5 times) concatenated, and the notebook's MK example + allocates 65 channels. The default follows the paper (65; ALL = U, V, W, SST flattened over time and level, + time-major - the order is not documented); all_channels=85 rebuilds the notebook graph, whose extra 20 + channels are not described anywhere. + - > + Figure 1 draws a Flatten + Dense(15) per branch and a 90-d concatenation before Dense 256 and 15, and a + single Flatten + Dense(15) after the IR VGG; the notebook concatenates the six flattened maps (212,992 + values) into one Dense(256) -> Dense(15) and gives the VGG Dense 1024-1024-15. The notebook (which the + printed summary confirms) is followed. + - > + Initialisation has Keras' distributions (glorot-uniform kernels, zero biases; checked) but not its random + draws, which come from TensorFlow's generator. No trained weights were released (the notebook saves + ./CMA/TCIF-fusion-best-uvwssthsat-1.h5, which is not in the repository); load_keras_weights maps such a + file's layers by their names. + - > + Model knowledge: the paper multiplies the inputs by the absolute Grad-CAM heatmaps of a first model; the + notebook's example only takes the gradient w.r.t. one input (SST), averages it over the batch and the + horizontal axes and then stores the raw input (it also passes the SST array as the IR input). PyHazards + completes the Grad-CAM recipe the example follows (heatmap = channel mean of the input weighted by the + averaged gradient), applies no normalisation (none is described), guides U, V, W, SST and IR (the inputs of + the paper's Figure 2), rebuilds ALL from the guided fields and leaves the history unchanged. + - > + Training is not part of the module: the notebook uses the MAE loss, Adam (learning rate 1e-4), batch 512, + 100 epochs, ReduceLROnPlateau (factor 0.5, patience 10, minimum 1e-6) and keeps the best validation + checkpoint (TCIF_TRAINING). The input-ablation models of Table 1 (TCIF-1 to TCIF-3) are not provided, and + the notebook's unused (and broken) attention helpers are not ported. tasks: - regression example: | import torch from pyhazards.models import build_model + from pyhazards.models.tcif_fusion import apply_model_knowledge, model_knowledge_heatmaps + + model = build_model(name="tcif_fusion", task="regression") # 299,588,223 parameters (about 1.2 GB) + inputs = { + "u": torch.randn(1, 25, 25, 5, 4), "v": torch.randn(1, 25, 25, 5, 4), "w": torch.randn(1, 25, 25, 5, 4), + "sst": torch.rand(1, 25, 25, 5, 1), # ALL (25, 25, 65) is built from these + "his": torch.rand(1, 30), + "ir": torch.rand(1, 224, 224, 5), + } + print(model(inputs).shape) # (1, 1): 24-hour intensity - model = build_model(name="tcif_fusion", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # MK-guided training: train a first model, then train a second one on the guided inputs. + guided = apply_model_knowledge(inputs, model_knowledge_heatmaps(model, inputs)) notes: - - "Outputs are shared storm forecast trajectories over the configured horizon." + - "The ALL input is not a heat-map input: Figure 1 labels it ALL and builds it from U, V, W and SST (the inventory had read inputs_h as the model-knowledge heatmaps). Model knowledge enters by multiplying the inputs." + - "The 30 history features (left_input; Figure 1: historical wind speed and pressure) are defined only in the paper's supplementary material, which could not be retrieved; the CMA best track, ERA5 and GridSat-B1 crops have no PyHazards reader yet, and tcif_fusion_synthetic gives random inputs in their layout for smoke tests." + - "The full model needs about 1.2 GB for its weights and roughly 10^11 multiply-adds per sample; the size arguments of the builder (grid_size, ir_size, widths, vgg_filters, vgg_fc) only exist to build small copies for smoke tests." smoke_test: task: regression build_kwargs: - input_dim: 8 - horizon: 5 - output_dim: 3 + grid_size: 9 + ir_size: 32 + widths: [4, 8, 8] + vgg_filters: [4, 4, 8, 8, 8] + vgg_fc: 16 input: - kind: tensor - tensor: - shape: [2, 6, 8] + kind: mapping + mapping: + u: + shape: [2, 9, 9, 5, 4] + v: + shape: [2, 9, 9, 5, 4] + w: + shape: [2, 9, 9, 5, 4] + sst: + shape: [2, 9, 9, 5, 1] + his: + shape: [2, 30] + ir: + shape: [2, 32, 32, 5] expected_output: kind: tensor - shape: [2, 5, 3] + shape: [2, 1] diff --git a/pyhazards/model_cards/tcn.yaml b/pyhazards/model_cards/tcn.yaml new file mode 100644 index 00000000..2d66bd1a --- /dev/null +++ b/pyhazards/model_cards/tcn.yaml @@ -0,0 +1,104 @@ +model_name: tcn +display_name: TCN +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/tcn.py +builder_name: tcn_builder +summary: > + Generic temporal convolutional network of Bai et al. (2018): causal dilated residual + convolutions with weight normalisation and a linear head, for per-step feature sequences. +description: + - > + ``tcn`` maps a ``(batch, time, features)`` sequence through residual blocks of two causal + dilated 1D convolutions (dilation ``2 ** i`` at level ``i``), each with weight normalisation, + ReLU and dropout, with a 1x1 convolution on the residual path when the width changes. The + output at step ``t`` only depends on steps up to ``t``. A linear head reads the last time step + (``readout="last"``, sequence classification or regression) or every step + (``readout="sequence"``). + - > + The implementation is a port of ``TemporalConvNet`` / ``TemporalBlock`` / ``Chomp1d`` from + the official locuslab/TCN code with the linear heads of its example tasks. Weight + normalisation uses ``torch.nn.utils.parametrizations.weight_norm`` instead of the deprecated + hook-based ``torch.nn.utils.weight_norm``; the computation and initialisation are identical, + official state dicts load with ``strict=True``, and ``to_official_state_dict`` converts back. + - > + No wildfire study using this network was found. The "TCN" of the WildfireIA benchmark is a + different, non-causal design (see Used In) and is not what this model implements. +paper: + title: "An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling" + url: https://arxiv.org/abs/1803.01271 + repo_url: https://github.com/locuslab/TCN +references: + - title: "A Nationwide Benchmark for Wildfire Initial Attack Failure Prediction with Public Environmental Data (WildfireIA)" + url: https://arxiv.org/abs/2606.15529 + repo_url: https://github.com/LabRAI/WildfireIA + note: > + Not this model. WildfireIA's TCN baseline (train.py TCNClassifier at aba9be9, MIT) has three + non-causal residual blocks (kernel 3 with symmetric padding, dilations 1/2/4, 128 channels, + BatchNorm instead of weight normalisation, no ReLU after the residual sum), mean-pools over + the T=5 daily weather / fire-danger steps and concatenates a static-feature MLP before an + MLP head. Initial-attack failure prediction on 38,128 FPA-FOD fires: AUPRC 50.4 +/- 0.3, + AUROC 83.7 +/- 0.5 (Table 3); containment duration: MAE 36.1 h (Table 6). +reproduction: + reference_code: https://github.com/locuslab/TCN + reference_commit: 2f8c2b817050206397458dfd1f5a25ce8a32fe65 + reference_license: MIT + reference_config: > + Adding problem TCN(2, 1, [30] * 8, kernel_size=7, dropout=0.0) (add_test.py defaults, the + builder defaults here); sequential MNIST TCN(1, 10, [25] * 8, kernel_size=7, dropout=0.05) + in eval and train mode (66,910 parameters); the per-step heads of copy memory + (TCN(1, 10, [10] * 8, kernel_size=8)) and polyphonic music (TCN(88, 88, [150] * 4, + kernel_size=5, dropout=0.25)); causality of TemporalConvNet. + parameter_count: 96001 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_tcn_oracle.py + deviations: + - > + Weight normalisation is ``torch.nn.utils.parametrizations.weight_norm``, so g and v are + stored as ``.parametrizations.weight.original0`` / ``original1`` instead of + ``weight_g`` / ``weight_v``. Official state dicts load unchanged (PyTorch renames the keys + while loading) and ``to_official_state_dict`` gives the official names; outputs are + identical. + - > + ``TCN`` takes ``(batch, time, features)`` and transposes it to the official + ``(batch, channels, length)``; ``TemporalConvNet`` keeps the official layout. + - > + Heads return raw scores: the sequential-MNIST model's ``log_softmax`` and the music model's + ``sigmoid`` (in float64) are left to the loss. + - > + Kernel sizes below 2 raise ValueError at construction; in the official code ``Chomp1d(0)`` + returns an empty sequence and the next convolution raises a RuntimeError. +tasks: + - classification + - regression +example: | + import torch + from pyhazards.models import build_model + + # Event classification from 5 days of 12 weather / fire-danger features. + model = build_model( + name="tcn", task="classification", input_dim=12, out_dim=2, + hidden_dim=32, num_levels=3, kernel_size=2, dropout=0.2, + ) + logits = model(torch.randn(8, 5, 12)) # (batch, days, features) + print(logits.shape) # (8, 2) +notes: + - "As in the official code, init_weights draws N(0, 0.01) into the computed weights of the weight-normalised convolutions, and weight normalisation discards them: those convolutions keep PyTorch's default initialisation, and only the 1x1 residual convolutions (and the head with head_init='normal') are N(0, 0.01). The draws are kept so a seed gives the official parameters." + - "Defaults reproduce the official adding-problem model (input_dim 2, 8 levels x 30 channels, kernel 7, no dropout). Paper Table 2 lists per-task settings of about 70K parameters, e.g. adding problem T=600: hidden_dim=24, num_levels=8, kernel_size=8." + - "The receptive field is 1 + 2 (kernel_size - 1)(2^num_levels - 1) steps (3,061 with the defaults); short wildfire histories need far fewer levels." + - "head_init='default' keeps PyTorch's Linear initialisation, as the official sequential-MNIST and music models do; readout='sequence' returns (batch, time, out_dim)." +smoke_test: + task: classification + build_kwargs: + input_dim: 6 + out_dim: 2 + hidden_dim: 8 + num_levels: 3 + kernel_size: 2 + input: + kind: tensor + tensor: + shape: [2, 5, 6] + expected_output: + kind: tensor + shape: [2, 2] diff --git a/pyhazards/model_cards/trajgru.yaml b/pyhazards/model_cards/trajgru.yaml new file mode 100644 index 00000000..b2865228 --- /dev/null +++ b/pyhazards/model_cards/trajgru.yaml @@ -0,0 +1,145 @@ +model_name: trajgru +display_name: TrajGRU +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/trajgru.py +builder_name: trajgru_builder +summary: > + Trajectory GRU encoder-forecaster for precipitation nowcasting (Shi et al., NeurIPS 2017): a + frames-to-frames forecaster whose recurrent connections follow learned flow fields, ported from + the official MXNet code with its HKO-7 and MovingMNIST++ weights. +description: + - > + TrajGRU replaces the fixed state-to-state convolution of ConvGRU with L learned links: a small + convolutional network predicts L flow fields from the current input and the previous state, the + state is bilinearly warped along each field, and a 1x1 convolution mixes the warped copies into + the reset gate, update gate and candidate. ``trajgru`` is the paper's encoder-forecaster: each + frame (with x/y coordinates and a constant channel appended) is embedded by a strided + convolution and encoded by three RNN blocks joined by strided convolutions; the forecaster + blocks start from the encoder's final states, the top one runs without input, transposed + convolutions pass outputs down, and a transposed convolution, a 3x3 convolution and a 1x1 + convolution produce each frame. Activations are leaky ReLUs (slope 0.2). + - > + ``config="hko7"`` (default) is the HKO-7 benchmark model (480x480 radar maps, 5 -> 20 frames, + blocks of 64 / 192 / 192 channels with 13 / 13 / 9 links); ``config="movingmnist"`` is the + TrajGRU-L13 of the MovingMNIST++ experiments (64x64, 10 -> 10, 64 / 96 / 96 channels, 13 links). + ``layer_type="ConvGRU"`` gives the paper's ConvGRU baseline in the same encoder-forecaster. + Parameter names map one-to-one to the MXNet names, so the released checkpoints load with + ``load_hko7_params``, and outputs match the official code on them. + - > + No wildfire study using TrajGRU was found. Its inventory entry had been merged with the Conv-GRU + baseline of FireCastNet, which is a different model (``convgru``); WildfireIA names TrajGRU only + among spatiotemporal templates in its related work. It is offered as a sequence architecture + for fire-spread rasters; ``task="segmentation"`` is a PyHazards adaptation for next-step fire + masks. +paper: + title: "Deep Learning for Precipitation Nowcasting: A Benchmark and A New Model" + url: https://arxiv.org/abs/1706.03458 + repo_url: https://github.com/sxjscience/HKO-7 +reproduction: + reference_code: https://github.com/sxjscience/HKO-7 + reference_commit: 57b987bd893bd6910996494c247359ace371d333 + reference_license: MIT (code and released checkpoints) + reference_config: > + The official encoder and forecaster networks, built by encoder_forecaster_build_networks from + the official configuration files and run on MXNet 1.9.1: HKO-7 TrajGRU + (trajgru_55_55_33_1_64_1_192_1_192_13_13_9_b4.yml) and ConvGRU with their released checkpoints + (480x480, 5 -> 20 frames); the seven MovingMNIST++ models of paper Table 1 (TrajGRU L5 / L9 / + L13 / L17, ConvGRU K3-D2 / K5 / K7) with their released checkpoints (64x64, 10 -> 10); parameter + names and shapes of all nine; random non-zero flow layers; stacked cells (encoder); + encoder states carried over between batches; the warp against MXNet's GridGenerator and + BilinearSampler; and the initialisation scheme. + parameter_count: 12150053 + checks: [parameter_count, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_trajgru_oracle.py + deviations: + - > + The reference is symbolic MXNet code that its authors tested on MXNet 0.12. It was run on + MXNet 1.9.1, the last release of the retired project, not on 0.12. + - > + Initial weights cannot match for a seed, since MXNet and PyTorch draw different random + numbers. The port applies the reference scheme (``MSRAPrelu(slope=0.2)``: Gaussian weights + with std ``sqrt(2 / 1.04 / fan_avg)``, zero biases, zero flow output layers so that every + link starts as the identity warp), which the oracle test compares by distribution. + - > + Inputs are ``(batch, T, C, H, W)`` and outputs ``(batch, T_out, out_channels, H, W)``; the + reference uses ``(T, batch, ...)``. ``in_channels`` and ``out_channels`` (1 and 1 in the + reference) are arguments. + - > + Not ported: the dynamic-filter (DFN) output of the ConvGRU-K5-DFN MovingMNIST++ experiment, + zoneout and the GAN blocks (``dbrnn``), none of which a TrajGRU configuration or released + checkpoint uses. + - > + Several cells per block (``stack_num`` > 1, with residual connections and reversed + forecaster states) follow the reference code, but only the encoder could be checked: the + reference forecaster fails to bind such networks on MXNet 1.9.1. Every released + configuration uses one cell per block. + - > + Frame sizes must let the decoder restore every encoder feature map (480x480 for ``hko7``, + multiples of 4 for ``movingmnist``); other sizes raise a ``ValueError`` that names the + mismatch, where the reference fails in shape inference. + - > + ``task="segmentation"`` (TrajGRUSegmenter) is a PyHazards adaptation, not from any wildfire + paper: the encoder-forecaster predicts one frame and its linear output is returned as logits + ``(batch, out_channels, H, W)``. Its state dict keys are those of the forecasting model. +tasks: + - forecasting + - segmentation +example: | + import torch + from pyhazards.models import build_model + from pyhazards.models.trajgru import load_hko7_params + + # HKO-7 TrajGRU: 5 radar frames of 480x480 (pixel / 255) -> the next 20 frames. + model = build_model(name="trajgru", task="forecasting") # 12,150,053 parameters + # Released checkpoints (MXNet .params), e.g. with mxnet installed: + # params = {**mx.nd.load("encoder_net-79999.params"), **mx.nd.load("forecaster_net-79999.params")} + # load_hko7_params(model, params) + future = model(torch.rand(1, 5, 1, 480, 480)) # (1, 20, 1, 480, 480) + + # MovingMNIST++ TrajGRU-L13 (64x64, 10 -> 10) and the paper's ConvGRU baseline. + l13 = build_model(name="trajgru", task="forecasting", config="movingmnist") # 4,000,397 + convgru = build_model(name="trajgru", task="forecasting", config="movingmnist", + layer_type="ConvGRU", h2h_kernel=5) # 4,767,505 + + # PyHazards adaptation: next-day fire-mask logits from 5 daily 64x64 rasters with 6 channels. + seg = build_model(name="trajgru", task="segmentation", config="movingmnist", in_channels=6) + logits = seg(torch.randn(2, 5, 6, 64, 64)) # (2, 1, 64, 64) +notes: + - > + Paper Table 1 lists the MovingMNIST++ parameter counts. The code reproduces 3.42M (Traj-L9), + 4.00M (Traj-L13), 4.77M (Conv-K5-D1) and 8.01M (Conv-K7-D1); it gives 2.60M for Conv-K3-D2 + and 2.84M for Traj-L5, the two values swapped in the table, and 4.58M for Traj-L17, which the + table lists as 4.77M. + - > + Warp direction: the code samples the previous state at the position minus the flow + (``GridGenerator(-flow)``), the paper's Eq. 5 at the position plus the flow. The flows are + learned, so the two only differ in the sign of the flow layer; the port follows the code, which + the released weights need. + - > + The model appends normalised x and y coordinates and a channel of ones to every frame (the + reference ``_pre_encode_frame``), so ``econv1`` sees ``in_channels + 3`` channels. The + reference feeds pixel values / 255; outputs have no activation. + - > + Training (outside the model): HKO-7 uses balanced MSE + MAE weighted by rain-rate thresholds + and masks, Adam (lr 1e-4, beta1 0.5), gradient clipping 50, batch 4, 100k iterations; + MovingMNIST++ uses MSE, clipping 1 and 200k iterations. The MovingMNIST++ script resets the + encoder states once and then starts every batch from the previous batch's final encoder states; + ``forward(x, initial_states=..., return_states=True)`` reproduces this (checked against the + reference). +smoke_test: + task: forecasting + build_kwargs: + config: movingmnist + num_filter: [8, 12, 12] + L: 3 + first_conv: [4, 3, 1, 1] + last_deconv: [4, 3, 1, 1] + num_output_frames: 2 + input: + kind: tensor + tensor: + shape: [2, 3, 1, 16, 16] + expected_output: + kind: tensor + shape: [2, 2, 1, 16, 16] diff --git a/pyhazards/model_cards/tropicalcyclone_mlp.yaml b/pyhazards/model_cards/tropicalcyclone_mlp.yaml index 98cb3f09..9cf7806b 100644 --- a/pyhazards/model_cards/tropicalcyclone_mlp.yaml +++ b/pyhazards/model_cards/tropicalcyclone_mlp.yaml @@ -1,43 +1,96 @@ model_name: tropicalcyclone_mlp display_name: Tropical Cyclone MLP hazard: Tropical Cyclone +catalog_status: core source_file: pyhazards/models/tropicalcyclone_mlp.py builder_name: tropicalcyclone_mlp_builder summary: > - A compact MLP baseline for hurricane track and intensity forecasting. + The 24-hour intensity-change MLP of Xu et al. (2021): 121 SHIPS predictors -> two hidden layers + of 2048 units (sigmoid, ReLU) -> the change of the maximum sustained wind over the next 24 hours. description: - > - ``tropicalcyclone_mlp`` complements ``hurricast`` with a lighter-weight - hurricane baseline that uses the same storm-history input contract. + ``tropicalcyclone_mlp`` is the operational 24-hour intensity model of Xu et al. (Weather and + Forecasting 2021). It maps one forecast time's 121 standardised SHIPS predictors (initial + intensity ``vs0``, 18 GOES PSLV, 21 MTPW and 20 IR00 predictors, 0-24 h averages of the SHIPS + environmental predictors and the 12-hour intensity change ``DELV-12``; the order is + ``SHIPS_PREDICTORS``) to one number, the 24-hour change of the maximum sustained wind + (``dvs24``, knots). It does not forecast tracks. - > - The adapter is useful for practical low-cost intensity and trajectory - experiments in basin-filtered settings. + The network is a port of ``models.mlp`` of the official Keras code (BSD-2-Clause): Dense(2048, + sigmoid) -> Dense(2048, ReLU) -> Dense(1, linear), 4,448,257 parameters, with Keras' default + glorot-uniform kernels and zero biases. Layers are named ``dense``, ``dense_1`` and ``dense_2`` + like the Keras layers, and ``load_keras_weights`` copies a Keras model's ``get_weights()``. + - > + Data: ``ships_xu2021`` reads the authors' predictor table (Zenodo 4784610, CC BY 4.0) and builds + the official leave-one-year-out folds; the benchmark scores it with the ``tc.intensity`` task + (MAE / RMSE in knots, per test year and their mean). paper: title: Deep Learning Experiments for Tropical Cyclone Intensity Forecasts - url: https://doi.org/10.1145/3447548.3467351 + url: https://doi.org/10.1175/WAF-D-20-0104.1 repo_url: https://github.com/wenweixu/tropicalcyclone_MLP +references: + - title: "Xu et al. (2021), Weather and Forecasting 36(4), 1453-1470 (full text: OSTI 1818206)" + url: https://www.osti.gov/biblio/1818206 + repo_url: https://github.com/wenweixu/tropicalcyclone_MLP + note: > + The paper's own evaluation (Table 5), Atlantic basin, 24-hour intensity change: leave-one-year-out + tests on 2010-2018 operational predictors (2,464 six-hourly cases) MAE 8.37 kt, RMSE 11.42 kt, + R2 0.75; independent 2019-2020 test (828 cases) MAE 8.22 kt, RMSE 11.07 kt, R2 0.83. NHC + references on the same cases (2010-18 / 2019-20 MAE): SHIPS 10.42 / 10.51, DSHP 9.37 / 8.69, + LGEM 9.21 / 8.98, HWFI 8.83 / 8.08, OFCL 8.16 / 7.45 kt. Not reproduced by PyHazards. +reproduction: + source: code + reference_code: https://github.com/wenweixu/tropicalcyclone_MLP + reference_commit: 73800596fc824c6d3f150fc41af0bdb7b9c3a7dc + reference_license: BSD-2-Clause (Copyright (c) 2021, Wenwei Xu); ported with the notice kept + reference_config: > + models.mlp(input_shape=(121,)) from the pinned models.py, executed with Keras 3.12.4 on the PyTorch + backend (the original Keras 2.2.4 / TensorFlow 1.12 stack no longer installs; only Adam(lr=) is + mapped to learning_rate=): 4,448,257 parameters, layer activations sigmoid / relu / linear, MAE loss + and Adam 1e-4; the official weights copied into the port give the same outputs (rtol 1e-5) on random + inputs and on real standardised predictors (tests/fixtures/ships_xu2021); the predictor list equals + utils.hand_features. + parameter_count: 4448257 + checks: [parameter_count, state_dict, forward] + oracle_test: tests/oracle/test_tropicalcyclone_mlp_oracle.py + deviations: + - > + Initialisation has Keras' distribution (glorot-uniform kernels, zero biases; checked against the + official model) but not its random draws, which come from TensorFlow's generator; the same seed + does not give the official initial weights. + - > + No trained weights were released, so the paper's numbers are not reproduced. Training is not part of + the module: the official setup is MAE loss, Adam (learning rate 1e-4), batch 32, up to 1000 epochs with + early stopping on a random 10 % validation split (min_delta 0.05 kt, patience 10, best weights + restored), 40 seed pairs (randomseed.bat). + - > + ``hidden_dims`` / ``activations`` can build other widths; only the default (the official 24-hour + model) is checked. The paper's 6-hour model (9 predictors, ReLU layers 128-256-128-256-256, scikit-learn + MLPRegressor) is not in the official repository. tasks: - regression example: | import torch from pyhazards.models import build_model + from pyhazards.models.tropicalcyclone_mlp import SHIPS_PREDICTORS + + model = build_model(name="tropicalcyclone_mlp", task="regression") + predictors = torch.randn(4, len(SHIPS_PREDICTORS)) # standardised SHIPS predictors, official order + print(model(predictors).shape) # (4, 1): 24-hour change of the maximum wind (kt) - model = build_model(name="tropicalcyclone_mlp", task="regression", input_dim=8, history=6) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + # Real data: ships_xu2021 reads train_global_fill_REA_na_wo_img_scaled.csv (Zenodo 4784610). + # from pyhazards.datasets import load_dataset + # fold = load_dataset("ships_xu2021", path="train_global_fill_REA_na_wo_img_scaled.csv", leave_out_year=2018).load() notes: - - "Outputs are lead-time sequences of latitude, longitude, and intensity targets." + - "Inputs must be the standardised predictors of the authors' table (train_global_fill_REA_na_wo_img_scaled.csv, standardised by the reanalysis STD); the operational 2019 / 2020 files of the Zenodo record are not standardised." + - "The official loyo_testing.py reads train_global_fill_REA_na_wo_img_scaled_w2020.csv, which is not in the Zenodo record; ships_xu2021 reads the published train_global_fill_REA_na_wo_img_scaled.csv." + - "The dvs24 targets of the table are in knots but not whole numbers (e.g. 5.004258), as published." smoke_test: task: regression - build_kwargs: - input_dim: 8 - history: 6 - horizon: 5 - output_dim: 3 input: kind: tensor tensor: - shape: [2, 6, 8] + shape: [2, 121] expected_output: kind: tensor - shape: [2, 5, 3] + shape: [2, 1] diff --git a/pyhazards/model_cards/tropicyclonenet.yaml b/pyhazards/model_cards/tropicyclonenet.yaml index e266ac89..4d52ad24 100644 --- a/pyhazards/model_cards/tropicyclonenet.yaml +++ b/pyhazards/model_cards/tropicyclonenet.yaml @@ -1,42 +1,154 @@ model_name: tropicyclonenet display_name: TropiCycloneNet hazard: Tropical Cyclone +catalog_status: core source_file: pyhazards/models/tropicyclonenet.py builder_name: tropicyclonenet_builder summary: > - A GRU plus attention baseline for all-basin tropical cyclone forecasting. + The TCN_M generator of Huang et al. (2025): a multimodal GAN with six decoders that samples + 6- to 24-hour forecasts of position, central pressure and maximum wind from the best track, + 500 hPa geopotential and environmental features; the released checkpoint is verified. description: - > - ``tropicyclonenet`` extends the shared storm benchmark stack beyond the - hurricane-only presets. + ``tropicyclonenet`` is the generator of TropiCycloneNet (Nature Communications 2025). It observes 8 + six-hourly steps (48 h) of a storm: the best-track longitude, latitude, central pressure and maximum + wind (normalised, plus their 6-hourly steps), 500 hPa geopotential crops resized to 64 x 64, and the + TCND Env-Data features (wind, intensity class, motion speed, month, location bins, 12/24-hour motion + direction and 24-hour intensity change). A 3D U-Net extrapolates the geopotential frames, LSTM + encoders combine the track with the frame embeddings, and the Env-T-Net transformer summarises the + environment. - > - The PyHazards adapter keeps a single storm-history to forecast-trajectory - interface so it can share the same evaluator as ``hurricast``. + Six LSTM decoders (generators) roll out the next four steps (6, 12, 18, 24 h) of relative + displacements. A chooser network gives logits over the six decoders; every sample draws a decoder from + them and a 16-d Gaussian noise vector, so the model outputs a set of samples (6 in the paper). The + module keeps the official forward signature and outputs (relative steps, GPH frames, chooser logits, + sampled decoder indices); ``forecast(batch)`` adds the official post-processing (cumulative sum from + the last observation, de-normalisation) and returns latitude / longitude (degrees), pressure (hPa) and + wind (m/s) shaped (storms, samples, 4). ``TrajectoryDiscriminator`` is the paper's discriminator. + - > + Port of the CC BY 4.0 code release (Zenodo 10.5281/zenodo.15024028), with module names unchanged: + 4,767,195 generator and 231,009 discriminator parameters, and the released checkpoint loads with + ``strict=True`` (``load_tropicyclonenet_checkpoint`` checks its sha256 first). Data: + ``tropicyclonenet_dataset`` reads the TCND files in the official loader's layout. + - > + Metric definition: the paper reports, for each lead time, the smallest error among the 6 samples, + taken separately for track distance, pressure and wind (so the three minima can come from different + samples), averaged over storms; the track distance uses 111 km per degree with the longitude + difference scaled by the cosine of the observed latitude. The PyHazards evaluator reports these as + ``best_of_k_*`` (``track_distance: tcn_equirectangular`` gives the paper's distance; the default is + great-circle, which differs by well under 1 % at these distances) and, for comparison with + single-forecast models, the errors of the sample mean. paper: title: Benchmark dataset and deep learning method for global tropical cyclone forecasting - url: https://www.nature.com/articles/s41597-023-02721-x + url: https://doi.org/10.1038/s41467-025-61087-4 repo_url: https://github.com/xiaochengfuhuo/TropiCycloneNet +references: + - title: "Huang et al. (2025), Nature Communications 16, 5923, Table 4" + url: https://doi.org/10.1038/s41467-025-61087-4 + repo_url: https://github.com/xiaochengfuhuo/TropiCycloneNet-Dataset + note: > + The paper's own evaluation on TCND (trained on all six basins, 1950-2016; test 2017-2021): Western + Pacific best-of-6 track error 22.98 / 43.83 / 66.41 / 93.76 km and wind error 0.72 / 1.09 / 1.43 / 1.75 + m/s at 6 / 12 / 18 / 24 h. Against agency forecasts (12 h / 24 h): North Atlantic 41.79 / 98.22 km and + 1.35 / 2.14 m/s (NHC OFCL 39.11 / 58.97 km, 2.97 / 4.42 m/s); Eastern Pacific 29.58 / 70.63 km and + 1.22 / 1.97 m/s; Western Pacific 43.83 / 93.76 km (CMA 52.27 / 74.18 km). TCN_M's numbers are + best-of-6 errors, the agencies' are single deterministic forecasts. Whether the released 16,000-iteration + checkpoint is the one behind Table 4 is not stated; not reproduced by PyHazards. +reproduction: + source: code + reference_code: https://github.com/xiaochengfuhuo/TropiCycloneNet + reference_commit: de9cf0e949bdee6e32cadf2605063b7bc6d33115 + reference_license: >- + CC BY 4.0 (Zenodo 10.5281/zenodo.15024028, TropiCycloneNet.zip git b4e7101, whose TCNM/*.py are identical + to the pinned GitHub commit up to line endings; the GitHub repository itself has no LICENSE file). + Checkpoint checkpoint_with_model_16000.pt: CC BY 4.0, sha256 + 68575d1d10fcd2d44eba2d54d0625410f5108cd3bf5d7b3e15df7491ba9f6215. + reference_config: > + TrajectoryGenerator / TrajectoryDiscriminator with the checkpoint's args (obs_len 8, pred_len 4, + embedding_dim 32, encoder/decoder h_dim 64, mlp_dim 128, noise_dim (16,), gaussian, noise_mix_type ped, + no pooling, pool_every_timestep False, bottleneck_dim 16, batch_norm 0, discriminator h_dim 128), + run on the CPU (its .cuda() calls redirected): parameter counts and seeded initial weights equal; the + released g_state / d_state load with strict=True; with the same seed the all-decoder outputs, GPH + frames, chooser logits, sampled decoder indices and discriminator scores are equal in eval mode, and + the all-decoder outputs and BatchNorm statistics in train mode; with official_sample_loop=True the + sampled forward pass is equal too; forecast() equals relative_to_abs + toNE; the best-of-k metrics equal + evaluate_model_Me.py's per-lead errors; the TCND reader equals TrajectoryDataset + seq_collate. + parameter_count: 4767195 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_tropicyclonenet_oracle.py + deviations: + - > + Sampling loop: for each sample the official forward visits decoder indices 0 .. (number of distinct + sampled indices - 1) instead of the distinct indices themselves, so storms whose sampled decoder is + not visited keep the placeholder value 1 for every step (a 1-unit normalised step = 5 degrees of + longitude, 50 hPa, 25 m/s); with the evaluation batch of 96 storms this is rare, with small batches + common. PyHazards visits the sampled decoders by default; ``official_sample_loop=True`` reproduces the + released code exactly (oracle-tested). + - > + Device-agnostic: the official code calls .cuda() for hidden states and noise; the port allocates them + on the input's device. Noise is still drawn from the CPU generator and moved, as the official + torch.randn(...).cuda() does, so seeds give the same noise. The sampled decoder indices are returned as + a tensor instead of a numpy array. + - > + ``pooling_type`` other than None and ``obs_len`` / ``pred_len`` other than 8 / 4 raise ValueError: the + official social-pooling branches are empty (the forward would fail on mismatched sizes), and the GPH + U-Net's output length (an 18-step temporal kernel over 28 stacked frames) only fits 8 + 4 steps. + - > + ``forward`` also takes a dict (``obs_traj``, ``obs_traj_rel``, ``image_obs``, ``env_data`` or the nine + Env-Data keys at the top level, optional ``seq_start_end``, which defaults to one storm per sequence); + ``user_noise`` is honoured with ``all_g_out=True`` (the official forward ignores it). + - > + Training (GAN losses, best-of-k variety loss, chooser training) is not part of the module. tasks: - regression example: | import torch - from pyhazards.models import build_model + from pyhazards.datasets.tc import synthetic_tcnd_batch + from pyhazards.models import build_model, load_tropicyclonenet_checkpoint - model = build_model(name="tropicyclonenet", task="regression", input_dim=8, horizon=5) - preds = model(torch.randn(2, 6, 8)) - print(preds.shape) + model = build_model(name="tropicyclonenet", task="regression").eval() + # model = load_tropicyclonenet_checkpoint("checkpoint_with_model_16000.pt").eval() # Zenodo 15024028 + batch = synthetic_tcnd_batch(2)["inputs"] # TCND layout; real data: load_dataset("tropicyclonenet_dataset", root=...) + with torch.no_grad(): + forecast = model.forecast(batch, num_samples=6) + print(forecast["lat"].shape, forecast["wind"].shape) # (2, 6, 4): storms, samples, 6-24 h notes: - - "Outputs are lead-time sequences of latitude, longitude, and intensity targets." + - "Inputs follow the TCND normalisation: lon = 5 x + 180 (degrees east), lat = 5 y, pressure = 50 p + 960 (hPa), wind = 25 w + 40 (m/s, 2-minute mean); GPH frames are 500 hPa geopotential resized to 64 x 64 and scaled with the range (44490.578125, 58768.4486860389)." + - "Unused official modules are kept so the checkpoint loads: a second Env-T-Net (env_net), the time_embedding layers of the encoders and decoders." + - "The released checkpoint (55.7 MB, CC BY 4.0) is downloaded by the user or the oracle workflow and never bundled; its g_state equals g_best_state, and the official evaluation script loads g_state." smoke_test: task: regression - build_kwargs: - input_dim: 8 - horizon: 5 - output_dim: 3 input: - kind: tensor - tensor: - shape: [2, 6, 8] + kind: mapping + mapping: + obs_traj: + shape: [8, 2, 4] + obs_traj_rel: + shape: [8, 2, 4] + image_obs: + shape: [2, 1, 8, 64, 64] + wind: + shape: [2, 8, 1] + intensity_class: + shape: [2, 8, 6] + move_velocity: + shape: [2, 8, 1] + month: + shape: [2, 8, 12] + location_long: + shape: [2, 8, 36] + location_lat: + shape: [2, 8, 12] + history_direction12: + shape: [2, 8, 8] + history_direction24: + shape: [2, 8, 8] + history_inte_change24: + shape: [2, 8, 4] expected_output: - kind: tensor - shape: [2, 5, 3] + kind: sequence + shapes: + - [4, 1, 2, 4] + - [2, 1, 12, 64, 64] + - [2, 6] + - [2, 1] diff --git a/pyhazards/model_cards/ts_satfire.yaml b/pyhazards/model_cards/ts_satfire.yaml new file mode 100644 index 00000000..1be5f36d --- /dev/null +++ b/pyhazards/model_cards/ts_satfire.yaml @@ -0,0 +1,94 @@ +model_name: ts_satfire +display_name: TS-SatFire Baselines +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/ts_satfire.py +builder_name: ts_satfire_builder +summary: > + The four spatio-temporal TS-SatFire prediction baselines (U-Net-3D, Attention-U-Net-3D, + UNETR-3D, SwinUNETR-3D) with the benchmark's own configurations. +description: + - > + ``ts_satfire`` builds one of the next-day wildfire progression baselines of the TS-SatFire + dataset, configured as in its prediction script. TS-SatFire is a dataset paper; its + prediction baselines are MONAI networks run in 3D over (time, height, width). + ``baseline`` selects ``unet3d``, ``attention_unet3d``, ``unetr3d`` or ``swinunetr3d`` + (default; the model behind the paper's seed and time-length studies). + - > + Each architecture is also available on its own (``unet3d``, ``attention_unet``, ``unetr``, + ``swin_unetr``) with configurable hyperparameters; this entry fixes them to the TS-SatFire + values. The input is ``(batch, T, 43, 256, 256)``: 27 VIIRS, weather, forecast, topography and + fuel bands with the 17-class land cover one-hot encoded in place, over T in {2, 4, 6} days. The + two-class logits are averaged over time to ``(batch, 2, 256, 256)``, as in the script. +paper: + title: "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction" + url: https://doi.org/10.1038/s41597-025-06271-3 + repo_url: https://github.com/zhaoyutim/TS-SatFire +reproduction: + reference_code: https://github.com/zhaoyutim/TS-SatFire + reference_commit: da7573219967edfe17e317310b66fd8a913f4a2e + reference_license: none (no LICENSE file; used only as a test oracle; the networks are ported from MONAI 1.3.2, Apache-2.0) + reference_config: > + run_spatial_temp_model_pred.py with n_channel 43, two classes and T days: UNet and AttentionUnet + (spatial_dims=3, channels (64, 128, 256, 512, 1024), strides (1, 2, 2)), UNETR (img_size + (T, 256, 256), patch (1, 16, 16), feature size 16, hidden 384, MLP 1536, batch norm) and + SwinUNETR (patch (1, 2, 2), window (T, 4, 4), feature size 36 (-ed), 3 heads per stage (-nh), + batch norm, attn_version "v1") from the repository's spatial_models, outputs averaged over time. + Parameter counts at T = 6, 256x256 (unet3d 31,712,970, attention_unet3d 94,555,506, unetr3d + 28,816,866, swinunetr3d 33,191,942; Table 3: 31.7M, 94.5M, 34.8M, 33.2M); names, seeded + initialisation and eval / train-mode outputs at T = 2 on 32x32 tiles for CPU speed. + parameter_count: 33191942 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_ts_satfire_oracle.py + deviations: + - > + The released prediction script cannot build ``unetr3d``: it reads an undefined + ``args.unetr_version`` and passes ``kernel_size_up_down=(1, 2, 2)``, which the released + unetr.py does not accept (it hard-codes that value). The preset builds the released file's + network with the script's default widths (hidden 384, MLP 1536, as in the paper text); + ``unetr_version="v0"`` gives the script's alternative 768 / 3072. + - > + UNETR feature size: the script uses 16, the paper text says 36 was picked for UNETR and + SwinUNETR; the preset follows the script (``feature_size`` overrides it). Table 3's 34.8M for + UNETR-3D is the 8-channel AF/BA configuration with feature size 36 (34,806,506 parameters), + not the prediction model (28,816,866; 38,282,426 with feature size 36). + - > + SwinUNETR's heads per stage (the script's ``-nh``) are not published; the preset uses 3 + (``num_heads``). Any of 3, 4, 6 or 12 gives Table 3's 33.2M. + - > + TS-SatFire averages the logits over time in its training loop; here that read-out is part + of the model (``time_reduction="mean"``), which also takes ``(batch, T, channels, H, W)`` + instead of ``(batch, channels, T, H, W)``. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # SwinUNETR-3D, the paper's reference prediction model, for 6 days of 43 channels. + model = build_model(name="ts_satfire", task="segmentation", baseline="swinunetr3d", history=6) + logits = model(torch.randn(1, 6, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) + + # The other baselines: "unet3d", "attention_unet3d", "unetr3d". + unet = build_model(name="ts_satfire", task="segmentation", baseline="unet3d", history=4) +notes: + - "Paper Table 3 (prediction, 6 days; F1 / IoU): U-Net-3D 0.375 / 0.338, Attention-U-Net-3D 0.354 / 0.312, UNETR-3D 0.371 / 0.336, SwinUNETR-3D 0.374 / 0.331. Table 4 (SwinUNETR-3D, seeds 42-44): F1 0.371 +/- 0.003, IoU 0.332 +/- 0.003." + - "Paper training for prediction: Dice + weighted cross-entropy (1:1, class weights [1, 446.78]) with learning rate 0.001 and batch 64 (U-Net-3D), 4 (UNETR-3D) or 8 (SwinUNETR-3D); Dice loss, learning rate 0.0012 and batch 8 for Attention-U-Net-3D. The released script uses MONAI's DiceLoss(sigmoid=True) with Adam for all four." + - "UNETR-3D and SwinUNETR-3D are built for exactly (history, image_size, image_size); the U-Nets need height and width divisible by 16." + - "The two output channels are the not-burning / burning one-hot target of TS-SatFire's FireDataset; the script scores channel 1 after a sigmoid and a 0.5 threshold." +smoke_test: + task: segmentation + build_kwargs: + baseline: swinunetr3d + in_channels: 4 + history: 2 + image_size: 32 + feature_size: 12 + input: + kind: tensor + tensor: + shape: [2, 2, 4, 32, 32] + expected_output: + kind: tensor + shape: [2, 2, 32, 32] diff --git a/pyhazards/model_cards/unet.yaml b/pyhazards/model_cards/unet.yaml new file mode 100644 index 00000000..b89d1c31 --- /dev/null +++ b/pyhazards/model_cards/unet.yaml @@ -0,0 +1,103 @@ +model_name: unet +display_name: U-Net +hazard: Wildfire +catalog_status: variant +source_file: pyhazards/models/unet.py +builder_name: unet_builder +summary: > + The original U-Net of Ronneberger et al. (MICCAI 2015): a contracting and an expansive path of + unpadded 3x3 convolutions joined by centre-cropped skip connections, without batch normalisation. +description: + - > + ``unet`` rebuilds the network of the paper's Fig. 1: four 2x2 max-pooling steps and four 2x2 + up-convolutions, 64-128-256-512-1024 channels, two unpadded 3x3 convolutions with ReLU per + level, concatenation of each up-sampled map with the centre-cropped feature map of the same + level, a final 1x1 convolution, dropout (p = 0.5) at the end of the contracting path and the + paper's Gaussian initialisation with standard deviation sqrt(2/N). It has 31,030,658 + parameters for one input channel and two classes. + - > + The paper's valid convolutions make the output smaller than the input (572 x 572 -> 388 x 388); + the paper tiles large images with mirrored borders (overlap-tile). ``unet_output_size`` and + ``unet_input_size`` in ``pyhazards.models.unet`` give the sizes, and valid inputs are + 16k + 60 pixels (k >= 8). ``padding="same"`` zero-pads the 3x3 convolutions so the output keeps + the input size, for fixed-size wildfire tiles; that is a PyHazards option, not the paper's network. + - > + The authors released a Caffe network without a license, so nothing was copied from it. It is + used as a test oracle: ``variant="phseg_v5"`` builds the released network (a ReLU after each + up-convolution, 128 output channels in the last up-convolution, 31,100,354 parameters), its + trained weights load with ``strict=True`` under the Caffe layer names, and the outputs match + the release run through OpenCV's Caffe importer. The release also fixed the details the paper + leaves open (concatenation order, centred crop, dropout placement, up-convolution initialisation). + - > + No wildfire study in the PyHazards inventory used this network. WildfireSpreadTS's U-Net is + segmentation_models_pytorch's ResNet-18 U-Net (``resnet18_unet``), TS-SatFire's is MONAI's + residual-unit UNet (ported separately as ``unet3d``), and Shadrin et al. (2024) cite Ronneberger + et al. for a ResNet-18 U-Net with three encoder stages. ``unet`` is the reference architecture. +paper: + title: "U-Net: Convolutional Networks for Biomedical Image Segmentation" + url: https://arxiv.org/abs/1505.04597 + repo_url: https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/ +reproduction: + source: paper + reference_code: https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/u-net-release-2015-10-02.tar.gz + reference_commit: u-net-release-2015-10-02 + reference_license: no license stated; fetched at test time only, nothing copied + reference_config: > + Paper Fig. 1 and Sections 2-3: 1 input channel, 2 classes, 572 x 572 input -> 388 x 388 output, + feature maps 568/280/136/64/28 on the contracting path and 52/100/196/388 on the expansive path. + The oracle test checks the released phseg_v5 network (``variant="phseg_v5"``): every layer of + phseg_v5-train.prototxt against the module of the same name, the release's patched Gaussian + weight filler, loading of phseg_v5.caffemodel with strict=True (31,100,354 parameters), and + outputs against OpenCV 4.10's Caffe runtime on a random 572 x 572 tile and on the first + 444 x 892 tile of the release's sample image (max abs difference about 1e-5 for outputs up to 11). + parameter_count: 31030658 + checks: [parameter_count, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_unet_oracle.py + deviations: + - > + The default follows the paper's Fig. 1 where it and the release differ: the release applies a + ReLU after every up-convolution and gives its last up-convolution 128 output channels instead + of 64 (31,100,354 instead of 31,030,658 parameters); ``variant="phseg_v5"`` reproduces it. + - > + Input sizes for which a 2x2 max-pooling would see an odd size raise ValueError: the paper + requires even sizes there (Sec. 2) and the release's tiling script only uses such sizes. On + other sizes the release's Caffe would still run, pooling in ceil mode and cropping with fixed + offsets, so its skip connections would be misaligned by half a pixel. + - > + ``padding="same"`` (zero-padded 3x3 convolutions, input divisible by 16, output size equal to + the input) is a PyHazards option for fixed-size wildfire tiles and is not in the paper. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + from pyhazards.models.unet import unet_input_size, unet_output_size + + # The paper's network: valid convolutions, 572 x 572 tile -> 388 x 388 two-class logits. + model = build_model(name="unet", task="segmentation", in_channels=1, out_channels=2).eval() + print(unet_output_size(572), unet_input_size(388)) # 388 572 + with torch.no_grad(): + print(model(torch.randn(1, 1, 572, 572)).shape) # (1, 2, 388, 388) + + # Same-size output for 64 x 64 wildfire tiles (not the paper's valid convolutions). + tiles = build_model(name="unet", task="segmentation", in_channels=12, out_channels=1, padding="same") + print(tiles(torch.randn(2, 12, 64, 64)).shape) # (2, 1, 64, 64) +notes: + - "Returns logits. The paper's energy function is a pixel-wise softmax with a weighted cross-entropy (class-balancing weights plus a border term with w0 = 10 and sigma = 5 pixels); the weight map depends on instance labels and is not part of the model." + - "Module names follow the Caffe layer names of the release (conv_d0a-b -> conv_d0a_b, upconv_d4c_u3a, ..., conv_u0d-score -> conv_u0d_score). The up-sampled map comes first in each concatenation, then the skip feature." + - "Dropout (p = 0.5, training only) follows the last ReLU of the 512- and 1024-channel levels. As in the release, where it is applied in place, the dropped-out 512-channel map also feeds the skip connection." + - "Weights are drawn from N(0, 2/n) with n the number of weights per output unit and biases start at zero, as in the release's patched Caffe filler. For the 2x2 up-convolutions this is n = 4 x output channels." + - "Training in the paper: SGD with momentum 0.99, one large tile per batch, elastic-deformation augmentation. Reported results: ISBI 2012 EM segmentation warping error 0.000353 and Rand error 0.0382; ISBI 2015 cell tracking IoU 0.9203 (PhC-U373) and 0.7756 (DIC-HeLa)." + - "The model takes (batch, channels, height, width); stack time steps into channels for multi-day wildfire input." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 1 + channels: [4, 8, 16, 32, 64] + input: + kind: tensor + tensor: + shape: [1, 1, 220, 220] + expected_output: + kind: tensor + shape: [1, 2, 36, 36] diff --git a/pyhazards/model_cards/unet3d.yaml b/pyhazards/model_cards/unet3d.yaml new file mode 100644 index 00000000..e3c374ac --- /dev/null +++ b/pyhazards/model_cards/unet3d.yaml @@ -0,0 +1,111 @@ +model_name: unet3d +display_name: U-Net-3D (MONAI) +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/unet3d.py +builder_name: unet3d_builder +summary: > + MONAI's strided-convolution U-Net, configured by default as the TS-SatFire spatio-temporal + (3D) baseline for next-day fire progression. +description: + - > + ``unet3d`` is MONAI's ``UNet``: an encoder-decoder in which each level down-samples with one + strided convolution and up-samples with one strided transposed convolution applied to the + concatenation of the skip feature and the up-sampled deeper feature, each followed by instance + norm, dropout and PReLU. MONAI documents it as the "enhanced" residual U-Net of Kerfoot et al. + (2018); with ``num_res_units > 0`` every unit becomes a residual unit. + - > + TS-SatFire calls it U-Net / U-Net-3D, but with ``num_res_units=0`` (its setting) it is + neither Ronneberger et al.'s U-Net nor Cicek et al.'s 3D U-Net (2016): there is one + convolution per level and side instead of two, no max pooling, no batch norm and no residual + connection. The port follows MONAI 1.3.2 with its parameter names, so MONAI state dicts load + with ``strict=True``. + - > + With the defaults (``spatial_dims=3``) the model is TS-SatFire's U-Net-3D: input + ``(batch, time, channels, H, W)``, 3D convolutions over (time, H, W) with stride (1, 2, 2) at + every level so time is never down-sampled, widths 64-1024, and two-class logits averaged over + time to ``(batch, 2, H, W)``. ``spatial_dims=2`` gives TS-SatFire's single-image U-Net + (stride 2 at every level, input ``(batch, channels, H, W)``). +paper: + title: "Left-Ventricle Quantification Using Residual U-Net" + url: https://doi.org/10.1007/978-3-030-12029-0_40 + repo_url: https://github.com/Project-MONAI/MONAI +references: + - title: "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction" + url: https://doi.org/10.1038/s41597-025-06271-3 + repo_url: https://github.com/zhaoyutim/TS-SatFire + note: > + U-Net-3D from the repository's modified MONAI copy (channels 64-1024, stride (1, 2, 2) at + every level, num_res_units 0) on 256x256 tiles of daily VIIRS and auxiliary data, 43 + channels after the land-cover one-hot for next-day progression prediction, T in {2, 4, 6}, + logits averaged over time; prediction trained with Dice + weighted CE (1:1, class weights + [1, 446.78]), learning rate 0.001, batch 64 (paper text). Paper Table 3 (6 input days; + arXiv 2412.11555): 31.7M parameters, F1 0.748 / 0.834 / 0.375 and IoU 0.628 / 0.746 / 0.338 + on active fire / burned area / prediction. The 2D U-Net (stock MONAI, stride 2) has 10.6M + parameters and F1 0.731 / 0.789 on active fire / burned area. +reproduction: + reference_code: https://github.com/Project-MONAI/MONAI + reference_commit: "1.3.2" + reference_license: Apache-2.0 + reference_config: > + TS-SatFire's UNet(spatial_dims=3, in_channels=43, out_channels=2, + channels=(64, 128, 256, 512, 1024), strides=(1, 2, 2)) from spatial_models/unet.py at da75732 + (MONAI 1.3.2 code whose only change is one stride shared by all levels; the repository has no + license and is used only as a test oracle), with its outputs averaged over time; MONAI 1.3.2 + UNet(spatial_dims=2, in_channels=8, out_channels=2, same channels, strides=(2, 2, 2, 2)) for the + 2D baseline (10,552,458 parameters); and 1D/2D/3D MONAI configurations with residual units, + batch norm, ReLU, dropout, larger kernels and non-uniform per-level strides. Forward passes use + 32x32 (3D, T=2) and 64x64 (2D) inputs instead of 256x256 to keep the CPU test fast. + parameter_count: 31712970 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_unet3d_oracle.py + deviations: + - > + TS-SatFire averages the 3D logits over time in its training script (``outputs.mean(2)``); + here that read-out is part of the model (``time_reduction="mean"``), which also takes + PyHazards' ``(batch, time, channels, H, W)`` layout instead of + ``(batch, channels, time, H, W)``. + - > + Activations and norms are given by name and limited to ``"prelu"`` / ``"relu"`` and + ``"instance"`` / ``"batch"`` (or ``None``); MONAI also accepts other layer names and + ``(name, kwargs)`` tuples. ``dropout`` is a rate (MONAI's default ``dropout_dim=1``). + - > + Configurations the reference rejects late or not at all -- too few strides, even kernel + sizes, spatial sizes not divisible by the stride product (a size-mismatch RuntimeError in + the reference) -- raise ValueError up front. + - > + The paper reports 31.7M parameters for U-Net-3D across all three tasks; the prediction + configuration with 43 input channels has 31,712,970 (31,652,490 with the 8-channel + active-fire / burned-area input). +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # TS-SatFire U-Net-3D prediction model: 43 channels, logits averaged over the input days. + model = build_model(name="unet3d", task="segmentation", in_channels=43) + logits = model(torch.randn(1, 4, 43, 64, 64)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 64, 64) + + # TS-SatFire's single-image 2D U-Net. + model_2d = build_model(name="unet3d", task="segmentation", in_channels=8, spatial_dims=2) + print(model_2d(torch.randn(1, 8, 64, 64)).shape) # (1, 2, 64, 64) +notes: + - "Every spatial size must be divisible by the product of the strides along that dimension: 16 for height and width with the default four levels; time is never down-sampled." + - "The default two output channels follow TS-SatFire (sigmoid Dice loss on both in its released script); use out_channels=1 for a single-logit binary head." + - "time_reduction='none' returns per-date maps (batch, classes, time, H, W), as TS-SatFire uses for its active-fire and burned-area tasks." + - "strides follow MONAI (one entry per level, each an int or one value per dimension); stride_mode='shared' takes TS-SatFire's single strides=(1, 2, 2) literally and builds the same network as strides=[(1, 2, 2)] * 4." + - "The top decoder unit is a bare transposed convolution (no norm or activation), so the output is unnormalised logits, as in MONAI." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 4 + channels: [8, 16, 32] + input: + kind: tensor + tensor: + shape: [2, 3, 4, 16, 16] + expected_output: + kind: tensor + shape: [2, 2, 16, 16] diff --git a/pyhazards/model_cards/unetr.yaml b/pyhazards/model_cards/unetr.yaml new file mode 100644 index 00000000..cc4ecd0e --- /dev/null +++ b/pyhazards/model_cards/unetr.yaml @@ -0,0 +1,114 @@ +model_name: unetr +display_name: UNETR +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/unetr.py +builder_name: unetr_builder +summary: > + Vision-Transformer encoder with a convolutional U-Net decoder (MONAI's UNETR), configured by + default as the TS-SatFire spatio-temporal (3D) baseline for next-day fire progression. +description: + - > + ``unetr`` is UNETR (Hatamizadeh et al., WACV 2022): a 12-layer ViT encodes non-overlapping + patches, and the tokens of layers 3, 6, 9 and 12 are reshaped to feature maps, up-sampled by + transposed convolutions and merged into a convolutional decoder with residual blocks. The + implementation is MONAI's (1.3.2, Apache-2.0; the authors' official code builds on it), ported to plain + PyTorch with MONAI's module names, so MONAI state dicts load with ``strict=True``. + - > + With the defaults (``spatial_dims=3``) the model is TS-SatFire's UNETR-3D: input + ``(batch, time, channels, H, W)`` built for ``img_size = (history, 256, 256)``, patches of + (1, 16, 16) so that tokens never span several days, (1, 2, 2) transposed convolutions, a + (1, 3, 3) kernel in ``decoder3``, feature size 16, hidden size 384, MLP 1536, batch norm, and + two-class logits averaged over time. ``spatial_dims=2`` gives TS-SatFire's UNETR-2D, which is + stock MONAI (patch 16) with the same widths. +paper: + title: "UNETR: Transformers for 3D Medical Image Segmentation" + url: https://arxiv.org/abs/2103.10504 + repo_url: https://github.com/Project-MONAI/research-contributions +references: + - title: "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire Detection and Prediction" + url: https://doi.org/10.1038/s41597-025-06271-3 + repo_url: https://github.com/zhaoyutim/TS-SatFire + note: > + UNETR-3D from the repository's modified MONAI copy (patch (1, 16, 16), (1, 2, 2) + up-sampling, (1, 3, 3) decoder3 kernel) on 256x256 tiles of daily VIIRS and auxiliary data, + 43 channels for next-day progression prediction, T in {2, 4, 6}, logits averaged over time; + prediction trained with Dice + weighted CE (1:1, class weights [1, 446.78]), learning rate + 0.001, batch 4 (paper text). The paper picks feature size 36 for UNETR and SwinUNETR, but + its prediction script builds UNETR-3D with feature size 16. Paper Table 3 (6 input days; + arXiv 2412.11555): 34.8M parameters, F1 0.811 / 0.823 / 0.371 and IoU 0.706 / 0.736 / 0.336 + on active fire / burned area / prediction. UNETR-2D (stock MONAI, hidden 384, MLP 1536, + feature size 16) has 23.52M parameters and F1 0.733 / 0.837 on active fire / burned area. +reproduction: + reference_code: https://github.com/Project-MONAI/MONAI + reference_commit: "1.3.2" + reference_license: Apache-2.0 + reference_config: > + TS-SatFire's UNETR(in_channels=43, out_channels=2, img_size=(T, H, W), spatial_dims=3, + norm_name="batch", feature_size=16, patch_size=(1, 16, 16), hidden_size=384, mlp_dim=1536) + from spatial_models/unetr/unetr.py at da75732 (MONAI 1.3.2 code with a patch_size argument and + hard-coded (1, 2, 2) up-sampling and (1, 3, 3) decoder3 kernel; the repository has no license + and is used only as a test oracle), with its outputs averaged over time, built for + (T, H, W) = (2, 32, 32) for the forward checks and at (6, 256, 256) on the meta device for the + parameter counts (28,816,866 for prediction; 34,806,506 for the 8-channel, feature-size-36 + AF/BA configuration); MONAI 1.3.2 UNETR(spatial_dims=2, in_channels=8, feature_size=16, + hidden_size=384, mlp_dim=1536, norm_name="batch") for the 2D baseline (23,521,186 parameters + at 256x256, forward at 64x64); and 2D/3D MONAI configurations with instance norm, dropout, qkv + bias, perceptron patch embedding, plain blocks and attention-matrix saving. + parameter_count: 28816866 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_unetr_oracle.py + deviations: + - > + The released TS-SatFire unetr.py has no ``kernel_size_up_down`` argument: it hard-codes + (1, 2, 2) for every transposed convolution, while the prediction script passes + ``kernel_size_up_down=(1, 2, 2)`` (and reads an undefined ``args.unetr_version``), so the + script cannot build UNETR-3D as released. Here ``kernel_size_up_down`` is an argument + (MONAI's 2 by default); at (1, 2, 2) it gives the released file's network exactly. + - > + Feature size: the paper says 36 was picked for UNETR and SwinUNETR, the prediction script + uses 16. The defaults follow the prediction script. Table 3's 34.8M is the AF/BA + configuration of the paper text (8 channels, feature size 36, T = 6: 34,806,506 parameters); + the prediction configuration has 28,816,866 (38,282,426 with feature size 36). + - > + TS-SatFire averages the 3D logits over time in its training script; here that read-out is + part of the model (``time_reduction="mean"``), which also takes ``(batch, time, channels, + H, W)`` instead of ``(batch, channels, time, H, W)``. + - > + The ViT classification head (``classification=True``) is not ported because UNETR never + builds it; the deprecated ``pos_embed`` argument is dropped. Inputs must have exactly + ``img_size`` (ValueError; the reference fails with a shape error), and configurations + whose decoder could not return to the input resolution (patch size not equal to + ``kernel_size_up_down ** 4``) raise ValueError up front. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + # TS-SatFire UNETR-3D prediction model for 4 days of 43 channels on 256x256 tiles. + model = build_model(name="unetr", task="segmentation", in_channels=43, history=4) + logits = model(torch.randn(1, 4, 43, 256, 256)) # (batch, days, channels, H, W) + print(logits.shape) # (1, 2, 256, 256) +notes: + - "The position embedding fixes the input size: the model is built for img_size = (history, image_size, image_size) and accepts only that size." + - "Each patch-size entry must equal kernel_size_up_down ** 4 (16 = 2 ** 4 in height and width, 1 = 1 ** 4 in time), so the four up-sampling steps return to the input resolution." + - "Pass hidden_size=768, mlp_dim=3072 for the prediction script's 'v0' widths or MONAI's defaults (also norm_name='instance')." + - "time_reduction='none' returns per-date maps (batch, classes, time, H, W)." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 4 + history: 2 + image_size: 32 + feature_size: 8 + hidden_size: 32 + mlp_dim: 64 + num_heads: 4 + input: + kind: tensor + tensor: + shape: [2, 2, 4, 32, 32] + expected_output: + kind: tensor + shape: [2, 2, 32, 32] diff --git a/pyhazards/model_cards/urbanfloodcast.yaml b/pyhazards/model_cards/urbanfloodcast.yaml index a1a1e033..a9d5f862 100644 --- a/pyhazards/model_cards/urbanfloodcast.yaml +++ b/pyhazards/model_cards/urbanfloodcast.yaml @@ -1,43 +1,104 @@ model_name: urbanfloodcast display_name: UrbanFloodCast hazard: Flood +catalog_status: core source_file: pyhazards/models/urbanfloodcast.py builder_name: urbanfloodcast_builder summary: > - A U-Net style urban inundation baseline for dense-grid flood prediction. + The deep neural operator (DNO) of UrbanFloodCast (Xu et al., J. Hydrology 2025): a U-shaped Fourier + neural operator in space and time that predicts urban water depth and discharge for 24 steps at once. description: - > - ``urbanfloodcast`` adds an urban-focused raster baseline to the PyHazards - inundation benchmark stack. + ``urbanfloodcast`` is the DNO of the paper (DNO-3, the default of the official code): the 5 inputs per + cell and output step (current depth and x / y unit discharge, the rainfall of that step and the + terrain) plus a (y, x, t) grid are lifted to width 10, passed through three U-NO operator blocks + (spectral convolution + point-wise MLP + point-wise linear branch, InstanceNorm, GELU) that go to 3/4 + of the spatial grid, then to twice the time steps, then back to the input grid with concatenated + skips, and projected to depth and the two discharges: ``(batch, Sy, Sx, T, 1, 5)`` -> + ``(batch, Sy, Sx, T, 3)``, all ``T`` (24, i.e. 2 hours) steps in one shot. 4,470,437 parameters + (complex Fourier weights counted once; 8,937,637 real numbers). Like any Fourier operator it accepts + other grid sizes (``Sy, Sx >= 27``, ``T >= 14`` for its fixed modes). - > - The implementation keeps the shared spatiotemporal tensor contract used by - the synthetic inundation smoke dataset. + The official repository has no licence, so the model is written from the paper and from U-NO (BSD-2) + and FNO (MIT) building blocks; parameter names follow the official model, whose state dicts load with + ``strict=True``, and parameters, seeded initialisation, outputs and gradients equal the official code. + - > + Data: :func:`pyhazards.datasets.flood.urbanfloodcast.prepare_urbanfloodcast_event` builds the official + one-shot inputs from an event tensor (checked against the official ``flood_data``). PyHazards does not + read the Berlin benchmark rasters yet (Zenodo 10.5281/zenodo.15700880, 7.3 GB GeoTIFF, CC BY 4.0); + ``urbanfloodcast_synthetic`` generates random events in the same layout. The flood benchmark scores + relative L2, NSE, Pearson r and depth CSI at 1 / 10 / 50 cm as the official test loop does. paper: - title: "UrbanFloodCast: WMO Urban Flooding Forecasting Challenge" - url: https://arxiv.org/abs/2405.21179 + title: "Urban flood modeling and forecasting with deep neural operator and transfer learning" + url: https://doi.org/10.1016/j.jhydrol.2025.133705 repo_url: https://github.com/HydroPML/UrbanFloodCast +references: + - title: "Urban flood modeling and forecasting with deep neural operator and transfer learning" + url: https://doi.org/10.1016/j.jhydrol.2025.133705 + repo_url: https://github.com/HydroPML/UrbanFloodCast + note: > + Xu, De Vos, Shi, Rüther, Bronstert and Zhu, Journal of Hydrology 661:133705 (2025). UrbanFloodCast + benchmark: hydrodynamic simulations of 125 design storms over two areas of Berlin (seen regions / + unseen rainfall events, unseen rainfall distributions, zero-shot downscaling), 24 future 5-minute + steps from the current state. Official training (DNO_main.py): batch 1, 100 epochs, Adam 1e-3 with + weight decay 1e-4, cosine annealing per step, relative L2 loss on the masked outputs. The paper is + paywalled and was not read, so its numbers (and which DNO variant it headlines) are not reproduced. + - title: "U-NO: U-shaped Neural Operators" + url: https://arxiv.org/abs/2204.11127 + repo_url: https://github.com/ashiq24/UNO + note: > + Rahman, Ross and Azizzadenesheli, arXiv:2204.11127 (2022). Source of the operator blocks (integral_operators.py, + BSD-2-Clause) that the DNO extends with a point-wise MLP branch. +reproduction: + source: paper + reference_code: https://github.com/HydroPML/UrbanFloodCast + reference_commit: f08846a1d0ed5a82d9241d2229df8ec8997ebfd5 + reference_license: none (no licence; used only as a test oracle, never vendored) + reference_config: > + DNO/models/DNO.py (DNO-3) as DNO_main.py builds it: DNO(num_channels=5, width=10, initial_step=1, + pad=False, factor=1) after torch.manual_seed(1); inputs (batch, 433, 692, 24, 1, 5) for Berlin, T=24, + strategy oneshot. Data pipeline and metrics: DNO/utils25.py (flood_data, LpLoss, nse, corr, + critical_success_index). + parameter_count: 4470437 + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_urbanfloodcast_oracle.py + deviations: + - > + Only ``pad=0`` (the default) is supported: the official ``--time_pad`` option overwrites the padding + on every call and crops twice the padded length, so the output no longer has T steps and the + official training script fails with it. + - > + The deeper DNO-4 and DNO-5 variants of the repository and the transfer-learning models (fine-tuning + and domain-adaptation TL-DNO with its discriminator) are not provided. + - > + The point-wise branch of each operator block is a 1x1x1 convolution plus trilinear resampling, as in + the DNO; the current U-NO code additionally low-pass filters it. + - > + No official weights were released, so no pretrained checkpoint is checked. tasks: - regression - - segmentation example: | import torch from pyhazards.models import build_model - model = build_model(name="urbanfloodcast", task="regression", in_channels=3, history=4) - preds = model(torch.randn(2, 4, 3, 16, 16)) - print(preds.shape) + model = build_model(name="urbanfloodcast", task="regression") # DNO-3, 4,470,437 parameters + x = torch.randn(1, 32, 32, 24, 1, 5) # (batch, Sy, Sx, T, T_in, depth / qx / qy / rainfall / terrain) + print(model(x).shape) # (1, 32, 32, 24, 3): depth, qx, qy at every future step notes: - - "Outputs are next-horizon inundation depth rasters." + - > + Input quirks of the official pipeline, kept by ``prepare_urbanfloodcast_event``: the terrain is + L2-normalised along the x axis (``F.normalize`` over dimension 1); missing terrain is meant to be set + to ``max + 30`` but ``torch.max`` propagates NaN, so a missing terrain cell turns the whole terrain + channel to NaN (the official TIFF conversion fills the DEM first). + - > + Pearson r of the official evaluation divides the population covariance by the product of sample + standard deviations; the benchmark reproduces it. smoke_test: task: regression - build_kwargs: - in_channels: 3 - history: 4 - base_channels: 32 input: kind: tensor tensor: - shape: [2, 4, 3, 16, 16] + shape: [1, 28, 28, 14, 1, 5] expected_output: kind: tensor - shape: [2, 1, 16, 16] + shape: [1, 28, 28, 14, 3] diff --git a/pyhazards/model_cards/utae.yaml b/pyhazards/model_cards/utae.yaml new file mode 100644 index 00000000..0ba81c30 --- /dev/null +++ b/pyhazards/model_cards/utae.yaml @@ -0,0 +1,74 @@ +model_name: utae +display_name: U-TAE +hazard: Wildfire +catalog_status: core +source_file: pyhazards/models/utae.py +builder_name: utae_builder +summary: > + U-Net whose temporal dimension is collapsed by a lightweight temporal attention encoder, + the strongest WildfireSpreadTS baseline. +description: + - > + ``utae`` encodes every date of a satellite image time series with a shared convolutional + encoder, collapses time at the lowest resolution with a Lightweight Temporal Attention + Encoder (L-TAE), reuses the attention masks to aggregate the skip connections, and decodes + to per-pixel scores (Sainte Fare Garnot & Landrieu, ICCV 2021). + - > + The implementation is a port of the official utae-paps code, which WildfireSpreadTS vendors + unchanged. Parameter names match the reference, so the official PASTIS checkpoints load + with ``strict=True``. Acquisition dates go in ``batch_positions`` (day of year in + WildfireSpreadTS); when omitted, ``0..T-1`` is used. +paper: + title: "Panoptic Segmentation of Satellite Image Time Series with Convolutional Temporal Attention Networks" + url: https://arxiv.org/abs/2107.07933 + repo_url: https://github.com/VSainteuf/utae-paps +references: + - title: "WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction" + url: https://openreview.net/forum?id=RgdGkPRQ03 + repo_url: https://github.com/SebastianGer/WildfireSpreadTS + note: > + Default U-TAE with out_conv (32, 1), 5 days x 40 channels with day-of-year positions, + BCE with positive-class weight, AdamW lr 0.01; best baseline in the paper (test AP 0.372 on + vegetation features). +reproduction: + reference_code: https://github.com/VSainteuf/utae-paps + reference_commit: 987874e27a98bb399277f2d55eb010744d26f881 + reference_license: MIT + reference_config: > + UTAE(input_dim=40, out_conv=[32, 1]) with the remaining defaults (WildfireSpreadTS), and + UTAE(input_dim=10, out_conv=[32, 20]) loaded with the official PASTIS fold-1 weights + (Zenodo 5172293, CC-BY-4.0). + parameter_count: 1099011 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_wildfirespreadts_oracle.py + deviations: + - > + To read the output shape for padded dates, the reference runs each shared encoder block + once more on an all-zero batch. That pass is skipped here; with the default GroupNorm it + has no effect on outputs. +tasks: + - segmentation +example: | + import torch + from pyhazards.models import build_model + + model = build_model(name="utae", task="segmentation", in_channels=40) + x = torch.randn(2, 5, 40, 128, 128) + day_of_year = torch.tensor([[150, 151, 152, 153, 154]] * 2, dtype=torch.float32) + scores = model(x, batch_positions=day_of_year) + print(scores.shape) # (2, 1, 128, 128) +notes: + - "Height and width must be divisible by 8 with the default three down-sampling stages." + - "As in the reference code, the output block ends with BatchNorm and ReLU, so scores are non-negative." + - "Dates whose frame equals pad_value (default 0) everywhere are treated as padding." +smoke_test: + task: segmentation + build_kwargs: + in_channels: 6 + input: + kind: tensor + tensor: + shape: [2, 4, 6, 32, 32] + expected_output: + kind: tensor + shape: [2, 1, 32, 32] diff --git a/pyhazards/model_cards/wavecastnet.yaml b/pyhazards/model_cards/wavecastnet.yaml index c3e4d526..32c86803 100644 --- a/pyhazards/model_cards/wavecastnet.yaml +++ b/pyhazards/model_cards/wavecastnet.yaml @@ -1,63 +1,126 @@ model_name: wavecastnet display_name: WaveCastNet hazard: Earthquake -catalog_status: variant +catalog_status: core source_file: pyhazards/models/wavecastnet.py builder_name: wavecastnet_builder summary: > - A ConvLEM-based sequence-to-sequence model for dense-grid earthquake wavefield - forecasting and early-warning style rollout experiments. + ConvLEM sequence-to-sequence network that forecasts ground-motion wavefields (three velocity components + on a regular grid) for earthquake early warning (Lyu et al., Nat. Commun. 2025), with dense-grid and + sparse-station inputs. description: - > - ``wavecastnet`` is the PyHazards entrypoint for dense-grid earthquake wavefield - forecasting based on the ConvLEM encoder-decoder design described by Lyu et al. (2025). + ``wavecastnet`` maps a wavefield history ``(batch, 3, time, height, width)`` to the next + ``future_seq`` frames ``(batch, 3, future_seq, height, width)``. Every frame is embedded by three + stride-2 ``Conv2d -> BatchNorm2d -> LeakyReLU`` layers (3 -> 36 -> 72 -> 144 channels, grid / 8); + two stacked ConvLEM cells with reset gate and per-pixel peepholes encode the sequence, two more, + started from the encoder states, decode the forecast; each latent frame is reconstructed by a + transposed convolution, ``PixelShuffle(4)`` and a 3x3 convolution. ``variant="sparse"`` + (``AEConvLEM_sparse``) reads the wavefield at station grid points, zeroes a random subset of the + stations (masked-autoencoder training, also applied in evaluation) and embeds the station vector with + two fully connected layers and two convolutions. - > - This implementation focuses on the core dense-grid forecasting path and keeps data - loading outside the model so users can adapt it to their own simulation or sensor pipelines. + It is a port of the official PyTorch code with the official parameter names, creation order and + initialisation. The released dense checkpoint ``best_lem_dense_.pt`` loads with ``strict=True`` + (``pretrained="dense"``) and reproduces the official outputs. As in the official code, the decoder's + first input is uniform random noise in training and evaluation, so forecasts are random: pass + ``generator=torch.Generator().manual_seed(...)`` (or ``decoder_noise=``) to ``forward`` / ``rollout`` + for repeatable outputs. ``rollout`` repeats the forecast on its own output like the official + validation (30 input frames, six calls of 30 frames and one of 15: 101.4 s at 0.52 s per frame). + ``WaveCastNetLoss`` is the official training loss and ``pyhazards.metrics.wavefield`` the official + ACC / RFNE / RMSE. paper: title: Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning url: https://doi.org/10.1038/s41467-025-65435-2 + repo_url: https://github.com/dwlyu/WaveCastNet +references: + - title: "Rapid wavefield forecasting for earthquake early warning via deep sequence to sequence learning (Lyu et al., Nature Communications 16:10622, 2025; arXiv:2405.20516)" + url: https://doi.org/10.1038/s41467-025-65435-2 + repo_url: https://github.com/dwlyu/WaveCastNet + note: > + SW4 viscoelastic simulations (<= 0.5 Hz) of 960 point sources (M < 4.5) on the Hayward fault, X / Y / Z + velocities on a 344 x 224 grid (300 m), 0.26 s sampling, split by epicentre per depth (README: 300 + training, 45 validation, 30 test events). Table 1a, 5.7 s after the onset, ACC / RFNE: dense input + 0.98 / 0.20, sparse input (101 ShakeAlert stations) 0.93 / 0.36. Table 1b (finite-fault ruptures): + M4.5 0.95 / 0.35 down to M7.0 0.53 / 0.86. The data (all_test.npy 16 GB, all_validation.npy 24 GB, + larger training file; shapes (events, 3, 376, 256, 461), cropped to 344 x 224 by the official loader) + are on the authors' Google Drive; PyHazards has no reader for them yet. +reproduction: + reference_code: https://github.com/dwlyu/WaveCastNet + reference_commit: c859e04c85acd6657306f08bce8c6f9129ba1480 + reference_license: MIT (code; Copyright (c) 2023 dwlyu). The Google Drive checkpoints carry no licence statement. + reference_config: > + ``AEConvLEM_dense(dt=1, num_channels=3, num_kernels=144, kernel_size=(3, 3), padding=(1, 1), + activation="tanh", frame_size=(43, 28))`` and ``AEConvLEM_sparse(..., mask_mode=1, mask_ratio=1 - 101/564)`` + from ``src/models_earthquake`` (README and load_pretrained_model.ipynb), ``Huber`` of + ``earthquake_train.py`` and ``Validation_pixel.py``. Dense: 10,093,242 parameters (embedding 209,844, + reconstruction 331,920, four ConvLEM cells of 2,387,808, output convolution 246); sparse with the + 564 stations of filtered_coord.npy: 16,535,430. Checked: names and shapes, seeded initialisation, + outputs in evaluation and training mode (exactly equal), batch-norm statistics and gradients, the + rolling validation forecast, the two cell variants, the released dense checkpoint (strict load, equal + outputs), the released sparse checkpoint (strict load with 558 stations, equal outputs), the loss and + the metrics. + parameter_count: 10093242 + checks: [parameter_count, initialization, state_dict, forward, pretrained_weights] + oracle_test: tests/oracle/test_wavecastnet_oracle.py + deviations: + - > + The released sparse checkpoint ``best_lem_irr_mask_shakealert_.pt`` was trained on 558 stations, but + the repository's ``filtered_coord.npy`` lists 564 (the paper mentions 558), and the 101 ShakeAlert + stations (``shakealert_coords.npy``) are not a subset of them; how they were fed to the model is not in + the released code. The checkpoint therefore cannot be used for real forecasts and is not offered by + ``pretrained``; it is only loaded in the oracle test (with 558 arbitrary stations). + - > + Station masking is one uniform draw per (sample, station) compared with ``mask_ratio`` (the code), not + an exact 80 % without replacement (the paper's wording). ``station_mask=`` replaces the draw. + - > + Without masking (``mask_mode=False``) the official ``Encoder1d`` calls a removed attention layer and + crashes; the port then uses all stations unmasked. + - > + Station coordinates, the grid size and the horizon are constructor arguments instead of hard-coded + NERSC paths and the 344 x 224 grid; the sparse layers scale with the grid (hidden width + ``(H/4)(W/4)/4``); only the official sizes are checked. ``num_kernels`` must equal + ``48 * channels`` as in the official embedding. + - > + The diagnostic ``return_dt`` output (gate histograms) is not ported; outputs are stacked instead of + written into a float32 zero tensor (same values for float32 inputs). + - > + Training is not part of the module: the official script uses Adam (learning rate 5e-4), StepLR (25 + epochs, gamma 0.5), 100 epochs, batch 64, 30-frame inputs and targets subsampled by 2 from 461-step + sequences, the delta-0.2 Huber variant, and keeps the weights with the lowest validation loss. tasks: - - regression + - forecasting example: | import torch from pyhazards.models import build_model - model = build_model( - name="wavecastnet", - task="regression", - in_channels=3, - height=32, - width=24, - temporal_in=6, - temporal_out=4, - hidden_dim=32, - num_layers=1, - dropout=0.0, - ) + # Official dense checkpoint (no licence stated), downloaded and checked by sha256 on first use: + # model = build_model(name="wavecastnet", task="forecasting", pretrained="dense") + model = build_model(name="wavecastnet", task="forecasting", height=64, width=48, future_seq=4).eval() - x = torch.randn(2, 3, 6, 32, 24) - y = model(x) - print(y.shape) + history = torch.randn(1, 3, 6, 64, 48) # (batch, X/Y/Z velocity, time, height, width) + with torch.no_grad(): + forecast = model(history, generator=torch.Generator().manual_seed(0)) # (1, 3, 4, 64, 48) + long = model.rollout(history, 10, generator=torch.Generator().manual_seed(0)) # (1, 3, 10, 64, 48) + print(forecast.shape, long.shape) notes: - - "The PyHazards version currently targets dense-grid forecasting rather than the paper's sparse-sensor variants." - - "The smoke test uses reduced spatial and temporal sizes so it stays CPU-safe in CI." + - "Lyu, Nakata, Ren, Mahoney, Pitarka, Nakata & Erichson, Nature Communications 16:10622 (2025); arXiv:2405.20516. Official code: dwlyu/WaveCastNet (MIT)." + - "Forecasts are random because the decoder starts from uniform noise (official behaviour, also in evaluation); the earthquake.forecasting benchmark passes a seeded generator (param ``seed``)." + - "The official model is tied to its grid: height and width must be multiples of 8 and equal the construction values (per-pixel peepholes on the H/8 x W/8 latent grid)." + - "``WaveCastNetLoss()`` is the training loss of the code (Huber variant with delta 0.2: standard Huber / delta + delta / 2); ``variant='paper'`` gives equation (4) of the paper." + - "WaveCastNet forecasts ground-motion wavefields. It is not related to AEFA (an earthquake-occurrence forecasting dataset) or pyCSEP (tests of earthquake-rate forecasts), which earlier versions of the catalog linked to it." + - "Breaking change: the former builder arguments ``temporal_in``, ``temporal_out``, ``hidden_dim``, ``num_layers`` and ``dropout`` are gone (any input length, horizon ``future_seq``), the task is ``forecasting`` (``regression`` still accepted) and ``ConvLEMCell`` takes ``frame_size`` and uses the official parameter names." smoke_test: - task: regression + task: forecasting build_kwargs: in_channels: 3 - height: 12 - width: 10 - temporal_in: 5 - temporal_out: 4 - hidden_dim: 16 - num_layers: 1 - kernel_size: 3 - dropout: 0.0 + height: 16 + width: 16 + future_seq: 2 input: kind: tensor tensor: - shape: [2, 3, 5, 12, 10] + shape: [1, 3, 3, 16, 16] expected_output: kind: tensor - shape: [2, 3, 4, 12, 10] + shape: [1, 3, 2, 16, 16] diff --git a/pyhazards/model_cards/wildfire_aspp.yaml b/pyhazards/model_cards/wildfire_aspp.yaml index 5bc55cf4..9f645113 100644 --- a/pyhazards/model_cards/wildfire_aspp.yaml +++ b/pyhazards/model_cards/wildfire_aspp.yaml @@ -5,18 +5,31 @@ catalog_status: variant source_file: pyhazards/models/wildfire_aspp.py builder_name: wildfire_aspp_builder summary: > - An explainable CNN segmentation model with an ASPP mechanism for next-day wildfire - spread prediction. + A fully convolutional network with an atrous spatial pyramid of four dilation rates for + next-day wildfire spread on Next Day Wildfire Spread tiles. description: - > - ``wildfire_aspp`` is the backward-compatible public PyHazards entrypoint for the - CNN + ASPP wildfire spread model. + ``wildfire_aspp`` reimplements CNN-ASPP (Marjani et al., IEEE GRSL 2024): two 3x3 + convolutions with 64 and 128 filters, four parallel 3x3 atrous convolutions with 32 filters + and dilation rates 1, 3, 6 and 12, two 3x3 convolutions with 32 filters, batch + normalisation and a 1x1 output convolution, all at full 64x64 resolution with ReLU + activations (paper Section II-C and Fig. 2). - > - PyHazards keeps the alias for compatibility while the implementation delegates to - the native ``wildfire_cnn_aspp`` builder under the hood. + The authors did not release code, so the network is rebuilt from the paper; it has + 274,657 parameters for the 12 Next Day Wildfire Spread input channels. The paper's final + sigmoid is left to the loss, and Keras defaults are used where the paper is silent + (Glorot-uniform initialisation, BatchNorm epsilon 1e-3 and momentum 0.99). paper: - title: Application of Explainable Artificial Intelligence in Predicting Wildfire Spread - url: https://ieeexplore.ieee.org/document/10568207 + title: "Application of Explainable Artificial Intelligence in Predicting Wildfire Spread: An ASPP-Enabled CNN Approach" + url: https://doi.org/10.1109/LGRS.2024.3417624 +references: + - title: "Next Day Wildfire Spread: A Machine Learning Dataset to Predict Wildfire Spreading From Remote-Sensing Data" + url: https://arxiv.org/abs/2112.02447 + note: > + Training and evaluation data in the CNN-ASPP paper (64x64 tiles, 12 channels; 8,616 training + and 685 validation samples), with the Tversky loss (0.7 on false negatives, 0.3 on false + positives), batch size 8, learning rate 4e-4; reported OA 96.46, recall 99.37, precision + 93.51, F1 96.35 (paper Table I). tasks: - segmentation aliases: @@ -24,18 +37,16 @@ aliases: example: | import torch from pyhazards.models import build_model + from pyhazards.models.wildfire_aspp import TverskyLoss - model = build_model( - name="wildfire_aspp", - task="segmentation", - in_channels=12, - ) - - x = torch.randn(2, 12, 64, 64) - logits = model(x) - print(logits.shape) + model = build_model(name="wildfire_aspp", task="segmentation", in_channels=12) + logits = model(torch.randn(2, 12, 64, 64)) + loss = TverskyLoss(alpha=0.3, beta=0.7)(logits, torch.randint(0, 2, (2, 1, 64, 64))) + print(logits.shape, float(loss)) notes: - - "``wildfire_cnn_aspp`` remains available as an alias for the same public model." + - "No reference implementation was released; this is a reimplementation from the paper text and Fig. 2." + - "TverskyLoss weights false positives with alpha and false negatives with beta; the paper's setting is alpha=0.3, beta=0.7." + - "``wildfire_cnn_aspp`` is an alias for the same model." smoke_test: task: segmentation build_kwargs: @@ -47,3 +58,15 @@ smoke_test: expected_output: kind: tensor shape: [2, 1, 16, 16] +reproduction: + source: paper + reference_config: > + Section II-C and Fig. 2 of the paper: 12 x 64 x 64 input, conv 64 and 128, atrous branches + of 32 filters at dilation 1, 3, 6, 12, conv 32, conv 32, BatchNorm, 1x1 conv. + parameter_count: 274657 + deviations: + - "Returns logits; the paper's last layer applies the sigmoid." + - > + The paper does not state the concatenation order of the atrous branches, the padding or + the initialisation; PyHazards concatenates in dilation order 1, 3, 6, 12, uses zero + padding that keeps the 64x64 size (as in Fig. 2), and Keras default initialisation. diff --git a/pyhazards/model_cards/wildfire_forecasting.yaml b/pyhazards/model_cards/wildfire_forecasting.yaml index 258dcd81..811f3321 100644 --- a/pyhazards/model_cards/wildfire_forecasting.yaml +++ b/pyhazards/model_cards/wildfire_forecasting.yaml @@ -5,49 +5,122 @@ catalog_status: core source_file: pyhazards/models/wildfire_forecasting.py builder_name: wildfire_forecasting_builder summary: > - A sequence forecasting baseline for next-window wildfire activity across weekly count features. + The LSTM and ConvLSTM of Kondylatos et al. (2022) that classify next-day wildfire danger of a + 1 km cell from ten days of weather, vegetation, terrain, human and land-cover covariates. description: - > - ``wildfire_forecasting`` is a compact GRU-attention forecaster for weekly wildfire - activity windows. + ``wildfire_forecasting`` builds one of the two deep models of Kondylatos et al. (GRL 2022) + for next-day wildfire danger in Greece and the Eastern Mediterranean. ``variant="lstm"`` + (default) reads the ten-day series of 25 features of one cell, ``(batch, 10, 25)``; + ``variant="convlstm"`` reads the ten-day block of 25 x 25 cells centred on it, + ``(batch, 10, 25, 25, 25)``. Both return ``(batch, 2)`` log-probabilities over + (no fire, fire). - > - The PyHazards implementation targets smoke-testable next-window size-group prediction - through the shared wildfire benchmark flow. + The 25 features per day are 10 dynamic variables (NDVI, day and night land surface + temperature, soil moisture index, and ERA5-Land maximum 2 m temperature, dew point, surface + pressure and wind speed, total precipitation and minimum relative humidity), 5 static + variables (elevation, slope, distance to roads and waterways, population density) and the 10 + Corine Land Cover class fractions, concatenated in that order; static variables and land cover + are repeated over the ten days. + - > + The implementation is a port of ``SimpleLSTM`` and ``SimpleConvLSTM`` from the official code. + Parameter names and initialisation order match the reference, so its state dicts load with + ``strict=True``; ``hidden_size`` defaults to the paper runs (64 for the LSTM, 32 for the + ConvLSTM). The paper's random forest and XGBoost baselines are the separate + ``random_forest`` and ``xgboost`` entries, which read the same daily tensors. paper: - title: Wildfire Danger Prediction and Understanding with Deep Learning + title: "Wildfire Danger Prediction and Understanding With Deep Learning" url: https://doi.org/10.1029/2022GL099368 repo_url: https://github.com/Orion-AI-Lab/wildfire_forecasting +references: + - title: "Wildfire Danger Prediction and Understanding With Deep Learning" + url: https://doi.org/10.1029/2022GL099368 + repo_url: https://github.com/Orion-AI-Lab/wildfire_forecasting + note: > + Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. Daily 1 km datacube + of Greece and the Eastern Mediterranean, 2009-2021 (data sets: Zenodo 6528394); target = cell inside a burned area larger than 30 ha + from a fire that started that day; two negatives per positive, sampled on fire-free days and + stratified by land cover. Train 2009-2018, validation 2019, test 2020 and 2021. Test F1 + (Table 1, 2020 / 2021): LSTM 0.804 / 0.879 (precision 0.861 / 0.904, recall 0.755 / 0.855), + ConvLSTM 0.806 / 0.871 (precision 0.923 / 0.950, recall 0.716 / 0.804); random forest + 0.703 / 0.778 and XGBoost 0.782 / 0.786 for comparison. + - title: "Deep Learning Methods for Daily Wildfire Danger Forecasting" + url: https://arxiv.org/abs/2111.02736 + note: > + Prapas, Kondylatos et al., NeurIPS 2021 workshop paper, the precursor on the same datacube + (train 2009-2018, validation 2019, test 2020). Same LSTM layer sizes (LSTM 64, linear 64-32); + its ConvLSTM had 16 filters and a 16-8 linear head, which this entry does not reproduce. + Test F1 0.751 (LSTM) and 0.714 (ConvLSTM), AUROC 0.920 and 0.926. +reproduction: + reference_code: https://github.com/Orion-AI-Lab/wildfire_forecasting + reference_commit: 2b18bcf194284d56bd4e1774f7d5315db94cba34 + reference_license: MIT + reference_config: > + SimpleLSTM (hidden_size 64, 1 layer, dropout 0.5; 29,652 parameters) and SimpleConvLSTM + (hidden_size 32, 1 layer, dropout 0.5, 25x25 patches; 372,212 parameters) from + wildfire_forecasting/models/modules/fire_modules.py with 10 dynamic + 5 static features and + the 10-d land-cover vector (clc='vec'), as set in configs/experiment/lstm_temporal_cls.yaml and + clstm_spatiotemporal_cls.yaml, which the repository names as the paper's hyperparameters. + The model code is unchanged since the v0.1-alpha release cited by the paper (Zenodo 6524771). + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_wildfire_forecasting_oracle.py + deviations: + - > + The ConvLSTM's first linear layer is sized from ``patch_size`` (default 25) instead of the + hard-coded ``25 // 2``; identical for the paper's 25x25 patches. + - > + Hyperparameters are constructor arguments (``input_dim``, ``hidden_size``, ``lstm_layers``, + ``dropout``) instead of an ``hparams`` dict whose input size is counted from feature-name + lists. + - > + The ConvLSTM recurrence is ``pyhazards.models.convlstm.ConvLSTM`` rather than a copy of the + repository's ``convlstm.py`` (from ndrplz/ConvLSTM_pytorch): same gates, zero initial state + and parameter names, outputs equal in the oracle test. The reference's ``dilation`` option, + always 1 in ``SimpleConvLSTM``, is not exposed. + - > + The reference LightningModule's ``attention=True`` option refers to an undefined + ``SimpleLSTMAttention`` class and crashes; it is not ported. tasks: - - forecasting - - regression + - classification example: | import torch from pyhazards.models import build_model - model = build_model( - name="wildfire_forecasting", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) - preds = model(torch.randn(2, 12, 7)) - print(preds.shape) + lstm = build_model(name="wildfire_forecasting", task="classification") + log_probs = lstm(torch.randn(4, 10, 25)) + danger = log_probs.exp()[:, 1] # probability of fire + print(log_probs.shape) # (4, 2) + + convlstm = build_model(name="wildfire_forecasting", task="classification", variant="convlstm") + print(convlstm(torch.randn(4, 10, 25, 25, 25)).shape) # (4, 2) notes: - - "This public adapter is exercised on the weekly wildfire smoke benchmark." + - > + The output is log-probabilities, as in the reference (``log_softmax`` over two classes). The + reference trains with ``nn.NLLLoss`` (class weights 0.5 / 0.5, i.e. unweighted); + ``nn.CrossEntropyLoss`` gives the same loss because ``log_softmax`` is idempotent. The paper + calls this a binary cross-entropy loss. + - > + Paper training settings (repository experiment configs): Adam, StepLR(step 15, gamma 0.1), + batch 256, 30 epochs; LSTM lr 1e-3 and weight decay 1e-3, ConvLSTM lr 1e-4 and weight decay + 0.01. Features are min-max scaled; missing dynamic values take the sample's mean over time + (LSTM) or space (ConvLSTM), other missing values become -1, missing land cover 0. + - > + The LSTM is the default: the paper builds its danger maps and explainability analysis on it, + its F1 is within 0.01 of the ConvLSTM in both test years, and it is about 12 times smaller. + - > + At the pinned commit the repository's dataset class validates on 2020 and tests on 2021 + (``val_year = 2020``), whereas the paper validates on 2019 and tests on 2020 and 2021. + - > + PyHazards does not load the Greek datacube yet; the smoke config uses the synthetic + ``wildfire_danger_synthetic`` dataset (``access_mode='temporal'`` or ``'spatiotemporal'``). smoke_test: - task: forecasting + task: classification build_kwargs: - input_dim: 7 - hidden_dim: 32 - output_dim: 5 - lookback: 12 - num_layers: 2 - dropout: 0.0 + variant: lstm input: kind: tensor tensor: - shape: [2, 12, 7] + shape: [2, 10, 25] expected_output: kind: tensor - shape: [2, 5] + shape: [2, 2] diff --git a/pyhazards/model_cards/wildfirespreadts.yaml b/pyhazards/model_cards/wildfirespreadts.yaml index b06dad73..cc6de880 100644 --- a/pyhazards/model_cards/wildfirespreadts.yaml +++ b/pyhazards/model_cards/wildfirespreadts.yaml @@ -1,50 +1,61 @@ model_name: wildfirespreadts -display_name: WildfireSpreadTS +display_name: WildfireSpreadTS Baselines hazard: Wildfire catalog_status: core source_file: pyhazards/models/wildfirespreadts.py builder_name: wildfirespreadts_builder summary: > - A temporal convolution wildfire spread baseline over short raster history windows. + The four learned WildfireSpreadTS baselines (logistic regression, ResNet-18 U-Net, ConvLSTM, + U-TAE) with the benchmark's own configurations. description: - > - ``wildfirespreadts`` models wildfire spread as a sequence-to-mask prediction task. + ``wildfirespreadts`` builds one of the learned baselines of the WildfireSpreadTS benchmark + for next-day active-fire segmentation, configured exactly as in the benchmark code. + ``baseline`` selects ``logistic_regression``, ``resnet18_unet``, ``convlstm`` or ``utae`` + (default). - > - The PyHazards adapter uses a compact 3D convolution stack that consumes short - raster history windows and predicts the next spread mask. + Each baseline is also available on its own (``logistic_regression``, ``resnet18_unet``, + ``convlstm``, ``utae``) with configurable hyperparameters; this entry fixes them to the + benchmark values. ``in_channels`` is the number of features per day (40 with all features) + and ``history`` the number of days that the U-Net and logistic regression flatten into + channels. paper: - title: "WildfireSpreadTS: A Dataset of Multi-Modal Time Series for Wildfire Spread Prediction" + title: "WildfireSpreadTS: A dataset of multi-modal time series for wildfire spread prediction" url: https://openreview.net/forum?id=RgdGkPRQ03 repo_url: https://github.com/SebastianGer/WildfireSpreadTS +reproduction: + reference_code: https://github.com/SebastianGer/WildfireSpreadTS + reference_commit: f62dc49f2c2a6d249c071533ae5340c0d01bfb95 + reference_license: MIT + reference_config: > + src/models (LogisticRegression, SMPModel, ConvLSTMLightning, UTAELightning) with 40 input + channels; parameter counts 361 / 14,444,241 / 240,449 / 1,099,011 match paper Table 5. + checks: [parameter_count, initialization, state_dict, forward] + oracle_test: tests/oracle/test_wildfirespreadts_oracle.py tasks: - segmentation - - regression example: | import torch from pyhazards.models import build_model - model = build_model( - name="wildfirespreadts", - task="segmentation", - history=4, - in_channels=6, - ) - logits = model(torch.randn(2, 4, 6, 16, 16)) - print(logits.shape) + model = build_model(name="wildfirespreadts", task="segmentation", baseline="utae", in_channels=40) + x = torch.randn(2, 5, 40, 128, 128) + day_of_year = torch.tensor([[150, 151, 152, 153, 154]] * 2, dtype=torch.float32) + print(model(x, batch_positions=day_of_year).shape) # (2, 1, 128, 128) notes: - - "The smoke dataset uses temporal wildfire spread tensors rather than single-frame rasters." + - "The benchmark trains on random 128x128 crops; ConvLSTM is evaluated by tiling 128x128 crops." + - "For the multi-day U-Net, the 20 static features (topography, land-cover one-hot) are kept for the last day only, as in the benchmark (remove_duplicate_features): 120 input channels and 14,695,121 parameters for 5 days." + - "Training losses differ per baseline: Dice (logistic regression, U-Net), Jaccard (ConvLSTM), weighted BCE (U-TAE)." smoke_test: task: segmentation build_kwargs: - history: 4 + baseline: utae in_channels: 6 - hidden_dim: 24 - out_channels: 1 - dropout: 0.0 + history: 4 input: kind: tensor tensor: - shape: [2, 4, 6, 16, 16] + shape: [2, 4, 6, 32, 32] expected_output: kind: tensor - shape: [2, 1, 16, 16] + shape: [2, 1, 32, 32] diff --git a/pyhazards/model_cards/wrf_sfire.yaml b/pyhazards/model_cards/wrf_sfire.yaml deleted file mode 100644 index d3b8a8d5..00000000 --- a/pyhazards/model_cards/wrf_sfire.yaml +++ /dev/null @@ -1,44 +0,0 @@ -model_name: wrf_sfire -display_name: WRF-SFIRE Adapter -hazard: Wildfire -catalog_status: core -source_file: pyhazards/models/wrf_sfire.py -builder_name: wrf_sfire_builder -summary: > - A lightweight raster wildfire spread adapter inspired by WRF-SFIRE style transport. -description: - - > - ``wrf_sfire`` approximates simulator-style spread transport with a fixed diffusion - and terrain-moisture modulation layer. - - > - The PyHazards adapter is designed for consistent smoke benchmarking rather than - full physical simulation. -paper: - title: Coupled atmosphere-wildland fire modeling with WRF 3.3 and SFIRE 2011 - url: https://doi.org/10.5194/gmd-4-591-2011 - repo_url: https://github.com/openwfm/WRF-SFIRE -tasks: - - segmentation - - regression -example: | - import torch - from pyhazards.models import build_model - - model = build_model(name="wrf_sfire", task="segmentation", in_channels=12) - logits = model(torch.randn(2, 12, 16, 16)) - print(logits.shape) -notes: - - "This smoke-path adapter keeps the simulator slot benchmarkable without external binaries." -smoke_test: - task: segmentation - build_kwargs: - in_channels: 12 - out_channels: 1 - diffusion_steps: 3 - input: - kind: tensor - tensor: - shape: [2, 12, 16, 16] - expected_output: - kind: tensor - shape: [2, 1, 16, 16] diff --git a/pyhazards/model_cards/xgboost.yaml b/pyhazards/model_cards/xgboost.yaml new file mode 100644 index 00000000..06527938 --- /dev/null +++ b/pyhazards/model_cards/xgboost.yaml @@ -0,0 +1,103 @@ +model_name: xgboost +display_name: XGBoost +hazard: Wildfire +catalog_status: variant +source_file: pyhazards/models/classical.py +builder_name: xgboost_builder +summary: > + Gradient-boosted trees (XGBoost) on the 35 instance features of Kondylatos et al. (2022) for + next-day wildfire danger, with library-default hyperparameters until the paper's are known. +description: + - > + ``xgboost`` wraps ``xgboost.XGBClassifier`` (Chen & Guestrin, KDD 2016), the second tree + baseline of Kondylatos et al. (GRL 2022). Like ``random_forest`` it takes the + ``wildfire_forecasting`` daily tensor ``(batch, 10, 25)`` or ready-made features + ``(batch, 35)``, builds the paper's instance features (ten-day mean and last-day value of + the 10 dynamic variables, 5 static variables, 10 land-cover fractions), and returns + ``(batch, 2)`` log-probabilities over (no fire, fire). + - > + The paper gives the XGBoost hyperparameters only in its Supporting Information (Text S2), + which has not been read, and the official repository has no XGBoost code. This entry + therefore uses the library defaults of xgboost 3.2.0 (100 boosting rounds, maximum depth 6, + learning rate 0.3, histogram trees with 256 bins, no subsampling, L2 regularisation 1, + binary logistic objective). Any of them can be overridden through the builder. + - > + ``xgboost`` is an optional dependency (``pip install 'pyhazards[xgboost]'``, or the CPU-only + ``xgboost-cpu``), imported only when the model is built. As for ``random_forest``, the module + is fitted with ``model.fit(inputs, targets)`` and refused by ``Trainer.fit``. +paper: + title: "XGBoost: A Scalable Tree Boosting System" + url: https://doi.org/10.1145/2939672.2939785 + repo_url: https://github.com/dmlc/xgboost +references: + - title: "Wildfire Danger Prediction and Understanding With Deep Learning" + url: https://doi.org/10.1029/2022GL099368 + repo_url: https://github.com/Orion-AI-Lab/wildfire_forecasting + note: > + Kondylatos et al., Geophysical Research Letters 49(17), e2022GL099368. XGBoost on the + instance-based data set (dynamic inputs at day t-1, their average over days t-1..t-10, + static features) of the daily 1 km Greek / Eastern Mediterranean datacube; train + 2009-2018, test 2020 and 2021. Hyperparameters in Supporting Information Text S2 (not + read). Test results (Table 1, 2020 / 2021): precision 0.852 / 0.867, recall 0.723 / 0.720, + F1 0.782 / 0.786 (TP 888 / 3,172, FP 154 / 488, TN 2,302 / 8,326, FN 340 / 1,235); random + forest F1 0.703 / 0.778, LSTM 0.804 / 0.879. +reproduction: + source: paper + reference_config: > + Kondylatos et al. (2022), Section 3: XGBoost on the instance-based features. PyHazards builds + the features as the official random-forest notebook (notebooks/RF.ipynb) does and uses + xgboost.XGBClassifier() with the defaults of xgboost 3.2.0; tests/oracle/test_classical_oracle.py + checks that its predictions equal those of XGBClassifier() 3.2.0 fitted on the notebook's + features. + oracle_test: tests/oracle/test_classical_oracle.py + deviations: + - > + Hyperparameters are pending the paper's Supporting Information (Text S2, behind the Wiley + site and not read): the xgboost 3.2.0 library defaults are used, which need not match the + paper's model or reproduce its scores. + - > + The library defaults depend on the xgboost release (2.0 switched to histogram trees and an + estimated base score); other releases may give different predictions. +tasks: + - classification + - regression +example: | + from pyhazards.datasets import load_dataset + from pyhazards.models import build_model + + data = load_dataset("wildfire_danger_synthetic", samples=120).load() + train, test = data.get_split("train"), data.get_split("test") + + model = build_model(name="xgboost", task="classification") # needs pyhazards[xgboost] + model.fit(train.inputs, train.targets) + print(model(test.inputs).shape) # (18, 2) log-probabilities +notes: + - > + Install with ``pip install 'pyhazards[xgboost]'`` (``xgboost>=2.0``) or ``pip install + xgboost-cpu`` (same module, no CUDA/NCCL wheels). Without it, building the model raises an + ``ImportError`` that says so, and the catalog smoke test is skipped. + - > + ``n_jobs`` defaults to all available cores (``OMP_NUM_THREADS`` caps it); pass ``n_jobs`` on + shared machines. + - > + The fitting, ``forward``, persistence (``save`` / ``EstimatorModule.load``, joblib) and + ``Trainer`` behaviour are those of ``random_forest``. +smoke_test: + task: classification + requires: [xgboost] + build_kwargs: + n_jobs: 1 + fit: + inputs: + shape: [16, 10, 25] + targets: + shape: [16] + dtype: int64 + num_classes: 2 + input: + kind: tensor + tensor: + shape: [4, 10, 25] + expected_output: + kind: tensor + shape: [4, 2] diff --git a/pyhazards/model_catalog.py b/pyhazards/model_catalog.py index 06c32178..9c06740b 100644 --- a/pyhazards/model_catalog.py +++ b/pyhazards/model_catalog.py @@ -1,5 +1,6 @@ from __future__ import annotations +import importlib.util import inspect from collections import defaultdict from pathlib import Path @@ -84,6 +85,7 @@ "flood.streamflow": "Streamflow", "flood.inundation": "Inundation", "tc.track_intensity": "Track + Intensity", + "tc.intensity": "Intensity", "classification": "Classification", "regression": "Forecasting", "segmentation": "Segmentation", @@ -104,10 +106,10 @@ } STARTER_MODELS = { - "Wildfire": "firecastnet", + "Wildfire": "wildfirespreadts", "Earthquake": "phasenet", - "Flood": "floodcast", - "Tropical Cyclone": "hurricast", + "Flood": "neuralhydrology_lstm", + "Tropical Cyclone": "tropicyclonenet", } @@ -117,9 +119,62 @@ class PaperReference(BaseModel): repo_url: Optional[str] = None +class UsageReference(PaperReference): + """A paper or benchmark that used this model, and how.""" + + note: Optional[str] = None + + +REPRODUCTION_CHECKS = { + "parameter_count": "parameter count", + "initialization": "seeded initialisation", + "state_dict": "parameter names and shapes", + "forward": "forward outputs", + "pretrained_weights": "official pretrained weights", +} + + +class ReproductionSpec(BaseModel): + """How the PyHazards implementation was checked against its source. + + ``source: code`` means it was compared with a pinned reference implementation by an oracle + test; ``source: paper`` means the model was rebuilt from the paper, either because no code was + released or because the released code may not be copied (it may still serve as an oracle). + """ + + source: Literal["code", "paper"] = "code" + reference_code: Optional[str] = None + reference_commit: Optional[str] = None + reference_license: Optional[str] = None + reference_config: str + parameter_count: Optional[int] = None + checks: List[Literal["parameter_count", "initialization", "state_dict", "forward", "pretrained_weights"]] = Field( + default_factory=list + ) + oracle_test: Optional[str] = None + deviations: List[str] = Field(default_factory=list) + + @model_validator(mode="after") + def validate_source(self) -> "ReproductionSpec": + if self.source == "code": + missing = [ + name + for name in ("reference_code", "reference_commit", "reference_license", "oracle_test") + if not getattr(self, name) + ] + if missing or not self.checks: + raise ValueError( + "reproduction with source 'code' needs reference_code, reference_commit, " + "reference_license, oracle_test and checks" + ) + return self + + class SmokeTensorSpec(BaseModel): shape: List[int] dtype: str = "float32" + # Integer tensors (e.g. graph edge indices): values drawn uniformly from [0, high). + high: Optional[int] = Field(default=None, ge=1) class SmokeInputSpec(BaseModel): @@ -143,9 +198,12 @@ def validate_payload(self) -> "SmokeInputSpec": class SmokeOutputSpec(BaseModel): + """Expected output: one tensor (``shape``), a tuple/list (``shapes``) or a dict of tensors (``mapping``).""" + kind: str = "tensor" shape: Optional[List[int]] = None shapes: List[List[int]] = Field(default_factory=list) + mapping: Dict[str, List[int]] = Field(default_factory=dict) @model_validator(mode="after") def validate_payload(self) -> "SmokeOutputSpec": @@ -154,14 +212,49 @@ def validate_payload(self) -> "SmokeOutputSpec": raise ValueError("tensor smoke outputs require the 'shape' field") if kind == "sequence" and not self.shapes: raise ValueError("sequence smoke outputs require the 'shapes' field") - if kind not in {"tensor", "sequence"}: - raise ValueError("smoke output kind must be one of: tensor, sequence") + if kind == "mapping" and not self.mapping: + raise ValueError("mapping smoke outputs require the 'mapping' field") + if kind not in {"tensor", "sequence", "mapping"}: + raise ValueError("smoke output kind must be one of: tensor, sequence, mapping") + return self + + @property + def expected(self) -> Any: + kind = self.kind.lower() + if kind == "tensor": + return self.shape + if kind == "sequence": + return self.shapes + return dict(self.mapping) + + +class SmokeFitSpec(BaseModel): + """Random training data for models fitted before the forward call (``model.fit(inputs, targets)``). + + Estimator models (e.g. scikit-learn wrappers) cannot predict before they are fitted. Inputs are + standard normal; with ``num_classes`` the targets are integer labels covering every class (the + first ``num_classes`` samples get one of each), otherwise standard normal values. + """ + + inputs: SmokeTensorSpec + targets: SmokeTensorSpec + num_classes: Optional[int] = Field(default=None, ge=1) + + @model_validator(mode="after") + def validate_payload(self) -> "SmokeFitSpec": + if not self.inputs.shape or not self.targets.shape or self.inputs.shape[0] != self.targets.shape[0]: + raise ValueError("smoke fit inputs and targets need the same leading (sample) dimension") + if self.num_classes is not None and self.targets.shape[0] < self.num_classes: + raise ValueError("smoke fit targets need at least one sample per class") return self class SmokeTestSpec(BaseModel): task: str build_kwargs: Dict[str, Any] = Field(default_factory=dict) + # Optional packages the model needs; the smoke test is skipped when one is not installed. + requires: List[str] = Field(default_factory=list) + fit: Optional[SmokeFitSpec] = None input: SmokeInputSpec expected_output: SmokeOutputSpec @@ -179,6 +272,8 @@ class ModelCard(BaseModel): summary: str description: List[str] paper: PaperReference + references: List[UsageReference] = Field(default_factory=list) + reproduction: Optional[ReproductionSpec] = None tasks: List[str] example: str notes: List[str] = Field(default_factory=list) @@ -621,6 +716,10 @@ def render_model_page(cards: Sequence[ModelCard]) -> str: "Browse PyHazards model implementations across hazard families, compare", "scope and maturity, and navigate to model-specific detail pages.", "", + "Prompted multimodal LLMs used as zero-shot wildfire-smoke detectors (SmokeBench: Qwen2.5-VL,", + "InternVL3, Idefics2, Gemini 2.5 Pro, GPT-4o) are not ``nn.Module`` models; they are documented", + "separately under :doc:`pyhazards_prompted`.", + "", "At a Glance", "-----------", "", @@ -818,7 +917,7 @@ def render_api_page(cards: Sequence[ModelCard]) -> str: "", " model = build_model(", ' name="phasenet",', - ' task="regression",', + ' task="picking",', " in_channels=3,", " )", "", @@ -991,6 +1090,21 @@ def render_module_page(card: ModelCard) -> str: "", _paper_links(card), "", + ] + ) + if card.references: + lines.extend(["Used In", "-------", ""]) + for reference in card.references: + entry = "- `{title} <{url}>`_".format(title=reference.title, url=reference.url) + if reference.repo_url: + entry += " (`repo <{url}>`__)".format(url=reference.repo_url) + if reference.note: + entry += ": " + _single_line(reference.note) + lines.append(entry) + lines.append("") + lines.extend(_render_reproduction(card)) + lines.extend( + [ "Registry Name", "-------------", "", @@ -1040,6 +1154,59 @@ def render_module_page(card: ModelCard) -> str: return "\n".join(lines) +def _short_commit(ref: str) -> str: + is_sha = len(ref) == 40 and all(char in "0123456789abcdef" for char in ref) + return ref[:7] if is_sha else ref + + +def _render_reproduction(card: ModelCard) -> List[str]: + lines = ["Reproduction", "------------", ""] + spec = card.reproduction + if spec is None: + lines.extend( + [ + "Not yet verified against a reference implementation.", + "", + ] + ) + return lines + if spec.source == "paper" and spec.reference_code: + lines.append( + "- **Reference implementation:** `{url} <{url}>`__ (``{commit}``, {license}); " + "not ported, the model is rebuilt from the paper and the release serves as a test oracle.".format( + url=spec.reference_code, + commit=_short_commit(spec.reference_commit or "unversioned"), + license=spec.reference_license or "license unknown", + ) + ) + elif spec.source == "paper": + lines.append("- **Reference implementation:** none released; rebuilt from the paper.") + else: + lines.append( + "- **Reference implementation:** `{url} <{url}>`__ at ``{commit}`` ({license})".format( + url=spec.reference_code, + commit=_short_commit(spec.reference_commit), + license=spec.reference_license, + ) + ) + label = "Paper configuration" if spec.source == "paper" else "Checked configuration" + lines.append("- **{label}:** {config}".format(label=label, config=_single_line(spec.reference_config))) + if spec.parameter_count is not None: + lines.append("- **Parameter count:** {count:,}".format(count=spec.parameter_count)) + if spec.checks: + lines.append( + "- **Verified:** {checks}".format( + checks=", ".join(REPRODUCTION_CHECKS[check] for check in spec.checks) + ) + ) + if spec.oracle_test: + lines.append("- **Oracle test:** ``{path}``".format(path=spec.oracle_test)) + for deviation in spec.deviations: + lines.append("- **Deviation:** {text}".format(text=_single_line(deviation))) + lines.append("") + return lines + + def rendered_docs(cards: Sequence[ModelCard]) -> Dict[Path, str]: targets: Dict[Path, str] = { MODEL_PAGE_PATH: render_model_page(cards), @@ -1152,7 +1319,10 @@ def _dtype_for_name(dtype_name: str) -> torch.dtype: def _make_tensor(spec: SmokeTensorSpec) -> torch.Tensor: - return torch.randn(*spec.shape, dtype=_dtype_for_name(spec.dtype)) + dtype = _dtype_for_name(spec.dtype) + if spec.high is not None: + return torch.randint(0, spec.high, tuple(spec.shape), dtype=dtype) + return torch.randn(*spec.shape, dtype=dtype) def _prepare_smoke_input(spec: SmokeInputSpec) -> Any: @@ -1169,18 +1339,52 @@ def _shape_of_output(output: Any) -> Any: return list(output.shape) if isinstance(output, (list, tuple)): return [_shape_of_output(item) for item in output] + if isinstance(output, Mapping): + return {key: _shape_of_output(value) for key, value in output.items()} return type(output).__name__ +def _make_fit_targets(spec: SmokeFitSpec) -> torch.Tensor: + if spec.num_classes is None: + return _make_tensor(spec.targets) + count = 1 + for size in spec.targets.shape: + count *= size + labels = torch.arange(count) % spec.num_classes + rest = labels[spec.num_classes :] + labels[spec.num_classes :] = rest[torch.randperm(rest.numel())] + return labels.reshape(spec.targets.shape).to(_dtype_for_name(spec.targets.dtype)) + + +def missing_smoke_requirements(card: ModelCard) -> List[str]: + """Optional packages of ``card.smoke_test.requires`` that are not installed.""" + return [name for name in card.smoke_test.requires if importlib.util.find_spec(name) is None] + + def run_smoke_test(card: ModelCard) -> Dict[str, Any]: from pyhazards.models import build_model + expected_shape = card.smoke_test.expected_output.expected + missing = missing_smoke_requirements(card) + if missing: + reason = "optional package(s) not installed: {names}".format(names=", ".join(missing)) + return { + "ok": True, + "skipped": reason, + "actual_shape": None, + "expected_shape": expected_shape, + "summary": "{name}: skipped ({reason})".format(name=card.model_name, reason=reason), + } + torch.manual_seed(0) model = build_model( name=card.model_name, task=card.smoke_test.task, **card.smoke_test.build_kwargs ) + fit_spec = card.smoke_test.fit + if fit_spec is not None: + model.fit(_make_tensor(fit_spec.inputs), _make_fit_targets(fit_spec)) model.eval() prepared = _prepare_smoke_input(card.smoke_test.input) with torch.no_grad(): @@ -1192,16 +1396,13 @@ def run_smoke_test(card: ModelCard) -> Dict[str, Any]: output = model(**prepared) actual_shape = _shape_of_output(output) - expected = card.smoke_test.expected_output - if expected.kind.lower() == "tensor": - ok = actual_shape == expected.shape - else: - ok = actual_shape == expected.shapes + ok = actual_shape == expected_shape return { "ok": ok, + "skipped": None, "actual_shape": actual_shape, - "expected_shape": expected.shape if expected.kind.lower() == "tensor" else expected.shapes, + "expected_shape": expected_shape, "summary": "{name}: output shape {actual}".format( name=card.model_name, actual=actual_shape, @@ -1216,7 +1417,12 @@ def touched_card_names(cards: Sequence[ModelCard], changed_files: Iterable[str]) } names: Set[str] = set() for path in changed_files: - if path.startswith("pyhazards/model_cards/") and path.endswith((".yaml", ".yml")): + # A card deleted by the change (a removed model) has nothing left to review. + if ( + path.startswith("pyhazards/model_cards/") + and path.endswith((".yaml", ".yml")) + and (REPO_ROOT / path).exists() + ): names.add(Path(path).stem) if path in source_to_name: names.add(source_to_name[path]) diff --git a/pyhazards/models/__init__.py b/pyhazards/models/__init__.py index ea923edc..18c23829 100644 --- a/pyhazards/models/__init__.py +++ b/pyhazards/models/__init__.py @@ -1,42 +1,76 @@ from .backbones import CNNPatchEncoder, MLPBackbone, TemporalEncoder from .asufm import ASUFM, asufm_builder +from .attention_unet import AttentionUnet, TemporalAttentionUnet, attention_unet_builder from .builder import build_model, default_builder +from .classical import EstimatorModule, kondylatos_instance_features, random_forest_builder, xgboost_builder from .cnn_aspp import WildfireCNNASPP, cnn_aspp_builder -from .eqnet import EQNet, eqnet_builder +from .earthfarseer import Earthfarseer, EarthfarseerSegmenter, earthfarseer_builder +from .convgru import ConvGRU, ConvGRUCell, ConvGRUSegmenter, convgru_builder +from .convlstm import ConvLSTM, ConvLSTMCell, ConvLSTMSegmenter, convlstm_builder +from .earthformer import CuboidTransformerModel, Earthformer, EarthformerSegmenter, earthformer_builder +from .deeplabv3 import DeepLabV3, deeplabv3_builder +from .deep_ensemble import DeepEnsemble, deep_ensemble_builder +from .eqnet import EQNet, EQNetLoss, eqnet_builder, eqnet_candidate_grid, eqnet_travel_times, shift_and_stack from .eqtransformer import EQTransformer, eqtransformer_builder from .firecastnet import FireCastNet, firecastnet_builder from .floodcast import FloodCast, floodcast_builder -from .forefire import ForeFireAdapter, forefire_builder -from .fourcastnet_tc import FourCastNetTC, fourcastnet_tc_builder from .gpd import GPD, gpd_builder from .google_flood_forecasting import GoogleFloodForecasting, google_flood_forecasting_builder -from .graphcast_tc import GraphCastTC, graphcast_tc_builder from .heads import ClassificationHead, RegressionHead, SegmentationHead -from .hurricast import Hurricast, hurricast_builder +from .hurricast import Hurricast, HurricastEncoderDecoder, hurricast_builder from .hydrographnet import HydroGraphNet, HydroGraphNetLoss, hydrographnet_builder +from .hurricast import Hurricast, hurricast_builder +from .hydrographnet import HydroGraphNet, HydroGraphNetLoss, hydrographnet_builder, hydrographnet_physics_loss +from .logistic_regression import PixelLogisticRegression, logistic_regression_builder from .neuralhydrology_ealstm import NeuralHydrologyEALSTM, neuralhydrology_ealstm_builder from .neuralhydrology_lstm import NeuralHydrologyLSTM, neuralhydrology_lstm_builder -from .pangu_tc import PanguTC, pangu_tc_builder from .phasenet import PhaseNet, phasenet_builder +from .prithvi import PrithviMAE, PrithviSegmentation, PrithviViT +from .prithvi_burnscars import prithvi_burnscars_builder +from .prithvi_eo_2_tl import prithvi_eo_2_tl_builder +from .rainformer import Rainformer, RainformerSegmenter, rainformer_builder from .registry import available_models, register_model +from .resnet_unet import ResNetUNet, resnet18_unet_builder from .saf_net import SAFNet, saf_net_builder +from .segformer import SegFormer, segformer_builder +from .swin_unet import SwinUnet, swin_unet_builder +from .swin_unetr import SwinUNETR, TemporalSwinUNETR, swin_unetr_builder +from .swinlstm import SwinLSTM, SwinLSTMSegmenter, swinlstm_builder from .tcif_fusion import TCIFFusion, tcif_fusion_builder -from .tropicalcyclone_mlp import TropicalCycloneMLP, tropicalcyclone_mlp_builder -from .tropicyclonenet import TropiCycloneNet, tropicyclonenet_builder +from .tcn import TCN, TemporalConvNet, tcn_builder +from .trajgru import TrajGRU, TrajGRUSegmenter, trajgru_builder +from .tropicalcyclone_mlp import TropicalCycloneMLP, load_keras_weights, tropicalcyclone_mlp_builder +from .tropicyclonenet import ( + TrajectoryDiscriminator, + TropiCycloneNet, + load_tropicyclonenet_checkpoint, + tropicyclonenet_builder, +) +from .unet import UNet, unet_builder +from .ts_satfire import TS_SATFIRE_BASELINES, ts_satfire_builder +from .unet3d import TemporalUNet, UNet, unet3d_builder +from .unetr import UNETR, TemporalUNETR, unetr_builder from .urbanfloodcast import UrbanFloodCast, urbanfloodcast_builder +from .utae import UTAE, utae_builder from .wavecastnet import ( ConvLEMCell, WaveCastNet, WaveCastNetLoss, + WaveCastNetSparse, WavefieldMetrics, wavecastnet_builder, + wavecastnet_station_coords, +) +from .wildfire_forecasting import ( + WILDFIRE_FORECASTING_VARIANTS, + SimpleConvLSTM, + SimpleLSTM, + wildfire_forecasting_builder, ) -from .wildfire_forecasting import WildfireForecasting, wildfire_forecasting_builder from .wildfire_aspp import TverskyLoss, WildfireASPP, wildfire_aspp_builder from .wildfire_fpa import WildfireFPA, wildfire_fpa_builder from .wildfire_mamba import WildfireMamba, wildfire_mamba_builder -from .wildfirespreadts import WildfireSpreadTS, wildfirespreadts_builder -from .wrf_sfire import WRFSFireAdapter, wrf_sfire_builder +from .wildfirespreadts import WILDFIRESPREADTS_BASELINES, wildfirespreadts_builder __all__ = [ @@ -48,47 +82,65 @@ "TemporalEncoder", "ASUFM", "asufm_builder", + "AttentionUnet", + "TemporalAttentionUnet", + "attention_unet_builder", "ClassificationHead", + "DeepEnsemble", + "deep_ensemble_builder", + "EstimatorModule", + "kondylatos_instance_features", + "random_forest_builder", + "xgboost_builder", "RegressionHead", "SegmentationHead", "EQNet", + "EQNetLoss", "eqnet_builder", + "eqnet_candidate_grid", + "eqnet_travel_times", + "shift_and_stack", "EQTransformer", "eqtransformer_builder", "FireCastNet", "firecastnet_builder", "FloodCast", "floodcast_builder", - "ForeFireAdapter", - "forefire_builder", - "FourCastNetTC", - "fourcastnet_tc_builder", "GPD", "gpd_builder", "GoogleFloodForecasting", "google_flood_forecasting_builder", - "GraphCastTC", - "graphcast_tc_builder", "Hurricast", + "HurricastEncoderDecoder", "hurricast_builder", "HydroGraphNet", "HydroGraphNetLoss", "hydrographnet_builder", + "hydrographnet_physics_loss", "NeuralHydrologyEALSTM", "neuralhydrology_ealstm_builder", "NeuralHydrologyLSTM", "neuralhydrology_lstm_builder", - "PanguTC", - "pangu_tc_builder", "PhaseNet", "phasenet_builder", + "PrithviMAE", + "PrithviSegmentation", + "PrithviViT", + "prithvi_burnscars_builder", + "prithvi_eo_2_tl_builder", "SAFNet", "saf_net_builder", "TCIFFusion", "tcif_fusion_builder", + "TCN", + "TemporalConvNet", + "tcn_builder", "TropicalCycloneMLP", + "load_keras_weights", "tropicalcyclone_mlp_builder", + "TrajectoryDiscriminator", "TropiCycloneNet", + "load_tropicyclonenet_checkpoint", "tropicyclonenet_builder", "UrbanFloodCast", "urbanfloodcast_builder", @@ -97,21 +149,72 @@ "wildfire_aspp_builder", "WildfireCNNASPP", "cnn_aspp_builder", - "WildfireForecasting", + "SimpleLSTM", + "SimpleConvLSTM", + "WILDFIRE_FORECASTING_VARIANTS", "wildfire_forecasting_builder", "WildfireFPA", "wildfire_fpa_builder", "WildfireMamba", "wildfire_mamba_builder", - "WildfireSpreadTS", + "WILDFIRESPREADTS_BASELINES", "wildfirespreadts_builder", - "WRFSFireAdapter", - "wrf_sfire_builder", + "ConvLSTM", + "ConvLSTMCell", + "ConvLSTMSegmenter", + "convlstm_builder", + "CuboidTransformerModel", + "Earthformer", + "EarthformerSegmenter", + "earthformer_builder", + "ConvGRU", + "ConvGRUCell", + "ConvGRUSegmenter", + "convgru_builder", + "PixelLogisticRegression", + "logistic_regression_builder", + "ResNetUNet", + "resnet18_unet_builder", + "UNet", + "unet_builder", + "DeepLabV3", + "deeplabv3_builder", + "SegFormer", + "segformer_builder", + "UTAE", + "utae_builder", + "SwinUnet", + "swin_unet_builder", + "Earthfarseer", + "EarthfarseerSegmenter", + "earthfarseer_builder", + "Rainformer", + "RainformerSegmenter", + "rainformer_builder", + "SwinUNETR", + "TemporalSwinUNETR", + "swin_unetr_builder", + "TS_SATFIRE_BASELINES", + "ts_satfire_builder", + "UNet", + "TemporalUNet", + "unet3d_builder", + "UNETR", + "TemporalUNETR", + "unetr_builder", + "SwinLSTM", + "SwinLSTMSegmenter", + "swinlstm_builder", + "TrajGRU", + "TrajGRUSegmenter", + "trajgru_builder", "ConvLEMCell", "WaveCastNet", "WaveCastNetLoss", + "WaveCastNetSparse", "WavefieldMetrics", "wavecastnet_builder", + "wavecastnet_station_coords", ] @@ -172,90 +275,265 @@ register_model( "wildfire_forecasting", wildfire_forecasting_builder, + # hidden_size is left to the builder: its paper value depends on the variant (64 / 32). defaults={ - "input_dim": 7, - "hidden_dim": 64, - "output_dim": 5, - "lookback": 12, - "num_layers": 2, - "dropout": 0.1, + "variant": "lstm", + "input_dim": 25, + "lstm_layers": 1, + "dropout": 0.5, + "patch_size": 25, }, ) +# Kondylatos et al. (2022) notebooks/RF.ipynb; the daily-tensor layout is a builder default. register_model( - "asufm", - asufm_builder, + "random_forest", + random_forest_builder, defaults={ - "input_dim": 7, - "hidden_dim": 64, - "output_dim": 5, - "lookback": 12, - "dropout": 0.1, + "n_estimators": 100, + "max_depth": 10, + "min_samples_split": 2, + "min_samples_leaf": 1, + "random_state": 123, }, ) +# Library defaults of xgboost.XGBClassifier (the paper's values are in its unread Supporting Information). +register_model("xgboost", xgboost_builder, defaults={}) + +register_model( + "deep_ensemble", + deep_ensemble_builder, + defaults={"num_members": 5, "regression_output": "gaussian", "mc_dropout_passes": 0}, +) + +register_model( + "asufm", + asufm_builder, + defaults={"in_channels": 6, "out_channels": 1, "img_size": 64, "window_size": 8, "focal": True}, +) + +register_model( + "swin_unet", + swin_unet_builder, + defaults={"out_channels": 1, "history": 1, "img_size": 224, "window_size": 7, "drop_path_rate": 0.2, "pretrained": None}, +) + +register_model( + "earthfarseer", + earthfarseer_builder, + defaults={"in_channels": 1, "history": 10, "img_size": 64, "out_channels": 1}, +) + +register_model( + "rainformer", + rainformer_builder, + defaults={"in_channels": 1, "history": 9, "img_size": 288, "out_channels": 1}, +) + +register_model( + "swinlstm", + swinlstm_builder, + defaults={"variant": "d", "in_channels": 1, "img_size": 64, "num_output_frames": 10}, +) + +register_model( + "trajgru", + trajgru_builder, + defaults={"config": "hko7", "in_channels": 1, "out_channels": 1, "layer_type": "TrajGRU"}, +) + register_model( "wildfirespreadts", wildfirespreadts_builder, defaults={ - "history": 4, - "in_channels": 6, - "hidden_dim": 32, - "out_channels": 1, - "dropout": 0.1, + "baseline": "utae", + "in_channels": 40, + "history": 5, + }, +) + +register_model( + "logistic_regression", + logistic_regression_builder, + defaults={"out_channels": 1, "history": 1, "kernel_size": 3}, +) + +register_model( + "resnet18_unet", + resnet18_unet_builder, + defaults={"out_channels": 1, "history": 1, "encoder_name": "resnet18", "encoder_weights": None}, +) + +register_model( + "unet", + unet_builder, + defaults={"in_channels": 1, "out_channels": 2, "padding": "valid", "dropout": 0.5, "variant": "paper"}, +) + +register_model( + "deeplabv3", + deeplabv3_builder, + # Shadrin et al. (2024): smp DeepLabV3, ResNet-18 encoder with three stages, 58 channels for day 3. + defaults={"in_channels": 58, "out_channels": 1, "encoder_name": "resnet18", "encoder_depth": 3, "encoder_weights": None}, +) + +register_model( + "segformer", + segformer_builder, + defaults={"out_channels": 1, "history": 1, "variant": "b2", "encoder_weights": None, "upsample": True}, +) + +register_model( + "convlstm", + convlstm_builder, + defaults={"out_channels": 1, "hidden_dim": 64, "kernel_size": 3, "num_layers": 1, "readout": "cell"}, +) + +register_model( + "convgru", + convgru_builder, + defaults={"in_channels": 11, "out_channels": 1, "hidden_dim": 128, "kernel_size": 5, "num_layers": 1}, +) + +register_model( + "utae", + utae_builder, + defaults={"out_channels": 1}, +) + +register_model( + "earthformer", + earthformer_builder, + # Shapes and hyperparameters come from the preset (official earthformer_sevir_v1.yaml). + defaults={"config": "sevir", "pretrained": None}, +) + +register_model( + "attention_unet", + attention_unet_builder, + defaults={ + "out_channels": 2, + "spatial_dims": 3, + "channels": (64, 128, 256, 512, 1024), + "strides": None, + "dropout": 0.0, + "time_reduction": "mean", }, ) register_model( - "forefire", - forefire_builder, + "unet3d", + unet3d_builder, defaults={ - "in_channels": 12, - "out_channels": 1, - "diffusion_steps": 2, + "out_channels": 2, + "spatial_dims": 3, + "channels": (64, 128, 256, 512, 1024), + "strides": None, + "num_res_units": 0, + "dropout": 0.0, + "time_reduction": "mean", }, ) register_model( - "wrf_sfire", - wrf_sfire_builder, + "unetr", + unetr_builder, defaults={ - "in_channels": 12, - "out_channels": 1, - "diffusion_steps": 3, + "out_channels": 2, + "spatial_dims": 3, + "history": 6, + "image_size": 256, + "feature_size": 16, + "hidden_size": 384, + "mlp_dim": 1536, + "num_heads": 12, + "norm_name": "batch", + "time_reduction": "mean", }, ) +register_model( + "swin_unetr", + swin_unetr_builder, + defaults={ + "out_channels": 2, + "spatial_dims": 3, + "history": 6, + "image_size": 256, + "norm_name": "batch", + "attn_version": "v1", + "time_reduction": "mean", + }, +) + +register_model( + "ts_satfire", + ts_satfire_builder, + defaults={ + "baseline": "swinunetr3d", + "in_channels": 43, + "history": 6, + "image_size": 256, + "out_channels": 2, + "num_heads": 3, + "time_reduction": "mean", + }, +) + +register_model( + "tcn", + tcn_builder, + defaults={ + "input_dim": 2, + "out_dim": 1, + "hidden_dim": 30, + "num_levels": 8, + "kernel_size": 7, + "dropout": 0.0, + "readout": "last", + "head_init": "normal", + }, +) + +register_model( + "prithvi_burnscars", + prithvi_burnscars_builder, + defaults={"in_channels": 6, "num_classes": 2, "pretrained": False}, +) + +register_model( + "prithvi_eo_2_tl", + prithvi_eo_2_tl_builder, + defaults={"variant": "300m", "in_channels": 6, "num_classes": 2, "num_frames": 1, "pretrained": False}, +) + register_model( "firecastnet", firecastnet_builder, defaults={ - "in_channels": 12, - "hidden_dim": 32, - "out_channels": 1, - "dropout": 0.1, + "in_channels": 11, + "timeseries_len": 24, }, ) register_model( "wildfire_cnn_aspp", cnn_aspp_builder, - defaults={ - "in_channels": 12, - "base_channels": 32, - "aspp_channels": 32, - "dilations": (1, 3, 6, 12), - "dropout": 0.0, - }, + defaults={"in_channels": 12, "dilations": (1, 3, 6, 12)}, ) register_model( "hydrographnet", hydrographnet_builder, defaults={ - "hidden_dim": 64, - "harmonics": 5, - "num_gn_blocks": 5, + "input_dim_nodes": 16, + "input_dim_edges": 3, + "output_dim": 2, + "processor_size": 15, + "hidden_dim_processor": 128, + "aggregation": "sum", + "num_harmonics": 5, }, ) @@ -263,11 +541,12 @@ "neuralhydrology_lstm", neuralhydrology_lstm_builder, defaults={ - "input_dim": 2, - "hidden_dim": 64, - "num_layers": 2, - "out_dim": 1, - "dropout": 0.1, + "n_dynamic": 5, + "n_static": 27, + "hidden_size": 256, + "n_targets": 1, + "output_dropout": 0.4, + "initial_forget_bias": 5.0, }, ) @@ -275,11 +554,12 @@ "neuralhydrology_ealstm", neuralhydrology_ealstm_builder, defaults={ - "input_dim": 2, - "hidden_dim": 64, - "num_layers": 1, - "out_dim": 1, - "dropout": 0.1, + "n_dynamic": 5, + "n_static": 27, + "hidden_size": 256, + "n_targets": 1, + "output_dropout": 0.4, + "initial_forget_bias": 5.0, }, ) @@ -299,77 +579,54 @@ "urbanfloodcast", urbanfloodcast_builder, defaults={ - "in_channels": 3, - "history": 4, - "base_channels": 32, - "out_channels": 1, + "num_channels": 5, + "width": 10, + "initial_step": 1, }, ) register_model( "google_flood_forecasting", google_flood_forecasting_builder, - defaults={ - "input_dim": 2, - "hidden_dim": 64, - "out_dim": 1, - "history": 4, - "dropout": 0.1, - }, + defaults={"config": "floodhub", "pretrained": False}, ) register_model( "phasenet", phasenet_builder, - defaults={ - "in_channels": 3, - "hidden_dim": 32, - }, + defaults={"in_channels": 3}, ) register_model( "eqtransformer", eqtransformer_builder, - defaults={ - "in_channels": 3, - "hidden_dim": 48, - "num_layers": 2, - "dropout": 0.1, - }, + defaults={"in_channels": 3}, ) register_model( "gpd", gpd_builder, - defaults={ - "in_channels": 3, - "hidden_dim": 32, - "dropout": 0.1, - }, + defaults={"in_channels": 3}, ) register_model( "eqnet", eqnet_builder, - defaults={ - "in_channels": 3, - "hidden_dim": 48, - "num_heads": 4, - "num_layers": 2, - "dropout": 0.1, - }, + defaults={"in_channels": 3, "sampling_rate": 100.0}, ) register_model( "wavecastnet", wavecastnet_builder, defaults={ - "hidden_dim": 144, - "num_layers": 2, + "variant": "dense", + "in_channels": 3, + "height": 344, + "width": 224, + "future_seq": 30, "kernel_size": 3, "dt": 1.0, "activation": "tanh", - "dropout": 0.1, }, ) @@ -377,25 +634,22 @@ "tropicalcyclone_mlp", tropicalcyclone_mlp_builder, defaults={ - "input_dim": 8, - "history": 6, - "hidden_dim": 64, - "horizon": 5, - "output_dim": 3, - "dropout": 0.1, + "input_dim": 121, + "hidden_dims": (2048, 2048), + "activations": ("sigmoid", "relu"), }, ) +# HUML-(stat/viz, xgb/cnn/transfo) of Boussioux et al. (2022): official CNN + Transformer presets, XGBoost with +# the defaults of the official run_embeddings.py. register_model( "hurricast", hurricast_builder, defaults={ - "input_dim": 8, - "hidden_dim": 64, - "num_layers": 2, - "horizon": 5, - "output_dim": 3, - "dropout": 0.1, + "target": "intensity", + "predictor": "xgboost", + "decoder_config": "transformer_config", + "encoder_config": "full_encoder_config", }, ) @@ -403,12 +657,8 @@ "tropicyclonenet", tropicyclonenet_builder, defaults={ - "input_dim": 8, - "hidden_dim": 64, - "horizon": 5, - "output_dim": 3, - "num_layers": 2, - "dropout": 0.1, + "num_sample": 6, + "official_sample_loop": False, }, ) @@ -416,60 +666,13 @@ "saf_net", saf_net_builder, defaults={ - "input_dim": 8, - "hidden_dim": 64, - "horizon": 5, - "dropout": 0.1, + "wide_dim": 96, + "num_times": 4, + "num_levels": 4, + "grid_size": 31, }, ) -register_model( - "tcif_fusion", - tcif_fusion_builder, - defaults={ - "input_dim": 8, - "hidden_dim": 64, - "horizon": 5, - "output_dim": 3, - "dropout": 0.1, - }, -) - -register_model( - "graphcast_tc", - graphcast_tc_builder, - defaults={ - "input_dim": 8, - "hidden_dim": 96, - "horizon": 5, - "output_dim": 3, - "num_layers": 2, - "num_heads": 4, - "dropout": 0.1, - }, -) - -register_model( - "pangu_tc", - pangu_tc_builder, - defaults={ - "input_dim": 8, - "hidden_dim": 96, - "horizon": 5, - "output_dim": 3, - "dropout": 0.1, - }, -) +# Wang et al. (2024): the notebook graph with the paper's 65-channel ALL input (all_channels=85: the notebook's). +register_model("tcif_fusion", tcif_fusion_builder, defaults={"all_channels": 65}) -register_model( - "fourcastnet_tc", - fourcastnet_tc_builder, - defaults={ - "input_dim": 8, - "history": 6, - "hidden_dim": 96, - "horizon": 5, - "output_dim": 3, - "dropout": 0.1, - }, -) diff --git a/pyhazards/models/_pretrained.py b/pyhazards/models/_pretrained.py new file mode 100644 index 00000000..ecd3c11c --- /dev/null +++ b/pyhazards/models/_pretrained.py @@ -0,0 +1,43 @@ +"""Download helper for official pretrained weights (pinned URL + sha256). + +Weights are never bundled with PyHazards. They are fetched on first use from the URLs pinned in each +model module, checked against their sha256 and cached under ``/checkpoints/pyhazards``. +""" + +from __future__ import annotations + +import hashlib +import urllib.error +from pathlib import Path +from typing import Sequence + +import torch + + +def sha256_of(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def cached_download(family: str, filename: str, urls: Sequence[str], sha256: str) -> Path: + """Local path of a pinned file, downloaded into the torch hub cache on first use.""" + path = Path(torch.hub.get_dir()) / "checkpoints" / "pyhazards" / family / filename + if path.exists() and sha256_of(path) == sha256: + return path + path.parent.mkdir(parents=True, exist_ok=True) + errors = [] + for url in urls: + try: + torch.hub.download_url_to_file(url, str(path), hash_prefix=sha256, progress=False) + if sha256_of(path) == sha256: + return path + errors.append(f"{url}: sha256 mismatch") + except (urllib.error.URLError, RuntimeError, OSError) as error: # HTTP errors or hash mismatch + errors.append(f"{url}: {error}") + raise RuntimeError(f"Could not download {family}/{filename}:\n" + "\n".join(errors)) + + +__all__ = ["cached_download", "sha256_of"] diff --git a/pyhazards/models/_seismic.py b/pyhazards/models/_seismic.py new file mode 100644 index 00000000..4f52176d --- /dev/null +++ b/pyhazards/models/_seismic.py @@ -0,0 +1,153 @@ +"""Interface shared by the seismic phase pickers (PhaseNet, EQTransformer, GPD). + +The ``earthquake.picking`` benchmark scores any model that follows this interface: + +- ``sampling_rate`` (Hz) and ``component_order`` (e.g. ``"ENZ"``) describe the waveforms the released + weights expect; the benchmark reorders dataset channels to ``component_order`` and refuses other + sampling rates. +- ``annotate(waveforms)`` takes raw windows ``(batch, 3, samples)``, applies the official per-window + normalisation and returns the model's probabilities (per-sample traces, or per-window values for + sliding-window classifiers). +- ``extract_picks(annotations)`` turns those probabilities into picks with the official + post-processing of each model: one ``{"P": [(sample, probability), ...], "S": [...]}`` dict per trace. +- Models with an event-detection output also provide ``extract_detections(annotations)``: one list of + ``(on, off, probability)`` windows per trace. +""" + +from __future__ import annotations + +from typing import Dict, List, Sequence, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +TracePicks = Dict[str, List[Tuple[float, float]]] + + +class WaveformPicker: + """Mixin documenting the phase-picker interface (see the module docstring).""" + + sampling_rate: float = 100.0 + component_order: str = "ZNE" + output_names: Tuple[str, ...] = () + + def annotate(self, waveforms: torch.Tensor) -> torch.Tensor: # pragma: no cover - interface + raise NotImplementedError + + def extract_picks(self, annotations: torch.Tensor, **kwargs) -> List[TracePicks]: # pragma: no cover + raise NotImplementedError + + +class KerasBatchNorm1d(nn.BatchNorm1d): + """``BatchNorm1d`` with the training-time running statistics of standalone Keras 2.2 / 2.3. + + Shared by the EQTransformer and GPD ports (released weights trained with Keras 2.2.2 / 2.2.4 / 2.3.0). + + Normalisation (batch statistics in train mode, running statistics in eval mode) is that of + ``BatchNorm1d`` with Keras' defaults (epsilon 1e-3, momentum 0.99). Only the running-statistics + update differs: ``keras/layers/normalization.py`` scales the batch variance by + ``n / (n - (1 + epsilon))`` (PyTorch: ``n / (n - 1)``), and ``K.moving_average_update`` is a plain + exponential moving average in Keras 2.3.0 (``zero_debias=False``, the paper model) but TensorFlow's + zero-debiased ``assign_moving_average`` in Keras 2.2.4 (``zero_debias=True``, the conservative + model): a zero-initialised accumulator divided by ``1 - 0.99 ** t``, with ``t`` counted by + ``num_batches_tracked`` (so it restarts after loading weights, as in Keras). + """ + + def __init__(self, num_features: int, zero_debias: bool = False, eps: float = 1e-3, keras_momentum: float = 0.99): + super().__init__(num_features, eps=eps, momentum=1.0 - keras_momentum) + self.zero_debias = bool(zero_debias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if not self.training: + return super().forward(x) + output = F.batch_norm(x, None, None, self.weight, self.bias, True, 0.0, self.eps) + with torch.no_grad(): + dims = [0] if x.ndim == 2 else [0, 2] + sample_size = float(x.numel() // x.shape[1]) + mean = x.mean(dim=dims) + variance = x.var(dim=dims, unbiased=False) * (sample_size / (sample_size - (1.0 + self.eps))) + decay = 1.0 - float(self.momentum) + steps = int(self.num_batches_tracked) + for buffer, value in ((self.running_mean, mean), (self.running_var, variance)): + value = value.to(buffer.dtype) + if self.zero_debias: + biased = buffer * (1.0 - decay**steps) if steps > 0 else torch.zeros_like(buffer) + biased = decay * biased + (1.0 - decay) * value + buffer.copy_(biased / (1.0 - decay ** (steps + 1))) + else: + buffer.sub_((buffer - value) * (1.0 - decay)) + self.num_batches_tracked.add_(1) + return output + + +def std_normalize(waveforms: torch.Tensor) -> torch.Tensor: + """Remove the mean of every channel and divide by its standard deviation (1 where it is 0). + + The per-window normalisation of PhaseNet (``normalize`` in ``phasenet/data_reader.py``) and of + EQTransformer (``normalize(data, mode="std")`` in ``EqT_utils.py``): population standard deviation + over the samples of each channel, ``(batch, channels, samples)`` layout. + """ + if waveforms.ndim != 3: + raise ValueError(f"Expected waveforms shaped (batch, channels, samples), got shape {tuple(waveforms.shape)}.") + centred = waveforms - waveforms.mean(dim=-1, keepdim=True) + std = centred.std(dim=-1, unbiased=False, keepdim=True) + return centred / torch.where(std == 0, torch.ones_like(std), std) + + +def reorder_components(waveforms: torch.Tensor, source: str, target: str) -> torch.Tensor: + """Reorder the channel axis from component order ``source`` (e.g. ``"ZNE"``) to ``target``.""" + source, target = source.upper(), target.upper() + if source == target: + return waveforms + if sorted(source) != sorted(target): + raise ValueError(f"Cannot reorder components {source!r} to {target!r}.") + index = [source.index(component) for component in target] + return waveforms[:, index] + + +def check_waveforms(waveforms: torch.Tensor, channels: int, name: str) -> None: + if waveforms.ndim != 3 or waveforms.shape[1] != channels: + raise ValueError( + f"{name} expects waveforms shaped (batch, {channels}, samples), got shape {tuple(waveforms.shape)}." + ) + + +def picks_from_peaks( + annotations: torch.Tensor, + phase_channels: Dict[str, int], + thresholds: Dict[str, float], + min_distance: int, +) -> List[TracePicks]: + """Peak picks on per-sample probability traces (the PhaseNet rule; see ``metrics.picking``).""" + from ..metrics.picking import peak_picks + + values = annotations.detach().cpu().double().numpy() + picks: List[TracePicks] = [] + for trace in values: + picks.append( + { + phase: peak_picks(trace[channel], thresholds[phase], min_distance) + for phase, channel in phase_channels.items() + } + ) + return picks + + +def as_sequence(value, names: Sequence[str]) -> Dict[str, float]: + """A per-phase dict from a scalar or a dict.""" + if isinstance(value, dict): + return {name: float(value[name]) for name in names} + return {name: float(value) for name in names} + + +__all__ = [ + "KerasBatchNorm1d", + "TracePicks", + "WaveformPicker", + "as_sequence", + "check_waveforms", + "picks_from_peaks", + "reorder_components", + "std_normalize", +] diff --git a/pyhazards/models/_tf_checkpoint.py b/pyhazards/models/_tf_checkpoint.py new file mode 100644 index 00000000..511da5c5 --- /dev/null +++ b/pyhazards/models/_tf_checkpoint.py @@ -0,0 +1,141 @@ +"""Read TensorFlow (V2 "tensor bundle") checkpoints without TensorFlow. + +A checkpoint ```` consists of ``.index`` and ``.data-NNNNN-of-MMMMM``. The index +is an SSTable (LevelDB table format: data blocks of prefix-compressed key/value entries, an index block +and a 48-byte footer) that maps each variable name to a ``BundleEntryProto`` (dtype, shape, shard, +offset, size); the data files hold the raw little-endian tensor bytes. This reader supports the +uncompressed, single-slice layout that ``tf.train.Saver`` writes, which is what the official PhaseNet +checkpoint uses. It was checked against ``tf.train.load_checkpoint`` (TensorFlow 2.11) in +``tests/oracle/test_phasenet_oracle.py``. +""" + +from __future__ import annotations + +import struct +from pathlib import Path +from typing import Dict, Iterator, List, Tuple, Union + +import numpy as np + +_MAGIC = 0xDB4775248B80FB57 +_DTYPES = {1: " Tuple[int, int]: + result, shift = 0, 0 + while True: + byte = buffer[pos] + pos += 1 + result |= (byte & 0x7F) << shift + if not byte & 0x80: + return result, pos + shift += 7 + + +def _block(data: bytes, offset: int, size: int) -> bytes: + compression = data[offset + size] + if compression != 0: + raise ValueError("Compressed TensorFlow checkpoint index blocks are not supported.") + return data[offset : offset + size] + + +def _entries(block: bytes) -> Iterator[Tuple[bytes, bytes]]: + num_restarts = struct.unpack_from(" Iterator[Tuple[int, int, Union[int, bytes]]]: + pos = 0 + while pos < len(message): + tag, pos = _varint(message, pos) + number, wire = tag >> 3, tag & 7 + if wire == 0: + value, pos = _varint(message, pos) + elif wire == 1: + value, pos = message[pos : pos + 8], pos + 8 + elif wire == 2: + length, pos = _varint(message, pos) + value, pos = message[pos : pos + length], pos + length + elif wire == 5: + value, pos = message[pos : pos + 4], pos + 4 + else: + raise ValueError(f"Unsupported protobuf wire type {wire}.") + yield number, wire, value + + +def _bundle_entry(value: bytes) -> Dict[str, object]: + entry: Dict[str, object] = {"dtype": 0, "shape": [], "shard_id": 0, "offset": 0, "size": 0, "slices": False} + for number, _, field in _fields(value): + if number == 1: + entry["dtype"] = field + elif number == 2: # TensorShapeProto: repeated Dim (field 2) with size (field 1) + dims: List[int] = [] + for dim_number, _, dim in _fields(field): # type: ignore[arg-type] + if dim_number == 2: + size = 0 + for size_number, _, size_value in _fields(dim): # type: ignore[arg-type] + if size_number == 1: + size = int(size_value) # type: ignore[arg-type] + dims.append(size) + entry["shape"] = dims + elif number == 3: + entry["shard_id"] = field + elif number == 4: + entry["offset"] = field + elif number == 5: + entry["size"] = field + elif number == 7: + entry["slices"] = True + return entry + + +def read_tf_checkpoint(prefix: Union[str, Path]) -> Dict[str, np.ndarray]: + """All numeric variables of a TensorFlow V2 checkpoint, keyed by variable name.""" + prefix = Path(prefix) + index = (prefix.parent / (prefix.name + ".index")).read_bytes() + footer = index[-48:] + if struct.unpack(" Tuple[torch.Tensor, List[torch.Tensor]]: + x = self.pos_drop(self.patch_embed(x)) + skips = [] + for layer in self.layers: + skips.append(x) + x = layer(x) + return self.norm(x), skips + + +class ASUFMDecoder(nn.Module): + def __init__( + self, + img_size: int, + patches_resolution: Sequence[int], + num_classes: int, + embed_dim: int, + depths: Sequence[int], + num_heads: Sequence[int], + window_size: int, + mlp_ratio: float, + qkv_bias: bool, + qk_scale: Optional[float], + drop_rate: float, + drop_path_rate: float, + focal: bool, + use_checkpoint: bool, + ): + super().__init__() + norm_layer = nn.LayerNorm + self.num_layers = len(depths) + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + self.patches_resolution = list(patches_resolution) + resolution = self.patches_resolution + dpr = stochastic_depth_rates(drop_path_rate, depths) + self.layers_up = nn.ModuleList() + self.concat_back_dim = nn.ModuleList() + for i in range(self.num_layers): + j = self.num_layers - 1 - i + dim = int(embed_dim * 2 ** j) + stage_resolution = (resolution[0] // 2 ** j, resolution[1] // 2 ** j) + concat_linear = nn.Linear(2 * dim, dim) if i > 0 else nn.Identity() + if i == 0: + layer_up = PatchExpand(stage_resolution, dim=dim, dim_scale=2, norm_layer=norm_layer) + else: + layer_up = BasicLayer_up( + dim=dim, + input_resolution=stage_resolution, + depth=depths[j], + num_heads=num_heads[j], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=0.0, + drop_path=dpr[sum(depths[:j]) : sum(depths[: j + 1])], + norm_layer=norm_layer, + upsample=i < self.num_layers - 1, + use_checkpoint=use_checkpoint, + focal_modulation="unused" if focal else None, + ) + self.layers_up.append(layer_up) + self.concat_back_dim.append(concat_linear) + self.norm = norm_layer(self.num_features) # unused, as in the reference + self.norm_up = norm_layer(embed_dim) + self.up = FinalPatchExpand_X4(input_resolution=(img_size // PATCH_SIZE, img_size // PATCH_SIZE), dim_scale=4, dim=embed_dim) + self.output = nn.Conv2d(in_channels=embed_dim, out_channels=num_classes, kernel_size=1, bias=False) + + def forward(self, x: torch.Tensor, skips: Sequence[torch.Tensor]) -> torch.Tensor: + for i, layer_up in enumerate(self.layers_up): + if i > 0: + skip = skips[self.num_layers - 1 - i] + # The reference fuses the same skip twice with the same linear layer. + x = self.concat_back_dim[i](torch.cat([x, skip], -1)) + x = self.concat_back_dim[i](torch.cat([x, skip], -1)) + x = layer_up(x) + x = self.norm_up(x) + h, w = self.patches_resolution + x = self.up(x).view(x.shape[0], 4 * h, 4 * w, -1).permute(0, 3, 1, 2) + return self.output(x) + + +class ASUFM(nn.Module): + """Attention Swin U-Net with Focal Modulation (official ``mode="swin"`` configuration). + + Input ``(batch, in_chans, img_size, img_size)`` (one NDWS day; a 5-D input with a time axis of + length one is accepted), output logits ``(batch, num_classes, img_size, img_size)``. + """ + + def __init__( + self, + in_chans: int = 6, + num_classes: int = 1, + img_size: int = 64, + embed_dim: int = 96, + depths: Sequence[int] = (2, 2, 2, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + window_size: int = 8, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + drop_path_rate: float = DROP_PATH_RATE, + focal: bool = True, + use_checkpoint: bool = False, + ): + super().__init__() + depths, num_heads = list(depths), list(num_heads) + if len(depths) != len(num_heads): + raise ValueError(f"depths and num_heads need the same length, got {depths} and {num_heads}.") + if in_chans <= 0 or num_classes <= 0: + raise ValueError(f"in_chans and num_classes must be positive, got {in_chans} and {num_classes}.") + check_swin_geometry(img_size, PATCH_SIZE, window_size, len(depths)) + self.in_chans = int(in_chans) + self.num_classes = int(num_classes) + self.img_size = int(img_size) + self.focal = focal + + # Unused stem of the reference (its in_chans is the patch size); kept for state-dict parity. + self.patch_embed = PatchEmbed(img_size=img_size, patch_size=PATCH_SIZE, in_chans=PATCH_SIZE, embed_dim=embed_dim, norm_layer=nn.LayerNorm) + common = dict( + embed_dim=embed_dim, depths=depths, num_heads=num_heads, window_size=window_size, + mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop_rate=drop_rate, + drop_path_rate=drop_path_rate, focal=focal, use_checkpoint=use_checkpoint, ) - self.head = nn.Sequential( - nn.Dropout(dropout), - nn.Linear(hidden_dim, output_dim), + self.encoder = ASUFMEncoder(in_chans=in_chans, img_size=img_size, **common) + self.decoder = ASUFMDecoder( + img_size=img_size, patches_resolution=self.patch_embed.patches_resolution, num_classes=num_classes, **common ) + self.apply(init_swin_weights) def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: + if x.ndim == 5 and x.size(1) == 1: + x = x[:, 0] + if x.ndim != 4: + raise ValueError( + f"ASUFM expects input shape (batch, channels, height, width), got {tuple(x.shape)}." + ) + if x.size(1) == 1 and self.in_chans == 3: + x = x.repeat(1, 3, 1, 1) # reference: grey-scale input to three channels + if x.size(1) != self.in_chans or tuple(x.shape[-2:]) != (self.img_size, self.img_size): raise ValueError( - "ASUFM expects input shape (batch, lookback, features), " + f"ASUFM expects input shape (batch, {self.in_chans}, {self.img_size}, {self.img_size}), " f"got {tuple(x.shape)}." ) - if x.size(1) != self.lookback: - raise ValueError(f"ASUFM expected lookback={self.lookback}, got sequence length {x.size(1)}.") - encoded = self.temporal(x.transpose(1, 2)) - gated = encoded * self.gate(encoded) - pooled = torch.mean(gated, dim=-1) - return self.head(pooled) + x, skips = self.encoder(x) + return self.decoder(x, skips) def asufm_builder( task: str, - input_dim: int = 7, - hidden_dim: int = 64, - output_dim: int = 5, - lookback: int = 12, - dropout: float = 0.1, + in_channels: int = 6, + out_channels: int = 1, + img_size: int = 64, + embed_dim: int = 96, + depths: Sequence[int] = (2, 2, 2, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + window_size: int = 8, + mlp_ratio: float = 4.0, + drop_rate: float = 0.0, + drop_path_rate: float = DROP_PATH_RATE, + focal: bool = True, + use_checkpoint: bool = False, **kwargs, ) -> nn.Module: + """ASUFM with the official configuration (6 NDWS channels by default; 12 for all features).""" _ = kwargs - if task.lower() not in {"forecasting", "regression"}: - raise ValueError(f"asufm supports task='forecasting' or 'regression', got {task!r}.") + if task.lower() != "segmentation": + raise ValueError(f"asufm supports task='segmentation', got {task!r}.") return ASUFM( - input_dim=input_dim, - hidden_dim=hidden_dim, - output_dim=output_dim, - lookback=lookback, - dropout=dropout, + in_chans=in_channels, + num_classes=out_channels, + img_size=img_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop_rate=drop_rate, + drop_path_rate=drop_path_rate, + focal=focal, + use_checkpoint=use_checkpoint, ) diff --git a/pyhazards/models/attention_unet.py b/pyhazards/models/attention_unet.py new file mode 100644 index 00000000..6be3f350 --- /dev/null +++ b/pyhazards/models/attention_unet.py @@ -0,0 +1,609 @@ +"""Attention U-Net as implemented by MONAI, with the TS-SatFire spatio-temporal configuration. + +Port of ``monai.networks.nets.AttentionUnet`` from MONAI 1.3.2 +(``monai/networks/nets/attentionunet.py``, Apache License 2.0, Copyright (c) MONAI Consortium), +together with the subset of ``monai.networks.blocks.Convolution`` / ``ADN`` and the layer +factories it relies on. Changes made for PyHazards: the MONAI blocks are re-implemented in plain +PyTorch (no MONAI dependency), invalid configurations raise ``ValueError`` up front, a +``stride_mode="shared"`` option reproduces the TS-SatFire modification described below, and +:class:`TemporalAttentionUnet` adds the TS-SatFire input layout and temporal read-out. Module +names, creation order and defaults follow MONAI, so MONAI state dicts load with ``strict=True`` +and the same seed gives the same initial weights. + +MONAI's network is "based on" Oktay et al., "Attention U-Net: Learning Where to Look for the +Pancreas" (MIDL 2018, arXiv:1804.03999) but is not the authors' implementation +(ozan-oktay/Attention-Gated-Networks): its additive gate is computed at the skip resolution from +the already up-sampled decoder feature, without the sub-sampled grid gating, the multiple gates +per level or the deep supervision of the official code. + +TS-SatFire (Zhao, Gerard & Ban, Scientific Data 12:1817, 2025) uses this network in two ways: +the 2D baseline is stock MONAI ``AttentionUnet(spatial_dims=2, channels=(64, 128, 256, 512, 1024), +strides=(2, 2, 2, 2))``; the 3D baseline ("Attention-U-Net-3D") uses the repository's copy +``spatial_models/attentionunet.py`` (MONAI 1.2/1.3.0 code), whose only change is that the single +``strides`` argument -- ``(1, 2, 2)`` over (time, height, width) -- is applied at every level +instead of one entry per level, so time is never down-sampled. The prediction script feeds +``(batch, channels, time, H, W)`` and averages the logits over time. +""" + +from __future__ import annotations + +from typing import Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn + +IntOrSeq = Union[int, Sequence[int]] + +_CONV = {1: nn.Conv1d, 2: nn.Conv2d, 3: nn.Conv3d} +_CONV_TRANSPOSE = {1: nn.ConvTranspose1d, 2: nn.ConvTranspose2d, 3: nn.ConvTranspose3d} +_BATCH_NORM = {1: nn.BatchNorm1d, 2: nn.BatchNorm2d, 3: nn.BatchNorm3d} +_INSTANCE_NORM = {1: nn.InstanceNorm1d, 2: nn.InstanceNorm2d, 3: nn.InstanceNorm3d} +_ACTIVATIONS = {"relu": nn.ReLU, "prelu": nn.PReLU} + +# TS-SatFire configuration (run_spatial_temp_model_pred.py). +TS_SATFIRE_CHANNELS = (64, 128, 256, 512, 1024) +TS_SATFIRE_3D_STRIDES = (1, 2, 2) + + +def _as_tuple(value: IntOrSeq, spatial_dims: int, name: str) -> Tuple[int, ...]: + if isinstance(value, int): + return (int(value),) * spatial_dims + values = tuple(int(v) for v in value) + if len(values) != spatial_dims: + raise ValueError(f"{name} must be an int or have {spatial_dims} entries, got {value!r}") + return values + + +def _same_padding(kernel_size: IntOrSeq) -> IntOrSeq: + """``monai.networks.layers.convutils.same_padding`` for dilation 1.""" + kernels = (kernel_size,) if isinstance(kernel_size, int) else tuple(kernel_size) + if any(int(k) % 2 == 0 for k in kernels): + raise ValueError(f"Same padding needs odd kernel sizes, got {kernel_size!r}") + padding = tuple((int(k) - 1) // 2 for k in kernels) + return padding if len(padding) > 1 else padding[0] + + +def _stride_minus_kernel_padding(kernel_size: IntOrSeq, stride: IntOrSeq) -> IntOrSeq: + """``monai.networks.layers.convutils.stride_minus_kernel_padding``.""" + kernels = (kernel_size,) if isinstance(kernel_size, int) else tuple(kernel_size) + strides = (stride,) if isinstance(stride, int) else tuple(stride) + if len(kernels) == 1 and len(strides) > 1: + kernels = kernels * len(strides) + if len(strides) == 1 and len(kernels) > 1: + strides = strides * len(kernels) + padding = tuple(int(s) - int(k) for s, k in zip(strides, kernels)) + return padding if len(padding) > 1 else padding[0] + + +class ADN(nn.Sequential): + """Normalisation, dropout and activation in a given order (``monai.networks.blocks.ADN``). + + Only the layers used by :class:`AttentionUnet` are supported: batch or instance norm, + ``nn.Dropout`` (MONAI's default ``dropout_dim=1``) and ReLU or PReLU with default arguments. + """ + + def __init__( + self, + ordering: str, + in_channels: int, + spatial_dims: int, + act: Optional[str] = "relu", + norm: Optional[str] = None, + dropout: Optional[float] = None, + ): + super().__init__() + layers = {"A": None, "D": None, "N": None} + if norm is not None: + if norm == "batch": + layers["N"] = _BATCH_NORM[spatial_dims](in_channels) + elif norm == "instance": + layers["N"] = _INSTANCE_NORM[spatial_dims](in_channels) + else: + raise ValueError(f"norm must be 'batch', 'instance' or None, got {norm!r}") + if act is not None: + if act not in _ACTIVATIONS: + raise ValueError(f"act must be one of {sorted(_ACTIVATIONS)} or None, got {act!r}") + layers["A"] = _ACTIVATIONS[act]() + if dropout is not None: + layers["D"] = nn.Dropout(p=float(dropout)) + for item in ordering.upper(): + if item not in layers: + raise ValueError(f"ordering must only contain 'A', 'D' and 'N', got {ordering!r}") + if layers[item] is not None: + self.add_module(item, layers[item]) + + +class Convolution(nn.Sequential): + """``(Conv | ConvTranspose) -> ADN`` block (``monai.networks.blocks.Convolution``). + + Defaults match MONAI: kernel 3, "same" padding, PReLU activation, instance norm, no dropout. + Transposed convolutions use ``output_padding = stride - 1``, so they scale sizes exactly by + the stride. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + strides: IntOrSeq = 1, + kernel_size: IntOrSeq = 3, + adn_ordering: str = "NDA", + act: Optional[str] = "prelu", + norm: Optional[str] = "instance", + dropout: Optional[float] = None, + bias: bool = True, + conv_only: bool = False, + is_transposed: bool = False, + padding: Optional[IntOrSeq] = None, + output_padding: Optional[IntOrSeq] = None, + ): + super().__init__() + self.spatial_dims = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.is_transposed = is_transposed + if padding is None: + padding = _same_padding(kernel_size) + if is_transposed: + if output_padding is None: + output_padding = _stride_minus_kernel_padding(1, strides) + conv: nn.Module = _CONV_TRANSPOSE[spatial_dims]( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + output_padding=output_padding, + bias=bias, + ) + else: + conv = _CONV[spatial_dims]( + in_channels, + out_channels, + kernel_size=kernel_size, + stride=strides, + padding=padding, + bias=bias, + ) + self.add_module("conv", conv) + if conv_only: + return + if act is None and norm is None and dropout is None: + return + self.add_module( + "adn", + ADN( + ordering=adn_ordering, + in_channels=out_channels, + spatial_dims=spatial_dims, + act=act, + norm=norm, + dropout=dropout, + ), + ) + + +class ConvBlock(nn.Module): + """Two ``Conv -> BatchNorm -> Dropout -> ReLU`` units; the first one carries the stride.""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq = 3, + strides: IntOrSeq = 1, + dropout: float = 0.0, + ): + super().__init__() + layers = [ + Convolution( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + strides=strides, + padding=None, + adn_ordering="NDA", + act="relu", + norm="batch", + dropout=dropout, + ), + Convolution( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=out_channels, + kernel_size=kernel_size, + strides=1, + padding=None, + adn_ordering="NDA", + act="relu", + norm="batch", + dropout=dropout, + ), + ] + self.conv = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv(x) + + +class UpConv(nn.Module): + """Transposed ``Conv -> BatchNorm -> Dropout -> ReLU`` that undoes one level's stride.""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq = 3, + strides: IntOrSeq = 2, + dropout: float = 0.0, + ): + super().__init__() + self.up = Convolution( + spatial_dims, + in_channels, + out_channels, + strides=strides, + kernel_size=kernel_size, + act="relu", + adn_ordering="NDA", + norm="batch", + dropout=dropout, + is_transposed=True, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.up(x) + + +class AttentionBlock(nn.Module): + """Additive attention gate ``x * sigmoid(BN(psi(relu(BN(W_g g) + BN(W_x x)))))``. + + ``g`` (gating signal) and ``x`` (skip feature) have the same resolution, as in MONAI. + """ + + def __init__(self, spatial_dims: int, f_int: int, f_g: int, f_l: int, dropout: float = 0.0): + super().__init__() + self.W_g = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_g, + out_channels=f_int, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + _BATCH_NORM[spatial_dims](f_int), + ) + self.W_x = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_l, + out_channels=f_int, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + _BATCH_NORM[spatial_dims](f_int), + ) + self.psi = nn.Sequential( + Convolution( + spatial_dims=spatial_dims, + in_channels=f_int, + out_channels=1, + kernel_size=1, + strides=1, + padding=0, + dropout=dropout, + conv_only=True, + ), + _BATCH_NORM[spatial_dims](1), + nn.Sigmoid(), + ) + self.relu = nn.ReLU() + + def forward(self, g: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + g1 = self.W_g(g) + x1 = self.W_x(x) + psi = self.relu(g1 + x1) + psi = self.psi(psi) + return x * psi + + +class AttentionLayer(nn.Module): + """One U-Net level: ``submodule`` (encoder + deeper levels), up-convolution, gate and merge. + + As in MONAI, the gate and the up-convolution never receive the dropout rate, and the merge + convolution uses MONAI's ``Convolution`` defaults (instance norm and PReLU). + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + submodule: nn.Module, + up_kernel_size: IntOrSeq = 3, + strides: IntOrSeq = 2, + dropout: float = 0.0, + ): + super().__init__() + self.attention = AttentionBlock( + spatial_dims=spatial_dims, f_g=in_channels, f_l=in_channels, f_int=in_channels // 2 + ) + self.upconv = UpConv( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=in_channels, + strides=strides, + kernel_size=up_kernel_size, + ) + self.merge = Convolution( + spatial_dims=spatial_dims, in_channels=2 * in_channels, out_channels=in_channels, dropout=dropout + ) + self.submodule = submodule + + def forward(self, x: torch.Tensor) -> torch.Tensor: + fromlower = self.upconv(self.submodule(x)) + att = self.attention(g=fromlower, x=x) + return self.merge(torch.cat((att, fromlower), dim=1)) + + +class AttentionUnet(nn.Module): + """MONAI ``AttentionUnet`` (1.3.2) in plain PyTorch. + + Args: + spatial_dims: 1, 2 or 3. + in_channels: input channels. + out_channels: output channels (logits, no activation). + channels: feature widths, top level first; at least two entries. + strides: with ``stride_mode="per_level"`` (MONAI), one stride per level + (``len(channels) - 1`` entries are used), each an int or one value per spatial + dimension. With ``stride_mode="shared"`` (the TS-SatFire copy), a single stride -- an + int or one value per spatial dimension -- used at every level. + kernel_size: convolution kernel size (odd). + up_kernel_size: transposed-convolution kernel size (odd). + dropout: dropout rate inside the encoder/decoder convolution blocks. + stride_mode: ``"per_level"`` or ``"shared"``. + + Input ``(batch, in_channels, *spatial)``; output ``(batch, out_channels, *spatial)``. Every + spatial size must be divisible by the product of that dimension's strides. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + channels: Sequence[int], + strides: Union[IntOrSeq, Sequence[IntOrSeq]], + kernel_size: IntOrSeq = 3, + up_kernel_size: IntOrSeq = 3, + dropout: float = 0.0, + stride_mode: str = "per_level", + ): + super().__init__() + if spatial_dims not in (1, 2, 3): + raise ValueError(f"spatial_dims must be 1, 2 or 3, got {spatial_dims}") + if in_channels <= 0 or out_channels <= 0: + raise ValueError("in_channels and out_channels must be positive.") + channels = tuple(int(c) for c in channels) + if len(channels) < 2: + raise ValueError(f"channels needs at least two entries, got {channels!r}") + n_levels = len(channels) - 1 + if stride_mode == "shared": + level_strides = [strides] * n_levels # TS-SatFire: the same stride at every level + elif stride_mode == "per_level": + if isinstance(strides, int): + raise ValueError("stride_mode='per_level' needs one stride per level; use stride_mode='shared'.") + level_strides = list(strides) + if len(level_strides) < n_levels: + raise ValueError( + f"strides needs {n_levels} entries (len(channels) - 1) with stride_mode='per_level', " + f"got {len(level_strides)}." + ) + level_strides = level_strides[:n_levels] # MONAI ignores extra entries as well + else: + raise ValueError(f"stride_mode must be 'per_level' or 'shared', got {stride_mode!r}") + self.level_strides = [_as_tuple(s, spatial_dims, "each stride") for s in level_strides] + for name, kernel in (("kernel_size", kernel_size), ("up_kernel_size", up_kernel_size)): + _as_tuple(kernel, spatial_dims, name) + _same_padding(kernel) + + self.dimensions = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.channels = channels + self.strides = strides + self.stride_mode = stride_mode + self.kernel_size = kernel_size + self.dropout = dropout + + # Creation order follows MONAI (head, output conv, then the levels from the bottom up), + # so a given seed produces the same initial weights. + head = ConvBlock( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=channels[0], + dropout=dropout, + kernel_size=self.kernel_size, + ) + reduce_channels = Convolution( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=out_channels, + kernel_size=1, + strides=1, + padding=0, + conv_only=True, + ) + self.up_kernel_size = up_kernel_size + + def _create_block(channels: Sequence[int], strides: Sequence[IntOrSeq]) -> nn.Module: + if len(channels) > 2: + subblock = _create_block(channels[1:], strides[1:]) + return AttentionLayer( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=channels[1], + submodule=nn.Sequential( + ConvBlock( + spatial_dims=spatial_dims, + in_channels=channels[0], + out_channels=channels[1], + strides=strides[0], + dropout=self.dropout, + kernel_size=self.kernel_size, + ), + subblock, + ), + up_kernel_size=self.up_kernel_size, + strides=strides[0], + dropout=dropout, + ) + # The next level is the bottom one: stop the recursion. + return self._get_bottom_layer(channels[0], channels[1], strides[0]) + + encdec = _create_block(self.channels, level_strides) + self.model = nn.Sequential(head, encdec, reduce_channels) + + def _get_bottom_layer(self, in_channels: int, out_channels: int, strides: IntOrSeq) -> nn.Module: + return AttentionLayer( + spatial_dims=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + submodule=ConvBlock( + spatial_dims=self.dimensions, + in_channels=in_channels, + out_channels=out_channels, + strides=strides, + dropout=self.dropout, + kernel_size=self.kernel_size, + ), + up_kernel_size=self.up_kernel_size, + strides=strides, + dropout=self.dropout, + ) + + def size_multiple(self) -> Tuple[int, ...]: + """Per-dimension factor that every input spatial size must be a multiple of.""" + factors = [1] * self.dimensions + for stride in self.level_strides: + factors = [f * s for f, s in zip(factors, stride)] + return tuple(factors) + + def _check_input(self, x: torch.Tensor, layout: str) -> None: + if x.ndim != self.dimensions + 2: + raise ValueError( + f"{type(self).__name__} expects input shape {layout}, got {tuple(x.shape)}." + ) + if x.size(1) != self.in_channels: + raise ValueError( + f"{type(self).__name__} expected {self.in_channels} input channels, got shape {tuple(x.shape)}." + ) + multiple = self.size_multiple() + if any(size % m for size, m in zip(x.shape[2:], multiple)): + raise ValueError( + f"Spatial shape {tuple(x.shape[2:])} must be divisible by {multiple} " + "(the product of the strides in each dimension)." + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + spatial = ", ".join(["H", "W"] if self.dimensions == 2 else ["D", "H", "W"][-self.dimensions :]) + self._check_input(x, f"(batch, channels, {spatial})") + return self.model(x) + + +class TemporalAttentionUnet(AttentionUnet): + """3D :class:`AttentionUnet` over ``(time, H, W)`` for raster time series (TS-SatFire usage). + + Takes PyHazards' ``(batch, time, channels, H, W)`` layout, runs the 3D network on + ``(batch, channels, time, H, W)`` and, with ``time_reduction="mean"`` (TS-SatFire's + prediction task), averages the logits over time to ``(batch, out_channels, H, W)``. + ``time_reduction="none"`` returns ``(batch, out_channels, time, H, W)``, the per-date maps + TS-SatFire uses for its active-fire and burned-area tasks. Parameter names are those of + :class:`AttentionUnet`, so 3D MONAI / TS-SatFire state dicts load unchanged. + """ + + def __init__(self, *args, time_reduction: str = "mean", **kwargs): + super().__init__(*args, **kwargs) + if self.dimensions != 3: + raise ValueError(f"TemporalAttentionUnet needs spatial_dims=3, got {self.dimensions}") + if time_reduction not in {"mean", "none"}: + raise ValueError(f"time_reduction must be 'mean' or 'none', got {time_reduction!r}") + self.time_reduction = time_reduction + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 5: + raise ValueError( + "TemporalAttentionUnet expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + x = x.transpose(1, 2).contiguous() + self._check_input(x, "(batch, time, channels, height, width)") + out = self.model(x) + return out.mean(2) if self.time_reduction == "mean" else out + + +def attention_unet_builder( + task: str, + in_channels: int, + out_channels: int = 2, + spatial_dims: int = 3, + channels: Sequence[int] = TS_SATFIRE_CHANNELS, + strides: Optional[Union[IntOrSeq, Sequence[IntOrSeq]]] = None, + stride_mode: str = "per_level", + kernel_size: IntOrSeq = 3, + up_kernel_size: IntOrSeq = 3, + dropout: float = 0.0, + time_reduction: str = "mean", + **kwargs, +) -> nn.Module: + """Build the Attention U-Net; the defaults are TS-SatFire's prediction model. + + ``spatial_dims=3`` returns a :class:`TemporalAttentionUnet` (input ``(B, T, C, H, W)``); + ``spatial_dims=2`` returns an :class:`AttentionUnet` (input ``(B, C, H, W)``). Without + ``strides``, TS-SatFire's strides are used: ``(1, 2, 2)`` at every level in 3D, ``2`` at every + level in 2D. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"attention_unet supports task='segmentation', got {task!r}.") + if strides is None: + strides = TS_SATFIRE_3D_STRIDES if spatial_dims == 3 else 2 + stride_mode = "shared" + common = dict( + in_channels=in_channels, + out_channels=out_channels, + channels=channels, + strides=strides, + kernel_size=kernel_size, + up_kernel_size=up_kernel_size, + dropout=dropout, + stride_mode=stride_mode, + ) + if spatial_dims == 3: + return TemporalAttentionUnet(spatial_dims=3, time_reduction=time_reduction, **common) + if spatial_dims == 2: + return AttentionUnet(spatial_dims=2, **common) + raise ValueError(f"attention_unet supports spatial_dims 2 or 3, got {spatial_dims}.") + + +__all__ = [ + "ADN", + "AttentionBlock", + "AttentionLayer", + "AttentionUnet", + "ConvBlock", + "Convolution", + "TemporalAttentionUnet", + "UpConv", + "attention_unet_builder", +] diff --git a/pyhazards/models/classical.py b/pyhazards/models/classical.py new file mode 100644 index 00000000..52faa14b --- /dev/null +++ b/pyhazards/models/classical.py @@ -0,0 +1,363 @@ +"""Classical tree-ensemble baselines (random forest, XGBoost) behind the PyHazards model interface. + +The registry builds ``nn.Module`` objects, so tree ensembles are wrapped in :class:`EstimatorModule`, +an ``nn.Module`` that holds a scikit-learn-compatible estimator. It is honest about what it is: + +- it has no parameters and is **not** trained by gradient descent. Fit it with + ``model.fit(inputs, targets)``; :class:`pyhazards.engine.Trainer` refuses to ``fit`` it (its + ``evaluate`` and ``predict`` work on a fitted module); +- ``forward`` raises :class:`sklearn.exceptions.NotFittedError` until it is fitted (no fallback); +- ``forward`` returns torch tensors: ``(batch, n_classes)`` **log-probabilities** for + classification (``log`` of ``predict_proba``, the convention of ``wildfire_forecasting``; columns + follow ``estimator.classes_``, and a class with probability 0 gets ``-inf``), and + ``(batch, n_targets)`` predictions for regression. Outputs carry no gradient; +- ``state_dict()`` is empty, so torch checkpoints do not hold the fitted trees. Use + :meth:`EstimatorModule.save` / :meth:`EstimatorModule.load` (joblib). + +Inputs are either ready-made features ``(batch, n_features)`` or, when a ``daily_layout`` is set, +the daily tensor ``(batch, time, n_dynamic + n_static + n_land_cover)`` that the +``wildfire_forecasting`` LSTM reads. Daily tensors are turned into the instance features of +Kondylatos et al. (2022) by :func:`kondylatos_instance_features`. + +``random_forest`` reproduces the random forest of Kondylatos, Prapas, Ronco, Papoutsis, Camps-Valls, +Piles, Fernandez-Torres & Carvalhais, "Wildfire Danger Prediction and Understanding With Deep +Learning", GRL 49(17), e2022GL099368 (2022), as configured in the official notebook +``notebooks/RF.ipynb`` of Orion-AI-Lab/wildfire_forecasting (MIT License, Copyright (c) 2022 iprapas, +commit 2b18bcf194284d56bd4e1774f7d5315db94cba34): scikit-learn ``RandomForestClassifier( +n_estimators=100, max_depth=10, min_samples_split=2, min_samples_leaf=1, random_state=123)`` on the +35 instance features. The feature construction follows the notebook's loop. ``xgboost`` wraps +``xgboost.XGBClassifier`` with the library defaults (the paper's XGBoost hyperparameters are in its +Supporting Information, which has not been read), and needs the optional ``xgboost`` package. +""" + +from __future__ import annotations + +import warnings +from pathlib import Path +from typing import Any, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn + +ESTIMATOR_TASKS = ("classification", "regression") + +# Kondylatos et al. (2022): 10 dynamic variables, 5 static variables and the 10 Corine Land Cover +# fractions per day, concatenated in that order (as combine_dynamic_static_inputs does for the LSTM). +KONDYLATOS_DAILY_LAYOUT = (10, 5, 10) + +# notebooks/RF.ipynb (cells 4 and 5). +KONDYLATOS_RF_PARAMS = { + "n_estimators": 100, + "max_depth": 10, + "min_samples_split": 2, + "min_samples_leaf": 1, + "random_state": 123, +} + +_SAVE_FORMAT = "pyhazards.EstimatorModule" +_SAVE_VERSION = 1 + +ArrayLike = Union[torch.Tensor, np.ndarray, Sequence[Any]] + + +def _to_numpy(values: ArrayLike) -> np.ndarray: + if isinstance(values, torch.Tensor): + return values.detach().cpu().numpy() + return np.asarray(values) + + +def _check_layout(layout: Sequence[int]) -> Tuple[int, int, int]: + if len(layout) != 3 or any(int(size) < 0 for size in layout) or int(layout[0]) < 1: + raise ValueError( + "daily_layout must be (n_dynamic, n_static, n_land_cover) with n_dynamic >= 1, " + f"got {tuple(layout)!r}" + ) + return int(layout[0]), int(layout[1]), int(layout[2]) + + +def kondylatos_instance_features( + daily: ArrayLike, + n_dynamic: int = 10, + n_static: int = 5, + n_land_cover: int = 10, +) -> np.ndarray: + """Instance features of Kondylatos et al. (2022) from a daily tensor. + + ``daily`` is ``(batch, time, n_dynamic + n_static + n_land_cover)``, oldest day first, with the + dynamic variables, the static variables and the land-cover fractions concatenated in that order + (the static and land-cover columns are repeated over time, as the official + ``combine_dynamic_static_inputs`` builds the LSTM input). Returns a float64 array + ``(batch, 2 * n_dynamic + n_static + n_land_cover)``, 35 columns for the paper's layout:: + + [nanmean of the dynamic variables over the days, dynamic variables on the last day (t-1), + static variables, land-cover fractions] + + exactly as ``notebooks/RF.ipynb`` concatenates them (NaNs are ignored by the mean; a variable + that is NaN on every day gives NaN, which the notebook also passes on). Static and land-cover + values are read from the last day. The computation is done in float64 like the notebook, so + the features match it bit for bit when ``daily`` holds the same values. + """ + n_dynamic, n_static, n_land_cover = _check_layout((n_dynamic, n_static, n_land_cover)) + array = np.asarray(_to_numpy(daily), dtype=np.float64) + expected = n_dynamic + n_static + n_land_cover + if array.ndim != 3 or array.shape[1] < 1 or array.shape[2] != expected: + raise ValueError( + "kondylatos_instance_features expects a daily tensor of shape (batch, time, " + f"{expected}) = (batch, time, {n_dynamic} dynamic + {n_static} static + " + f"{n_land_cover} land cover), got shape {tuple(array.shape)}." + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=RuntimeWarning) # all-NaN columns, as in the notebook + dynamic_mean = np.nanmean(array[:, :, :n_dynamic], axis=1) + last_day = array[:, -1, :] # dynamic at t-1, then static, then land cover + return np.concatenate([dynamic_mean, last_day], axis=1) + + +class EstimatorModule(nn.Module): + """``nn.Module`` holding a fitted-or-not scikit-learn-compatible estimator. + + Parameters + ---------- + estimator: + Any object with ``fit`` / ``predict`` (and ``predict_proba`` for classification), e.g. a + scikit-learn or ``xgboost`` estimator. + task: + ``"classification"`` or ``"regression"``. + daily_layout: + ``(n_dynamic, n_static, n_land_cover)``. When set, 3-D input ``(batch, time, sum)`` is + converted with :func:`kondylatos_instance_features`; 2-D input is always used as features. + name: + Label used in messages (the registry name). + + Saving and loading use joblib, i.e. pickle: :meth:`load` can execute arbitrary code from the + file, so only load files you trust. + """ + + def __init__( + self, + estimator: Any, + task: str = "classification", + daily_layout: Optional[Sequence[int]] = None, + name: Optional[str] = None, + ): + super().__init__() + task = task.lower() + if task not in ESTIMATOR_TASKS: + raise ValueError(f"EstimatorModule supports task in {ESTIMATOR_TASKS}, got {task!r}.") + if task == "classification" and not hasattr(estimator, "predict_proba"): + raise ValueError(f"{type(estimator).__name__} has no predict_proba; it cannot back a classifier.") + self.estimator = estimator + self.task = task + self.daily_layout = _check_layout(daily_layout) if daily_layout is not None else None + self.name = name or type(estimator).__name__ + + @property + def custom_fit_reason(self) -> str: + """Why :class:`pyhazards.engine.Trainer` must not ``fit`` this module (it raises with this text).""" + return ( + f"'{self.name}' wraps a {type(self.estimator).__name__} and is not trained by gradient " + "descent. Fit it on the whole training split with model.fit(inputs, targets), e.g. " + "model.fit(bundle.get_split('train').inputs, bundle.get_split('train').targets); " + "Trainer.evaluate and Trainer.predict work on the fitted model." + ) + + @property + def is_fitted(self) -> bool: + from sklearn.exceptions import NotFittedError # scikit-learn is imported only when used + from sklearn.utils.validation import check_is_fitted + + try: + check_is_fitted(self.estimator) + except NotFittedError: + return False + return True + + def features(self, inputs: ArrayLike) -> np.ndarray: + """The 2-D feature matrix the estimator sees for ``inputs``.""" + array = _to_numpy(inputs) + if array.ndim == 2: + return array + if array.ndim == 3 and self.daily_layout is not None: + return kondylatos_instance_features(array, *self.daily_layout) + expected = "(batch, features)" + if self.daily_layout is not None: + expected += " or a daily tensor (batch, time, {n})".format(n=sum(self.daily_layout)) + raise ValueError(f"{self.name} expects input shape {expected}, got shape {tuple(array.shape)}.") + + def fit(self, inputs: ArrayLike, targets: ArrayLike, **fit_kwargs: Any) -> "EstimatorModule": + """Fit the estimator on all of ``inputs`` / ``targets`` (tensors or arrays) and return ``self``. + + Classification targets are class labels ``(batch,)`` (``(batch, 1)`` is flattened, as the + notebook's ``y_train.ravel()``). Extra keyword arguments go to ``estimator.fit``. + """ + features = self.features(inputs) + labels = _to_numpy(targets) + if self.task == "classification": + if labels.ndim == 2 and labels.shape[1] == 1: + labels = labels.ravel() + if labels.ndim != 1: + raise ValueError( + f"{self.name} classification targets must have shape (batch,), got shape {tuple(labels.shape)}." + ) + if labels.shape[0] != features.shape[0]: + raise ValueError( + f"{self.name} got {features.shape[0]} input rows but targets of shape {tuple(labels.shape)}." + ) + self.estimator.fit(features, labels, **fit_kwargs) + return self + + def _fitted_features(self, inputs: ArrayLike) -> np.ndarray: + from sklearn.exceptions import NotFittedError + + if not self.is_fitted: + raise NotFittedError( + f"{self.name} is not fitted yet: call model.fit(inputs, targets) before predicting." + ) + features = self.features(inputs) + expected = getattr(self.estimator, "n_features_in_", None) + if expected is not None and features.shape[1] != expected: + raise ValueError( + f"{self.name} was fitted on {expected} features, but the input gives " + f"{features.shape[1]} (input shape {tuple(_to_numpy(inputs).shape)})." + ) + return features + + def predict_proba(self, inputs: ArrayLike) -> np.ndarray: + """Class probabilities from ``estimator.predict_proba`` (classification only).""" + if self.task != "classification": + raise ValueError(f"{self.name} is a regressor; predict_proba needs task='classification'.") + return self.estimator.predict_proba(self._fitted_features(inputs)) + + def predict(self, inputs: ArrayLike) -> np.ndarray: + """``estimator.predict``: class labels for classification, values for regression.""" + return self.estimator.predict(self._fitted_features(inputs)) + + def forward(self, x: ArrayLike) -> torch.Tensor: + if self.task == "classification": + with np.errstate(divide="ignore"): + values = np.log(self.predict_proba(x)) + else: + values = self.predict(x) + if values.ndim == 1: + values = values.reshape(-1, 1) + if isinstance(x, torch.Tensor): + dtype = x.dtype if x.is_floating_point() else torch.get_default_dtype() + return torch.as_tensor(values, dtype=dtype, device=x.device) + return torch.as_tensor(values, dtype=torch.get_default_dtype()) + + def save(self, path: Union[str, Path]) -> None: + """Write the module (estimator, task, layout, name) to ``path`` with joblib.""" + import joblib + + joblib.dump( + { + "format": _SAVE_FORMAT, + "version": _SAVE_VERSION, + "name": self.name, + "task": self.task, + "daily_layout": self.daily_layout, + "estimator": self.estimator, + }, + path, + ) + + @classmethod + def load(cls, path: Union[str, Path]) -> "EstimatorModule": + """Load a module written by :meth:`save`. + + This unpickles the file (joblib), which can run arbitrary code: only load trusted files. + """ + import joblib + + payload = joblib.load(path) + if not isinstance(payload, dict) or payload.get("format") != _SAVE_FORMAT: + raise ValueError(f"{path} was not written by EstimatorModule.save.") + return cls( + payload["estimator"], + task=payload["task"], + daily_layout=payload["daily_layout"], + name=payload["name"], + ) + + def extra_repr(self) -> str: + return f"name={self.name!r}, task={self.task!r}, fitted={self.is_fitted}, estimator={self.estimator!r}" + + +def _estimator_task(task: str, name: str) -> str: + task = task.lower() + if task not in ESTIMATOR_TASKS: + raise ValueError(f"{name} supports task in {ESTIMATOR_TASKS}, got {task!r}.") + return task + + +def random_forest_builder( + task: str, + n_estimators: int = 100, + max_depth: Optional[int] = 10, + min_samples_split: int = 2, + min_samples_leaf: int = 1, + random_state: Optional[int] = 123, + daily_layout: Optional[Sequence[int]] = KONDYLATOS_DAILY_LAYOUT, + **kwargs: Any, +) -> EstimatorModule: + """Random forest (Breiman, 2001) with the Kondylatos et al. (2022) notebook configuration. + + ``task="classification"`` builds ``RandomForestClassifier``, ``task="regression"`` + ``RandomForestRegressor``, both with the notebook's hyperparameters unless overridden. Other + keyword arguments (``n_jobs``, ``class_weight``, ...) go to the scikit-learn estimator. + """ + from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor + + kwargs.pop("name", None) + task = _estimator_task(task, "random_forest") + estimator_cls = RandomForestClassifier if task == "classification" else RandomForestRegressor + estimator = estimator_cls( + n_estimators=n_estimators, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + random_state=random_state, + **kwargs, + ) + return EstimatorModule(estimator, task=task, daily_layout=daily_layout, name="random_forest") + + +def _import_xgboost(): + try: + import xgboost + except ImportError as exc: + raise ImportError( + "The 'xgboost' model needs the optional xgboost package: pip install 'pyhazards[xgboost]' " + "(or the CPU-only build, pip install xgboost-cpu)." + ) from exc + return xgboost + + +def xgboost_builder( + task: str, + daily_layout: Optional[Sequence[int]] = KONDYLATOS_DAILY_LAYOUT, + **kwargs: Any, +) -> EstimatorModule: + """XGBoost (Chen & Guestrin, 2016) on the Kondylatos et al. (2022) instance features. + + Builds ``xgboost.XGBClassifier`` (``task="classification"``) or ``XGBRegressor`` with the library + defaults; keyword arguments (``n_estimators``, ``max_depth``, ``learning_rate``, ``n_jobs``, ...) + are passed to it. ``xgboost`` is imported only here. + """ + kwargs.pop("name", None) + task = _estimator_task(task, "xgboost") + xgboost = _import_xgboost() + estimator_cls = xgboost.XGBClassifier if task == "classification" else xgboost.XGBRegressor + return EstimatorModule(estimator_cls(**kwargs), task=task, daily_layout=daily_layout, name="xgboost") + + +__all__ = [ + "ESTIMATOR_TASKS", + "EstimatorModule", + "KONDYLATOS_DAILY_LAYOUT", + "KONDYLATOS_RF_PARAMS", + "kondylatos_instance_features", + "random_forest_builder", + "xgboost_builder", +] diff --git a/pyhazards/models/cnn_aspp.py b/pyhazards/models/cnn_aspp.py index d2dc8f10..97889bb8 100644 --- a/pyhazards/models/cnn_aspp.py +++ b/pyhazards/models/cnn_aspp.py @@ -1,172 +1,86 @@ +"""CNN-ASPP for next-day wildfire spread (Marjani et al., IEEE GRSL 2024). + +Reimplementation of the network described in Marjani, Mahdianpari, Ahmadi, Hemmati, +Mohammadimanesh & Mesgari, "Application of Explainable Artificial Intelligence in Predicting +Wildfire Spread: An ASPP-Enabled CNN Approach", IEEE Geoscience and Remote Sensing Letters 21 +(2024) 2504005, doi:10.1109/LGRS.2024.3417624 (Section II-C and Fig. 2). No code was released. + +Architecture (all convolutions keep the 64 x 64 resolution of Next Day Wildfire Spread tiles): +two 3x3 convolutions with 64 and 128 filters; four parallel 3x3 atrous convolutions with 32 +filters and dilation rates 1, 3, 6 and 12, concatenated (128 channels); two 3x3 convolutions +with 32 filters; batch normalisation; a 1x1 convolution to one output. Every convolution +except the last uses ReLU. The paper applies a sigmoid in the last layer; this module returns +the logits and leaves the sigmoid to the loss. The paper trains with the Tversky loss +(alpha = 0.7 on false negatives, beta = 0.3 on false positives), batch size 8 and learning +rate 4e-4 in TensorFlow; Keras defaults (Glorot-uniform kernels, zero biases, BatchNorm +epsilon 1e-3 and momentum 0.99) are used for what the paper does not state. +""" + from __future__ import annotations from typing import Sequence import torch import torch.nn as nn -import torch.nn.functional as F - - -# --------------------------------------------------------------------- -# Basic blocks -# --------------------------------------------------------------------- - -class ConvBNReLU(nn.Module): - def __init__( - self, - in_ch: int, - out_ch: int, - k: int = 3, - s: int = 1, - p: int = 1, - d: int = 1, - ): - super().__init__() - self.conv = nn.Conv2d( - in_ch, - out_ch, - kernel_size=k, - stride=s, - padding=p, - dilation=d, - bias=False, - ) - self.bn = nn.BatchNorm2d(out_ch) - self.act = nn.ReLU(inplace=True) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.act(self.bn(self.conv(x))) - -# --------------------------------------------------------------------- -# ASPP -# --------------------------------------------------------------------- - -class ASPP(nn.Module): - """ - Atrous Spatial Pyramid Pooling (ASPP). - - Parallel atrous convolutions + image pooling branch, - followed by projection. - """ - - def __init__( - self, - in_ch: int, - out_ch: int, - dilations: Sequence[int] = (1, 3, 6, 12), - ): - super().__init__() - - if len(dilations) != 4: - raise ValueError("ASPP expects exactly 4 dilation rates") - - d1, d2, d3, d4 = dilations - - self.b1 = ConvBNReLU(in_ch, out_ch, k=1, p=0, d=d1) - self.b2 = ConvBNReLU(in_ch, out_ch, k=3, p=d2, d=d2) - self.b3 = ConvBNReLU(in_ch, out_ch, k=3, p=d3, d=d3) - self.b4 = ConvBNReLU(in_ch, out_ch, k=3, p=d4, d=d4) - - self.pool = nn.Sequential( - nn.AdaptiveAvgPool2d(1), - ConvBNReLU(in_ch, out_ch, k=1, p=0), - ) - - self.proj = ConvBNReLU(out_ch * 5, out_ch, k=1, p=0) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - b, c, h, w = x.shape - - p = self.pool(x) - p = F.interpolate(p, size=(h, w), mode="bilinear", align_corners=False) - - y = torch.cat( - [self.b1(x), self.b2(x), self.b3(x), self.b4(x), p], - dim=1, - ) - return self.proj(y) - - -# --------------------------------------------------------------------- -# CNN + ASPP model -# --------------------------------------------------------------------- class WildfireCNNASPP(nn.Module): - """ - CNN + ASPP wildfire segmentation model. - - Input: - x : (B, C, H, W) float tensor + """CNN-ASPP: input ``(batch, channels, height, width)``, output ``(batch, 1, height, width)`` logits.""" - Output: - logits : (B, 1, H, W) float tensor - (sigmoid applied externally) - """ - - def __init__( - self, - in_channels: int = 12, - base_channels: int = 32, - aspp_channels: int = 32, - dilations: Sequence[int] = (1, 3, 6, 12), - dropout: float = 0.0, - ): + def __init__(self, in_channels: int = 12, dilations: Sequence[int] = (1, 3, 6, 12)): super().__init__() - - self.stem = nn.Sequential( - ConvBNReLU(in_channels, base_channels, k=3, p=1), - ConvBNReLU(base_channels, base_channels, k=3, p=1), + if in_channels <= 0: + raise ValueError(f"in_channels must be positive, got {in_channels}") + dilations = tuple(int(d) for d in dilations) + if len(dilations) != 4 or min(dilations) <= 0: + raise ValueError(f"dilations must be four positive integers, got {dilations}") + self.in_channels = int(in_channels) + self.encoder = nn.Sequential( + nn.Conv2d(in_channels, 64, kernel_size=3, padding=1), + nn.ReLU(), + nn.Conv2d(64, 128, kernel_size=3, padding=1), + nn.ReLU(), ) - - self.aspp = ASPP( - in_ch=base_channels, - out_ch=aspp_channels, - dilations=dilations, + self.aspp = nn.ModuleList( + nn.Sequential(nn.Conv2d(128, 32, kernel_size=3, padding=d, dilation=d), nn.ReLU()) + for d in dilations ) - - self.drop = nn.Dropout2d(dropout) if dropout > 0 else nn.Identity() - self.head = nn.Conv2d(aspp_channels, 1, kernel_size=1) + self.decoder = nn.Sequential( + nn.Conv2d(32 * len(dilations), 32, kernel_size=3, padding=1), + nn.ReLU(), + nn.Conv2d(32, 32, kernel_size=3, padding=1), + nn.ReLU(), + # Keras BatchNormalization defaults: epsilon 1e-3, moving-average momentum 0.99. + nn.BatchNorm2d(32, eps=1e-3, momentum=0.01), + ) + self.head = nn.Conv2d(32, 1, kernel_size=1) + for module in self.modules(): + if isinstance(module, nn.Conv2d): + nn.init.xavier_uniform_(module.weight) + nn.init.zeros_(module.bias) def forward(self, x: torch.Tensor) -> torch.Tensor: if x.ndim != 4: raise ValueError( - f"Expected input of shape (B,C,H,W), got {tuple(x.shape)}" + f"WildfireCNNASPP expects input shape (batch, channels, height, width), got {tuple(x.shape)}." ) - - f = self.stem(x) - y = self.aspp(f) - y = self.drop(y) - return self.head(y) + if x.size(1) != self.in_channels: + raise ValueError(f"WildfireCNNASPP expected {self.in_channels} channels, got {x.size(1)}.") + features = self.encoder(x) + features = torch.cat([branch(features) for branch in self.aspp], dim=1) + return self.head(self.decoder(features)) -# --------------------------------------------------------------------- -# PyHazards model builder -# --------------------------------------------------------------------- - def cnn_aspp_builder( task: str, in_channels: int = 12, - base_channels: int = 32, - aspp_channels: int = 32, dilations: Sequence[int] = (1, 3, 6, 12), - dropout: float = 0.0, **kwargs, ) -> nn.Module: - """ - PyHazards-style model builder. - """ - _ = kwargs # explicitly ignore unused builder args + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"wildfire_aspp supports task='segmentation', got {task!r}.") + return WildfireCNNASPP(in_channels=in_channels, dilations=dilations) - if "segmentation" not in task: - raise ValueError( - f"WildfireCNNASPP is segmentation-only. Got task='{task}'" - ) - return WildfireCNNASPP( - in_channels=in_channels, - base_channels=base_channels, - aspp_channels=aspp_channels, - dilations=dilations, - dropout=dropout, - ) +__all__ = ["WildfireCNNASPP", "cnn_aspp_builder"] diff --git a/pyhazards/models/convgru.py b/pyhazards/models/convgru.py new file mode 100644 index 00000000..69a70811 --- /dev/null +++ b/pyhazards/models/convgru.py @@ -0,0 +1,187 @@ +"""Convolutional GRU encoder with a convolutional head: the Conv-GRU baseline of FireCastNet. + +The recurrence is the convolutional GRU of Ballas et al. (ICLR 2016, arXiv:1511.06432, Eq. 7-8): +``z = sigmoid(W_z * x + U_z * h)``, ``r = sigmoid(W_r * x + U_r * h)``, +``h~ = tanh(W * x + U * (r . h))``, ``h' = (1 - z) . h + z . h~``, with ``W * x + U * h`` +computed as one convolution over ``[x, h]``. The model is the ``ConvGRUSeg`` network that +FireCastNet (Michail et al., Scientific Reports 2025, arXiv:2502.01550) trained as its Conv-GRU +baseline: a stack of cells over ``(batch, time, channels, height, width)`` and a ``Conv2d`` head on +the last hidden state. + +This file is written for PyHazards from those equations and parallels +:mod:`pyhazards.models.convlstm`. FireCastNet's implementation (SeasFire/firecastnet, +``seasfire/backbones/conv_gru.py``, "modified from TUM-LMF/MTLCC-pytorch") has no license, so none +of its code is copied; it is used only as the test oracle. Module names and creation order follow +it, so its state dicts load with ``strict=True`` and the same seed gives the same initial weights. +""" + +from __future__ import annotations + +from typing import List, Sequence, Tuple, Union + +import torch +import torch.nn as nn + +KernelSize = Union[int, Tuple[int, int]] + + +def _pair(kernel_size: KernelSize) -> Tuple[int, int]: + if isinstance(kernel_size, int): + return (kernel_size, kernel_size) + kernel = tuple(int(k) for k in kernel_size) + if len(kernel) != 2: + raise ValueError(f"kernel_size must be an int or a pair, got {kernel_size!r}") + return kernel # type: ignore[return-value] + + +class ConvGRUCell(nn.Module): + """One ConvGRU step: ``in_conv`` gives the update and reset gates, ``out_conv`` the candidate.""" + + def __init__(self, input_dim: int, hidden_dim: int, kernel_size: KernelSize = 3, bias: bool = True): + super().__init__() + self.input_dim = int(input_dim) + self.hidden_dim = int(hidden_dim) + self.kernel_size = _pair(kernel_size) + self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2) + self.in_conv = nn.Conv2d( + self.input_dim + self.hidden_dim, 2 * self.hidden_dim, self.kernel_size, padding=self.padding, bias=bias + ) + self.out_conv = nn.Conv2d( + self.input_dim + self.hidden_dim, self.hidden_dim, self.kernel_size, padding=self.padding, bias=bias + ) + + def forward(self, x: torch.Tensor, h: torch.Tensor) -> torch.Tensor: + update, reset = torch.sigmoid(self.in_conv(torch.cat([x, h], dim=1))).chunk(2, dim=1) + candidate = torch.tanh(self.out_conv(torch.cat([x, reset * h], dim=1))) + return (1 - update) * h + update * candidate + + def init_hidden(self, batch_size: int, height: int, width: int, like: torch.Tensor) -> torch.Tensor: + return like.new_zeros(batch_size, self.hidden_dim, height, width) + + +class ConvGRU(nn.Module): + """Stacked ConvGRU over ``(batch, time, channels, height, width)`` sequences. + + Returns the per-step hidden states of the last layer and the final hidden state of every layer. + """ + + def __init__( + self, + input_dim: int, + hidden_dim: Union[int, Sequence[int]], + kernel_size: Union[KernelSize, Sequence[KernelSize]] = 3, + num_layers: int = 1, + bias: bool = True, + ): + super().__init__() + if num_layers <= 0: + raise ValueError(f"num_layers must be positive, got {num_layers}") + hidden_dims = list(hidden_dim) if isinstance(hidden_dim, (list, tuple)) else [hidden_dim] * num_layers + if isinstance(kernel_size, (list, tuple)) and kernel_size and isinstance(kernel_size[0], (list, tuple)): + kernel_sizes = [_pair(k) for k in kernel_size] + else: + kernel_sizes = [_pair(kernel_size)] * num_layers + if not len(hidden_dims) == len(kernel_sizes) == num_layers: + raise ValueError("hidden_dim and kernel_size lists must have num_layers entries.") + self.input_dim = int(input_dim) + self.hidden_dim = [int(h) for h in hidden_dims] + self.num_layers = int(num_layers) + self.cell_list = nn.ModuleList( + ConvGRUCell( + input_dim=self.input_dim if i == 0 else self.hidden_dim[i - 1], + hidden_dim=self.hidden_dim[i], + kernel_size=kernel_sizes[i], + bias=bias, + ) + for i in range(self.num_layers) + ) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + if x.ndim != 5: + raise ValueError( + f"ConvGRU expects input shape (batch, time, channels, height, width), got {tuple(x.shape)}." + ) + batch, steps, _, height, width = x.shape + layer_input = x + last_states: List[torch.Tensor] = [] + for cell in self.cell_list: + h = cell.init_hidden(batch, height, width, like=x) + outputs = [] + for t in range(steps): + h = cell(layer_input[:, t], h) + outputs.append(h) + layer_input = torch.stack(outputs, dim=1) + last_states.append(h) + return layer_input, last_states + + +class ConvGRUSegmenter(nn.Module): + """ConvGRU encoder + ``Conv2d`` head on the last hidden state (FireCastNet's ``ConvGRUSeg``). + + Input ``(batch, time, channels, height, width)``; output ``(batch, num_classes, height, width)`` + logits. The head uses the cells' kernel size with padding ``(kernel - 1) // 2`` per dimension. + """ + + def __init__( + self, + input_dim: int, + num_classes: int = 1, + hidden_dim: int = 128, + kernel_size: KernelSize = 5, + num_layers: int = 1, + ): + super().__init__() + if input_dim <= 0: + raise ValueError(f"input_dim must be positive, got {input_dim}") + if num_classes <= 0: + raise ValueError(f"num_classes must be positive, got {num_classes}") + kernel = _pair(kernel_size) + self.input_dim = int(input_dim) + self.convgru_encoder = ConvGRU(input_dim=input_dim, hidden_dim=hidden_dim, kernel_size=kernel, num_layers=num_layers) + self.classification_layer = nn.Conv2d( + in_channels=int(hidden_dim), + out_channels=num_classes, + kernel_size=kernel, + padding=((kernel[0] - 1) // 2, (kernel[1] - 1) // 2), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 5: + raise ValueError( + "ConvGRUSegmenter expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + if x.size(2) != self.input_dim: + raise ValueError(f"ConvGRUSegmenter expected {self.input_dim} channels, got input of shape {tuple(x.shape)}.") + _, states = self.convgru_encoder(x) + return self.classification_layer(states[-1]) + + +def convgru_builder( + task: str, + in_channels: int = 11, + out_channels: int = 1, + hidden_dim: int = 128, + kernel_size: KernelSize = 5, + num_layers: int = 1, + **kwargs, +) -> nn.Module: + """FireCastNet's Conv-GRU baseline; defaults are its ``configs/conv-gru-config.yaml``.""" + _ = kwargs + if task.lower() != "segmentation": + raise ValueError( + f"convgru supports task='segmentation' (the FireCastNet ConvGRUSeg model), got {task!r}. " + "For a ConvGRU frame forecaster use build_model('trajgru', task='forecasting', layer_type='ConvGRU')." + ) + if hidden_dim <= 0: + raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") + return ConvGRUSegmenter( + input_dim=in_channels, + num_classes=out_channels, + hidden_dim=hidden_dim, + kernel_size=kernel_size, + num_layers=num_layers, + ) + + +__all__ = ["ConvGRUCell", "ConvGRU", "ConvGRUSegmenter", "convgru_builder"] diff --git a/pyhazards/models/convlstm.py b/pyhazards/models/convlstm.py new file mode 100644 index 00000000..60ea05bb --- /dev/null +++ b/pyhazards/models/convlstm.py @@ -0,0 +1,203 @@ +"""ConvLSTM encoder with a convolutional segmentation head. + +Port of the ConvLSTM used by the WildfireSpreadTS benchmark (Gerard et al., NeurIPS 2023 +Datasets & Benchmarks). WildfireSpreadTS vendors it from ``VSainteuf/utae-paps`` +(``src/backbones/convlstm.py``, MIT), which in turn takes it from ``TUM-LMF/MTLCC-pytorch``. +The recurrence follows Shi et al. (NeurIPS 2015) without peephole connections, and the +segmentation head reads the *cell state* of the last time step, exactly as the reference +``ConvLSTM_Seg`` does. + +Parameter names match the reference modules, so reference state dicts load with +``strict=True``. +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn + +KernelSize = Union[int, Tuple[int, int]] + + +def _pair(kernel_size: KernelSize) -> Tuple[int, int]: + if isinstance(kernel_size, int): + return (kernel_size, kernel_size) + kernel = tuple(int(k) for k in kernel_size) + if len(kernel) != 2: + raise ValueError(f"kernel_size must be an int or a pair, got {kernel_size!r}") + return kernel # type: ignore[return-value] + + +class ConvLSTMCell(nn.Module): + """One ConvLSTM step: a single convolution over ``[x_t, h_{t-1}]`` produces the four gates.""" + + def __init__(self, input_dim: int, hidden_dim: int, kernel_size: KernelSize = 3, bias: bool = True): + super().__init__() + self.input_dim = int(input_dim) + self.hidden_dim = int(hidden_dim) + self.kernel_size = _pair(kernel_size) + self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2) + self.conv = nn.Conv2d( + in_channels=self.input_dim + self.hidden_dim, + out_channels=4 * self.hidden_dim, + kernel_size=self.kernel_size, + padding=self.padding, + bias=bias, + ) + + def forward( + self, x: torch.Tensor, state: Tuple[torch.Tensor, torch.Tensor] + ) -> Tuple[torch.Tensor, torch.Tensor]: + h_cur, c_cur = state + gates = self.conv(torch.cat([x, h_cur], dim=1)) + cc_i, cc_f, cc_o, cc_g = torch.split(gates, self.hidden_dim, dim=1) + i = torch.sigmoid(cc_i) + f = torch.sigmoid(cc_f) + o = torch.sigmoid(cc_o) + g = torch.tanh(cc_g) + c_next = f * c_cur + i * g + h_next = o * torch.tanh(c_next) + return h_next, c_next + + def init_hidden(self, batch_size: int, height: int, width: int, like: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + zeros = like.new_zeros(batch_size, self.hidden_dim, height, width) + return zeros, zeros.clone() + + +class ConvLSTM(nn.Module): + """Stacked ConvLSTM over ``(batch, time, channels, height, width)`` sequences. + + Returns the per-step hidden states of the last layer and the final ``(h, c)`` of every layer. + Unlike the reference code, the spatial size is taken from the input instead of being fixed + at construction time; outputs are identical for the size the reference was built with. + """ + + def __init__( + self, + input_dim: int, + hidden_dim: Union[int, Sequence[int]], + kernel_size: Union[KernelSize, Sequence[KernelSize]] = 3, + num_layers: int = 1, + bias: bool = True, + ): + super().__init__() + if num_layers <= 0: + raise ValueError(f"num_layers must be positive, got {num_layers}") + hidden_dims = list(hidden_dim) if isinstance(hidden_dim, (list, tuple)) else [hidden_dim] * num_layers + if isinstance(kernel_size, (list, tuple)) and kernel_size and isinstance(kernel_size[0], (list, tuple)): + kernel_sizes = [_pair(k) for k in kernel_size] + else: + kernel_sizes = [_pair(kernel_size)] * num_layers + if not len(hidden_dims) == len(kernel_sizes) == num_layers: + raise ValueError("hidden_dim and kernel_size lists must have num_layers entries.") + + self.input_dim = int(input_dim) + self.hidden_dim = [int(h) for h in hidden_dims] + self.num_layers = int(num_layers) + self.cell_list = nn.ModuleList( + ConvLSTMCell( + input_dim=self.input_dim if i == 0 else self.hidden_dim[i - 1], + hidden_dim=self.hidden_dim[i], + kernel_size=kernel_sizes[i], + bias=bias, + ) + for i in range(self.num_layers) + ) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[Tuple[torch.Tensor, torch.Tensor]]]: + if x.ndim != 5: + raise ValueError( + "ConvLSTM expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + batch, steps, _, height, width = x.shape + layer_input = x + last_states: List[Tuple[torch.Tensor, torch.Tensor]] = [] + for cell in self.cell_list: + h, c = cell.init_hidden(batch, height, width, like=x) + outputs = [] + for t in range(steps): + h, c = cell(layer_input[:, t], (h, c)) + outputs.append(h) + layer_input = torch.stack(outputs, dim=1) + last_states.append((h, c)) + return layer_input, last_states + + +class ConvLSTMSegmenter(nn.Module): + """ConvLSTM encoder + ``Conv2d`` head on the last cell state (the WildfireSpreadTS ConvLSTM). + + Input ``(batch, time, channels, height, width)``; output ``(batch, num_classes, height, width)`` logits. + """ + + def __init__( + self, + input_dim: int, + num_classes: int = 1, + hidden_dim: int = 64, + kernel_size: KernelSize = 3, + num_layers: int = 1, + readout: str = "cell", + ): + super().__init__() + if input_dim <= 0: + raise ValueError(f"input_dim must be positive, got {input_dim}") + if num_classes <= 0: + raise ValueError(f"num_classes must be positive, got {num_classes}") + if readout not in {"cell", "hidden"}: + raise ValueError(f"readout must be 'cell' or 'hidden', got {readout!r}") + kernel = _pair(kernel_size) + self.input_dim = int(input_dim) + self.readout = readout + self.convlstm_encoder = ConvLSTM( + input_dim=input_dim, + hidden_dim=hidden_dim, + kernel_size=kernel, + num_layers=num_layers, + ) + self.classification_layer = nn.Conv2d( + in_channels=int(hidden_dim), + out_channels=num_classes, + kernel_size=kernel, + padding=(kernel[0] // 2, kernel[1] // 2), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 5: + raise ValueError( + "ConvLSTMSegmenter expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + if x.size(2) != self.input_dim: + raise ValueError(f"ConvLSTMSegmenter expected {self.input_dim} channels, got {x.size(2)}.") + _, states = self.convlstm_encoder(x) + h, c = states[-1] + return self.classification_layer(c if self.readout == "cell" else h) + + +def convlstm_builder( + task: str, + in_channels: int, + out_channels: int = 1, + hidden_dim: int = 64, + kernel_size: KernelSize = 3, + num_layers: int = 1, + readout: str = "cell", + **kwargs, +) -> nn.Module: + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"convlstm supports task='segmentation', got {task!r}.") + return ConvLSTMSegmenter( + input_dim=in_channels, + num_classes=out_channels, + hidden_dim=hidden_dim, + kernel_size=kernel_size, + num_layers=num_layers, + readout=readout, + ) + + +__all__ = ["ConvLSTMCell", "ConvLSTM", "ConvLSTMSegmenter", "convlstm_builder"] diff --git a/pyhazards/models/deep_ensemble.py b/pyhazards/models/deep_ensemble.py new file mode 100644 index 00000000..3caa8b86 --- /dev/null +++ b/pyhazards/models/deep_ensemble.py @@ -0,0 +1,455 @@ +"""Deep ensembles of any registered PyHazards model. + +Lakshminarayanan, Pritzel & Blundell, "Simple and Scalable Predictive Uncertainty Estimation using +Deep Ensembles", NeurIPS 2017 (arXiv 1612.01474). The paper released no code; this module follows +its Section 2 and Algorithm 1: + +- ``M`` members (default 5) of the same architecture, each from its own random initialisation + (``seeds``; the builder seeds ``torch`` with ``seeds[m]`` before building member ``m``) and + trained independently on the whole training set with its own data shuffling + (:meth:`DeepEnsemble.fit`; the paper found bagging unnecessary); +- prediction is the uniformly weighted mixture of the members: classification averages the member + probabilities, regression with mean/variance outputs moment-matches the Gaussian mixture, + ``mu = mean_m mu_m`` and ``sigma^2 = mean_m (sigma_m^2 + mu_m^2) - mu^2``; +- optional adversarial training with the fast gradient sign method (:func:`fgsm_example`): each + step minimises ``loss(x, y) + loss(x', y)`` with ``x' = x + epsilon * sign(grad_x loss)`` and + ``epsilon`` 1% of the training-data range of each input dimension (:func:`input_range_epsilon`). + +The uncertainty decomposition for classification (:func:`classification_uncertainties`) is the +``uncertainties`` function of the code of Kondylatos, Papadopoulos, Camps-Valls & Papoutsis, +"Uncertainty-Aware Deep Learning for Wildfire Danger Forecasting" (arXiv 2509.25017), repository +Orion-AI-Lab/uncertainty-wildfires, ``utils/train_functions.py`` (MIT License, Copyright (c) 2025 +Orion Lab, commit fcfbfb894926d173e2f4cafc95b08f02cefe6e00). That paper's deep ensemble is 10 LSTMs +(``base_model="wildfire_forecasting", base_kwargs={"hidden_size": 128}``); tests/oracle checks the +aggregation against the reference with its 10 released members. + +Outputs of :meth:`DeepEnsemble.forward` per ``task``: + +- ``classification`` / ``segmentation`` with ``C >= 2`` channels along dim 1 (logits or + log-probabilities; members are mapped to probabilities with a softmax over dim 1): the log of the + mixture probability, same shape as one member's output (e.g. ``(batch, 2)`` for + ``wildfire_forecasting``); ``exp`` gives the ensemble probabilities. +- ``classification`` / ``segmentation`` with one channel (binary logits, e.g. + ``(batch, 1, H, W)``; members are mapped with a sigmoid): the logit of the mixture probability, so + ``sigmoid`` of the output is the ensemble probability. +- ``regression`` / ``forecasting``: a tuple ``(mean, variance)``. With + ``regression_output="gaussian"`` (the paper) every member outputs ``2 * K`` channels along dim 1, + the ``K`` means followed by ``K`` raw variances that are mapped with + ``softplus(.) + min_variance`` (the paper's footnote 2); build the base model with twice the + output channels. With ``regression_output="point"`` members output point predictions and the + variance is their spread across members (the MSE-ensemble heuristic the paper compares against). + +:meth:`DeepEnsemble.predict_uncertainty` returns the ensemble prediction with its uncertainty terms. +""" + +from __future__ import annotations + +import math +from contextlib import contextmanager +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +CLASSIFICATION_TASKS = ("classification", "segmentation") +REGRESSION_TASKS = ("regression", "forecasting") +REGRESSION_OUTPUTS = ("gaussian", "point") +DEFAULT_NUM_MEMBERS = 5 # Algorithm 1: "Recommended default values are M = 5" +MIN_VARIANCE = 1e-6 # footnote 2: softplus plus a minimum variance of 1e-6 +ENTROPY_EPS = 1e-6 # ``e`` in uncertainty-wildfires' uncertainties() + +Epsilon = Union[float, torch.Tensor] +LossFn = Callable[[torch.Tensor, torch.Tensor], torch.Tensor] + + +def classification_uncertainties(member_probs: torch.Tensor, eps: float = ENTROPY_EPS) -> Dict[str, torch.Tensor]: + """Mixture prediction and uncertainty terms from member class probabilities. + + ``member_probs`` is ``(samples, batch, classes, ...)``: one probability map per ensemble member + (and per MC-dropout pass). Returns, with the class dimension at dim 1: + + - ``probs``: the uniform mixture ``mean_m p_m``; + - ``epistemic``: ``var_m p_m`` per class (population variance over the samples); + - ``aleatoric``: ``mean_m p_m (1 - p_m)`` per class; + - ``entropy``: ``-sum_c p log(p + eps)`` of the mixture (class dimension reduced); + - ``mutual_information``: entropy minus the mean member entropy + ``-mean_m sum_c p_m log(p_m + eps)``. + + These are the definitions of ``uncertainties`` in uncertainty-wildfires + (``utils/train_functions.py``), with ``eps = 1e-6`` as there. + """ + if member_probs.ndim < 3: + raise ValueError( + "classification_uncertainties expects member probabilities of shape (samples, batch, " + f"classes, ...), got shape {tuple(member_probs.shape)}." + ) + mean = member_probs.mean(dim=0) + entropy = -torch.sum(mean * torch.log(mean + eps), dim=1) + member_neg_entropy = torch.sum(member_probs * torch.log(member_probs + eps), dim=2).mean(dim=0) + return { + "probs": mean, + "epistemic": member_probs.var(dim=0, unbiased=False), + "aleatoric": (member_probs * (1 - member_probs)).mean(dim=0), + "entropy": entropy, + "mutual_information": entropy + member_neg_entropy, + } + + +def gaussian_mixture_moments(means: torch.Tensor, variances: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """Mean and variance of the uniform mixture of ``N(means[m], variances[m])`` over dim 0. + + ``sigma^2 = mean_m (sigma_m^2 + mu_m^2) - mu^2``, computed in the equivalent and numerically + safer form ``mean_m sigma_m^2 + var_m mu_m``. + """ + if means.shape != variances.shape: + raise ValueError(f"means and variances must have the same shape, got {tuple(means.shape)} and {tuple(variances.shape)}.") + return means.mean(dim=0), variances.mean(dim=0) + means.var(dim=0, unbiased=False) + + +def split_gaussian_output(output: torch.Tensor, min_variance: float = MIN_VARIANCE) -> Tuple[torch.Tensor, torch.Tensor]: + """Split a mean/variance network output ``(batch, 2K, ...)`` into ``(mean, variance)``. + + The first ``K`` channels are the means, the last ``K`` raw variances mapped with + ``softplus(.) + min_variance``. + """ + if output.ndim < 2 or output.size(1) % 2: + raise ValueError( + "A mean/variance output needs an even number of channels along dim 1 (K means followed by " + f"K raw variances), got shape {tuple(output.shape)}. Build the base model with twice the " + "output channels, or use regression_output='point'." + ) + mean, raw = output.chunk(2, dim=1) + return mean, F.softplus(raw) + min_variance + + +def gaussian_nll_loss(output: torch.Tensor, target: torch.Tensor, min_variance: float = MIN_VARIANCE) -> torch.Tensor: + """Equation 1 of the paper, averaged: ``log(sigma^2) / 2 + (y - mu)^2 / (2 sigma^2)``. + + ``output`` is a member's raw mean/variance output (see :func:`split_gaussian_output`) and + ``target`` has the shape of the mean half. + """ + mean, variance = split_gaussian_output(output, min_variance) + if target.shape != mean.shape: + raise ValueError(f"target shape {tuple(target.shape)} does not match the mean shape {tuple(mean.shape)}.") + return (0.5 * torch.log(variance) + (target - mean) ** 2 / (2 * variance)).mean() + + +def input_range_epsilon(inputs: torch.Tensor, fraction: float = 0.01, dims: Sequence[int] = (0,)) -> torch.Tensor: + """FGSM step size per input dimension: ``fraction`` of the training-data range (paper: 1%). + + The range ``max - min`` is taken over ``dims`` (default: the sample dimension), so every other + position (feature, time step, pixel) gets its own epsilon. The reduced dimensions are kept with + size 1, so the result broadcasts against a batch. NaNs are ignored; a dimension without finite + values gets epsilon 0. + """ + if fraction <= 0: + raise ValueError(f"fraction must be positive, got {fraction}") + if not inputs.is_floating_point(): + inputs = inputs.to(torch.get_default_dtype()) + dims = tuple(sorted({d % inputs.ndim for d in dims})) + missing = torch.isnan(inputs) + high = torch.where(missing, torch.full_like(inputs, -math.inf), inputs).amax(dim=dims, keepdim=True) + low = torch.where(missing, torch.full_like(inputs, math.inf), inputs).amin(dim=dims, keepdim=True) + return torch.nan_to_num(fraction * (high - low), nan=0.0, posinf=0.0, neginf=0.0) + + +def fgsm_example(model: nn.Module, inputs: torch.Tensor, targets: torch.Tensor, loss_fn: LossFn, epsilon: Epsilon) -> torch.Tensor: + """Fast gradient sign adversarial example ``x + epsilon * sign(grad_x loss(model(x), y))``. + + Only the input gradient is computed; parameter gradients are left untouched. + """ + perturbed = inputs.detach().clone().requires_grad_(True) + loss = loss_fn(model(perturbed), targets) + (gradient,) = torch.autograd.grad(loss, perturbed) + epsilon = torch.as_tensor(epsilon, dtype=inputs.dtype, device=inputs.device) + return (perturbed + epsilon * gradient.sign()).detach() + + +@contextmanager +def _dropout_enabled(module: nn.Module) -> Iterator[None]: + """Put the dropout layers in training mode (MC dropout), as ``enable_dropout`` in the reference.""" + dropouts = [m for m in module.modules() if "Dropout" in type(m).__name__] + previous = [m.training for m in dropouts] + for m in dropouts: + m.train() + try: + yield + finally: + for m, mode in zip(dropouts, previous): + m.train(mode) + + +class DeepEnsemble(nn.Module): + """Uniform mixture of independently initialised and trained members (deep ensemble). + + Parameters + ---------- + members: + The ``M`` member networks (same architecture, distinct initialisations). + task: + ``classification`` / ``segmentation`` (probability mixture) or ``regression`` / + ``forecasting`` (moment-matched Gaussian); see the module docstring for the outputs. + seeds: + The member seeds (used for initialisation by the builder and for data shuffling by + :meth:`fit`); defaults to ``0 .. M-1``. + regression_output: + ``"gaussian"`` (members output means and raw variances) or ``"point"``. + mc_dropout_passes: + ``0`` (default) runs each member once. ``k > 0`` keeps the members' dropout layers active + at prediction and pools ``k`` passes per member (``M * k`` samples), the "deep ensemble + MC + dropout" of Chakravarty (2025) and the ``forward_passes`` / ``dropout`` options of the + uncertainty-wildfires test script. + min_variance: + Added after the softplus of the variance outputs (``1e-6``). + """ + + def __init__( + self, + members: Sequence[nn.Module], + task: str = "classification", + seeds: Optional[Sequence[int]] = None, + regression_output: str = "gaussian", + mc_dropout_passes: int = 0, + min_variance: float = MIN_VARIANCE, + ): + super().__init__() + task = task.lower() + if task not in CLASSIFICATION_TASKS + REGRESSION_TASKS: + raise ValueError(f"DeepEnsemble supports task in {CLASSIFICATION_TASKS + REGRESSION_TASKS}, got {task!r}.") + if len(members) < 1: + raise ValueError("DeepEnsemble needs at least one member.") + if regression_output not in REGRESSION_OUTPUTS: + raise ValueError(f"regression_output must be one of {REGRESSION_OUTPUTS}, got {regression_output!r}.") + if mc_dropout_passes < 0: + raise ValueError(f"mc_dropout_passes must be >= 0, got {mc_dropout_passes}.") + seeds = list(range(len(members))) if seeds is None else [int(seed) for seed in seeds] + if len(seeds) != len(members) or len(set(seeds)) != len(seeds): + raise ValueError(f"seeds must be {len(members)} distinct integers, got {seeds}.") + self.members = nn.ModuleList(members) + self.task = task + self.seeds = seeds + self.regression_output = regression_output + self.mc_dropout_passes = int(mc_dropout_passes) + self.min_variance = float(min_variance) + + @property + def num_members(self) -> int: + return len(self.members) + + @property + def custom_fit_reason(self) -> str: + """Why :class:`pyhazards.engine.Trainer` must not ``fit`` the ensemble as one network.""" + return ( + "deep_ensemble members are trained independently, each on its own loss (Algorithm 1 of " + "Lakshminarayanan et al.); training the averaged output as one network is a different " + "method. Use ensemble.fit(inputs, targets, loss_fn=..., optimizer_factory=...) or train " + "each of ensemble.members with its own Trainer; Trainer.evaluate and Trainer.predict " + "work on the ensemble." + ) + + def member_outputs(self, *inputs: Any, **kwargs: Any) -> List[torch.Tensor]: + """Raw outputs of every member (and every MC-dropout pass), member by member. + + All arguments are passed to every member (e.g. U-TAE's ``batch_positions``). + """ + outputs: List[torch.Tensor] = [] + for member in self.members: + if self.mc_dropout_passes: + with _dropout_enabled(member): + outputs.extend(member(*inputs, **kwargs) for _ in range(self.mc_dropout_passes)) + else: + outputs.append(member(*inputs, **kwargs)) + for output in outputs: + if not isinstance(output, torch.Tensor): + raise ValueError( + f"deep_ensemble members must return one tensor, got {type(output).__name__}." + ) + if any(output.shape != outputs[0].shape for output in outputs): + raise ValueError(f"member outputs differ in shape: {[tuple(o.shape) for o in outputs]}.") + if outputs[0].ndim < 2: + raise ValueError( + f"deep_ensemble expects member outputs with a channel dimension, (batch, C, ...), got shape {tuple(outputs[0].shape)}." + ) + return outputs + + def _member_probs(self, outputs: List[torch.Tensor]) -> torch.Tensor: + stacked = torch.stack(outputs) + if stacked.size(2) == 1: + return torch.sigmoid(stacked) + return torch.softmax(stacked, dim=2) + + def _regression_moments(self, outputs: List[torch.Tensor]) -> Dict[str, torch.Tensor]: + stacked = torch.stack(outputs) + if self.regression_output == "point": + mean, epistemic = stacked.mean(dim=0), stacked.var(dim=0, unbiased=False) + return {"mean": mean, "variance": epistemic, "epistemic": epistemic, "member_means": stacked} + means, variances = split_gaussian_output(stacked.flatten(0, 1), self.min_variance) + means = means.unflatten(0, stacked.shape[:2]) + variances = variances.unflatten(0, stacked.shape[:2]) + mean, variance = gaussian_mixture_moments(means, variances) + return { + "mean": mean, + "variance": variance, + "epistemic": means.var(dim=0, unbiased=False), + "aleatoric": variances.mean(dim=0), + "member_means": means, + "member_variances": variances, + } + + def forward(self, *inputs: Any, **kwargs: Any) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + outputs = self.member_outputs(*inputs, **kwargs) + if self.task in REGRESSION_TASKS: + moments = self._regression_moments(outputs) + return moments["mean"], moments["variance"] + stacked = torch.stack(outputs) + log_m = math.log(stacked.size(0)) + if stacked.size(2) == 1: + log_p = torch.logsumexp(F.logsigmoid(stacked), dim=0) - log_m + log_not_p = torch.logsumexp(F.logsigmoid(-stacked), dim=0) - log_m + return log_p - log_not_p + return torch.logsumexp(torch.log_softmax(stacked, dim=2), dim=0) - log_m + + def predict_uncertainty(self, *inputs: Any, **kwargs: Any) -> Dict[str, torch.Tensor]: + """Ensemble prediction and uncertainty terms. + + Classification / segmentation: ``probs``, ``epistemic``, ``aleatoric``, ``entropy``, + ``mutual_information`` (see :func:`classification_uncertainties`) and ``member_probs`` + ``(samples, batch, C, ...)``. For one-channel binary outputs the terms are those of the + two-class distribution ``(1 - p, p)``, reported for the positive class. + Regression: ``mean``, ``variance`` (mixture), ``epistemic`` (variance of the member means), + ``member_means`` and, for Gaussian members, ``aleatoric`` (mean member variance) and + ``member_variances``. + """ + outputs = self.member_outputs(*inputs, **kwargs) + if self.task in REGRESSION_TASKS: + return self._regression_moments(outputs) + member_probs = self._member_probs(outputs) + if member_probs.size(2) == 1: + terms = classification_uncertainties(torch.cat([1 - member_probs, member_probs], dim=2)) + for key in ("probs", "epistemic", "aleatoric"): + terms[key] = terms[key][:, 1:2] + else: + terms = classification_uncertainties(member_probs) + terms["member_probs"] = member_probs + return terms + + def fit( + self, + inputs: torch.Tensor, + targets: torch.Tensor, + loss_fn: LossFn, + optimizer_factory: Callable[[Any], torch.optim.Optimizer], + epochs: int = 1, + batch_size: int = 100, + adversarial_epsilon: Optional[Epsilon] = None, + device: Optional[Union[str, torch.device]] = None, + ) -> "DeepEnsemble": + """Train every member independently (Algorithm 1) on all of ``inputs`` / ``targets``. + + Member ``m`` gets its own optimizer ``optimizer_factory(member.parameters())`` and its own + data order, drawn from a generator seeded with ``seeds[m]``; minibatches of ``batch_size`` + (the paper used 100 with Adam). ``loss_fn(member_output, targets)`` must be a proper scoring + rule for the member's output, e.g. ``nn.NLLLoss()`` for log-probabilities, + ``nn.CrossEntropyLoss()`` for logits, :func:`gaussian_nll_loss` for mean/variance outputs. + With ``adversarial_epsilon`` (a float or a tensor broadcasting against a batch of inputs, see + :func:`input_range_epsilon`) each step minimises ``loss(x, y) + loss(x', y)`` with the FGSM + example ``x'``. Returns ``self``; afterwards the members follow the ensemble's mode again + (call ``ensemble.eval()`` before predicting, as for any module). + """ + if inputs.shape[0] != targets.shape[0]: + raise ValueError(f"inputs and targets differ in length: shape {tuple(inputs.shape)} vs {tuple(targets.shape)}.") + if epochs < 1 or batch_size < 1: + raise ValueError(f"epochs and batch_size must be positive, got {epochs} and {batch_size}.") + n_samples = inputs.shape[0] + for member, seed in zip(self.members, self.seeds): + member_device = torch.device(device) if device is not None else next( + (p.device for p in member.parameters()), torch.device("cpu") + ) + member.to(member_device).train() + optimizer = optimizer_factory(member.parameters()) + generator = torch.Generator().manual_seed(seed) + for _ in range(epochs): + order = torch.randperm(n_samples, generator=generator) + for start in range(0, n_samples, batch_size): + index = order[start : start + batch_size] + x_batch = inputs[index].to(member_device) + y_batch = targets[index].to(member_device) + optimizer.zero_grad() + loss = loss_fn(member(x_batch), y_batch) + if adversarial_epsilon is not None: + x_adv = fgsm_example(member, x_batch, y_batch, loss_fn, adversarial_epsilon) + loss = loss + loss_fn(member(x_adv), y_batch) + loss.backward() + optimizer.step() + member.train(self.training) + return self + + def extra_repr(self) -> str: + return ( + f"task={self.task!r}, num_members={self.num_members}, seeds={self.seeds}, " + f"regression_output={self.regression_output!r}, mc_dropout_passes={self.mc_dropout_passes}" + ) + + +def deep_ensemble_builder( + task: str, + base_model: str = "", + base_kwargs: Optional[Dict[str, Any]] = None, + num_members: int = DEFAULT_NUM_MEMBERS, + seeds: Optional[Sequence[int]] = None, + regression_output: str = "gaussian", + mc_dropout_passes: int = 0, + **kwargs: Any, +) -> DeepEnsemble: + """Build a deep ensemble of ``num_members`` copies of the registered model ``base_model``. + + Member ``m`` is ``build_model(base_model, task=task, **base_kwargs)`` built right after + ``torch.manual_seed(seeds[m])`` (default seeds ``0 .. num_members-1``), so it has the same + initial weights as a single model built with that seed. The global RNG state is restored + afterwards. + """ + from .builder import build_model + + kwargs.pop("name", None) + if kwargs: + raise TypeError( + f"deep_ensemble got unexpected arguments {sorted(kwargs)}; member arguments go in base_kwargs." + ) + if not base_model: + raise ValueError("deep_ensemble needs base_model, the registry name of the member model.") + if base_model == "deep_ensemble": + raise ValueError("deep_ensemble cannot use itself as base_model.") + if num_members < 1: + raise ValueError(f"num_members must be at least 1, got {num_members}.") + seeds = list(range(num_members)) if seeds is None else [int(seed) for seed in seeds] + if len(seeds) != num_members or len(set(seeds)) != num_members: + raise ValueError(f"seeds must be {num_members} distinct integers, got {seeds}.") + members = [] + with torch.random.fork_rng(devices=[]): + for seed in seeds: + torch.manual_seed(seed) + members.append(build_model(base_model, task=task, **dict(base_kwargs or {}))) + return DeepEnsemble( + members, + task=task, + seeds=seeds, + regression_output=regression_output, + mc_dropout_passes=mc_dropout_passes, + ) + + +__all__ = [ + "CLASSIFICATION_TASKS", + "DEFAULT_NUM_MEMBERS", + "DeepEnsemble", + "REGRESSION_OUTPUTS", + "REGRESSION_TASKS", + "classification_uncertainties", + "deep_ensemble_builder", + "fgsm_example", + "gaussian_mixture_moments", + "gaussian_nll_loss", + "input_range_epsilon", + "split_gaussian_output", +] diff --git a/pyhazards/models/deeplabv3.py b/pyhazards/models/deeplabv3.py new file mode 100644 index 00000000..2fce3037 --- /dev/null +++ b/pyhazards/models/deeplabv3.py @@ -0,0 +1,192 @@ +"""DeepLabV3 with a ResNet encoder, equivalent to ``segmentation_models_pytorch.DeepLabV3``. + +Architecture paper: Chen, Papandreou, Schroff & Adam, "Rethinking Atrous Convolution for Semantic +Image Segmentation", arXiv:1706.05587 (2017). + +Shadrin et al., "Wildfire spreading prediction using multimodal data and deep neural network +approach", Scientific Reports 14:2606 (2024), compare U-Net, U-Net++, MA-Net and DeepLabV3 with +"encoder backbone ResNet18, number of stages used in encoder equals to 3, ... default values for +the other hyperparameters": the argument names and defaults of segmentation_models_pytorch (smp), +whose ``micro-imagewise`` metric reduction the paper also names. No code was released. This module +re-implements ``smp.DeepLabV3`` in plain PyTorch with smp's parameter names, creation order and +initialisation, so smp state dicts load with ``strict=True`` and seeds give identical weights. + +Ported from segmentation_models_pytorch 0.3.2 (MIT License, Copyright (c) 2019 Pavel Iakubovskii): +``decoders/deeplabv3/model.py``, ``base/heads.py``, ``encoders/_base.py`` and ``encoders/_utils.py`` +(the ResNet encoder is shared with ``resnet_unet.py``). smp's ``decoders/deeplabv3/decoder.py`` +(ASPP and decoder) is itself taken from torchvision (BSD 3-Clause License, Copyright (c) Soumith +Chintala 2016). The DeepLabV3 code path is identical in smp 0.2.0 through 0.3.4 (0.3.x only adds the +input-size check); 0.3.3 was the current release when the wildfire paper was submitted. +""" + +from __future__ import annotations + +from typing import Optional, Sequence + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .resnet_unet import RESNET_LAYERS, ResNetEncoder + + +class ASPPConv(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, dilation: int): + super().__init__( + nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=dilation, dilation=dilation, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ) + + +class ASPPPooling(nn.Sequential): + """Image-level features: global average pooling, 1x1 conv-BN-ReLU, bilinear up-sampling.""" + + def __init__(self, in_channels: int, out_channels: int): + super().__init__( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + size = x.shape[-2:] + for module in self: + x = module(x) + return F.interpolate(x, size=size, mode="bilinear", align_corners=False) + + +class ASPP(nn.Module): + """Atrous spatial pyramid pooling: a 1x1 branch, three 3x3 atrous branches and image pooling.""" + + def __init__(self, in_channels: int, out_channels: int, atrous_rates: Sequence[int]): + super().__init__() + rate1, rate2, rate3 = tuple(atrous_rates) + self.convs = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d(in_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ), + ASPPConv(in_channels, out_channels, rate1), + ASPPConv(in_channels, out_channels, rate2), + ASPPConv(in_channels, out_channels, rate3), + ASPPPooling(in_channels, out_channels), + ] + ) + self.project = nn.Sequential( + nn.Conv2d(5 * out_channels, out_channels, kernel_size=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + nn.Dropout(0.5), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.project(torch.cat([conv(x) for conv in self.convs], dim=1)) + + +class DeepLabV3Decoder(nn.Sequential): + """ASPP on the deepest encoder feature, then a 3x3 conv-BN-ReLU (smp / torchvision ``DeepLabHead``).""" + + def __init__(self, in_channels: int, out_channels: int = 256, atrous_rates: Sequence[int] = (12, 24, 36)): + super().__init__( + ASPP(in_channels, out_channels, atrous_rates), + nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ) + self.out_channels = out_channels + + def forward(self, *features: torch.Tensor) -> torch.Tensor: + return super().forward(features[-1]) + + +class DeepLabV3(nn.Module): + """``smp.DeepLabV3`` with a ResNet-18/34 encoder: ``(batch, C, H, W)`` -> ``(batch, classes, H, W)`` logits. + + The defaults are smp's (ResNet-34, five encoder stages) except ``encoder_weights``, which is + ``None`` here and ``"imagenet"`` in smp. The encoder runs at output stride 8 (strides of + ``layer3``/``layer4`` replaced by dilation 2/4); height and width must be divisible by + ``min(8, 2 ** encoder_depth)``. + """ + + def __init__( + self, + in_channels: int = 3, + classes: int = 1, + encoder_name: str = "resnet34", + encoder_depth: int = 5, + encoder_weights: Optional[str] = None, + decoder_channels: int = 256, + upsampling: int = 8, + ): + super().__init__() + if encoder_name not in RESNET_LAYERS: + raise ValueError(f"encoder_name must be one of {sorted(RESNET_LAYERS)}, got {encoder_name!r}") + if not 3 <= encoder_depth <= 5: + raise ValueError(f"encoder_depth must be in [3, 5] for DeepLabV3, got {encoder_depth}") + if classes <= 0 or decoder_channels <= 0 or upsampling <= 0: + raise ValueError( + f"classes, decoder_channels and upsampling must be positive, got {classes}, " + f"{decoder_channels}, {upsampling}" + ) + if encoder_weights not in (None, "imagenet"): + raise ValueError(f"encoder_weights must be None or 'imagenet', got {encoder_weights!r}") + self.encoder = ResNetEncoder(encoder_name, in_channels=3, depth=encoder_depth) + if encoder_weights is not None: + self.encoder.load_imagenet_weights() + self.encoder.set_in_channels(in_channels, pretrained=encoder_weights is not None) + self.encoder.make_dilated(8) + self.in_channels = int(in_channels) + self.decoder = DeepLabV3Decoder(self.encoder.out_channels[-1], decoder_channels) + # smp's SegmentationHead: 1x1 conv, UpsamplingBilinear2d (align_corners=True), activation. + self.segmentation_head = nn.Sequential( + nn.Conv2d(decoder_channels, classes, kernel_size=1), + nn.UpsamplingBilinear2d(scale_factor=upsampling) if upsampling > 1 else nn.Identity(), + nn.Identity(), + ) + # smp 0.3.x never calls initialize() for DeepLabV3, so the decoder and head keep PyTorch's + # default initialisation (unlike smp's U-Net); nothing is re-initialised here either. + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 4: + raise ValueError(f"DeepLabV3 expects input shape (batch, channels, height, width), got {tuple(x.shape)}.") + if x.size(1) != self.in_channels: + raise ValueError(f"DeepLabV3 expected {self.in_channels} input channels, got {x.size(1)}.") + h, w = x.shape[-2:] + stride = self.encoder.output_stride + if h % stride or w % stride: + raise ValueError(f"DeepLabV3 needs height and width divisible by {stride}, got {(h, w)}.") + features = self.encoder(x) + return self.segmentation_head(self.decoder(*features)) + + +def deeplabv3_builder( + task: str, + in_channels: int = 58, + out_channels: int = 1, + encoder_name: str = "resnet18", + encoder_depth: int = 3, + encoder_weights: Optional[str] = None, + decoder_channels: int = 256, + upsampling: int = 8, + **kwargs, +) -> nn.Module: + """DeepLabV3 in Shadrin et al.'s configuration by default (ResNet-18, three encoder stages).""" + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"deeplabv3 supports task='segmentation', got {task!r}.") + return DeepLabV3( + in_channels=in_channels, + classes=out_channels, + encoder_name=encoder_name, + encoder_depth=encoder_depth, + encoder_weights=encoder_weights, + decoder_channels=decoder_channels, + upsampling=upsampling, + ) + + +__all__ = ["ASPP", "DeepLabV3", "DeepLabV3Decoder", "deeplabv3_builder"] diff --git a/pyhazards/models/earthfarseer.py b/pyhazards/models/earthfarseer.py new file mode 100644 index 00000000..48a73002 --- /dev/null +++ b/pyhazards/models/earthfarseer.py @@ -0,0 +1,631 @@ +"""Earthfarseer: local CNN and global Fourier-transformer spatio-temporal forecaster. + +Architecture paper: Wu, Liang, Xiong, Zhou, Huang, Wang and Wang, "Earthfarseer: Versatile +Spatio-Temporal Dynamical Systems Modeling in One Model", AAAI 2024 (arXiv:2312.08403; the AAAI +proceedings spell it "Earthfarsser"). Wildfire usage: the Sim2Real-Fire benchmark (Li et al., +NeurIPS 2024 Datasets and Benchmarks) reports it as a fire-forecasting baseline. + +The official code (github.com/easylearningscores/EarthFarseer, now Alexander-wu/EarthFarseer) has +no license, so this module is written from the paper and from permissively licensed parts; the +official code is used only as a test oracle (tests/oracle/test_earthfarseer_oracle.py). +Module and parameter names match the official ``Earthfarseer_model`` so its state dicts load with +``strict=True``, and modules are created in the same order, so the same seed gives the same +initial weights. + +Attribution: + +- ``GroupConv2d`` and ``Inception`` (the SimVP Inception block) follow ``gInception_ST`` and + ``GroupConv2d`` in chengtan9907/OpenSTL ``openstl/modules/simvp_modules.py`` at commit + ``eecf8a3078f0a178dbc7b28723da20f94ce36985`` (Apache-2.0, Copyright the OpenSTL authors). +- The convolutional encoder/decoder, the SimVP translator (``MidXnet``) and the skip branch are + written from the SimVP paper (Gao et al., CVPR 2022), which Earthfarseer builds on. +- The adaptive Fourier neural operator block is written from the AFNO paper (Guibas et al., ICLR + 2022) and the Earthfarseer paper (Sec. "Spatial block FoTF"); ``trunc_normal_`` is the + timm-compatible helper of :mod:`pyhazards.models.swin_blocks`. + +Behaviour of the official code that is kept (it changes outputs or parameter counts): + +- the FoTF spatial block applies the *same* global Fourier transformer (``gf_block``) and local + branch (``lc_block``) seven times (once, then twice per interaction for three interactions); +- the transformer MLP computes ``fc1`` and replaces ``fc2`` by an average pool over groups of + ``mlp_ratio`` hidden features (``fc3``); ``fc2`` exists, is initialised and counted, but is + never used; +- in the second spectral layer of the Fourier operator the imaginary part is computed from the + *updated* real part; +- the model output is ``decoder(TeDev(encoder(FoTF(x))))`` plus a full SimVP network + (``skip_conneciton``, spelling kept) whose sizes are fixed (16 / 256 / 4 / 8) whatever the + model's ``hid_S``, ``hid_T``, ``N_S`` and ``N_T``; +- a second convolutional encoder (``enc``) is built and counted but never used in the forward + pass; +- the output has as many frames as the input; the paper's temporal projection to another length + is not in the released code. +""" + +from __future__ import annotations + +from collections import OrderedDict +from typing import List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .swin_blocks import to_2tuple, trunc_normal_ + +# Patch size of the global Fourier transformer; its transposed-convolution head upsamples by +# 2 * 2 * 4 = 16, so the two must agree. +GF_PATCH_SIZE = 16 + +# The skip branch is a SimVP with the constructor defaults of the official ``skip_connection``. +SKIP_HID_S, SKIP_HID_T, SKIP_N_S, SKIP_N_T = 16, 256, 4, 8 + + +def _layer_norm(dim: int) -> nn.LayerNorm: + return nn.LayerNorm(dim, eps=1e-6) + + +# --------------------------------------------------------------------------- SimVP parts + + +def stride_generator(n: int, reverse: bool = False) -> List[int]: + """Strides of the SimVP encoder: 1, 2, 1, 2, ... (``n`` layers), optionally reversed.""" + strides = [1, 2] * 10 + return list(reversed(strides[:n])) if reverse else strides[:n] + + +class BasicConv2d(nn.Module): + """3x3 convolution (transposed for 2x upsampling), GroupNorm(2) and LeakyReLU(0.2).""" + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int, + padding: int, + transpose: bool = False, + act_norm: bool = False, + ): + super().__init__() + self.act_norm = act_norm + if transpose: + self.conv = nn.ConvTranspose2d( + in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, + output_padding=stride // 2, + ) + else: + self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding) + self.norm = nn.GroupNorm(2, out_channels) + self.act = nn.LeakyReLU(0.2, inplace=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + y = self.conv(x) + return self.act(self.norm(y)) if self.act_norm else y + + +class ConvSC(nn.Module): + def __init__(self, C_in: int, C_out: int, stride: int, transpose: bool = False, act_norm: bool = True): + super().__init__() + self.conv = BasicConv2d( + C_in, C_out, kernel_size=3, stride=stride, padding=1, transpose=transpose and stride != 1, + act_norm=act_norm, + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv(x) + + +class GroupConv2d(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int, + padding: int, + groups: int, + act_norm: bool = False, + ): + super().__init__() + self.act_norm = act_norm + if in_channels % groups != 0: + groups = 1 + self.conv = nn.Conv2d( + in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups + ) + self.norm = nn.GroupNorm(groups, out_channels) + self.activate = nn.LeakyReLU(0.2, inplace=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + y = self.conv(x) + return self.activate(self.norm(y)) if self.act_norm else y + + +class Inception(nn.Module): + """1x1 reduction, then the sum of grouped convolutions with several kernel sizes.""" + + def __init__(self, C_in: int, C_hid: int, C_out: int, incep_ker: Sequence[int] = (3, 5, 7, 11), groups: int = 8): + super().__init__() + self.conv1 = nn.Conv2d(C_in, C_hid, kernel_size=1, stride=1, padding=0) + self.layers = nn.Sequential( + *[ + GroupConv2d(C_hid, C_out, kernel_size=k, stride=1, padding=k // 2, groups=groups, act_norm=True) + for k in incep_ker + ] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.conv1(x) + y = 0 + for layer in self.layers: + y = y + layer(x) + return y + + +class Encoder(nn.Module): + """``N_S`` ConvSC layers (strides 1, 2, 1, 2, ...); returns the latent and the first features.""" + + def __init__(self, C_in: int, C_hid: int, N_S: int): + super().__init__() + strides = stride_generator(N_S) + self.enc = nn.Sequential( + ConvSC(C_in, C_hid, stride=strides[0]), *[ConvSC(C_hid, C_hid, stride=s) for s in strides[1:]] + ) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + enc1 = self.enc[0](x) + latent = enc1 + for layer in list(self.enc)[1:]: + latent = layer(latent) + return latent, enc1 + + +class Decoder(nn.Module): + """Mirror of :class:`Encoder`; the last layer also sees the first encoder features.""" + + def __init__(self, C_hid: int, C_out: int, N_S: int): + super().__init__() + strides = stride_generator(N_S, reverse=True) + self.dec = nn.Sequential( + *[ConvSC(C_hid, C_hid, stride=s, transpose=True) for s in strides[:-1]], + ConvSC(2 * C_hid, C_hid, stride=strides[-1], transpose=True), + ) + self.readout = nn.Conv2d(C_hid, C_out, 1) + + def forward(self, hid: torch.Tensor, enc1: torch.Tensor) -> torch.Tensor: + for layer in list(self.dec)[:-1]: + hid = layer(hid) + y = self.dec[-1](torch.cat([hid, enc1], dim=1)) + return self.readout(y) + + +def _inception_stacks(channel_in: int, channel_hid: int, N_T: int, incep_ker, groups) -> Tuple[list, list]: + """Encoder and decoder Inception layers of the SimVP translator (U-shaped, with skips).""" + kw = dict(incep_ker=incep_ker, groups=groups) + enc = [Inception(channel_in, channel_hid // 2, channel_hid, **kw)] + enc += [Inception(channel_hid, channel_hid // 2, channel_hid, **kw) for _ in range(1, N_T)] + dec = [Inception(channel_hid, channel_hid // 2, channel_hid, **kw)] + dec += [Inception(2 * channel_hid, channel_hid // 2, channel_hid, **kw) for _ in range(1, N_T - 1)] + dec.append(Inception(2 * channel_hid, channel_hid // 2, channel_in, **kw)) + return enc, dec + + +def _run_translator(enc: nn.Sequential, dec: nn.Sequential, z: torch.Tensor, N_T: int, middle=None) -> torch.Tensor: + skips = [] + for i in range(N_T): + z = enc[i](z) + if i < N_T - 1: + skips.append(z) + if middle is not None: + z = middle(z) + z = dec[0](z) + for i in range(1, N_T): + z = dec[i](torch.cat([z, skips[-i]], dim=1)) + return z + + +class MidXnet(nn.Module): + """SimVP translator: frames stacked as channels through U-shaped Inception layers.""" + + def __init__(self, channel_in: int, channel_hid: int, N_T: int, incep_ker=(3, 5, 7, 11), groups: int = 8): + super().__init__() + self.N_T = N_T + enc, dec = _inception_stacks(channel_in, channel_hid, N_T, incep_ker, groups) + self.enc = nn.Sequential(*enc) + self.dec = nn.Sequential(*dec) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + z = _run_translator(self.enc, self.dec, x.reshape(b, t * c, h, w), self.N_T) + return z.reshape(b, t, c, h, w) + + +class SkipConnection(nn.Module): + """The SimVP network the official model adds to its prediction (fixed sizes).""" + + def __init__(self, shape_in: Sequence[int], incep_ker=(3, 5, 7, 11), groups: int = 8): + super().__init__() + t, c, _, _ = shape_in + self.enc = Encoder(c, SKIP_HID_S, SKIP_N_S) + self.hid = MidXnet(t * SKIP_HID_S, SKIP_HID_T, SKIP_N_T, incep_ker, groups) + self.dec = Decoder(SKIP_HID_S, c, SKIP_N_S) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + embed, skip = self.enc(x.reshape(b * t, c, h, w)) + _, c_, h_, w_ = embed.shape + hid = self.hid(embed.reshape(b, t, c_, h_, w_)).reshape(b * t, c_, h_, w_) + return self.dec(hid, skip).reshape(b, t, c, h, w) + + +# --------------------------------------------------------------------------- Fourier blocks + + +class Mlp(nn.Module): + """Linear expansion followed by an average pool back to ``out_features`` (``fc2`` is unused).""" + + def __init__(self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer=nn.GELU, drop: float = 0.0): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) # kept for state-dict compatibility + self.fc3 = nn.AdaptiveAvgPool1d(out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.drop(self.act(self.fc1(x))) + return self.drop(self.fc3(x)) + + +class AdativeFourierNeuralOperator(nn.Module): + """Token mixing in the 2D Fourier domain with a two-layer block-diagonal complex MLP. + + Tokens ``(B, h * w, C)`` are reshaped to the ``h x w`` grid, transformed with a real 2D FFT, + mixed per frequency by two complex linear layers (``num_blocks`` diagonal blocks, ReLU in + between), transformed back, and added to a 1x1-convolution bias path. (Class name spelled as + in the reference.) + """ + + def __init__(self, dim: int, h: int = 14, w: int = 14, is_fno_bias: bool = True): + super().__init__() + self.hidden_size = dim + self.h = h + self.w = w + self.num_blocks = 2 + if dim % self.num_blocks: + raise ValueError(f"Fourier operator width {dim} must be divisible by {self.num_blocks}.") + self.block_size = dim // self.num_blocks + self.scale = 0.02 + nb, bs = self.num_blocks, self.block_size + self.w1 = nn.Parameter(self.scale * torch.randn(2, nb, bs, bs)) + self.b1 = nn.Parameter(self.scale * torch.randn(2, nb, bs)) + self.w2 = nn.Parameter(self.scale * torch.randn(2, nb, bs, bs)) + self.b2 = nn.Parameter(self.scale * torch.randn(2, nb, bs)) + self.relu = nn.ReLU() + self.is_fno_bias = is_fno_bias + self.bias = nn.Conv1d(dim, dim, 1) if is_fno_bias else None + self.softshrink = 0.0 + + @staticmethod + def multiply(x: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + return torch.einsum("...bd,bdk->...bk", x, weights) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, n, c = x.shape + if self.bias is not None: + bias = self.bias(x.permute(0, 2, 1)).permute(0, 2, 1) + else: + bias = torch.zeros_like(x) + + x = torch.fft.rfft2(x.reshape(b, self.h, self.w, c), dim=(1, 2), norm="ortho") + x = x.reshape(b, x.shape[1], x.shape[2], self.num_blocks, self.block_size) + re, im = x.real, x.imag + w1, b1, w2, b2 = self.w1, self.b1, self.w2, self.b2 + hid_re = F.relu(self.multiply(re, w1[0]) - self.multiply(im, w1[1]) + b1[0]) + hid_im = F.relu(self.multiply(re, w1[1]) + self.multiply(im, w1[0]) + b1[1]) + out_re = self.multiply(hid_re, w2[0]) - self.multiply(hid_im, w2[1]) + b2[0] + # Reference behaviour: the imaginary part uses the already updated real part. + out_im = self.multiply(out_re, w2[1]) + self.multiply(hid_im, w2[0]) + b2[1] + + x = torch.stack([out_re, out_im], dim=-1) + if self.softshrink: + x = F.softshrink(x, lambd=self.softshrink) + x = torch.view_as_complex(x).reshape(b, x.shape[1], x.shape[2], c) + x = torch.fft.irfft2(x, s=(self.h, self.w), dim=(1, 2), norm="ortho") + return x.reshape(b, n, c) + bias + + +class FourierNetBlock(nn.Module): + """Pre-norm Fourier token mixing and pre-norm MLP, each with a residual connection.""" + + def __init__(self, dim: int, mlp_ratio: float = 4.0, drop: float = 0.0, act_layer=nn.GELU, norm_layer=_layer_norm, h: int = 14, w: int = 14): + super().__init__() + self.normlayer1 = norm_layer(dim) + self.filter = AdativeFourierNeuralOperator(dim, h=h, w=w) + self.drop_path = nn.Identity() # every reference drop-path rate is 0 + self.normlayer2 = norm_layer(dim) + self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop) + self.double_skip = True + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.drop_path(self.filter(self.normlayer1(x))) + return x + self.drop_path(self.mlp(self.normlayer2(x))) + + +class PatchEmbed(nn.Module): + def __init__(self, img_size, patch_size: int = 16, in_c: int = 1, embed_dim: int = 768): + super().__init__() + self.img_size = to_2tuple(img_size) + self.patch_size = to_2tuple(patch_size) + self.grid_size = (self.img_size[0] // self.patch_size[0], self.img_size[1] // self.patch_size[1]) + self.num_patches = self.grid_size[0] * self.grid_size[1] + self.projection = nn.Conv2d(in_c, embed_dim, kernel_size=self.patch_size, stride=self.patch_size) + self.norm = nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.norm(self.projection(x).flatten(2).transpose(1, 2)) + + +class GFBlock(nn.Module): + """Global Fourier transformer: patchify each frame, ``depth`` Fourier blocks, unpatchify. + + Unpatchifying uses three transposed convolutions (x2, x2, x4) with tanh in between. + """ + + def __init__(self, img_size, in_channels: int, out_channels: int, input_frames: int, embed_dim: int = 768, depth: int = 12, mlp_ratio: float = 4.0, drop_rate: float = 0.0): + super().__init__() + self.embed_dim = embed_dim + self.num_frames = input_frames + self.patch_embed = PatchEmbed(img_size=img_size, patch_size=GF_PATCH_SIZE, in_c=in_channels, embed_dim=embed_dim) + self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches, embed_dim)) + self.pos_drop = nn.Dropout(p=drop_rate) + self.h, self.w = self.patch_embed.grid_size + self.blocks = nn.ModuleList( + [ + FourierNetBlock(dim=embed_dim, mlp_ratio=mlp_ratio, drop=drop_rate, h=self.h, w=self.w) + for _ in range(depth) + ] + ) + self.norm = _layer_norm(embed_dim) + self.linearprojection = nn.Sequential( + OrderedDict( + [ + ("transposeconv1", nn.ConvTranspose2d(embed_dim, out_channels * 16, kernel_size=(2, 2), stride=(2, 2))), + ("act1", nn.Tanh()), + ("transposeconv2", nn.ConvTranspose2d(out_channels * 16, out_channels * 4, kernel_size=(2, 2), stride=(2, 2))), + ("act2", nn.Tanh()), + ("transposeconv3", nn.ConvTranspose2d(out_channels * 4, out_channels, kernel_size=(4, 4), stride=(4, 4))), + ] + ) + ) + self.final_dropout = nn.Identity() + trunc_normal_(self.pos_embed, std=0.02) + self.apply(self._init_weights) + + @staticmethod + def _init_weights(module: nn.Module) -> None: + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.bias, 0) + nn.init.constant_(module.weight, 1.0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + x = self.pos_drop(self.patch_embed(x.reshape(b * t, c, h, w)) + self.pos_embed) + for block in self.blocks: + x = block(x) + x = self.norm(x).transpose(1, 2).reshape(-1, self.embed_dim, self.h, self.w) + x = self.linearprojection(self.final_dropout(x)) + return x.reshape(b, t, c, h, w) + + +class LocalCNNBranch(nn.Module): + """Per-frame 1x1 transposed convolution (the released local branch).""" + + def __init__(self, in_channels: int, out_channels: int): + super().__init__() + self.in_channel = in_channels + self.out_channel = out_channels + self.upconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + x = self.upconv(x.reshape(b * t, c, h, w)) + return x.reshape(b, t, self.out_channel, x.shape[2], x.shape[3]) + + +class FoTF(nn.Module): + """Spatial block: the global and local branches exchange information ``num_interactions`` times.""" + + def __init__(self, shape_in: Sequence[int], num_interactions: int = 3, embed_dim: int = 768, depth: int = 12): + super().__init__() + t, c, h, w = shape_in + self.lc_block = LocalCNNBranch(in_channels=c, out_channels=c) + self.gf_block = GFBlock(img_size=(h, w), in_channels=c, out_channels=c, input_frames=t, embed_dim=embed_dim, depth=depth) + self.up = nn.ConvTranspose2d(c, c, kernel_size=3, stride=1, padding=1) + self.down = nn.Conv2d(c, c, kernel_size=3, stride=1, padding=1) + self.conv1x1 = nn.Conv2d(c, c, kernel_size=1) + self.num_interactions = num_interactions + + def _framewise(self, layer: nn.Module, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + return layer(x.reshape(b * t, c, h, w)).reshape(b, t, c, h, w) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + gf, lc = self.gf_block(x), self.lc_block(x) + for _ in range(self.num_interactions): + for exchange in (self.up, self.down): + combined = self._framewise(exchange, gf) + self._framewise(self.conv1x1, lc) + gf, lc = self.gf_block(combined), self.lc_block(combined) + return gf + lc + + +class TeDev(nn.Module): + """Temporal block: SimVP Inception translator with 12 Fourier blocks at its bottleneck.""" + + def __init__(self, channel_in: int, channel_hid: int, N_T: int, h: int, w: int, incep_ker=(3, 5, 7, 11), groups: int = 8, num_blocks: int = 12): + super().__init__() + self.N_T = N_T + enc, dec = _inception_stacks(channel_in, channel_hid, N_T, incep_ker, groups) + # Registration order (norm, enc, blocks, dec) and creation order (enc, dec, blocks) follow + # the reference, so state-dict order and seeded initialisation match. + self.norm = _layer_norm(channel_hid) + self.enc = nn.Sequential(*enc) + self.h, self.w = h, w + self.blocks = nn.ModuleList( + [FourierNetBlock(dim=channel_hid, mlp_ratio=4, h=h, w=w) for _ in range(num_blocks)] + ) + self.dec = nn.Sequential(*dec) + + def _spectral(self, z: torch.Tensor) -> torch.Tensor: + b, d, h, w = z.shape + z = z.permute(0, 2, 3, 1).reshape(b, h * w, d) + for block in self.blocks: + z = block(z) + return self.norm(z).permute(0, 2, 1).reshape(b, d, h, w) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, t, c, h, w = x.shape + z = _run_translator(self.enc, self.dec, x.reshape(b, t * c, h, w), self.N_T, middle=self._spectral) + return z.reshape(b, t, c, h, w) + x + + +def _check_shape_in(shape_in: Sequence[int], N_S: int, N_T: int) -> Tuple[int, int, int, int, int, int]: + if len(shape_in) != 4: + raise ValueError(f"shape_in must be (frames, channels, height, width), got {tuple(shape_in)}.") + t, c, h, w = (int(v) for v in shape_in) + if min(t, c, h, w) <= 0: + raise ValueError(f"shape_in entries must be positive, got {tuple(shape_in)}.") + if N_S < 1 or N_T < 2: + raise ValueError(f"Earthfarseer needs N_S >= 1 and N_T >= 2, got N_S={N_S}, N_T={N_T}.") + if h % GF_PATCH_SIZE or w % GF_PATCH_SIZE: + raise ValueError( + f"Earthfarseer needs height and width divisible by {GF_PATCH_SIZE} (FoTF patch size), got shape_in {tuple(shape_in)}." + ) + scale = 2 ** stride_generator(N_S).count(2) + skip_scale = 2 ** stride_generator(SKIP_N_S).count(2) + for side in (h, w): + if side % scale or side % skip_scale: + raise ValueError( + f"Earthfarseer with N_S={N_S} needs height and width divisible by {max(scale, skip_scale)}, got {(h, w)}." + ) + return t, c, h, w, h // scale, w // scale + + +class Earthfarseer(nn.Module): + """Earthfarseer (``Earthfarseer_model``): ``(B, T, C, H, W)`` -> ``(B, T, C, H, W)``. + + ``shape_in = (T, C, H, W)`` fixes the input size, as in the reference. The output frames are + the forecast for the ``T`` frames that follow the input. ``gf_embed_dim``, ``gf_depth`` and + ``num_interactions`` are fixed in the reference (768, 12, 3) and exposed only to build + smaller models. + """ + + def __init__( + self, + shape_in: Sequence[int] = (10, 1, 64, 64), + hid_S: int = 512, + hid_T: int = 256, + N_S: int = 4, + N_T: int = 8, + incep_ker: Sequence[int] = (3, 5, 7, 11), + groups: int = 8, + gf_embed_dim: int = 768, + gf_depth: int = 12, + num_interactions: int = 3, + ): + super().__init__() + t, c, h, w, h1, w1 = _check_shape_in(shape_in, N_S, N_T) + self.shape_in = (t, c, h, w) + incep_ker = list(incep_ker) + # Token grid of the TeDev Fourier blocks. The reference computes it with a formula that + # adds 1 when H is divisible by 3; that only differs from the true latent size in + # configurations where the reference fails (see the model card). + self.H1, self.W1 = h1, w1 + + self.fotf_encoder = FoTF(shape_in=self.shape_in, num_interactions=num_interactions, embed_dim=gf_embed_dim, depth=gf_depth) + self.skip_conneciton = SkipConnection(shape_in=self.shape_in) + self.latent_projection = Encoder(c, hid_S, N_S) + self.enc = Encoder(c, hid_S, N_S) # built and counted by the reference, unused in forward + self.TeDev_block = TeDev(t * hid_S, hid_T, N_T, self.H1, self.W1, incep_ker, groups) + self.dec = Decoder(hid_S, c, N_S) + + def _check_input(self, x: torch.Tensor) -> None: + if x.ndim != 5 or tuple(x.shape[1:]) != self.shape_in: + raise ValueError( + "Earthfarseer expects input shape (batch, {}, {}, {}, {}) = (batch, time, channels, height, " + "width), got {}.".format(*self.shape_in, tuple(x.shape)) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + self._check_input(x) + b, t, c, h, w = x.shape + skip_feature = self.skip_conneciton(x) + spatial = self.fotf_encoder(x).reshape(b * t, c, h, w) + embed, enc1 = self.latent_projection(spatial) + _, c_, h_, w_ = embed.shape + hidden = self.TeDev_block(embed.reshape(b, t, c_, h_, w_)).reshape(b * t, c_, h_, w_) + return self.dec(hidden, enc1).reshape(b, t, c, h, w) + skip_feature + + +class EarthfarseerSegmenter(Earthfarseer): + """PyHazards adaptation for next-step masks: ``(B, T, C, H, W)`` -> logits ``(B, out, H, W)``. + + Runs :class:`Earthfarseer` and maps the channels of the first predicted frame to + ``out_channels`` logits with a 1x1 convolution (``segmentation_head``). The Earthfarseer + parameters keep their reference names at the top level. + """ + + def __init__(self, shape_in: Sequence[int] = (10, 1, 64, 64), out_channels: int = 1, **kwargs): + super().__init__(shape_in=shape_in, **kwargs) + if out_channels <= 0: + raise ValueError(f"out_channels must be positive, got {out_channels}.") + self.segmentation_head = nn.Conv2d(self.shape_in[1], out_channels, kernel_size=1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.segmentation_head(super().forward(x)[:, 0]) + + +def earthfarseer_builder( + task: str, + in_channels: int = 1, + history: int = 10, + img_size: Union[int, Sequence[int]] = 64, + out_channels: int = 1, + hid_S: int = 512, + hid_T: int = 256, + N_S: int = 4, + N_T: int = 8, + incep_ker: Sequence[int] = (3, 5, 7, 11), + groups: int = 8, + gf_embed_dim: int = 768, + gf_depth: int = 12, + num_interactions: int = 3, + **kwargs, +) -> nn.Module: + """Earthfarseer with the official default ``Earthfarseer_model(shape_in=(10, 1, 64, 64))``. + + ``task="forecasting"``: ``(B, history, in_channels, H, W)`` -> the next ``history`` frames. + ``task="segmentation"``: the same input -> ``(B, out_channels, H, W)`` logits (PyHazards + adaptation, see :class:`EarthfarseerSegmenter`). + """ + _ = kwargs + task = task.lower() + if task not in {"forecasting", "segmentation"}: + raise ValueError(f"earthfarseer supports task='forecasting' or 'segmentation', got {task!r}.") + h, w = to_2tuple(img_size) + config = dict( + shape_in=(history, in_channels, h, w), hid_S=hid_S, hid_T=hid_T, N_S=N_S, N_T=N_T, incep_ker=incep_ker, + groups=groups, gf_embed_dim=gf_embed_dim, gf_depth=gf_depth, num_interactions=num_interactions, + ) + if task == "segmentation": + return EarthfarseerSegmenter(out_channels=out_channels, **config) + return Earthfarseer(**config) + + +__all__ = ["Earthfarseer", "EarthfarseerSegmenter", "earthfarseer_builder"] diff --git a/pyhazards/models/earthformer.py b/pyhazards/models/earthformer.py new file mode 100644 index 00000000..0982cf3c --- /dev/null +++ b/pyhazards/models/earthformer.py @@ -0,0 +1,3138 @@ +"""Earthformer: a space-time Transformer built from cuboid attention. + +Gao, Shi, Wang, Zhu, Wang, Li & Yeung, "Earthformer: Exploring Space-Time Transformers for Earth +System Forecasting", NeurIPS 2022 (https://arxiv.org/abs/2207.05833). + +Port of the official code, amazon-science/earth-forecasting-transformer at commit +``7732b03bdb366110563516c3502315deab4c2026``: +``src/earthformer/cuboid_transformer/cuboid_transformer.py``, ``cuboid_transformer_patterns.py`` and +``utils.py``. Licensed under the Apache License, Version 2.0 +(http://www.apache.org/licenses/LICENSE-2.0). NOTICE of the original work: "Copyright Amazon.com, +Inc. or its affiliates. All Rights Reserved." + +Changes made for PyHazards (the network itself is unchanged): + +- the cuboid patterns are kept in plain dictionaries instead of the GluonNLP ``Registry`` class, + the unused ``einops`` import is dropped, and ``DownSampling3D`` (not used by + ``CuboidTransformerModel``) is not ported; +- ``torch.meshgrid`` gets ``indexing="ij"`` and gradient checkpointing ``use_reentrant=True`` + explicitly (the defaults of the PyTorch versions the official code was written for; current + PyTorch warns when they are omitted), and cuboid strategies are stored as tuples so that the + cached mask functions also accept lists; +- three code paths that only raise errors in the official code work here: ``PatchMerging3D`` pads + when only the time axis needs padding (official: ``if pad_h or pad_h or pad_w``), the + ``CTHW`` layout of ``Upsample3DLayer`` (official: ``self.output_size``), and cross-attention + masks for ``padding_type`` "zeros"/"nearest" when padding is needed (official: undefined mask); +- ``CuboidTransformerModel.forward`` checks the input shape and raises ``ValueError``; +- :class:`Earthformer` / :class:`EarthformerSegmenter` (PyHazards wrappers: ``(batch, time, + channels, height, width)`` layout, next-fire-mask head), the configuration presets and + :func:`earthformer_builder` are additions. + +Parameter names, creation order and initialisation follow ``CuboidTransformerModel``, so its state +dicts (including the official SEVIR and ICAR-ENSO checkpoints) load with ``strict=True`` and the +same seed gives the same initial weights. +""" + +from __future__ import annotations + +import functools +import hashlib +import inspect +import urllib.error +from collections import OrderedDict +from functools import lru_cache +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Sequence, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint + + +# -------------------------------------------------------------------------------------------------- +# utils.py +# -------------------------------------------------------------------------------------------------- + + +def round_to(dat, c): + return dat + (dat - dat % c) % c + + +def get_activation(act, inplace=False, **kwargs): + """Activation layer by name ('leaky' is LeakyReLU with slope 0.1).""" + if act is None: + return lambda x: x + if isinstance(act, str): + if act == "leaky": + negative_slope = kwargs.get("negative_slope", 0.1) + return nn.LeakyReLU(negative_slope, inplace=inplace) + elif act == "identity": + return nn.Identity() + elif act == "elu": + return nn.ELU(inplace=inplace) + elif act == "gelu": + return nn.GELU() + elif act == "relu": + return nn.ReLU() + elif act == "sigmoid": + return nn.Sigmoid() + elif act == "tanh": + return nn.Tanh() + elif act == "softrelu" or act == "softplus": + return nn.Softplus() + elif act == "softsign": + return nn.Softsign() + else: + raise NotImplementedError(f'act="{act}" is not supported.') + else: + return act + + +class RMSNorm(nn.Module): + """Root Mean Square Layer Normalization (Zhang & Sennrich, NeurIPS 2019).""" + + def __init__(self, d, p=-1.0, eps=1e-8, bias=False): + super(RMSNorm, self).__init__() + self.eps = eps + self.d = d + self.p = p + self.bias = bias + + self.scale = nn.Parameter(torch.ones(d)) + self.register_parameter("scale", self.scale) + + if self.bias: + self.offset = nn.Parameter(torch.zeros(d)) + self.register_parameter("offset", self.offset) + + def forward(self, x): + if self.p < 0.0 or self.p > 1.0: + norm_x = x.norm(2, dim=-1, keepdim=True) + d_x = self.d + else: + partial_size = int(self.d * self.p) + partial_x, _ = torch.split(x, [partial_size, self.d - partial_size], dim=-1) + norm_x = partial_x.norm(2, dim=-1, keepdim=True) + d_x = partial_size + + rms_x = norm_x * d_x ** (-1.0 / 2) + x_normed = x / (rms_x + self.eps) + + if self.bias: + return self.scale * x_normed + self.offset + return self.scale * x_normed + + +def get_norm_layer(normalization: str = "layer_norm", axis: int = -1, epsilon: float = 1e-5, in_channels: int = 0, **kwargs): + """Normalization layer over the last axis: 'layer_norm', 'rms_norm' or None (identity).""" + if isinstance(normalization, str): + if normalization == "layer_norm": + assert in_channels > 0 + assert axis == -1 + norm_layer = nn.LayerNorm(normalized_shape=in_channels, eps=epsilon, **kwargs) + elif normalization == "rms_norm": + assert axis == -1 + norm_layer = RMSNorm(d=in_channels, eps=epsilon, **kwargs) + else: + raise NotImplementedError(f"normalization={normalization} is not supported") + return norm_layer + elif normalization is None: + return nn.Identity() + else: + raise NotImplementedError("The type of normalization must be str") + + +def _generalize_padding(x, pad_t, pad_h, pad_w, padding_type, t_pad_left=False): + """Pad ``x`` of shape (B, T, H, W, C) to (B, T + pad_t, H + pad_h, W + pad_w, C).""" + if pad_t == 0 and pad_h == 0 and pad_w == 0: + return x + + assert padding_type in ["zeros", "ignore", "nearest"] + B, T, H, W, C = x.shape + + if padding_type == "nearest": + return F.interpolate(x.permute(0, 4, 1, 2, 3), size=(T + pad_t, H + pad_h, W + pad_w)).permute(0, 2, 3, 4, 1) + else: + if t_pad_left: + return F.pad(x, (0, 0, 0, pad_w, 0, pad_h, pad_t, 0)) + else: + return F.pad(x, (0, 0, 0, pad_w, 0, pad_h, 0, pad_t)) + + +def _generalize_unpadding(x, pad_t, pad_h, pad_w, padding_type): + assert padding_type in ["zeros", "ignore", "nearest"] + B, T, H, W, C = x.shape + if pad_t == 0 and pad_h == 0 and pad_w == 0: + return x + + if padding_type == "nearest": + return F.interpolate(x.permute(0, 4, 1, 2, 3), size=(T - pad_t, H - pad_h, W - pad_w)).permute(0, 2, 3, 4, 1) + else: + return x[:, : (T - pad_t), : (H - pad_h), : (W - pad_w), :].contiguous() + + +def apply_initialization(m, linear_mode="0", conv_mode="0", norm_mode="0", embed_mode="0"): + if isinstance(m, nn.Linear): + if linear_mode in ("0",): + nn.init.kaiming_normal_(m.weight, mode="fan_in", nonlinearity="linear") + elif linear_mode in ("1",): + nn.init.kaiming_normal_(m.weight, a=0.1, mode="fan_out", nonlinearity="leaky_relu") + else: + raise NotImplementedError + if hasattr(m, "bias") and m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.Conv2d, nn.Conv3d, nn.ConvTranspose2d, nn.ConvTranspose3d)): + if conv_mode in ("0",): + nn.init.kaiming_normal_(m.weight, a=0.1, mode="fan_out", nonlinearity="leaky_relu") + else: + raise NotImplementedError + if hasattr(m, "bias") and m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + if norm_mode in ("0",): + if m.elementwise_affine: + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + else: + raise NotImplementedError + elif isinstance(m, nn.GroupNorm): + if norm_mode in ("0",): + if m.affine: + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + else: + raise NotImplementedError + elif isinstance(m, nn.Embedding): + if embed_mode in ("0",): + nn.init.trunc_normal_(m.weight.data, std=0.02) + else: + raise NotImplementedError + else: + pass + + +def _checkpoint(function, *args): + # The official code calls checkpoint.checkpoint(function, *args), i.e. the reentrant variant. + return checkpoint.checkpoint(function, *args, use_reentrant=True) + + +# -------------------------------------------------------------------------------------------------- +# cuboid_transformer_patterns.py +# -------------------------------------------------------------------------------------------------- + + +def full_attention(input_shape): + T, H, W, _ = input_shape + cuboid_size = [(T, H, W)] + strategy = [("l", "l", "l")] + shift_size = [(0, 0, 0)] + return cuboid_size, strategy, shift_size + + +def self_axial(input_shape): + """Axial attention (Ho et al., arXiv:1912.12180): (T, 1, 1) -> (1, H, 1) -> (1, 1, W).""" + T, H, W, _ = input_shape + cuboid_size = [(T, 1, 1), (1, H, 1), (1, 1, W)] + strategy = [("l", "l", "l"), ("l", "l", "l"), ("l", "l", "l")] + shift_size = [(0, 0, 0), (0, 0, 0), (0, 0, 0)] + return cuboid_size, strategy, shift_size + + +def self_video_swin(input_shape, P=2, M=4): + """Video Swin Transformer windows (Liu et al., arXiv:2106.13230).""" + T, H, W, _ = input_shape + P = min(P, T) + M = min(M, H, W) + cuboid_size = [(P, M, M), (P, M, M)] + strategy = [("l", "l", "l"), ("l", "l", "l")] + shift_size = [(0, 0, 0), (P // 2, M // 2, M // 2)] + return cuboid_size, strategy, shift_size + + +def self_divided_space_time(input_shape): + T, H, W, _ = input_shape + cuboid_size = [(T, 1, 1), (1, H, W)] + strategy = [("l", "l", "l"), ("l", "l", "l")] + shift_size = [(0, 0, 0), (0, 0, 0)] + return cuboid_size, strategy, shift_size + + +def self_spatial_lg_v1(input_shape, M=4): + T, H, W, _ = input_shape + if H <= M and W <= M: + cuboid_size = [(T, 1, 1), (1, H, W)] + strategy = [("l", "l", "l"), ("l", "l", "l")] + shift_size = [(0, 0, 0), (0, 0, 0)] + else: + cuboid_size = [(T, 1, 1), (1, M, M), (1, M, M)] + strategy = [("l", "l", "l"), ("l", "l", "l"), ("d", "d", "d")] + shift_size = [(0, 0, 0), (0, 0, 0), (0, 0, 0)] + return cuboid_size, strategy, shift_size + + +def self_axial_space_dilate_K(input_shape, K=2): + T, H, W, _ = input_shape + K = min(K, H, W) + cuboid_size = [(T, 1, 1), (1, H // K, 1), (1, H // K, 1), (1, 1, W // K), (1, 1, W // K)] + strategy = [("l", "l", "l"), ("d", "d", "d"), ("l", "l", "l"), ("d", "d", "d"), ("l", "l", "l")] + shift_size = [(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)] + return cuboid_size, strategy, shift_size + + +def cross_KxK(mem_shape, K): + T_mem, H, W, _ = mem_shape + K = min(K, H, W) + cuboid_hw = [(K, K)] + shift_hw = [(0, 0)] + strategy = [("l", "l", "l")] + n_temporal = [1] + return cuboid_hw, shift_hw, strategy, n_temporal + + +def cross_KxK_lg(mem_shape, K): + T_mem, H, W, _ = mem_shape + K = min(K, H, W) + cuboid_hw = [(K, K), (K, K)] + shift_hw = [(0, 0), (0, 0)] + strategy = [("l", "l", "l"), ("d", "d", "d")] + n_temporal = [1, 1] + return cuboid_hw, shift_hw, strategy, n_temporal + + +def cross_KxK_heter(mem_shape, K): + T_mem, H, W, _ = mem_shape + K = min(K, H, W) + cuboid_hw = [(K, K), (K, K), (K, K)] + shift_hw = [(0, 0), (0, 0), (K // 2, K // 2)] + strategy = [("l", "l", "l"), ("d", "d", "d"), ("l", "l", "l")] + n_temporal = [1, 1, 1] + return cuboid_hw, shift_hw, strategy, n_temporal + + +CuboidSelfAttentionPatterns: Dict[str, Any] = { + "full": full_attention, + "axial": self_axial, + "video_swin": self_video_swin, + "divided_st": self_divided_space_time, +} +for _p in [1, 2, 4, 8, 10]: + for _m in [1, 2, 4, 8, 16, 32]: + CuboidSelfAttentionPatterns[f"video_swin_{_p}x{_m}"] = functools.partial(self_video_swin, P=_p, M=_m) +CuboidSelfAttentionPatterns["spatial_lg_v1"] = self_spatial_lg_v1 +for _m in [1, 2, 4, 8, 16, 32]: + CuboidSelfAttentionPatterns[f"spatial_lg_{_m}"] = functools.partial(self_spatial_lg_v1, M=_m) +for _k in [2, 4, 8]: + CuboidSelfAttentionPatterns[f"axial_space_dilate_{_k}"] = functools.partial(self_axial_space_dilate_K, K=_k) + +CuboidCrossAttentionPatterns: Dict[str, Any] = {} +for _k in [1, 2, 4, 8]: + CuboidCrossAttentionPatterns[f"cross_{_k}x{_k}"] = functools.partial(cross_KxK, K=_k) + CuboidCrossAttentionPatterns[f"cross_{_k}x{_k}_lg"] = functools.partial(cross_KxK_lg, K=_k) + CuboidCrossAttentionPatterns[f"cross_{_k}x{_k}_heter"] = functools.partial(cross_KxK_heter, K=_k) + + +def _get_pattern(patterns: Mapping[str, Any], key: str, kind: str): + if key not in patterns: + raise ValueError(f"Unknown cuboid {kind} pattern {key!r}; expected one of {sorted(patterns)}.") + return patterns[key] + + +# -------------------------------------------------------------------------------------------------- +# cuboid_transformer.py +# -------------------------------------------------------------------------------------------------- + + +class PosEmbed(nn.Module): + """Learned space-time positional embedding added to (B, T, H, W, C): 't+h+w' or 't+hw'.""" + + def __init__(self, embed_dim, maxT, maxH, maxW, typ="t+h+w"): + super(PosEmbed, self).__init__() + self.typ = typ + + assert self.typ in ["t+h+w", "t+hw"] + self.maxT = maxT + self.maxH = maxH + self.maxW = maxW + self.embed_dim = embed_dim + if self.typ == "t+h+w": + self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim) + self.H_embed = nn.Embedding(num_embeddings=maxH, embedding_dim=embed_dim) + self.W_embed = nn.Embedding(num_embeddings=maxW, embedding_dim=embed_dim) + elif self.typ == "t+hw": + self.T_embed = nn.Embedding(num_embeddings=maxT, embedding_dim=embed_dim) + self.HW_embed = nn.Embedding(num_embeddings=maxH * maxW, embedding_dim=embed_dim) + else: + raise NotImplementedError + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, embed_mode="0") + + def forward(self, x): + _, T, H, W, _ = x.shape + t_idx = torch.arange(T, device=x.device) + h_idx = torch.arange(H, device=x.device) + w_idx = torch.arange(W, device=x.device) + if self.typ == "t+h+w": + return ( + x + + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim) + + self.H_embed(h_idx).reshape(1, H, 1, self.embed_dim) + + self.W_embed(w_idx).reshape(1, 1, W, self.embed_dim) + ) + elif self.typ == "t+hw": + spatial_idx = h_idx.unsqueeze(-1) * self.maxW + w_idx + return x + self.T_embed(t_idx).reshape(T, 1, 1, self.embed_dim) + self.HW_embed(spatial_idx) + else: + raise NotImplementedError + + +class PositionwiseFFN(nn.Module): + """Position-wise FFN. + + pre_norm=True: norm(data) -> fc1 -> act -> act_dropout -> fc2 -> dropout -> res(+data) + pre_norm=False: data -> fc1 -> act -> act_dropout -> fc2 -> dropout -> norm(res(+data)) + gated_proj uses act(fc1_gate(data)) * fc1(data). + """ + + def __init__( + self, + units: int = 512, + hidden_size: int = 2048, + activation_dropout: float = 0.0, + dropout: float = 0.1, + gated_proj: bool = False, + activation="relu", + normalization: str = "layer_norm", + layer_norm_eps: float = 1e-5, + pre_norm: bool = False, + linear_init_mode="0", + norm_init_mode="0", + ): + super().__init__() + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + + self._pre_norm = pre_norm + self._gated_proj = gated_proj + self._kwargs = OrderedDict( + [ + ("units", units), + ("hidden_size", hidden_size), + ("activation_dropout", activation_dropout), + ("activation", activation), + ("dropout", dropout), + ("normalization", normalization), + ("layer_norm_eps", layer_norm_eps), + ("gated_proj", gated_proj), + ("pre_norm", pre_norm), + ] + ) + self.dropout_layer = nn.Dropout(dropout) + self.activation_dropout_layer = nn.Dropout(activation_dropout) + self.ffn_1 = nn.Linear(in_features=units, out_features=hidden_size, bias=True) + if self._gated_proj: + self.ffn_1_gate = nn.Linear(in_features=units, out_features=hidden_size, bias=True) + self.activation = get_activation(activation) + self.ffn_2 = nn.Linear(in_features=hidden_size, out_features=units, bias=True) + self.layer_norm = get_norm_layer(normalization=normalization, in_channels=units, epsilon=layer_norm_eps) + self.reset_parameters() + + def reset_parameters(self): + apply_initialization(self.ffn_1, linear_mode=self.linear_init_mode) + if self._gated_proj: + apply_initialization(self.ffn_1_gate, linear_mode=self.linear_init_mode) + apply_initialization(self.ffn_2, linear_mode=self.linear_init_mode) + apply_initialization(self.layer_norm, norm_mode=self.norm_init_mode) + + def forward(self, data): + residual = data + if self._pre_norm: + data = self.layer_norm(data) + if self._gated_proj: + out = self.activation(self.ffn_1_gate(data)) * self.ffn_1(data) + else: + out = self.activation(self.ffn_1(data)) + out = self.activation_dropout_layer(out) + out = self.ffn_2(out) + out = self.dropout_layer(out) + out = out + residual + if not self._pre_norm: + out = self.layer_norm(out) + return out + + +class PatchMerging3D(nn.Module): + """Patch merging: (B, T, H, W, C) -> (B, T/dt, H/dh, W/dw, out_dim) via norm + linear.""" + + def __init__( + self, + dim, + out_dim=None, + downsample=(1, 2, 2), + norm_layer="layer_norm", + padding_type="nearest", + linear_init_mode="0", + norm_init_mode="0", + ): + super().__init__() + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + self.dim = dim + if out_dim is None: + out_dim = max(downsample) * dim + self.out_dim = out_dim + self.downsample = downsample + self.padding_type = padding_type + self.reduction = nn.Linear(downsample[0] * downsample[1] * downsample[2] * dim, out_dim, bias=False) + self.norm = get_norm_layer(norm_layer, in_channels=downsample[0] * downsample[1] * downsample[2] * dim) + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, linear_mode=self.linear_init_mode, norm_mode=self.norm_init_mode) + + def get_out_shape(self, data_shape): + T, H, W, C_in = data_shape + pad_t = (self.downsample[0] - T % self.downsample[0]) % self.downsample[0] + pad_h = (self.downsample[1] - H % self.downsample[1]) % self.downsample[1] + pad_w = (self.downsample[2] - W % self.downsample[2]) % self.downsample[2] + return ( + (T + pad_t) // self.downsample[0], + (H + pad_h) // self.downsample[1], + (W + pad_w) // self.downsample[2], + self.out_dim, + ) + + def forward(self, x): + B, T, H, W, C = x.shape + + pad_t = (self.downsample[0] - T % self.downsample[0]) % self.downsample[0] + pad_h = (self.downsample[1] - H % self.downsample[1]) % self.downsample[1] + pad_w = (self.downsample[2] - W % self.downsample[2]) % self.downsample[2] + # The official condition is ``pad_h or pad_h or pad_w``, which skips the padding (and then + # fails in reshape) when only the time axis needs it; identical whenever pad_t == 0. + if pad_t or pad_h or pad_w: + T += pad_t + H += pad_h + W += pad_w + x = _generalize_padding(x, pad_t, pad_h, pad_w, padding_type=self.padding_type) + + x = ( + x.reshape( + ( + B, + T // self.downsample[0], + self.downsample[0], + H // self.downsample[1], + self.downsample[1], + W // self.downsample[2], + self.downsample[2], + C, + ) + ) + .permute(0, 1, 3, 5, 2, 4, 6, 7) + .reshape( + B, + T // self.downsample[0], + H // self.downsample[1], + W // self.downsample[2], + self.downsample[0] * self.downsample[1] * self.downsample[2] * C, + ) + ) + x = self.norm(x) + x = self.reduction(x) + return x + + +class Upsample3DLayer(nn.Module): + """Nearest-neighbour upsampling followed by a 3x3 convolution. + + temporal_upsample=False: interpolation-2d (nearest) -> conv3x3(dim, out_dim) per frame; + otherwise interpolation-3d (nearest) -> conv (the official code uses a Conv2d here too). + """ + + def __init__( + self, + dim, + out_dim, + target_size, + temporal_upsample=False, + kernel_size=3, + layout="THWC", + conv_init_mode="0", + ): + super(Upsample3DLayer, self).__init__() + self.conv_init_mode = conv_init_mode + self.target_size = target_size + self.out_dim = out_dim + self.temporal_upsample = temporal_upsample + if temporal_upsample: + self.up = nn.Upsample(size=target_size, mode="nearest") + else: + self.up = nn.Upsample(size=(target_size[1], target_size[2]), mode="nearest") + self.conv = nn.Conv2d( + in_channels=dim, + out_channels=out_dim, + kernel_size=(kernel_size, kernel_size), + padding=(kernel_size // 2, kernel_size // 2), + ) + assert layout in ["THWC", "CTHW"] + self.layout = layout + + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, conv_mode=self.conv_init_mode) + + def forward(self, x): + if self.layout == "THWC": + B, T, H, W, C = x.shape + if self.temporal_upsample: + x = x.permute(0, 4, 1, 2, 3) + return self.conv(self.up(x)).permute(0, 2, 3, 4, 1) + else: + assert self.target_size[0] == T + x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) + x = self.up(x) + return self.conv(x).permute(0, 2, 3, 1).reshape((B,) + tuple(self.target_size) + (self.out_dim,)) + elif self.layout == "CTHW": + B, C, T, H, W = x.shape + if self.temporal_upsample: + return self.conv(self.up(x)) + else: + assert self.target_size[0] == T # official: self.output_size, an AttributeError + x = x.permute(0, 2, 1, 3, 4) + x = x.reshape(B * T, C, H, W) + return ( + self.conv(self.up(x)) + .reshape(B, self.target_size[0], self.out_dim, self.target_size[1], self.target_size[2]) + .permute(0, 2, 1, 3, 4) + ) + + +def cuboid_reorder(data, cuboid_size, strategy): + """Reorder (B, T, H, W, C) into (B, num_cuboids, bT * bH * bW, C). + + The tensor shape must be divisible by the cuboid size. Strategy 'l' groups neighbouring + elements (local), 'd' strided ones (dilated). + """ + B, T, H, W, C = data.shape + num_cuboids = T // cuboid_size[0] * H // cuboid_size[1] * W // cuboid_size[2] + cuboid_volume = cuboid_size[0] * cuboid_size[1] * cuboid_size[2] + intermediate_shape = [] + + nblock_axis = [] + block_axis = [] + for i, (block_size, total_size, ele_strategy) in enumerate(zip(cuboid_size, (T, H, W), strategy)): + if ele_strategy == "l": + intermediate_shape.extend([total_size // block_size, block_size]) + nblock_axis.append(2 * i + 1) + block_axis.append(2 * i + 2) + elif ele_strategy == "d": + intermediate_shape.extend([block_size, total_size // block_size]) + nblock_axis.append(2 * i + 2) + block_axis.append(2 * i + 1) + else: + raise NotImplementedError + data = data.reshape((B,) + tuple(intermediate_shape) + (C,)) + reordered_data = data.permute((0,) + tuple(nblock_axis) + tuple(block_axis) + (7,)) + reordered_data = reordered_data.reshape((B, num_cuboids, cuboid_volume, C)) + return reordered_data + + +def cuboid_reorder_reverse(data, cuboid_size, strategy, orig_data_shape): + """Inverse of :func:`cuboid_reorder`.""" + B, num_cuboids, cuboid_volume, C = data.shape + T, H, W = orig_data_shape + + permutation_axis = [0] + for i, (block_size, total_size, ele_strategy) in enumerate(zip(cuboid_size, (T, H, W), strategy)): + if ele_strategy == "l": + permutation_axis.append(i + 1) + permutation_axis.append(i + 4) + elif ele_strategy == "d": + permutation_axis.append(i + 4) + permutation_axis.append(i + 1) + else: + raise NotImplementedError + permutation_axis.append(7) + data = data.reshape( + B, T // cuboid_size[0], H // cuboid_size[1], W // cuboid_size[2], cuboid_size[0], cuboid_size[1], cuboid_size[2], C + ) + data = data.permute(permutation_axis) + data = data.reshape((B, T, H, W, C)) + return data + + +@lru_cache() +def compute_cuboid_self_attention_mask(data_shape, cuboid_size, shift_size, strategy, padding_type, device): + """Shifted-window attention mask of shape (num_cuboid, cuboid_vol, cuboid_vol). + + Padded positions are masked when padding_type is 'ignore'; the shift mask keeps shifted + windows from attending across the wrap-around. + """ + T, H, W = data_shape + pad_t = (cuboid_size[0] - T % cuboid_size[0]) % cuboid_size[0] + pad_h = (cuboid_size[1] - H % cuboid_size[1]) % cuboid_size[1] + pad_w = (cuboid_size[2] - W % cuboid_size[2]) % cuboid_size[2] + data_mask = None + if pad_t > 0 or pad_h > 0 or pad_w > 0: + if padding_type == "ignore": + data_mask = torch.ones((1, T, H, W, 1), dtype=torch.bool, device=device) + data_mask = F.pad(data_mask, (0, 0, 0, pad_w, 0, pad_h, 0, pad_t)) + else: + data_mask = torch.ones((1, T + pad_t, H + pad_h, W + pad_w, 1), dtype=torch.bool, device=device) + if any(i > 0 for i in shift_size): + if padding_type == "ignore": + data_mask = torch.roll(data_mask, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)) + if padding_type == "ignore": + data_mask = cuboid_reorder(data_mask, cuboid_size, strategy=strategy) + data_mask = data_mask.squeeze(-1).squeeze(0) + shift_mask = torch.zeros((1, T + pad_t, H + pad_h, W + pad_w, 1), device=device) + cnt = 0 + for t in slice(-cuboid_size[0]), slice(-cuboid_size[0], -shift_size[0]), slice(-shift_size[0], None): + for h in slice(-cuboid_size[1]), slice(-cuboid_size[1], -shift_size[1]), slice(-shift_size[1], None): + for w in slice(-cuboid_size[2]), slice(-cuboid_size[2], -shift_size[2]), slice(-shift_size[2], None): + shift_mask[:, t, h, w, :] = cnt + cnt += 1 + shift_mask = cuboid_reorder(shift_mask, cuboid_size, strategy=strategy) + shift_mask = shift_mask.squeeze(-1).squeeze(0) + attn_mask = (shift_mask.unsqueeze(1) - shift_mask.unsqueeze(2)) == 0 + if padding_type == "ignore": + attn_mask = data_mask.unsqueeze(1) * data_mask.unsqueeze(2) * attn_mask + return attn_mask + + +def masked_softmax(att_score, mask, axis: int = -1): + """Softmax that ignores masked elements (mask: 1 keep, 0 masked; broadcastable).""" + if mask is not None: + if att_score.dtype == torch.float16: + att_score = att_score.masked_fill(torch.logical_not(mask), -1e4) + else: + att_score = att_score.masked_fill(torch.logical_not(mask), -1e18) + att_weights = torch.softmax(att_score, dim=axis) * mask + else: + att_weights = torch.softmax(att_score, dim=axis) + return att_weights + + +def update_cuboid_size_shift_size(data_shape, cuboid_size, shift_size, strategy): + """Shrink the cuboid to the data where the data is smaller; no shift on dilated axes.""" + new_cuboid_size = list(cuboid_size) + new_shift_size = list(shift_size) + for i in range(len(data_shape)): + if strategy[i] == "d": + new_shift_size[i] = 0 + if data_shape[i] <= cuboid_size[i]: + new_cuboid_size[i] = data_shape[i] + new_shift_size[i] = 0 + return tuple(new_cuboid_size), tuple(new_shift_size) + + +class CuboidSelfAttentionLayer(nn.Module): + """Cuboid self-attention: decompose (T, H, W) into cuboids and attend within each cuboid. + + Optional global vectors attend to the whole tensor and every cuboid attends to them. + """ + + def __init__( + self, + dim, + num_heads, + cuboid_size=(2, 7, 7), + shift_size=(0, 0, 0), + strategy=("l", "l", "l"), + padding_type="ignore", + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_final_proj=True, + norm_layer="layer_norm", + use_global_vector=False, + use_global_self_attn=False, + separate_global_qkv=False, + global_dim_ratio=1, + checkpoint_level=True, + use_relative_pos=True, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + norm_init_mode="0", + ): + super(CuboidSelfAttentionLayer, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.norm_init_mode = norm_init_mode + + assert dim % num_heads == 0 + self.num_heads = num_heads + self.dim = dim + self.cuboid_size = tuple(cuboid_size) + self.shift_size = tuple(shift_size) + self.strategy = tuple(strategy) + self.padding_type = padding_type + self.use_final_proj = use_final_proj + self.use_relative_pos = use_relative_pos + self.use_global_vector = use_global_vector + self.use_global_self_attn = use_global_self_attn + self.separate_global_qkv = separate_global_qkv + if global_dim_ratio != 1: + assert separate_global_qkv is True, "Setting global_dim_ratio != 1 requires separate_global_qkv == True." + self.global_dim_ratio = global_dim_ratio + + assert self.padding_type in ["ignore", "zeros", "nearest"] + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + if use_relative_pos: + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * cuboid_size[0] - 1) * (2 * cuboid_size[1] - 1) * (2 * cuboid_size[2] - 1), num_heads) + ) + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + coords_t = torch.arange(self.cuboid_size[0]) + coords_h = torch.arange(self.cuboid_size[1]) + coords_w = torch.arange(self.cuboid_size[2]) + coords = torch.stack(torch.meshgrid(coords_t, coords_h, coords_w, indexing="ij")) + + coords_flatten = torch.flatten(coords, 1) + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + relative_coords[:, :, 0] += self.cuboid_size[0] - 1 + relative_coords[:, :, 1] += self.cuboid_size[1] - 1 + relative_coords[:, :, 2] += self.cuboid_size[2] - 1 + + relative_coords[:, :, 0] *= (2 * self.cuboid_size[1] - 1) * (2 * self.cuboid_size[2] - 1) + relative_coords[:, :, 1] *= 2 * self.cuboid_size[2] - 1 + relative_position_index = relative_coords.sum(-1) + self.register_buffer("relative_position_index", relative_position_index) + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + + if self.use_global_vector: + if self.separate_global_qkv: + self.l2g_q_net = nn.Linear(dim, dim, bias=qkv_bias) + self.l2g_global_kv_net = nn.Linear(in_features=global_dim_ratio * dim, out_features=dim * 2, bias=qkv_bias) + self.g2l_global_q_net = nn.Linear(in_features=global_dim_ratio * dim, out_features=dim, bias=qkv_bias) + self.g2l_k_net = nn.Linear(in_features=dim, out_features=dim, bias=qkv_bias) + self.g2l_v_net = nn.Linear(in_features=dim, out_features=global_dim_ratio * dim, bias=qkv_bias) + if self.use_global_self_attn: + self.g2g_global_qkv_net = nn.Linear( + in_features=global_dim_ratio * dim, out_features=global_dim_ratio * dim * 3, bias=qkv_bias + ) + else: + self.global_qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.global_attn_drop = nn.Dropout(attn_drop) + + if use_final_proj: + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + if self.use_global_vector: + self.global_proj = nn.Linear(in_features=global_dim_ratio * dim, out_features=global_dim_ratio * dim) + + self.norm = get_norm_layer(norm_layer, in_channels=dim) + if self.use_global_vector: + self.global_vec_norm = get_norm_layer(norm_layer, in_channels=global_dim_ratio * dim) + + self.checkpoint_level = checkpoint_level + self.reset_parameters() + + def reset_parameters(self): + apply_initialization(self.qkv, linear_mode=self.attn_linear_init_mode) + if self.use_final_proj: + apply_initialization(self.proj, linear_mode=self.ffn_linear_init_mode) + apply_initialization(self.norm, norm_mode=self.norm_init_mode) + if self.use_global_vector: + if self.separate_global_qkv: + apply_initialization(self.l2g_q_net, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.l2g_global_kv_net, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.g2l_global_q_net, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.g2l_k_net, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.g2l_v_net, linear_mode=self.attn_linear_init_mode) + if self.use_global_self_attn: + apply_initialization(self.g2g_global_qkv_net, linear_mode=self.attn_linear_init_mode) + else: + apply_initialization(self.global_qkv, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.global_vec_norm, norm_mode=self.norm_init_mode) + + def forward(self, x, global_vectors=None): + x = self.norm(x) + + B, T, H, W, C_in = x.shape + assert C_in == self.dim + if self.use_global_vector: + _, num_global, _ = global_vectors.shape + global_vectors = self.global_vec_norm(global_vectors) + + cuboid_size, shift_size = update_cuboid_size_shift_size((T, H, W), self.cuboid_size, self.shift_size, self.strategy) + # Step-1: pad the input + pad_t = (cuboid_size[0] - T % cuboid_size[0]) % cuboid_size[0] + pad_h = (cuboid_size[1] - H % cuboid_size[1]) % cuboid_size[1] + pad_w = (cuboid_size[2] - W % cuboid_size[2]) % cuboid_size[2] + + x = _generalize_padding(x, pad_t, pad_h, pad_w, self.padding_type) + + # Step-2: shift the tensor (shifted-window attention) + if any(i > 0 for i in shift_size): + shifted_x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)) + else: + shifted_x = x + # Step-3: reorder into (B, num_cuboids, cuboid_volume, C) + reordered_x = cuboid_reorder(shifted_x, cuboid_size=cuboid_size, strategy=self.strategy) + _, num_cuboids, cuboid_volume, _ = reordered_x.shape + # Step-4: self-attention, mask of shape (num_cuboids, cuboid_volume, cuboid_volume) + attn_mask = compute_cuboid_self_attention_mask( + (T, H, W), cuboid_size, shift_size=shift_size, strategy=self.strategy, padding_type=self.padding_type, device=x.device + ) + head_C = C_in // self.num_heads + qkv = ( + self.qkv(reordered_x) + .reshape(B, num_cuboids, cuboid_volume, 3, self.num_heads, head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + q, k, v = qkv[0], qkv[1], qkv[2] + q = q * self.scale + attn_score = q @ k.transpose(-2, -1) + + if self.use_relative_pos: + # Sliced to the (possibly shrunk) cuboid volume exactly as in the official code. + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index[:cuboid_volume, :cuboid_volume].reshape(-1) + ].reshape(cuboid_volume, cuboid_volume, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(1) + attn_score = attn_score + relative_position_bias + + # Local-to-global attention + if self.use_global_vector: + global_head_C = self.global_dim_ratio * head_C + if self.separate_global_qkv: + l2g_q = ( + self.l2g_q_net(reordered_x) + .reshape(B, num_cuboids, cuboid_volume, self.num_heads, head_C) + .permute(0, 3, 1, 2, 4) + ) + l2g_q = l2g_q * self.scale + l2g_global_kv = ( + self.l2g_global_kv_net(global_vectors) + .reshape(B, 1, num_global, 2, self.num_heads, head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + l2g_global_k, l2g_global_v = l2g_global_kv[0], l2g_global_kv[1] + g2l_global_q = ( + self.g2l_global_q_net(global_vectors).reshape(B, num_global, self.num_heads, head_C).permute(0, 2, 1, 3) + ) + g2l_global_q = g2l_global_q * self.scale + g2l_k = ( + self.g2l_k_net(reordered_x) + .reshape(B, num_cuboids, cuboid_volume, self.num_heads, head_C) + .permute(0, 3, 1, 2, 4) + ) + g2l_v = ( + self.g2l_v_net(reordered_x) + .reshape(B, num_cuboids, cuboid_volume, self.num_heads, global_head_C) + .permute(0, 3, 1, 2, 4) + ) + if self.use_global_self_attn: + g2g_global_qkv = ( + self.g2g_global_qkv_net(global_vectors) + .reshape(B, 1, num_global, 3, self.num_heads, global_head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + g2g_global_q, g2g_global_k, g2g_global_v = g2g_global_qkv[0], g2g_global_qkv[1], g2g_global_qkv[2] + g2g_global_q = g2g_global_q.squeeze(2) * self.scale + else: + q_global, k_global, v_global = ( + self.global_qkv(global_vectors) + .reshape(B, 1, num_global, 3, self.num_heads, head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + q_global = q_global.squeeze(2) * self.scale + l2g_q, g2l_k, g2l_v = q, k, v + g2l_global_q, l2g_global_k, l2g_global_v = q_global, k_global, v_global + if self.use_global_self_attn: + g2g_global_q, g2g_global_k, g2g_global_v = q_global, k_global, v_global + l2g_attn_score = l2g_q @ l2g_global_k.transpose(-2, -1) + attn_score_l2l_l2g = torch.cat((attn_score, l2g_attn_score), dim=-1) + attn_mask_l2l_l2g = F.pad(attn_mask, (0, num_global), "constant", 1) + v_l_g = torch.cat((v, l2g_global_v.expand(B, self.num_heads, num_cuboids, num_global, head_C)), dim=3) + attn_score_l2l_l2g = masked_softmax(attn_score_l2l_l2g, mask=attn_mask_l2l_l2g) + attn_score_l2l_l2g = self.attn_drop(attn_score_l2l_l2g) + reordered_x = (attn_score_l2l_l2g @ v_l_g).permute(0, 2, 3, 1, 4).reshape(B, num_cuboids, cuboid_volume, self.dim) + # Update the global vectors + if self.padding_type == "ignore": + g2l_attn_mask = torch.ones((1, T, H, W, 1), device=x.device) + if pad_t > 0 or pad_h > 0 or pad_w > 0: + g2l_attn_mask = F.pad(g2l_attn_mask, (0, 0, 0, pad_w, 0, pad_h, 0, pad_t)) + if any(i > 0 for i in shift_size): + g2l_attn_mask = torch.roll( + g2l_attn_mask, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3) + ) + g2l_attn_mask = g2l_attn_mask.reshape((-1,)) + else: + g2l_attn_mask = None + g2l_attn_score = g2l_global_q @ g2l_k.reshape(B, self.num_heads, num_cuboids * cuboid_volume, head_C).transpose(-2, -1) + if self.use_global_self_attn: + g2g_attn_score = g2g_global_q @ g2g_global_k.squeeze(2).transpose(-2, -1) + g2all_attn_score = torch.cat((g2l_attn_score, g2g_attn_score), dim=-1) + if g2l_attn_mask is not None: + g2all_attn_mask = F.pad(g2l_attn_mask, (0, num_global), "constant", 1) + else: + g2all_attn_mask = None + new_v = torch.cat( + ( + g2l_v.reshape(B, self.num_heads, num_cuboids * cuboid_volume, global_head_C), + g2g_global_v.reshape(B, self.num_heads, num_global, global_head_C), + ), + dim=2, + ) + else: + g2all_attn_score = g2l_attn_score + g2all_attn_mask = g2l_attn_mask + new_v = g2l_v.reshape(B, self.num_heads, num_cuboids * cuboid_volume, global_head_C) + g2all_attn_score = masked_softmax(g2all_attn_score, mask=g2all_attn_mask) + g2all_attn_score = self.global_attn_drop(g2all_attn_score) + new_global_vector = ( + (g2all_attn_score @ new_v).permute(0, 2, 1, 3).reshape(B, num_global, self.global_dim_ratio * self.dim) + ) + else: + attn_score = masked_softmax(attn_score, mask=attn_mask) + attn_score = self.attn_drop(attn_score) + reordered_x = (attn_score @ v).permute(0, 2, 3, 1, 4).reshape(B, num_cuboids, cuboid_volume, self.dim) + + if self.use_final_proj: + reordered_x = self.proj_drop(self.proj(reordered_x)) + if self.use_global_vector: + new_global_vector = self.proj_drop(self.global_proj(new_global_vector)) + # Step-5: shift back and slice + shifted_x = cuboid_reorder_reverse( + reordered_x, cuboid_size=cuboid_size, strategy=self.strategy, orig_data_shape=(T + pad_t, H + pad_h, W + pad_w) + ) + if any(i > 0 for i in shift_size): + x = torch.roll(shifted_x, shifts=(shift_size[0], shift_size[1], shift_size[2]), dims=(1, 2, 3)) + else: + x = shifted_x + x = _generalize_unpadding(x, pad_t=pad_t, pad_h=pad_h, pad_w=pad_w, padding_type=self.padding_type) + if self.use_global_vector: + return x, new_global_vector + else: + return x + + +class StackCuboidSelfAttentionBlock(nn.Module): + """A stack of cuboid self-attention layers (one per pattern), each followed by an FFN when + ``use_inter_ffn`` (pre-LN residual), else one FFN after the stack.""" + + def __init__( + self, + dim, + num_heads, + block_cuboid_size=[(4, 4, 4), (4, 4, 4)], + block_shift_size=[(0, 0, 0), (2, 2, 2)], + block_strategy=[("d", "d", "d"), ("l", "l", "l")], + padding_type="ignore", + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + ffn_drop=0.0, + activation="leaky", + gated_ffn=False, + norm_layer="layer_norm", + use_inter_ffn=False, + use_global_vector=False, + use_global_vector_ffn=True, + use_global_self_attn=False, + separate_global_qkv=False, + global_dim_ratio=1, + checkpoint_level=True, + use_relative_pos=True, + use_final_proj=True, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + norm_init_mode="0", + ): + super(StackCuboidSelfAttentionBlock, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.norm_init_mode = norm_init_mode + + assert len(block_cuboid_size[0]) > 0 and len(block_shift_size) > 0 and len(block_strategy) > 0, ( + f"Format of the block cuboid size is not correct. block_cuboid_size={block_cuboid_size}" + ) + assert len(block_cuboid_size) == len(block_shift_size) == len(block_strategy) + self.num_attn = len(block_cuboid_size) + self.checkpoint_level = checkpoint_level + self.use_inter_ffn = use_inter_ffn + self.use_global_vector = use_global_vector + self.use_global_vector_ffn = use_global_vector_ffn + self.use_global_self_attn = use_global_self_attn + self.global_dim_ratio = global_dim_ratio + + def ffn(units, hidden_size): + return PositionwiseFFN( + units=units, + hidden_size=hidden_size, + activation_dropout=ffn_drop, + dropout=ffn_drop, + gated_proj=gated_ffn, + activation=activation, + normalization=norm_layer, + pre_norm=True, + linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + + num_ffn = self.num_attn if self.use_inter_ffn else 1 + self.ffn_l = nn.ModuleList([ffn(dim, 4 * dim) for _ in range(num_ffn)]) + if self.use_global_vector_ffn and self.use_global_vector: + self.global_ffn_l = nn.ModuleList( + [ffn(global_dim_ratio * dim, global_dim_ratio * 4 * dim) for _ in range(num_ffn)] + ) + self.attn_l = nn.ModuleList( + [ + CuboidSelfAttentionLayer( + dim=dim, + num_heads=num_heads, + cuboid_size=ele_cuboid_size, + shift_size=ele_shift_size, + strategy=ele_strategy, + padding_type=padding_type, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=proj_drop, + norm_layer=norm_layer, + use_global_vector=use_global_vector, + use_global_self_attn=use_global_self_attn, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + use_final_proj=use_final_proj, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for ele_cuboid_size, ele_shift_size, ele_strategy in zip(block_cuboid_size, block_shift_size, block_strategy) + ] + ) + + def reset_parameters(self): + for m in self.ffn_l: + m.reset_parameters() + if self.use_global_vector_ffn and self.use_global_vector: + for m in self.global_ffn_l: + m.reset_parameters() + for m in self.attn_l: + m.reset_parameters() + + def forward(self, x, global_vectors=None): + if self.use_inter_ffn: + if self.use_global_vector: + for idx, (attn, ffn) in enumerate(zip(self.attn_l, self.ffn_l)): + if self.checkpoint_level >= 2 and self.training: + x_out, global_vectors_out = _checkpoint(attn, x, global_vectors) + else: + x_out, global_vectors_out = attn(x, global_vectors) + x = x + x_out + global_vectors = global_vectors + global_vectors_out + + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(ffn, x) + if self.use_global_vector_ffn: + global_vectors = _checkpoint(self.global_ffn_l[idx], global_vectors) + else: + x = ffn(x) + if self.use_global_vector_ffn: + global_vectors = self.global_ffn_l[idx](global_vectors) + return x, global_vectors + else: + for idx, (attn, ffn) in enumerate(zip(self.attn_l, self.ffn_l)): + if self.checkpoint_level >= 2 and self.training: + x = x + _checkpoint(attn, x) + else: + x = x + attn(x) + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(ffn, x) + else: + x = ffn(x) + return x + else: + if self.use_global_vector: + for idx, attn in enumerate(self.attn_l): + if self.checkpoint_level >= 2 and self.training: + x_out, global_vectors_out = _checkpoint(attn, x, global_vectors) + else: + x_out, global_vectors_out = attn(x, global_vectors) + x = x + x_out + global_vectors = global_vectors + global_vectors_out + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(self.ffn_l[0], x) + if self.use_global_vector_ffn: + global_vectors = _checkpoint(self.global_ffn_l[0], global_vectors) + else: + x = self.ffn_l[0](x) + if self.use_global_vector_ffn: + global_vectors = self.global_ffn_l[0](global_vectors) + return x, global_vectors + else: + for idx, attn in enumerate(self.attn_l): + if self.checkpoint_level >= 2 and self.training: + out = _checkpoint(attn, x) + else: + out = attn(x) + x = x + out + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(self.ffn_l[0], x) + else: + x = self.ffn_l[0](x) + return x + + +@lru_cache() +def compute_cuboid_cross_attention_mask(T_x, T_mem, H, W, n_temporal, cuboid_hw, shift_hw, strategy, padding_type, device): + """Cross-attention mask of shape (num_cuboid, x_cuboid_vol, mem_cuboid_vol).""" + pad_t_mem = (n_temporal - T_mem % n_temporal) % n_temporal + pad_t_x = (n_temporal - T_x % n_temporal) % n_temporal + pad_h = (cuboid_hw[0] - H % cuboid_hw[0]) % cuboid_hw[0] + pad_w = (cuboid_hw[1] - W % cuboid_hw[1]) % cuboid_hw[1] + + mem_cuboid_size = ((T_mem + pad_t_mem) // n_temporal,) + cuboid_hw + x_cuboid_size = ((T_x + pad_t_x) // n_temporal,) + cuboid_hw + # The official code leaves mem_mask / x_mask undefined when padding is needed and padding_type + # is not 'ignore'; here the padded entries then count as tokens, as in the self-attention mask. + if (pad_t_mem > 0 or pad_h > 0 or pad_w > 0) and padding_type == "ignore": + mem_mask = torch.ones((1, T_mem, H, W, 1), dtype=torch.bool, device=device) + mem_mask = F.pad(mem_mask, (0, 0, 0, pad_w, 0, pad_h, pad_t_mem, 0)) + else: + mem_mask = torch.ones((1, T_mem + pad_t_mem, H + pad_h, W + pad_w, 1), dtype=torch.bool, device=device) + if (pad_t_x > 0 or pad_h > 0 or pad_w > 0) and padding_type == "ignore": + x_mask = torch.ones((1, T_x, H, W, 1), dtype=torch.bool, device=device) + x_mask = F.pad(x_mask, (0, 0, 0, pad_w, 0, pad_h, 0, pad_t_x)) + else: + x_mask = torch.ones((1, T_x + pad_t_x, H + pad_h, W + pad_w, 1), dtype=torch.bool, device=device) + + if any(i > 0 for i in shift_hw): + if padding_type == "ignore": + x_mask = torch.roll(x_mask, shifts=(-shift_hw[0], -shift_hw[1]), dims=(2, 3)) + mem_mask = torch.roll(mem_mask, shifts=(-shift_hw[0], -shift_hw[1]), dims=(2, 3)) + x_mask = cuboid_reorder(x_mask, x_cuboid_size, strategy=strategy) + x_mask = x_mask.squeeze(-1).squeeze(0) + num_cuboids, x_cuboid_volume = x_mask.shape + mem_mask = cuboid_reorder(mem_mask, mem_cuboid_size, strategy=strategy) + mem_mask = mem_mask.squeeze(-1).squeeze(0) + _, mem_cuboid_volume = mem_mask.shape + + shift_mask = torch.zeros((1, n_temporal, H + pad_h, W + pad_w, 1), device=device) + + cnt = 0 + for h in slice(-cuboid_hw[0]), slice(-cuboid_hw[0], -shift_hw[0]), slice(-shift_hw[0], None): + for w in slice(-cuboid_hw[1]), slice(-cuboid_hw[1], -shift_hw[1]), slice(-shift_hw[1], None): + shift_mask[:, :, h, w, :] = cnt + cnt += 1 + shift_mask = cuboid_reorder(shift_mask, (1,) + cuboid_hw, strategy=strategy) + shift_mask = shift_mask.squeeze(-1).squeeze(0) + shift_mask = (shift_mask.unsqueeze(1) - shift_mask.unsqueeze(2)) == 0 + bh_bw = cuboid_hw[0] * cuboid_hw[1] + attn_mask = ( + shift_mask.reshape((num_cuboids, 1, bh_bw, 1, bh_bw)) + * x_mask.reshape((num_cuboids, -1, bh_bw, 1, 1)) + * mem_mask.reshape(num_cuboids, 1, 1, -1, bh_bw) + ) + attn_mask = attn_mask.reshape(num_cuboids, x_cuboid_volume, mem_cuboid_volume) + return attn_mask + + +class CuboidCrossAttentionLayer(nn.Module): + """Cuboid cross-attention between a query tensor (T2, H, W, C) and a memory (T1, H, W, C). + + Both are cut into the same number of cuboids (``n_temporal`` along time, ``cuboid_hw`` in + space); the memory is padded on the left in time, the query on the right. + """ + + def __init__( + self, + dim, + num_heads, + n_temporal=1, + cuboid_hw=(7, 7), + shift_hw=(0, 0), + strategy=("d", "l", "l"), + padding_type="ignore", + cross_last_n_frames=None, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + max_temporal_relative=50, + norm_layer="layer_norm", + use_global_vector=True, + separate_global_qkv=False, + global_dim_ratio=1, + checkpoint_level=1, + use_relative_pos=True, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + norm_init_mode="0", + ): + super(CuboidCrossAttentionLayer, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.norm_init_mode = norm_init_mode + + self.dim = dim + self.num_heads = num_heads + self.n_temporal = n_temporal + assert n_temporal > 0 + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + shift_hw = list(shift_hw) + if strategy[1] == "d": + shift_hw[0] = 0 + if strategy[2] == "d": + shift_hw[1] = 0 + self.cuboid_hw = tuple(cuboid_hw) + self.shift_hw = tuple(shift_hw) + self.strategy = tuple(strategy) + self.padding_type = padding_type + self.max_temporal_relative = max_temporal_relative + self.cross_last_n_frames = cross_last_n_frames + self.use_relative_pos = use_relative_pos + self.use_global_vector = use_global_vector + self.separate_global_qkv = separate_global_qkv + if global_dim_ratio != 1: + assert separate_global_qkv is True, "Setting global_dim_ratio != 1 requires separate_global_qkv == True." + self.global_dim_ratio = global_dim_ratio + + assert self.padding_type in ["ignore", "zeros", "nearest"] + + if use_relative_pos: + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * max_temporal_relative - 1) * (2 * cuboid_hw[0] - 1) * (2 * cuboid_hw[1] - 1), num_heads) + ) + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + coords_t = torch.arange(max_temporal_relative) + coords_h = torch.arange(self.cuboid_hw[0]) + coords_w = torch.arange(self.cuboid_hw[1]) + coords = torch.stack(torch.meshgrid(coords_t, coords_h, coords_w, indexing="ij")) + + coords_flatten = torch.flatten(coords, 1) + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + relative_coords[:, :, 0] += max_temporal_relative - 1 + relative_coords[:, :, 1] += self.cuboid_hw[0] - 1 + relative_coords[:, :, 2] += self.cuboid_hw[1] - 1 + relative_position_index = ( + relative_coords[:, :, 0] * (2 * self.cuboid_hw[0] - 1) * (2 * self.cuboid_hw[1] - 1) + + relative_coords[:, :, 1] * (2 * self.cuboid_hw[1] - 1) + + relative_coords[:, :, 2] + ) + self.register_buffer("relative_position_index", relative_position_index) + + self.q_proj = nn.Linear(dim, dim, bias=qkv_bias) + self.kv_proj = nn.Linear(dim, dim * 2, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + if self.use_global_vector: + if self.separate_global_qkv: + self.l2g_q_net = nn.Linear(dim, dim, bias=qkv_bias) + self.l2g_global_kv_net = nn.Linear(in_features=global_dim_ratio * dim, out_features=dim * 2, bias=qkv_bias) + + self.norm = get_norm_layer(norm_layer, in_channels=dim) + + self._checkpoint_level = checkpoint_level + + self.reset_parameters() + + def reset_parameters(self): + apply_initialization(self.q_proj, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.kv_proj, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.proj, linear_mode=self.ffn_linear_init_mode) + apply_initialization(self.norm, norm_mode=self.norm_init_mode) + if self.use_global_vector: + if self.separate_global_qkv: + apply_initialization(self.l2g_q_net, linear_mode=self.attn_linear_init_mode) + apply_initialization(self.l2g_global_kv_net, linear_mode=self.attn_linear_init_mode) + + def forward(self, x, mem, mem_global_vectors=None): + if self.cross_last_n_frames is not None: + cross_last_n_frames = int(min(self.cross_last_n_frames, mem.shape[1])) + mem = mem[:, -cross_last_n_frames:, ...] + if self.use_global_vector: + _, num_global, _ = mem_global_vectors.shape + x = self.norm(x) + B, T_x, H, W, C_in = x.shape + B_mem, T_mem, H_mem, W_mem, C_mem = mem.shape + assert T_x < self.max_temporal_relative and T_mem < self.max_temporal_relative + cuboid_hw = self.cuboid_hw + n_temporal = self.n_temporal + shift_hw = self.shift_hw + assert B_mem == B and H == H_mem and W == W_mem and C_in == C_mem, ( + f"Shape of memory and the input tensor does not match. x.shape={x.shape}, mem.shape={mem.shape}" + ) + pad_t_mem = (n_temporal - T_mem % n_temporal) % n_temporal + pad_t_x = (n_temporal - T_x % n_temporal) % n_temporal + pad_h = (cuboid_hw[0] - H % cuboid_hw[0]) % cuboid_hw[0] + pad_w = (cuboid_hw[1] - W % cuboid_hw[1]) % cuboid_hw[1] + + # Step-1: pad the memory and x + mem = _generalize_padding(mem, pad_t_mem, pad_h, pad_w, self.padding_type, t_pad_left=True) + x = _generalize_padding(x, pad_t_x, pad_h, pad_w, self.padding_type, t_pad_left=False) + + # Step-2: shift the tensors (shifted-window attention) + if any(i > 0 for i in shift_hw): + shifted_x = torch.roll(x, shifts=(-shift_hw[0], -shift_hw[1]), dims=(2, 3)) + shifted_mem = torch.roll(mem, shifts=(-shift_hw[0], -shift_hw[1]), dims=(2, 3)) + else: + shifted_x = x + shifted_mem = mem + + # Step-3: reorder the tensors + mem_cuboid_size = (mem.shape[1] // n_temporal,) + cuboid_hw + x_cuboid_size = (x.shape[1] // n_temporal,) + cuboid_hw + + reordered_mem = cuboid_reorder(shifted_mem, cuboid_size=mem_cuboid_size, strategy=self.strategy) + reordered_x = cuboid_reorder(shifted_x, cuboid_size=x_cuboid_size, strategy=self.strategy) + _, num_cuboids_mem, mem_cuboid_volume, _ = reordered_mem.shape + _, num_cuboids, x_cuboid_volume, _ = reordered_x.shape + assert num_cuboids_mem == num_cuboids, ( + f"Number of cuboids do not match. num_cuboids={num_cuboids}, num_cuboids_mem={num_cuboids_mem}" + ) + + # Step-4: cross-attention, mask of shape (num_cuboids, x_cuboid_volume, mem_cuboid_volume) + attn_mask = compute_cuboid_cross_attention_mask( + T_x, T_mem, H, W, n_temporal, cuboid_hw, shift_hw, strategy=self.strategy, padding_type=self.padding_type, device=x.device + ) + head_C = C_in // self.num_heads + + kv = ( + self.kv_proj(reordered_mem) + .reshape(B, num_cuboids, mem_cuboid_volume, 2, self.num_heads, head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + k, v = kv[0], kv[1] + q = self.q_proj(reordered_x).reshape(B, num_cuboids, x_cuboid_volume, self.num_heads, head_C).permute(0, 3, 1, 2, 4) + q = q * self.scale + attn_score = q @ k.transpose(-2, -1) + + if self.use_relative_pos: + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index[:x_cuboid_volume, :mem_cuboid_volume].reshape(-1) + ].reshape(x_cuboid_volume, mem_cuboid_volume, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(1) + attn_score = attn_score + relative_position_bias + + if self.use_global_vector: + if self.separate_global_qkv: + l2g_q = ( + self.l2g_q_net(reordered_x) + .reshape(B, num_cuboids, x_cuboid_volume, self.num_heads, head_C) + .permute(0, 3, 1, 2, 4) + ) + l2g_q = l2g_q * self.scale + l2g_global_kv = ( + self.l2g_global_kv_net(mem_global_vectors) + .reshape(B, 1, num_global, 2, self.num_heads, head_C) + .permute(3, 0, 4, 1, 2, 5) + ) + l2g_global_k, l2g_global_v = l2g_global_kv[0], l2g_global_kv[1] + else: + kv_global = ( + self.kv_proj(mem_global_vectors).reshape(B, 1, num_global, 2, self.num_heads, head_C).permute(3, 0, 4, 1, 2, 5) + ) + l2g_global_k, l2g_global_v = kv_global[0], kv_global[1] + l2g_q = q + l2g_attn_score = l2g_q @ l2g_global_k.transpose(-2, -1) + attn_score_l2l_l2g = torch.cat((attn_score, l2g_attn_score), dim=-1) + attn_mask_l2l_l2g = F.pad(attn_mask, (0, num_global), "constant", 1) + v_l_g = torch.cat((v, l2g_global_v.expand(B, self.num_heads, num_cuboids, num_global, head_C)), dim=3) + attn_score_l2l_l2g = masked_softmax(attn_score_l2l_l2g, mask=attn_mask_l2l_l2g) + attn_score_l2l_l2g = self.attn_drop(attn_score_l2l_l2g) + reordered_x = (attn_score_l2l_l2g @ v_l_g).permute(0, 2, 3, 1, 4).reshape(B, num_cuboids, x_cuboid_volume, self.dim) + else: + attn_score = masked_softmax(attn_score, mask=attn_mask) + attn_score = self.attn_drop(attn_score) + reordered_x = (attn_score @ v).permute(0, 2, 3, 1, 4).reshape(B, num_cuboids, x_cuboid_volume, self.dim) + reordered_x = self.proj_drop(self.proj(reordered_x)) + # Step-5: shift back and slice + shifted_x = cuboid_reorder_reverse( + reordered_x, cuboid_size=x_cuboid_size, strategy=self.strategy, orig_data_shape=(x.shape[1], x.shape[2], x.shape[3]) + ) + if any(i > 0 for i in shift_hw): + x = torch.roll(shifted_x, shifts=(shift_hw[0], shift_hw[1]), dims=(2, 3)) + else: + x = shifted_x + x = _generalize_unpadding(x, pad_t=pad_t_x, pad_h=pad_h, pad_w=pad_w, padding_type=self.padding_type) + return x + + +class CuboidTransformerEncoder(nn.Module): + """x --> attn_block --> patch_merge --> attn_block --> patch_merge --> ... --> out.""" + + def __init__( + self, + input_shape, + base_units=128, + block_units=None, + scale_alpha=1.0, + depth=[4, 4, 4], + downsample=2, + downsample_type="patch_merge", + block_attn_patterns=None, + block_cuboid_size=[(4, 4, 4), (4, 4, 4)], + block_strategy=[("l", "l", "l"), ("d", "d", "d")], + block_shift_size=[(0, 0, 0), (0, 0, 0)], + num_heads=4, + attn_drop=0.0, + proj_drop=0.0, + ffn_drop=0.0, + activation="leaky", + ffn_activation="leaky", + gated_ffn=False, + norm_layer="layer_norm", + use_inter_ffn=True, + padding_type="ignore", + checkpoint_level=True, + use_relative_pos=True, + self_attn_use_final_proj=True, + use_global_vector=False, + use_global_vector_ffn=True, + use_global_self_attn=False, + separate_global_qkv=False, + global_dim_ratio=1, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + conv_init_mode="0", + down_linear_init_mode="0", + norm_init_mode="0", + ): + super(CuboidTransformerEncoder, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.conv_init_mode = conv_init_mode + self.down_linear_init_mode = down_linear_init_mode + self.norm_init_mode = norm_init_mode + + self.input_shape = input_shape + self.depth = depth + self.num_blocks = len(depth) + self.base_units = base_units + self.scale_alpha = scale_alpha + if not isinstance(downsample, (tuple, list)): + downsample = (1, downsample, downsample) + self.downsample = downsample + self.downsample_type = downsample_type + self.num_heads = num_heads + self.use_global_vector = use_global_vector + self.checkpoint_level = checkpoint_level + if block_units is None: + block_units = [round_to(base_units * int((max(downsample) ** scale_alpha) ** i), 4) for i in range(self.num_blocks)] + else: + assert len(block_units) == self.num_blocks and block_units[0] == base_units + self.block_units = block_units + + if self.num_blocks > 1: + if downsample_type == "patch_merge": + self.down_layers = nn.ModuleList( + [ + PatchMerging3D( + dim=self.block_units[i], + downsample=downsample, + padding_type=padding_type, + out_dim=self.block_units[i + 1], + linear_init_mode=down_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for i in range(self.num_blocks - 1) + ] + ) + else: + raise NotImplementedError + if self.use_global_vector: + self.down_layer_global_proj = nn.ModuleList( + [ + nn.Linear( + in_features=global_dim_ratio * self.block_units[i], + out_features=global_dim_ratio * self.block_units[i + 1], + ) + for i in range(self.num_blocks - 1) + ] + ) + + if block_attn_patterns is not None: + mem_shapes = self.get_mem_shapes() + if isinstance(block_attn_patterns, (tuple, list)): + assert len(block_attn_patterns) == self.num_blocks + else: + block_attn_patterns = [block_attn_patterns for _ in range(self.num_blocks)] + block_cuboid_size = [] + block_strategy = [] + block_shift_size = [] + for idx, key in enumerate(block_attn_patterns): + func = _get_pattern(CuboidSelfAttentionPatterns, key, "self-attention") + cuboid_size, strategy, shift_size = func(mem_shapes[idx]) + block_cuboid_size.append(cuboid_size) + block_strategy.append(strategy) + block_shift_size.append(shift_size) + else: + if not isinstance(block_cuboid_size[0][0], (list, tuple)): + block_cuboid_size = [block_cuboid_size for _ in range(self.num_blocks)] + else: + assert len(block_cuboid_size) == self.num_blocks, ( + f"Incorrect input format! Received block_cuboid_size={block_cuboid_size}" + ) + + if not isinstance(block_strategy[0][0], (list, tuple)): + block_strategy = [block_strategy for _ in range(self.num_blocks)] + else: + assert len(block_strategy) == self.num_blocks, f"Incorrect input format! Received block_strategy={block_strategy}" + + if not isinstance(block_shift_size[0][0], (list, tuple)): + block_shift_size = [block_shift_size for _ in range(self.num_blocks)] + else: + assert len(block_shift_size) == self.num_blocks, ( + f"Incorrect input format! Received block_shift_size={block_shift_size}" + ) + self.block_cuboid_size = block_cuboid_size + self.block_strategy = block_strategy + self.block_shift_size = block_shift_size + + self.blocks = nn.ModuleList( + [ + nn.Sequential( + *[ + StackCuboidSelfAttentionBlock( + dim=self.block_units[i], + num_heads=num_heads, + block_cuboid_size=block_cuboid_size[i], + block_strategy=block_strategy[i], + block_shift_size=block_shift_size[i], + attn_drop=attn_drop, + proj_drop=proj_drop, + ffn_drop=ffn_drop, + activation=ffn_activation, + gated_ffn=gated_ffn, + norm_layer=norm_layer, + use_inter_ffn=use_inter_ffn, + padding_type=padding_type, + use_global_vector=use_global_vector, + use_global_vector_ffn=use_global_vector_ffn, + use_global_self_attn=use_global_self_attn, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + use_final_proj=self_attn_use_final_proj, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for _ in range(depth[i]) + ] + ) + for i in range(self.num_blocks) + ] + ) + self.reset_parameters() + + def reset_parameters(self): + if self.num_blocks > 1: + for m in self.down_layers: + m.reset_parameters() + if self.use_global_vector: + apply_initialization(self.down_layer_global_proj, linear_mode=self.down_linear_init_mode) + for ms in self.blocks: + for m in ms: + m.reset_parameters() + + def get_mem_shapes(self): + """Shapes (T, H, W, C) of the encoder outputs, used to build the decoder.""" + if self.num_blocks == 1: + return [self.input_shape] + else: + mem_shapes = [self.input_shape] + curr_shape = self.input_shape + for down_layer in self.down_layers: + curr_shape = down_layer.get_out_shape(curr_shape) + mem_shapes.append(curr_shape) + return mem_shapes + + def forward(self, x, global_vectors=None): + B, T, H, W, C_in = x.shape + assert (T, H, W, C_in) == tuple(self.input_shape) + + if self.use_global_vector: + out = [] + global_mem_out = [] + for i in range(self.num_blocks): + for l in self.blocks[i]: + x, global_vectors = l(x, global_vectors) + out.append(x) + global_mem_out.append(global_vectors) + if self.num_blocks > 1 and i < self.num_blocks - 1: + x = self.down_layers[i](x) + global_vectors = self.down_layer_global_proj[i](global_vectors) + return out, global_mem_out + else: + out = [] + for i in range(self.num_blocks): + x = self.blocks[i](x) + out.append(x) + if self.num_blocks > 1 and i < self.num_blocks - 1: + x = self.down_layers[i](x) + return out + + +class StackCuboidCrossAttentionBlock(nn.Module): + """A stack of cuboid cross-attention layers, each followed by an FFN when ``use_inter_ffn``.""" + + def __init__( + self, + dim, + num_heads, + block_cuboid_hw=[(4, 4), (4, 4)], + block_shift_hw=[(0, 0), (2, 2)], + block_n_temporal=[1, 2], + block_strategy=[("d", "d", "d"), ("l", "l", "l")], + padding_type="ignore", + cross_last_n_frames=None, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + ffn_drop=0.0, + activation="leaky", + gated_ffn=False, + norm_layer="layer_norm", + use_inter_ffn=True, + max_temporal_relative=50, + checkpoint_level=1, + use_relative_pos=True, + use_global_vector=False, + separate_global_qkv=False, + global_dim_ratio=1, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + norm_init_mode="0", + ): + super(StackCuboidCrossAttentionBlock, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.norm_init_mode = norm_init_mode + + assert len(block_cuboid_hw[0]) > 0 and len(block_shift_hw) > 0 and len(block_strategy) > 0, ( + f"Incorrect format. block_cuboid_hw={block_cuboid_hw}, block_shift_hw={block_shift_hw}, " + f"block_strategy={block_strategy}" + ) + assert len(block_cuboid_hw) == len(block_shift_hw) == len(block_strategy) + self.num_attn = len(block_cuboid_hw) + self.checkpoint_level = checkpoint_level + self.use_inter_ffn = use_inter_ffn + self.use_global_vector = use_global_vector + num_ffn = self.num_attn if self.use_inter_ffn else 1 + self.ffn_l = nn.ModuleList( + [ + PositionwiseFFN( + units=dim, + hidden_size=4 * dim, + activation_dropout=ffn_drop, + dropout=ffn_drop, + gated_proj=gated_ffn, + activation=activation, + normalization=norm_layer, + pre_norm=True, + linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for _ in range(num_ffn) + ] + ) + self.attn_l = nn.ModuleList( + [ + CuboidCrossAttentionLayer( + dim=dim, + num_heads=num_heads, + cuboid_hw=ele_cuboid_hw, + shift_hw=ele_shift_hw, + strategy=ele_strategy, + n_temporal=ele_n_temporal, + cross_last_n_frames=cross_last_n_frames, + padding_type=padding_type, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=proj_drop, + norm_layer=norm_layer, + max_temporal_relative=max_temporal_relative, + use_global_vector=use_global_vector, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for ele_cuboid_hw, ele_shift_hw, ele_strategy, ele_n_temporal in zip( + block_cuboid_hw, block_shift_hw, block_strategy, block_n_temporal + ) + ] + ) + + def reset_parameters(self): + for m in self.ffn_l: + m.reset_parameters() + for m in self.attn_l: + m.reset_parameters() + + def forward(self, x, mem, mem_global_vector=None): + if self.use_inter_ffn: + for attn, ffn in zip(self.attn_l, self.ffn_l): + if self.checkpoint_level >= 2 and self.training: + x = x + _checkpoint(attn, x, mem, mem_global_vector) + else: + x = x + attn(x, mem, mem_global_vector) + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(ffn, x) + else: + x = ffn(x) + return x + else: + for attn in self.attn_l: + if self.checkpoint_level >= 2 and self.training: + x = x + _checkpoint(attn, x, mem, mem_global_vector) + else: + x = x + attn(x, mem, mem_global_vector) + if self.checkpoint_level >= 1 and self.training: + x = _checkpoint(self.ffn_l[0], x) + else: + x = self.ffn_l[0](x) + return x + + +class CuboidTransformerDecoder(nn.Module): + """For each hierarchy (top to bottom): StackCuboidSelfAttention, then StackCuboidCrossAttention + with the encoder memory of that hierarchy, then upsampling.""" + + def __init__( + self, + target_temporal_length, + mem_shapes, + cross_start=0, + depth=[2, 2], + upsample_type="upsample", + upsample_kernel_size=3, + block_self_attn_patterns=None, + block_self_cuboid_size=[(4, 4, 4), (4, 4, 4)], + block_self_cuboid_strategy=[("l", "l", "l"), ("d", "d", "d")], + block_self_shift_size=[(1, 1, 1), (0, 0, 0)], + block_cross_attn_patterns=None, + block_cross_cuboid_hw=[(4, 4), (4, 4)], + block_cross_cuboid_strategy=[("l", "l", "l"), ("d", "l", "l")], + block_cross_shift_hw=[(0, 0), (0, 0)], + block_cross_n_temporal=[1, 2], + cross_last_n_frames=None, + num_heads=4, + attn_drop=0.0, + proj_drop=0.0, + ffn_drop=0.0, + ffn_activation="leaky", + gated_ffn=False, + norm_layer="layer_norm", + use_inter_ffn=False, + hierarchical_pos_embed=False, + pos_embed_type="t+hw", + max_temporal_relative=50, + padding_type="ignore", + checkpoint_level=True, + use_relative_pos=True, + self_attn_use_final_proj=True, + use_first_self_attn=False, + use_self_global=False, + self_update_global=True, + use_cross_global=False, + use_global_vector_ffn=True, + use_global_self_attn=False, + separate_global_qkv=False, + global_dim_ratio=1, + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + conv_init_mode="0", + up_linear_init_mode="0", + norm_init_mode="0", + ): + super(CuboidTransformerDecoder, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.conv_init_mode = conv_init_mode + self.up_linear_init_mode = up_linear_init_mode + self.norm_init_mode = norm_init_mode + + assert len(depth) == len(mem_shapes) + self.target_temporal_length = target_temporal_length + self.num_blocks = len(mem_shapes) + self.cross_start = cross_start + self.mem_shapes = mem_shapes + self.depth = depth + self.upsample_type = upsample_type + self.hierarchical_pos_embed = hierarchical_pos_embed + self.checkpoint_level = checkpoint_level + self.use_self_global = use_self_global + self.self_update_global = self_update_global + self.use_cross_global = use_cross_global + self.use_global_vector_ffn = use_global_vector_ffn + self.use_first_self_attn = use_first_self_attn + if block_self_attn_patterns is not None: + if isinstance(block_self_attn_patterns, (tuple, list)): + assert len(block_self_attn_patterns) == self.num_blocks + else: + block_self_attn_patterns = [block_self_attn_patterns for _ in range(self.num_blocks)] + block_self_cuboid_size = [] + block_self_cuboid_strategy = [] + block_self_shift_size = [] + for idx, key in enumerate(block_self_attn_patterns): + func = _get_pattern(CuboidSelfAttentionPatterns, key, "self-attention") + cuboid_size, strategy, shift_size = func(mem_shapes[idx]) + block_self_cuboid_size.append(cuboid_size) + block_self_cuboid_strategy.append(strategy) + block_self_shift_size.append(shift_size) + else: + if not isinstance(block_self_cuboid_size[0][0], (list, tuple)): + block_self_cuboid_size = [block_self_cuboid_size for _ in range(self.num_blocks)] + else: + assert len(block_self_cuboid_size) == self.num_blocks, ( + f"Incorrect input format! Received block_self_cuboid_size={block_self_cuboid_size}" + ) + + if not isinstance(block_self_cuboid_strategy[0][0], (list, tuple)): + block_self_cuboid_strategy = [block_self_cuboid_strategy for _ in range(self.num_blocks)] + else: + assert len(block_self_cuboid_strategy) == self.num_blocks, ( + f"Incorrect input format! Received block_self_cuboid_strategy={block_self_cuboid_strategy}" + ) + + if not isinstance(block_self_shift_size[0][0], (list, tuple)): + block_self_shift_size = [block_self_shift_size for _ in range(self.num_blocks)] + else: + assert len(block_self_shift_size) == self.num_blocks, ( + f"Incorrect input format! Received block_self_shift_size={block_self_shift_size}" + ) + self_blocks = [] + for i in range(self.num_blocks): + if not self.use_first_self_attn and i == self.num_blocks - 1: + # The top block has no additional self-attention layer. + ele_depth = depth[i] - 1 + else: + ele_depth = depth[i] + stack_cuboid_blocks = [ + StackCuboidSelfAttentionBlock( + dim=self.mem_shapes[i][-1], + num_heads=num_heads, + block_cuboid_size=block_self_cuboid_size[i], + block_strategy=block_self_cuboid_strategy[i], + block_shift_size=block_self_shift_size[i], + attn_drop=attn_drop, + proj_drop=proj_drop, + ffn_drop=ffn_drop, + activation=ffn_activation, + gated_ffn=gated_ffn, + norm_layer=norm_layer, + use_inter_ffn=use_inter_ffn, + padding_type=padding_type, + use_global_vector=use_self_global, + use_global_vector_ffn=use_global_vector_ffn, + use_global_self_attn=use_global_self_attn, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + use_final_proj=self_attn_use_final_proj, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for _ in range(ele_depth) + ] + self_blocks.append(nn.ModuleList(stack_cuboid_blocks)) + self.self_blocks = nn.ModuleList(self_blocks) + + if block_cross_attn_patterns is not None: + if isinstance(block_cross_attn_patterns, (tuple, list)): + assert len(block_cross_attn_patterns) == self.num_blocks + else: + block_cross_attn_patterns = [block_cross_attn_patterns for _ in range(self.num_blocks)] + + block_cross_cuboid_hw = [] + block_cross_cuboid_strategy = [] + block_cross_shift_hw = [] + block_cross_n_temporal = [] + for idx, key in enumerate(block_cross_attn_patterns): + if key == "last_frame_dst": + cuboid_hw = None + shift_hw = None + strategy = None + n_temporal = None + else: + func = _get_pattern(CuboidCrossAttentionPatterns, key, "cross-attention") + cuboid_hw, shift_hw, strategy, n_temporal = func(mem_shapes[idx]) + block_cross_cuboid_hw.append(cuboid_hw) + block_cross_cuboid_strategy.append(strategy) + block_cross_shift_hw.append(shift_hw) + block_cross_n_temporal.append(n_temporal) + else: + if not isinstance(block_cross_cuboid_hw[0][0], (list, tuple)): + block_cross_cuboid_hw = [block_cross_cuboid_hw for _ in range(self.num_blocks)] + else: + assert len(block_cross_cuboid_hw) == self.num_blocks, ( + f"Incorrect input format! Received block_cross_cuboid_hw={block_cross_cuboid_hw}" + ) + + if not isinstance(block_cross_cuboid_strategy[0][0], (list, tuple)): + block_cross_cuboid_strategy = [block_cross_cuboid_strategy for _ in range(self.num_blocks)] + else: + assert len(block_cross_cuboid_strategy) == self.num_blocks, ( + f"Incorrect input format! Received block_cross_cuboid_strategy={block_cross_cuboid_strategy}" + ) + + if not isinstance(block_cross_shift_hw[0][0], (list, tuple)): + block_cross_shift_hw = [block_cross_shift_hw for _ in range(self.num_blocks)] + else: + assert len(block_cross_shift_hw) == self.num_blocks, ( + f"Incorrect input format! Received block_cross_shift_hw={block_cross_shift_hw}" + ) + if not isinstance(block_cross_n_temporal[0], (list, tuple)): + block_cross_n_temporal = [block_cross_n_temporal for _ in range(self.num_blocks)] + else: + assert len(block_cross_n_temporal) == self.num_blocks, ( + f"Incorrect input format! Received block_cross_n_temporal={block_cross_n_temporal}" + ) + self.cross_blocks = nn.ModuleList() + for i in range(self.cross_start, self.num_blocks): + cross_block = nn.ModuleList( + [ + StackCuboidCrossAttentionBlock( + dim=self.mem_shapes[i][-1], + num_heads=num_heads, + block_cuboid_hw=block_cross_cuboid_hw[i], + block_strategy=block_cross_cuboid_strategy[i], + block_shift_hw=block_cross_shift_hw[i], + block_n_temporal=block_cross_n_temporal[i], + cross_last_n_frames=cross_last_n_frames, + attn_drop=attn_drop, + proj_drop=proj_drop, + ffn_drop=ffn_drop, + gated_ffn=gated_ffn, + norm_layer=norm_layer, + use_inter_ffn=use_inter_ffn, + activation=ffn_activation, + max_temporal_relative=max_temporal_relative, + padding_type=padding_type, + use_global_vector=use_cross_global, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + for _ in range(depth[i]) + ] + ) + self.cross_blocks.append(cross_block) + + if self.num_blocks > 1: + if self.upsample_type == "upsample": + self.upsample_layers = nn.ModuleList( + [ + Upsample3DLayer( + dim=self.mem_shapes[i + 1][-1], + out_dim=self.mem_shapes[i][-1], + target_size=(target_temporal_length,) + tuple(self.mem_shapes[i][1:3]), + kernel_size=upsample_kernel_size, + temporal_upsample=False, + conv_init_mode=conv_init_mode, + ) + for i in range(self.num_blocks - 1) + ] + ) + else: + raise NotImplementedError + if self.hierarchical_pos_embed: + self.hierarchical_pos_embed_l = nn.ModuleList( + [ + PosEmbed( + embed_dim=self.mem_shapes[i][-1], + typ=pos_embed_type, + maxT=target_temporal_length, + maxH=self.mem_shapes[i][1], + maxW=self.mem_shapes[i][2], + ) + for i in range(self.num_blocks - 1) + ] + ) + + self.reset_parameters() + + def reset_parameters(self): + for ms in self.self_blocks: + for m in ms: + m.reset_parameters() + for ms in self.cross_blocks: + for m in ms: + m.reset_parameters() + if self.num_blocks > 1: + for m in self.upsample_layers: + m.reset_parameters() + if self.hierarchical_pos_embed: + for m in self.hierarchical_pos_embed_l: + m.reset_parameters() + + def forward(self, x, mem_l, mem_global_vector_l=None): + B, T_top, H_top, W_top, C = x.shape + assert T_top == self.target_temporal_length + assert (H_top, W_top) == (self.mem_shapes[-1][1], self.mem_shapes[-1][2]) + for i in range(self.num_blocks - 1, -1, -1): + mem_global_vector = None if mem_global_vector_l is None else mem_global_vector_l[i] + if not self.use_first_self_attn and i == self.num_blocks - 1: + # The top block starts directly with cross-attention. + if i >= self.cross_start: + x = self.cross_blocks[i - self.cross_start][0](x, mem_l[i], mem_global_vector) + for idx in range(self.depth[i] - 1): + if self.use_self_global: + if self.self_update_global: + x, mem_global_vector = self.self_blocks[i][idx](x, mem_global_vector) + else: + x, _ = self.self_blocks[i][idx](x, mem_global_vector) + else: + x = self.self_blocks[i][idx](x) + if i >= self.cross_start: + x = self.cross_blocks[i - self.cross_start][idx + 1](x, mem_l[i], mem_global_vector) + else: + for idx in range(self.depth[i]): + if self.use_self_global: + if self.self_update_global: + x, mem_global_vector = self.self_blocks[i][idx](x, mem_global_vector) + else: + x, _ = self.self_blocks[i][idx](x, mem_global_vector) + else: + x = self.self_blocks[i][idx](x) + if i >= self.cross_start: + x = self.cross_blocks[i - self.cross_start][idx](x, mem_l[i], mem_global_vector) + if i > 0: + x = self.upsample_layers[i - 1](x) + if self.hierarchical_pos_embed: + x = self.hierarchical_pos_embed_l[i - 1](x) + return x + + +class InitialEncoder(nn.Module): + """[K x (Conv3x3 -> GroupNorm(16) -> act)] -> PatchMerge, applied frame by frame.""" + + def __init__( + self, + dim, + out_dim, + downsample_scale: Union[int, Sequence[int]], + num_conv_layers=2, + activation="leaky", + padding_type="nearest", + conv_init_mode="0", + linear_init_mode="0", + norm_init_mode="0", + ): + super(InitialEncoder, self).__init__() + + self.num_conv_layers = num_conv_layers + self.conv_init_mode = conv_init_mode + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + + conv_block = [] + for i in range(num_conv_layers): + if i == 0: + conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=dim, out_channels=out_dim)) + conv_block.append(nn.GroupNorm(16, out_dim)) + conv_block.append(get_activation(activation)) + else: + conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=out_dim, out_channels=out_dim)) + conv_block.append(nn.GroupNorm(16, out_dim)) + conv_block.append(get_activation(activation)) + + self.conv_block = nn.Sequential(*conv_block) + if isinstance(downsample_scale, int): + patch_merge_downsample = (1, downsample_scale, downsample_scale) + elif len(downsample_scale) == 2: + patch_merge_downsample = (1, *downsample_scale) + elif len(downsample_scale) == 3: + patch_merge_downsample = tuple(downsample_scale) + else: + raise NotImplementedError(f"downsample_scale {downsample_scale} format not supported!") + self.patch_merge = PatchMerging3D( + dim=out_dim, + out_dim=out_dim, + padding_type=padding_type, + downsample=patch_merge_downsample, + linear_init_mode=linear_init_mode, + norm_init_mode=norm_init_mode, + ) + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, conv_mode=self.conv_init_mode, linear_mode=self.linear_init_mode, norm_mode=self.norm_init_mode) + + def forward(self, x): + B, T, H, W, C = x.shape + if self.num_conv_layers > 0: + x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) + x = self.conv_block(x).permute(0, 2, 3, 1) + x = self.patch_merge(x.reshape(B, T, H, W, -1)) + else: + x = self.patch_merge(x) + return x + + +class FinalDecoder(nn.Module): + """Upsample -> [K x (Conv3x3 -> GroupNorm(16) -> act)], applied frame by frame.""" + + def __init__( + self, + target_thw, + dim, + num_conv_layers=2, + activation="leaky", + conv_init_mode="0", + linear_init_mode="0", + norm_init_mode="0", + ): + super(FinalDecoder, self).__init__() + self.target_thw = target_thw + self.dim = dim + self.num_conv_layers = num_conv_layers + self.conv_init_mode = conv_init_mode + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + + conv_block = [] + for i in range(num_conv_layers): + conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=dim, out_channels=dim)) + conv_block.append(nn.GroupNorm(16, dim)) + conv_block.append(get_activation(activation)) + self.conv_block = nn.Sequential(*conv_block) + self.upsample = Upsample3DLayer(dim=dim, out_dim=dim, target_size=target_thw, kernel_size=3, conv_init_mode=conv_init_mode) + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, conv_mode=self.conv_init_mode, linear_mode=self.linear_init_mode, norm_mode=self.norm_init_mode) + + def forward(self, x): + x = self.upsample(x) + if self.num_conv_layers > 0: + B, T, H, W, C = x.shape + x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) + x = self.conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1) + return x + + +class InitialStackPatchMergingEncoder(nn.Module): + """[K x Conv2D] -> PatchMerge -> ... -> [K x Conv2D] -> PatchMerge (GroupNorm groups = dim // 4).""" + + def __init__( + self, + num_merge: int, + in_dim, + out_dim_list, + downsample_scale_list, + num_conv_per_merge_list=None, + activation="leaky", + padding_type="nearest", + conv_init_mode="0", + linear_init_mode="0", + norm_init_mode="0", + ): + super(InitialStackPatchMergingEncoder, self).__init__() + + self.conv_init_mode = conv_init_mode + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + + self.num_merge = num_merge + self.in_dim = in_dim + self.out_dim_list = out_dim_list[:num_merge] + self.downsample_scale_list = downsample_scale_list[:num_merge] + self.num_conv_per_merge_list = num_conv_per_merge_list + self.num_group_list = [max(1, out_dim // 4) for out_dim in self.out_dim_list] + + self.conv_block_list = nn.ModuleList() + self.patch_merge_list = nn.ModuleList() + for i in range(num_merge): + if i == 0: + in_dim = in_dim + else: + in_dim = self.out_dim_list[i - 1] + out_dim = self.out_dim_list[i] + downsample_scale = self.downsample_scale_list[i] + + conv_block = [] + for j in range(self.num_conv_per_merge_list[i]): + if j == 0: + conv_in_dim = in_dim + else: + conv_in_dim = out_dim + conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=conv_in_dim, out_channels=out_dim)) + conv_block.append(nn.GroupNorm(self.num_group_list[i], out_dim)) + conv_block.append(get_activation(activation)) + + conv_block = nn.Sequential(*conv_block) + self.conv_block_list.append(conv_block) + patch_merge = PatchMerging3D( + dim=out_dim, + out_dim=out_dim, + padding_type=padding_type, + downsample=(1, downsample_scale, downsample_scale), + linear_init_mode=linear_init_mode, + norm_init_mode=norm_init_mode, + ) + self.patch_merge_list.append(patch_merge) + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, conv_mode=self.conv_init_mode, linear_mode=self.linear_init_mode, norm_mode=self.norm_init_mode) + + def get_out_shape_list(self, input_shape): + """Shapes (T, H, W, C) after each patch merging.""" + out_shape_list = [] + for patch_merge in self.patch_merge_list: + input_shape = patch_merge.get_out_shape(input_shape) + out_shape_list.append(input_shape) + return out_shape_list + + def forward(self, x): + for i, (conv_block, patch_merge) in enumerate(zip(self.conv_block_list, self.patch_merge_list)): + B, T, H, W, C = x.shape + if self.num_conv_per_merge_list[i] > 0: + x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) + x = conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1) + x = patch_merge(x) + return x + + +class FinalStackUpsamplingDecoder(nn.Module): + """Upsample -> [K x Conv2D] -> ... -> Upsample -> [K x Conv2D] (GroupNorm groups = dim // 4).""" + + def __init__( + self, + target_shape_list, + in_dim, + num_conv_per_up_list=None, + activation="leaky", + conv_init_mode="0", + linear_init_mode="0", + norm_init_mode="0", + ): + super(FinalStackUpsamplingDecoder, self).__init__() + self.conv_init_mode = conv_init_mode + self.linear_init_mode = linear_init_mode + self.norm_init_mode = norm_init_mode + + self.target_shape_list = target_shape_list + self.out_dim_list = [target_shape[-1] for target_shape in self.target_shape_list] + self.num_upsample = len(target_shape_list) + self.in_dim = in_dim + self.num_conv_per_up_list = num_conv_per_up_list + self.num_group_list = [max(1, out_dim // 4) for out_dim in self.out_dim_list] + + self.conv_block_list = nn.ModuleList() + self.upsample_list = nn.ModuleList() + for i in range(self.num_upsample): + if i == 0: + in_dim = in_dim + else: + in_dim = self.out_dim_list[i - 1] + out_dim = self.out_dim_list[i] + + upsample = Upsample3DLayer( + dim=in_dim, out_dim=in_dim, target_size=tuple(target_shape_list[i][:-1]), kernel_size=3, conv_init_mode=conv_init_mode + ) + self.upsample_list.append(upsample) + conv_block = [] + for j in range(num_conv_per_up_list[i]): + if j == 0: + conv_in_dim = in_dim + else: + conv_in_dim = out_dim + conv_block.append(nn.Conv2d(kernel_size=(3, 3), padding=(1, 1), in_channels=conv_in_dim, out_channels=out_dim)) + conv_block.append(nn.GroupNorm(self.num_group_list[i], out_dim)) + conv_block.append(get_activation(activation)) + conv_block = nn.Sequential(*conv_block) + self.conv_block_list.append(conv_block) + self.reset_parameters() + + def reset_parameters(self): + for m in self.children(): + apply_initialization(m, conv_mode=self.conv_init_mode, linear_mode=self.linear_init_mode, norm_mode=self.norm_init_mode) + + @staticmethod + def get_init_params(enc_input_shape, enc_out_shape_list, large_channel=False): + dec_target_shape_list = list(enc_out_shape_list[:-1])[::-1] + [tuple(enc_input_shape)] + if large_channel: + dec_target_shape_list_large_channel = [] + for i, enc_out_shape in enumerate(enc_out_shape_list[::-1]): + dec_target_shape_large_channel = list(dec_target_shape_list[i]) + dec_target_shape_large_channel[-1] = enc_out_shape[-1] + dec_target_shape_list_large_channel.append(tuple(dec_target_shape_large_channel)) + dec_target_shape_list = dec_target_shape_list_large_channel + dec_in_dim = enc_out_shape_list[-1][-1] + return dec_target_shape_list, dec_in_dim + + def forward(self, x): + for i, (conv_block, upsample) in enumerate(zip(self.conv_block_list, self.upsample_list)): + x = upsample(x) + if self.num_conv_per_up_list[i] > 0: + B, T, H, W, C = x.shape + x = x.reshape(B * T, H, W, C).permute(0, 3, 1, 2) + x = conv_block(x).permute(0, 2, 3, 1).reshape(B, T, H, W, -1) + return x + + +class CuboidTransformerModel(nn.Module): + """Earthformer (official ``CuboidTransformerModel``): a non-autoregressive hierarchical + encoder-decoder built from cuboid attention. + + :: + + x --> downsample (optional) --> (+pos_embed) --> enc --> mem_l initial_z (+pos_embed) --> FC + | | + |----------| + | + y <-- upsample (optional) <-- dec <--------------------- + + Input ``(batch, T_in, H, W, C_in)`` (layout NTHWC as in the official code) with + ``(T_in, H, W, C_in) == input_shape``; output ``(batch, T_out, H, W, C_out)`` with + ``target_shape = (T_out, H, W, C_out)``. + """ + + def __init__( + self, + input_shape, + target_shape, + base_units=128, + block_units=None, + scale_alpha=1.0, + num_heads=4, + attn_drop=0.0, + proj_drop=0.0, + ffn_drop=0.0, + # inter-attn downsample/upsample + downsample=2, + downsample_type="patch_merge", + upsample_type="upsample", + upsample_kernel_size=3, + # encoder + enc_depth=[4, 4, 4], + enc_attn_patterns=None, + enc_cuboid_size=[(4, 4, 4), (4, 4, 4)], + enc_cuboid_strategy=[("l", "l", "l"), ("d", "d", "d")], + enc_shift_size=[(0, 0, 0), (0, 0, 0)], + enc_use_inter_ffn=True, + # decoder + dec_depth=[2, 2], + dec_cross_start=0, + dec_self_attn_patterns=None, + dec_self_cuboid_size=[(4, 4, 4), (4, 4, 4)], + dec_self_cuboid_strategy=[("l", "l", "l"), ("d", "d", "d")], + dec_self_shift_size=[(1, 1, 1), (0, 0, 0)], + dec_cross_attn_patterns=None, + dec_cross_cuboid_hw=[(4, 4), (4, 4)], + dec_cross_cuboid_strategy=[("l", "l", "l"), ("d", "l", "l")], + dec_cross_shift_hw=[(0, 0), (0, 0)], + dec_cross_n_temporal=[1, 2], + dec_cross_last_n_frames=None, + dec_use_inter_ffn=True, + dec_hierarchical_pos_embed=False, + # global vectors + num_global_vectors=4, + use_dec_self_global=True, + dec_self_update_global=True, + use_dec_cross_global=True, + use_global_vector_ffn=True, + use_global_self_attn=False, + separate_global_qkv=False, + global_dim_ratio=1, + z_init_method="nearest_interp", + # initial downsample and final upsample + initial_downsample_type="conv", + initial_downsample_activation="leaky", + # initial_downsample_type == "conv" + initial_downsample_scale=1, + initial_downsample_conv_layers=2, + final_upsample_conv_layers=2, + # initial_downsample_type == "stack_conv" + initial_downsample_stack_conv_num_layers=1, + initial_downsample_stack_conv_dim_list=None, + initial_downsample_stack_conv_downscale_list=[1], + initial_downsample_stack_conv_num_conv_list=[2], + ffn_activation="leaky", + gated_ffn=False, + norm_layer="layer_norm", + padding_type="ignore", + pos_embed_type="t+hw", + checkpoint_level=True, + use_relative_pos=True, + self_attn_use_final_proj=True, + dec_use_first_self_attn=False, + # initialization + attn_linear_init_mode="0", + ffn_linear_init_mode="0", + conv_init_mode="0", + down_up_linear_init_mode="0", + norm_init_mode="0", + ): + super(CuboidTransformerModel, self).__init__() + self.attn_linear_init_mode = attn_linear_init_mode + self.ffn_linear_init_mode = ffn_linear_init_mode + self.conv_init_mode = conv_init_mode + self.down_up_linear_init_mode = down_up_linear_init_mode + self.norm_init_mode = norm_init_mode + + assert len(enc_depth) == len(dec_depth) + self.base_units = base_units + self.num_global_vectors = num_global_vectors + if global_dim_ratio != 1: + assert separate_global_qkv is True, "Setting global_dim_ratio != 1 requires separate_global_qkv == True." + self.global_dim_ratio = global_dim_ratio + self.z_init_method = z_init_method + assert self.z_init_method in ["zeros", "nearest_interp", "last", "mean"] + + self.input_shape = tuple(input_shape) + self.target_shape = tuple(target_shape) + T_in, H_in, W_in, C_in = self.input_shape + T_out, H_out, W_out, C_out = self.target_shape + assert H_in == H_out and W_in == W_out + + if self.num_global_vectors > 0: + self.init_global_vectors = nn.Parameter(torch.zeros((self.num_global_vectors, global_dim_ratio * base_units))) + + new_input_shape = self.get_initial_encoder_final_decoder( + initial_downsample_scale=initial_downsample_scale, + initial_downsample_type=initial_downsample_type, + activation=initial_downsample_activation, + initial_downsample_conv_layers=initial_downsample_conv_layers, + final_upsample_conv_layers=final_upsample_conv_layers, + padding_type=padding_type, + initial_downsample_stack_conv_num_layers=initial_downsample_stack_conv_num_layers, + initial_downsample_stack_conv_dim_list=initial_downsample_stack_conv_dim_list, + initial_downsample_stack_conv_downscale_list=initial_downsample_stack_conv_downscale_list, + initial_downsample_stack_conv_num_conv_list=initial_downsample_stack_conv_num_conv_list, + ) + T_in, H_in, W_in, _ = new_input_shape + + self.encoder = CuboidTransformerEncoder( + input_shape=(T_in, H_in, W_in, base_units), + base_units=base_units, + block_units=block_units, + scale_alpha=scale_alpha, + depth=enc_depth, + downsample=downsample, + downsample_type=downsample_type, + block_attn_patterns=enc_attn_patterns, + block_cuboid_size=enc_cuboid_size, + block_strategy=enc_cuboid_strategy, + block_shift_size=enc_shift_size, + num_heads=num_heads, + attn_drop=attn_drop, + proj_drop=proj_drop, + ffn_drop=ffn_drop, + gated_ffn=gated_ffn, + ffn_activation=ffn_activation, + norm_layer=norm_layer, + use_inter_ffn=enc_use_inter_ffn, + padding_type=padding_type, + use_global_vector=num_global_vectors > 0, + use_global_vector_ffn=use_global_vector_ffn, + use_global_self_attn=use_global_self_attn, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + self_attn_use_final_proj=self_attn_use_final_proj, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + conv_init_mode=conv_init_mode, + down_linear_init_mode=down_up_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + self.enc_pos_embed = PosEmbed(embed_dim=base_units, typ=pos_embed_type, maxH=H_in, maxW=W_in, maxT=T_in) + mem_shapes = self.encoder.get_mem_shapes() + + self.z_proj = nn.Linear(mem_shapes[-1][-1], mem_shapes[-1][-1]) + self.dec_pos_embed = PosEmbed( + embed_dim=mem_shapes[-1][-1], typ=pos_embed_type, maxT=T_out, maxH=mem_shapes[-1][1], maxW=mem_shapes[-1][2] + ) + self.decoder = CuboidTransformerDecoder( + target_temporal_length=T_out, + mem_shapes=mem_shapes, + cross_start=dec_cross_start, + depth=dec_depth, + upsample_type=upsample_type, + block_self_attn_patterns=dec_self_attn_patterns, + block_self_cuboid_size=dec_self_cuboid_size, + block_self_shift_size=dec_self_shift_size, + block_self_cuboid_strategy=dec_self_cuboid_strategy, + block_cross_attn_patterns=dec_cross_attn_patterns, + block_cross_cuboid_hw=dec_cross_cuboid_hw, + block_cross_shift_hw=dec_cross_shift_hw, + block_cross_cuboid_strategy=dec_cross_cuboid_strategy, + block_cross_n_temporal=dec_cross_n_temporal, + cross_last_n_frames=dec_cross_last_n_frames, + num_heads=num_heads, + attn_drop=attn_drop, + proj_drop=proj_drop, + ffn_drop=ffn_drop, + upsample_kernel_size=upsample_kernel_size, + ffn_activation=ffn_activation, + gated_ffn=gated_ffn, + norm_layer=norm_layer, + use_inter_ffn=dec_use_inter_ffn, + max_temporal_relative=T_in + T_out, + padding_type=padding_type, + hierarchical_pos_embed=dec_hierarchical_pos_embed, + pos_embed_type=pos_embed_type, + use_self_global=(num_global_vectors > 0) and use_dec_self_global, + self_update_global=dec_self_update_global, + use_cross_global=(num_global_vectors > 0) and use_dec_cross_global, + use_global_vector_ffn=use_global_vector_ffn, + use_global_self_attn=use_global_self_attn, + separate_global_qkv=separate_global_qkv, + global_dim_ratio=global_dim_ratio, + checkpoint_level=checkpoint_level, + use_relative_pos=use_relative_pos, + self_attn_use_final_proj=self_attn_use_final_proj, + use_first_self_attn=dec_use_first_self_attn, + attn_linear_init_mode=attn_linear_init_mode, + ffn_linear_init_mode=ffn_linear_init_mode, + conv_init_mode=conv_init_mode, + up_linear_init_mode=down_up_linear_init_mode, + norm_init_mode=norm_init_mode, + ) + self.reset_parameters() + + def get_initial_encoder_final_decoder( + self, + initial_downsample_type, + activation, + initial_downsample_scale, + initial_downsample_conv_layers, + final_upsample_conv_layers, + padding_type, + initial_downsample_stack_conv_num_layers, + initial_downsample_stack_conv_dim_list, + initial_downsample_stack_conv_downscale_list, + initial_downsample_stack_conv_num_conv_list, + ): + T_in, H_in, W_in, C_in = self.input_shape + T_out, H_out, W_out, C_out = self.target_shape + self.initial_downsample_type = initial_downsample_type + if self.initial_downsample_type == "conv": + if isinstance(initial_downsample_scale, int): + initial_downsample_scale = (1, initial_downsample_scale, initial_downsample_scale) + elif len(initial_downsample_scale) == 2: + initial_downsample_scale = (1, *initial_downsample_scale) + elif len(initial_downsample_scale) == 3: + initial_downsample_scale = tuple(initial_downsample_scale) + else: + raise NotImplementedError(f"initial_downsample_scale {initial_downsample_scale} format not supported!") + self.initial_encoder = InitialEncoder( + dim=C_in, + out_dim=self.base_units, + downsample_scale=initial_downsample_scale, + num_conv_layers=initial_downsample_conv_layers, + padding_type=padding_type, + activation=activation, + conv_init_mode=self.conv_init_mode, + linear_init_mode=self.down_up_linear_init_mode, + norm_init_mode=self.norm_init_mode, + ) + self.final_decoder = FinalDecoder( + dim=self.base_units, + target_thw=(T_out, H_out, W_out), + num_conv_layers=final_upsample_conv_layers, + activation=activation, + conv_init_mode=self.conv_init_mode, + linear_init_mode=self.down_up_linear_init_mode, + norm_init_mode=self.norm_init_mode, + ) + new_input_shape = self.initial_encoder.patch_merge.get_out_shape(self.input_shape) + self.dec_final_proj = nn.Linear(self.base_units, C_out) + elif self.initial_downsample_type == "stack_conv": + if initial_downsample_stack_conv_dim_list is None: + initial_downsample_stack_conv_dim_list = [self.base_units] * initial_downsample_stack_conv_num_layers + self.initial_encoder = InitialStackPatchMergingEncoder( + num_merge=initial_downsample_stack_conv_num_layers, + in_dim=C_in, + out_dim_list=initial_downsample_stack_conv_dim_list, + downsample_scale_list=initial_downsample_stack_conv_downscale_list, + num_conv_per_merge_list=initial_downsample_stack_conv_num_conv_list, + padding_type=padding_type, + activation=activation, + conv_init_mode=self.conv_init_mode, + linear_init_mode=self.down_up_linear_init_mode, + norm_init_mode=self.norm_init_mode, + ) + # self.target_shape gives the correct T_out + initial_encoder_out_shape_list = self.initial_encoder.get_out_shape_list(self.target_shape) + dec_target_shape_list, dec_in_dim = FinalStackUpsamplingDecoder.get_init_params( + enc_input_shape=self.target_shape, enc_out_shape_list=initial_encoder_out_shape_list, large_channel=True + ) + self.final_decoder = FinalStackUpsamplingDecoder( + target_shape_list=dec_target_shape_list, + in_dim=dec_in_dim, + num_conv_per_up_list=initial_downsample_stack_conv_num_conv_list[::-1], + activation=activation, + conv_init_mode=self.conv_init_mode, + linear_init_mode=self.down_up_linear_init_mode, + norm_init_mode=self.norm_init_mode, + ) + self.dec_final_proj = nn.Linear(dec_target_shape_list[-1][-1], C_out) + new_input_shape = self.initial_encoder.get_out_shape_list(self.input_shape)[-1] + else: + raise NotImplementedError + self.input_shape_after_initial_downsample = new_input_shape + return new_input_shape + + def reset_parameters(self): + if self.num_global_vectors > 0: + nn.init.trunc_normal_(self.init_global_vectors, std=0.02) + if hasattr(self.initial_encoder, "reset_parameters"): + self.initial_encoder.reset_parameters() + else: + apply_initialization( + self.initial_encoder, + conv_mode=self.conv_init_mode, + linear_mode=self.down_up_linear_init_mode, + norm_mode=self.norm_init_mode, + ) + if hasattr(self.final_decoder, "reset_parameters"): + self.final_decoder.reset_parameters() + else: + apply_initialization( + self.final_decoder, + conv_mode=self.conv_init_mode, + linear_mode=self.down_up_linear_init_mode, + norm_mode=self.norm_init_mode, + ) + apply_initialization(self.dec_final_proj, linear_mode=self.down_up_linear_init_mode) + self.encoder.reset_parameters() + self.enc_pos_embed.reset_parameters() + self.decoder.reset_parameters() + self.dec_pos_embed.reset_parameters() + apply_initialization(self.z_proj, linear_mode="0") + + def get_initial_z(self, final_mem, T_out): + B = final_mem.shape[0] + if self.z_init_method == "zeros": + z_shape = (1, T_out) + final_mem.shape[2:] + initial_z = torch.zeros(z_shape, dtype=final_mem.dtype, device=final_mem.device) + initial_z = self.z_proj(self.dec_pos_embed(initial_z)).expand(B, -1, -1, -1, -1) + elif self.z_init_method == "nearest_interp": + initial_z = F.interpolate( + final_mem.permute(0, 4, 1, 2, 3), size=(T_out, final_mem.shape[2], final_mem.shape[3]) + ).permute(0, 2, 3, 4, 1) + initial_z = self.z_proj(initial_z) + elif self.z_init_method == "last": + initial_z = torch.broadcast_to(final_mem[:, -1:, :, :, :], (B, T_out) + final_mem.shape[2:]) + initial_z = self.z_proj(initial_z) + elif self.z_init_method == "mean": + initial_z = torch.broadcast_to(final_mem.mean(axis=1, keepdims=True), (B, T_out) + final_mem.shape[2:]) + initial_z = self.z_proj(initial_z) + else: + raise NotImplementedError + return initial_z + + def forward(self, x, verbose=False): + """``x``: ``(batch, T_in, H, W, C_in)``; returns ``(batch, T_out, H, W, C_out)``.""" + if x.ndim != 5 or tuple(x.shape[1:]) != self.input_shape: + raise ValueError( + "CuboidTransformerModel expects input of shape (batch, T, H, W, C) = " + f"(batch, {', '.join(map(str, self.input_shape))}), got {tuple(x.shape)}." + ) + B, _, _, _, _ = x.shape + T_out = self.target_shape[0] + x = self.initial_encoder(x) + x = self.enc_pos_embed(x) + if self.num_global_vectors > 0: + init_global_vectors = self.init_global_vectors.expand(B, self.num_global_vectors, self.global_dim_ratio * self.base_units) + mem_l, mem_global_vector_l = self.encoder(x, init_global_vectors) + else: + mem_l = self.encoder(x) + if verbose: + for i, mem in enumerate(mem_l): + print(f"mem[{i}].shape = {mem.shape}") + initial_z = self.get_initial_z(final_mem=mem_l[-1], T_out=T_out) + if self.num_global_vectors > 0: + dec_out = self.decoder(initial_z, mem_l, mem_global_vector_l) + else: + dec_out = self.decoder(initial_z, mem_l) + dec_out = self.final_decoder(dec_out) + out = self.dec_final_proj(dec_out) + return out + + +# -------------------------------------------------------------------------------------------------- +# PyHazards additions: configuration presets, layout wrappers, checkpoints and builder +# -------------------------------------------------------------------------------------------------- + +# ``model`` sections of the official configuration files (scripts/cuboid_transformer/...), verbatim. +# ``block_units`` is commented out in every file and falls back to None. +_SEVIR_V1: Dict[str, Any] = { + "input_shape": [13, 384, 384, 1], + "target_shape": [12, 384, 384, 1], + "base_units": 128, + "block_units": None, + "scale_alpha": 1.0, + "enc_depth": [1, 1], + "dec_depth": [1, 1], + "enc_use_inter_ffn": True, + "dec_use_inter_ffn": True, + "dec_hierarchical_pos_embed": False, + "downsample": 2, + "downsample_type": "patch_merge", + "upsample_type": "upsample", + "num_global_vectors": 8, + "use_dec_self_global": False, + "dec_self_update_global": True, + "use_dec_cross_global": False, + "use_global_vector_ffn": False, + "use_global_self_attn": True, + "separate_global_qkv": True, + "global_dim_ratio": 1, + "self_pattern": "axial", + "cross_self_pattern": "axial", + "cross_pattern": "cross_1x1", + "dec_cross_last_n_frames": None, + "attn_drop": 0.1, + "proj_drop": 0.1, + "ffn_drop": 0.1, + "num_heads": 4, + "ffn_activation": "gelu", + "gated_ffn": False, + "norm_layer": "layer_norm", + "padding_type": "zeros", + "pos_embed_type": "t+h+w", + "use_relative_pos": True, + "self_attn_use_final_proj": True, + "dec_use_first_self_attn": False, + "z_init_method": "zeros", + "checkpoint_level": 0, + "initial_downsample_type": "stack_conv", + "initial_downsample_activation": "leaky", + "initial_downsample_stack_conv_num_layers": 3, + "initial_downsample_stack_conv_dim_list": [16, 64, 128], + "initial_downsample_stack_conv_downscale_list": [3, 2, 2], + "initial_downsample_stack_conv_num_conv_list": [2, 2, 2], + "attn_linear_init_mode": "0", + "ffn_linear_init_mode": "0", + "conv_init_mode": "0", + "down_up_linear_init_mode": "0", + "norm_init_mode": "0", +} + +_SEVIR_LR: Dict[str, Any] = dict( + _SEVIR_V1, + input_shape=[7, 128, 128, 1], + target_shape=[6, 128, 128, 1], + base_units=64, + num_global_vectors=0, + use_global_self_attn=False, + separate_global_qkv=False, + initial_downsample_stack_conv_dim_list=[4, 16, 64], + initial_downsample_stack_conv_downscale_list=[1, 2, 2], +) + +_MOVING_MNIST: Dict[str, Any] = { + "input_shape": [10, 64, 64, 1], + "target_shape": [10, 64, 64, 1], + "base_units": 64, + "block_units": None, + "scale_alpha": 1.0, + "enc_depth": [4, 4], + "dec_depth": [4, 4], + "enc_use_inter_ffn": True, + "dec_use_inter_ffn": True, + "dec_hierarchical_pos_embed": False, + "downsample": 2, + "downsample_type": "patch_merge", + "upsample_type": "upsample", + "num_global_vectors": 0, + "use_dec_self_global": False, + "dec_self_update_global": True, + "use_dec_cross_global": False, + "use_global_vector_ffn": False, + "use_global_self_attn": False, + "separate_global_qkv": False, + "global_dim_ratio": 1, + "self_pattern": "axial", + "cross_self_pattern": "axial", + "cross_pattern": "cross_1x1", + "dec_cross_last_n_frames": None, + "attn_drop": 0.1, + "proj_drop": 0.1, + "ffn_drop": 0.1, + "num_heads": 4, + "ffn_activation": "gelu", + "gated_ffn": False, + "norm_layer": "layer_norm", + "padding_type": "zeros", + "pos_embed_type": "t+hw", + "use_relative_pos": True, + "self_attn_use_final_proj": True, + "dec_use_first_self_attn": False, + "z_init_method": "zeros", + "initial_downsample_type": "conv", + "initial_downsample_activation": "leaky", + "initial_downsample_scale": 2, + "initial_downsample_conv_layers": 2, + "final_upsample_conv_layers": 1, + "checkpoint_level": 0, + "attn_linear_init_mode": "0", + "ffn_linear_init_mode": "0", + "conv_init_mode": "0", + "down_up_linear_init_mode": "0", + "norm_init_mode": "0", +} + +_ENSO_V1: Dict[str, Any] = dict( + _MOVING_MNIST, + input_shape=[12, 24, 48, 1], + target_shape=[14, 24, 48, 1], + enc_depth=[1, 1], + dec_depth=[1, 1], + pos_embed_type="t+h+w", + initial_downsample_scale=[1, 1, 2], +) + +EARTHFORMER_CONFIGS: Dict[str, Dict[str, Any]] = { + # scripts/cuboid_transformer/sevir/earthformer_sevir_v1.yaml (= cfg_sevir.yaml): 8,659,677 params, + # the configuration of the released SEVIR checkpoint. + "sevir": _SEVIR_V1, + # scripts/cuboid_transformer/sevir/cfg_sevirlr.yaml (SEVIR-LR, 128x128): 1,505,069 params. + "sevir_lr": _SEVIR_LR, + # scripts/cuboid_transformer/moving_mnist/cfg.yaml (nbody/cfg.yaml is identical): 6,702,109 params. + "moving_mnist": _MOVING_MNIST, + "nbody": _MOVING_MNIST, + # scripts/cuboid_transformer/enso/earthformer_enso_v1.yaml (= cfg.yaml): 1,394,325 params, the + # configuration of the released ICAR-ENSO checkpoint. + "enso": _ENSO_V1, +} + +# YAML pattern keys and the CuboidTransformerModel arguments the training scripts expand them into. +_PATTERN_KEYS = { + "self_pattern": "enc_attn_patterns", + "cross_self_pattern": "dec_self_attn_patterns", + "cross_pattern": "dec_cross_attn_patterns", +} +_MODEL_ARGS = frozenset(name for name in inspect.signature(CuboidTransformerModel.__init__).parameters if name != "self") + + +def earthformer_config(config: str = "sevir", **overrides: Any) -> Dict[str, Any]: + """Keyword arguments of :class:`CuboidTransformerModel` for an official configuration. + + ``config`` names a preset in :data:`EARTHFORMER_CONFIGS`; ``overrides`` replace entries of + its ``model`` section (YAML keys, including ``self_pattern`` / ``cross_self_pattern`` / + ``cross_pattern``) or set any other ``CuboidTransformerModel`` argument. Patterns are expanded + to one per hierarchy exactly as the official training scripts do. + """ + if config not in EARTHFORMER_CONFIGS: + raise ValueError(f"Unknown Earthformer config {config!r}; expected one of {sorted(EARTHFORMER_CONFIGS)}.") + unknown = sorted(set(overrides) - _MODEL_ARGS - set(_PATTERN_KEYS)) + if unknown: + raise ValueError(f"Unknown Earthformer arguments: {unknown}.") + cfg = dict(EARTHFORMER_CONFIGS[config]) + cfg.update(overrides) + num_blocks = len(cfg["enc_depth"]) + kwargs = {key: value for key, value in cfg.items() if key not in _PATTERN_KEYS} + for yaml_key, arg in _PATTERN_KEYS.items(): + if arg not in overrides: # an explicit enc_attn_patterns etc. wins over the YAML key + pattern = cfg[yaml_key] + kwargs[arg] = [pattern] * num_blocks if isinstance(pattern, str) else list(pattern) + return kwargs + + +class Earthformer(CuboidTransformerModel): + """:class:`CuboidTransformerModel` with the PyHazards frame layout. + + Input ``(batch, T_in, C_in, H, W)``, output ``(batch, T_out, C_out, H, W)``. Parameters are those + of ``CuboidTransformerModel`` (no prefix), so official state dicts load with ``strict=True``. + """ + + def _check_frames(self, x: torch.Tensor) -> None: + T_in, H, W, C_in = self.input_shape + if x.ndim != 5 or tuple(x.shape[1:]) != (T_in, C_in, H, W): + raise ValueError( + f"{type(self).__name__} expects input of shape (batch, time, channels, height, width) = " + f"(batch, {T_in}, {C_in}, {H}, {W}), got {tuple(x.shape)}." + ) + + def forward(self, x: torch.Tensor, verbose: bool = False) -> torch.Tensor: + self._check_frames(x) + out = super().forward(x.permute(0, 1, 3, 4, 2), verbose=verbose) + return out.permute(0, 1, 4, 2, 3) + + +class EarthformerSegmenter(Earthformer): + """PyHazards next-fire-mask adaptation: one predicted frame returned as logits. + + The network is :class:`CuboidTransformerModel` with ``target_shape = (1, H, W, out_channels)``; + ``forward`` maps ``(batch, T_in, C_in, H, W)`` to ``(batch, out_channels, H, W)``. + """ + + def forward(self, x: torch.Tensor, verbose: bool = False) -> torch.Tensor: + return super().forward(x, verbose=verbose)[:, 0] + + +# Official checkpoints (README "Pretrained Weights"): state dicts of CuboidTransformerModel. +# The S3 bucket answered HTTP 403 on 2026-10-07; the Internet Archive kept byte-identical copies. +EARTHFORMER_CHECKPOINTS: Dict[str, Dict[str, Any]] = { + "sevir": { + "config": "sevir", + "urls": ( + "https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_sevir.pt", + "https://web.archive.org/web/20250517094035id_/https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_sevir.pt", + ), + "sha256": "2795b23a32cc03ebd77a6c6b57ebbe133070ff9cae1b365d82bb363fd6967215", + }, + "icarenso2021": { + "config": "enso", + "urls": ( + "https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_icarenso2021.pt", + "https://web.archive.org/web/20250517094035id_/https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_icarenso2021.pt", + ), + "sha256": "3428356328ec02291461f737684ea597a3126af86a09fe173b75ed54ffe1511f", + }, +} + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def earthformer_checkpoint_path(name: str) -> Path: + """Local path of an official checkpoint, downloaded into the torch hub cache on first use.""" + if name not in EARTHFORMER_CHECKPOINTS: + raise ValueError(f"Unknown Earthformer checkpoint {name!r}; expected one of {sorted(EARTHFORMER_CHECKPOINTS)}.") + spec = EARTHFORMER_CHECKPOINTS[name] + path = Path(torch.hub.get_dir()) / "checkpoints" / f"earthformer_{name}.pt" + if path.exists() and _sha256(path) == spec["sha256"]: + return path + path.parent.mkdir(parents=True, exist_ok=True) + errors = [] + for url in spec["urls"]: + try: + torch.hub.download_url_to_file(url, str(path), hash_prefix=spec["sha256"], progress=False) + return path + except (urllib.error.URLError, RuntimeError) as error: # HTTP 403 or hash mismatch + errors.append(f"{url}: {error}") + raise RuntimeError("Could not download the Earthformer checkpoint:\n" + "\n".join(errors)) + + +def load_earthformer_state_dict(source: Union[str, Path]) -> Dict[str, torch.Tensor]: + """State dict of an official checkpoint name (``"sevir"``, ``"icarenso2021"``) or a local file.""" + path = earthformer_checkpoint_path(str(source)) if str(source) in EARTHFORMER_CHECKPOINTS else Path(source) + return dict(torch.load(path, map_location="cpu", weights_only=True)) + + +def earthformer_builder( + task: str, + config: str = "sevir", + in_channels: Optional[int] = None, + out_channels: Optional[int] = None, + history: Optional[int] = None, + horizon: Optional[int] = None, + img_size: Optional[Union[int, Sequence[int]]] = None, + pretrained: Optional[Union[str, Path]] = None, + **kwargs: Any, +) -> nn.Module: + """Earthformer at an official configuration (``config``: sevir, sevir_lr, moving_mnist, nbody, enso). + + ``task="forecasting"``: frames to frames, ``(batch, history, in_channels, H, W)`` -> + ``(batch, horizon, out_channels, H, W)``. ``task="segmentation"``: the PyHazards next-fire-mask + adaptation, ``(batch, history, in_channels, H, W)`` -> ``(batch, out_channels, H, W)`` logits + with one predicted frame and ``out_channels=1`` by default. ``history``, ``horizon``, + ``in_channels``, ``out_channels`` and ``img_size`` (int or (H, W)) override the preset's + ``input_shape`` / ``target_shape``; other keyword arguments override preset entries + (see :func:`earthformer_config`). ``pretrained`` is ``"sevir"``, ``"icarenso2021"`` or a path to + a ``CuboidTransformerModel`` state dict, loaded with ``strict=True``. + """ + kwargs.pop("name", None) + task = task.lower() + if task not in ("forecasting", "segmentation"): + raise ValueError(f"earthformer supports task='forecasting' or 'segmentation', got {task!r}.") + if config not in EARTHFORMER_CONFIGS: + raise ValueError(f"Unknown Earthformer config {config!r}; expected one of {sorted(EARTHFORMER_CONFIGS)}.") + for key in ("input_shape", "target_shape"): + if key in kwargs: + raise ValueError(f"Set history, horizon, in_channels, out_channels and img_size instead of {key}.") + preset = EARTHFORMER_CONFIGS[config] + T_in, H, W, C_in = preset["input_shape"] + T_out, _, _, C_out = preset["target_shape"] + if task == "segmentation": + if horizon not in (None, 1): + raise ValueError(f"task='segmentation' predicts one frame; got horizon={horizon}.") + T_out, C_out = 1, 1 + if img_size is not None: + H, W = (img_size, img_size) if isinstance(img_size, int) else tuple(img_size) + T_in = T_in if history is None else history + T_out = T_out if horizon is None else horizon + C_in = C_in if in_channels is None else in_channels + C_out = C_out if out_channels is None else out_channels + for label, value in (("history", T_in), ("horizon", T_out), ("in_channels", C_in), ("out_channels", C_out), ("height", H), ("width", W)): + if int(value) <= 0: + raise ValueError(f"{label} must be positive, got {value}.") + + model_kwargs = earthformer_config(config, input_shape=[T_in, H, W, C_in], target_shape=[T_out, H, W, C_out], **kwargs) + model_cls = EarthformerSegmenter if task == "segmentation" else Earthformer + model = model_cls(**model_kwargs) + if pretrained is not None: + name = str(pretrained) + if name in EARTHFORMER_CHECKPOINTS: + expected = EARTHFORMER_CHECKPOINTS[name]["config"] + preset_shapes = (EARTHFORMER_CONFIGS[expected]["input_shape"], EARTHFORMER_CONFIGS[expected]["target_shape"]) + if task != "forecasting" or config != expected or (model.input_shape, model.target_shape) != tuple(map(tuple, preset_shapes)): + raise ValueError( + f"The {name!r} checkpoint needs task='forecasting', config={expected!r} and the preset's " + "input and target shapes." + ) + model.load_state_dict(load_earthformer_state_dict(pretrained), strict=True) + return model + + +__all__ = [ + "EARTHFORMER_CHECKPOINTS", + "EARTHFORMER_CONFIGS", + "CuboidCrossAttentionLayer", + "CuboidSelfAttentionLayer", + "CuboidTransformerDecoder", + "CuboidTransformerEncoder", + "CuboidTransformerModel", + "Earthformer", + "EarthformerSegmenter", + "earthformer_builder", + "earthformer_checkpoint_path", + "earthformer_config", + "load_earthformer_state_dict", +] diff --git a/pyhazards/models/eqnet.py b/pyhazards/models/eqnet.py index 1f7784a7..2b2e568c 100644 --- a/pyhazards/models/eqnet.py +++ b/pyhazards/models/eqnet.py @@ -1,65 +1,539 @@ +"""EQNet: end-to-end earthquake detection with joint phase picking and association. + +Zhu, Tai, Mousavi, Bailis & Beroza, "An End-to-End Earthquake Detection Method for Joint Phase Picking and +Association Using Deep Learning", J. Geophys. Res. Solid Earth 127(3), e2021JB023283 (2022), +doi:10.1029/2021JB023283 (arXiv 2109.09911). + +Rebuilt from the paper (Section 2.1, Figure 3, Section 2.2 and the Discussion); no code was copied. The +official repository AI4EPS/EQNet is under an academic / non-commercial licence (and had no licence before +2023-10-26), it was published after the paper, and it does not contain the paper's shift-and-stack model. +It serves only as a test oracle (``tests/oracle/test_eqnet_oracle.py``): its ``ResNet(BasicBlock, +[2, 2, 2, 2])`` (``eqnet/models/resnet1d.py`` at af94a08) for the feature extractor, and the author's +first EQNet heads (``eqnet/models/eqnet.py`` at a9df49a, July 2022) at the paper's channel widths for +the picking and detection heads. Module names of the feature extractor follow torchvision's ResNet +(BSD-3-Clause), which the 1-D network is "modified from" (paper, Section 2.1). + +Architecture (1,043,619 parameters): + +- Feature extraction (Figure 3a, 996,960 parameters): a 1-D ResNet-18 applied to every station, + ``Conv1d(3, 32, 7, stride 2) -> BN -> ReLU -> MaxPool(3, 2)``, four stages of two basic blocks with 32, + 64, 128 and 256 channels (stride 2 in stages 2-4), and ``Conv1d(256, 128, 1) -> BN``: waveforms + ``[Nt, 3]`` become features ``[Nt/32, 128]``. +- Phase picking (Figure 3b, 2 x 7,825 parameters): one sub-network for P on feature channels 0-63 and one + for S on channels 64-127 (paper: "each network takes half of the extracted features"), each + ``Conv1d(64, 32, 3) -> BN -> ReLU -> x4 -> Conv1d(32, 16, 3) -> BN -> ReLU -> x4 -> Conv1d(16, 1, 3)``: + an activation sequence ``[Nt/2]`` (output sample ``j`` is input sample ``2 j``). +- Shift-and-stack (Section 2.1): for every candidate hypocentre the P features of each station are read + ``t_P`` seconds later and the S features ``t_S`` seconds later (theoretical travel times from the + station to the candidate), so that both align on the origin time, and averaged over the stations: + features ``[Nt/32, 128]`` per candidate. +- Event detection (Figure 3c, 31,009 parameters): ``Conv1d(128, 64, 3) -> BN -> ReLU -> Conv1d(64, 32, 3) + -> BN -> ReLU -> Conv1d(32, 1, 3)``: an activation over origin time ``[Nt/32]`` for every candidate. + +Choices the paper leaves open (each one is listed under ``reproduction.deviations`` on the model card): +reflect padding, bias-free convolutions before batch normalisation and a biased output convolution, +linear x4 interpolation (``align_corners=False``) and no ReLU after the extractor's last batch +normalisation follow the author's code; the station average, linear interpolation of fractional shifts, +zero features outside the window and per-channel standardisation of each station's window (as in the +official data reader) are PyHazards choices. +""" + from __future__ import annotations +import math +from typing import Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F +from ._seismic import TracePicks, WaveformPicker, as_sequence, std_normalize -class EQNet(nn.Module): - """Transformer-style earthquake phase-picking baseline.""" +FEATURE_STRIDE = 32 # input samples per feature sample (Figure 3a: [Nt/32, 128]) +PICK_STRIDE = 2 # input samples per picking-output sample (Figure 3b: [Nt/2, 1]) - def __init__( - self, - in_channels: int = 3, - hidden_dim: int = 48, - num_heads: int = 4, - num_layers: int = 2, - dropout: float = 0.1, - ): + +def _conv3(in_planes: int, out_planes: int, stride: int = 1, bias: bool = False) -> nn.Conv1d: + return nn.Conv1d(in_planes, out_planes, 3, stride=stride, padding=1, bias=bias, padding_mode="reflect") + + +class BasicBlock1d(nn.Module): + """ResNet basic block on ``(batch, channels, time)``: two 3-tap convolutions with BN, identity or + 1x1-projection shortcut, ReLU after the sum.""" + + def __init__(self, inplanes: int, planes: int, stride: int = 1, downsample: Optional[nn.Module] = None): super().__init__() - self.proj = nn.Conv1d(in_channels, hidden_dim, kernel_size=5, padding=2) - encoder_layer = nn.TransformerEncoderLayer( - d_model=hidden_dim, - nhead=num_heads, - dim_feedforward=2 * hidden_dim, - dropout=dropout, - batch_first=True, - activation="gelu", - ) - self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) - self.head = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, 2), - ) + self.conv1 = _conv3(inplanes, planes, stride) + self.bn1 = nn.BatchNorm1d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = _conv3(planes, planes) + self.bn2 = nn.BatchNorm1d(planes) + self.downsample = downsample + + def forward(self, x: torch.Tensor) -> torch.Tensor: + identity = x if self.downsample is None else self.downsample(x) + out = self.relu(self.bn1(self.conv1(x))) + out = self.bn2(self.conv2(out)) + return self.relu(out + identity) + + +class EQNetBackbone(nn.Module): + """Feature extraction network (Figure 3a): ``(n, 3, samples)`` -> ``(n, 128, samples / 32)``.""" + + widths = (32, 64, 128, 256) + + def __init__(self, in_channels: int = 3, blocks: Sequence[int] = (2, 2, 2, 2), out_channels: int = 128): + super().__init__() + self.inplanes = self.widths[0] + self.conv1 = nn.Conv1d(in_channels, self.inplanes, 7, stride=2, padding=3, bias=False, padding_mode="reflect") + self.bn1 = nn.BatchNorm1d(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(self.widths[0], blocks[0], stride=1) + self.layer2 = self._make_layer(self.widths[1], blocks[1], stride=2) + self.layer3 = self._make_layer(self.widths[2], blocks[2], stride=2) + self.layer4 = self._make_layer(self.widths[3], blocks[3], stride=2) + self.conv2 = nn.Conv1d(self.widths[3], out_channels, 1, bias=False) + self.bn2 = nn.BatchNorm1d(out_channels) + for module in self.modules(): + if isinstance(module, nn.Conv1d): + nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(module, nn.BatchNorm1d): + nn.init.constant_(module.weight, 1) + nn.init.constant_(module.bias, 0) + + def _make_layer(self, planes: int, blocks: int, stride: int) -> nn.Sequential: + downsample = None + if stride != 1 or self.inplanes != planes: + downsample = nn.Sequential( + nn.Conv1d(self.inplanes, planes, 1, stride=stride, bias=False), nn.BatchNorm1d(planes) + ) + layers = [BasicBlock1d(self.inplanes, planes, stride, downsample)] + self.inplanes = planes + layers.extend(BasicBlock1d(planes, planes) for _ in range(1, blocks)) + return nn.Sequential(*layers) def forward(self, x: torch.Tensor) -> torch.Tensor: if x.ndim != 3: - raise ValueError("EQNet expects inputs shaped (batch, channels, length).") - seq = self.proj(x).transpose(1, 2) - encoded = self.encoder(seq) - pooled = encoded.mean(dim=1) - return self.head(pooled) + raise ValueError(f"EQNetBackbone expects (n, channels, samples), got shape {tuple(x.shape)}.") + x = self.maxpool(self.relu(self.bn1(self.conv1(x)))) + x = self.layer4(self.layer3(self.layer2(self.layer1(x)))) + return self.bn2(self.conv2(x)) + + +class PhasePickingHead(nn.Module): + """Phase picking sub-network (Figure 3b): ``(n, 64, T)`` features -> ``(n, 16 T)`` logits.""" + + def __init__(self, in_channels: int = 64, channels: Sequence[int] = (32, 16), scale: int = 4): + super().__init__() + self.scale = int(scale) + self.conv1 = _conv3(in_channels, channels[0]) + self.bn1 = nn.BatchNorm1d(channels[0]) + self.conv2 = _conv3(channels[0], channels[1]) + self.bn2 = nn.BatchNorm1d(channels[1]) + self.conv_out = _conv3(channels[1], 1, bias=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = F.interpolate(F.relu(self.bn1(self.conv1(x))), scale_factor=self.scale, mode="linear", align_corners=False) + x = F.interpolate(F.relu(self.bn2(self.conv2(x))), scale_factor=self.scale, mode="linear", align_corners=False) + return self.conv_out(x).squeeze(1) + + +class EventDetectionHead(nn.Module): + """Event detection sub-network (Figure 3c): ``(n, 128, T)`` stacked features -> ``(n, T)`` logits.""" + + def __init__(self, in_channels: int = 128, channels: Sequence[int] = (64, 32)): + super().__init__() + self.conv1 = _conv3(in_channels, channels[0]) + self.bn1 = nn.BatchNorm1d(channels[0]) + self.conv2 = _conv3(channels[0], channels[1]) + self.bn2 = nn.BatchNorm1d(channels[1]) + self.conv_out = _conv3(channels[1], 1, bias=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = F.relu(self.bn1(self.conv1(x))) + x = F.relu(self.bn2(self.conv2(x))) + return self.conv_out(x).squeeze(1) + + +def _shift(features: torch.Tensor, shifts: torch.Tensor) -> torch.Tensor: + """``out[b, s, k, c, t] = features[b, s, c, t + shifts[b, s, k]]``, linear in the fractional part, + zero outside ``[0, T - 1]``. ``features`` ``(B, S, C, T)``, ``shifts`` ``(B, S, K)`` (feature samples).""" + batch, stations, channels, length = features.shape + position = torch.arange(length, device=features.device, dtype=features.dtype) + shifts.unsqueeze(-1) + lower = torch.floor(position) + weight = (position - lower).unsqueeze(3) # (B, S, K, 1, T) + lower = lower.long() + out = 0 + for index, factor in ((lower, 1.0 - weight), (lower + 1, weight)): + valid = ((index >= 0) & (index < length)).unsqueeze(3) + gather_index = index.clamp(0, length - 1).unsqueeze(3).expand(-1, -1, -1, channels, -1) + source = features.unsqueeze(2).expand(-1, -1, gather_index.shape[2], -1, -1) + out = out + torch.gather(source, 4, gather_index) * factor * valid + return out + + +def shift_and_stack( + features: torch.Tensor, + travel_times: torch.Tensor, + feature_rate: float, + station_mask: Optional[torch.Tensor] = None, + p_channels: Optional[int] = None, +) -> torch.Tensor: + """Shift-and-stack module: align station features on the origin time of each candidate hypocentre. + + ``features``: ``(batch, stations, channels, T)`` backbone features; the first ``p_channels`` (default + half) are shifted by the P travel time, the rest by the S travel time. ``travel_times``: + ``(batch, stations, candidates, 2)`` P and S travel times in seconds. ``feature_rate``: feature samples + per second (``sampling_rate / 32``). ``station_mask``: ``(batch, stations)``, ``False`` for padded + stations. Returns ``(batch, candidates, channels, T)``: at time ``t`` and candidate ``k``, the mean over + stations of the features at ``t + travel_time``. + """ + if features.ndim != 4 or travel_times.ndim != 4 or travel_times.shape[-1] != 2: + raise ValueError( + "shift_and_stack expects features shaped (batch, stations, channels, time) and travel_times " + f"(batch, stations, candidates, 2); got shapes {tuple(features.shape)} and {tuple(travel_times.shape)}." + ) + if travel_times.shape[:2] != features.shape[:2]: + raise ValueError( + f"travel_times shape {tuple(travel_times.shape)} does not match {features.shape[0]} batches of " + f"{features.shape[1]} stations." + ) + split = features.shape[2] // 2 if p_channels is None else int(p_channels) + shifts = travel_times.to(features.dtype) * float(feature_rate) + shifted = torch.cat( + [_shift(features[:, :, :split], shifts[..., 0]), _shift(features[:, :, split:], shifts[..., 1])], dim=3 + ) # (B, S, K, C, T) + if station_mask is None: + return shifted.mean(dim=1) + weights = station_mask.to(features.dtype).reshape(*station_mask.shape, 1, 1, 1) + return (shifted * weights).sum(dim=1) / weights.sum(dim=1).clamp_min(1.0) + + +def eqnet_travel_times( + station_locations: torch.Tensor, + candidate_locations: torch.Tensor, + vp: float = 6.0, + vs: float = 3.4, +) -> torch.Tensor: + """Travel times ``(batch, stations, candidates, 2)`` in seconds in a uniform velocity model. + + Locations are Cartesian coordinates in km, ``(batch, stations, 3)`` (or ``(stations, 3)``) and + ``(candidates, 3)`` (or ``(batch, candidates, 3)``); the distance is Euclidean. The defaults are the + paper's Ridgecrest setting: 6 km/s for P and 3.4 km/s for S (Discussion). + """ + stations = torch.as_tensor(station_locations) + candidates = torch.as_tensor(candidate_locations, dtype=stations.dtype, device=stations.device) + if stations.ndim == 2: + stations = stations.unsqueeze(0) + if candidates.ndim == 2: + candidates = candidates.unsqueeze(0).expand(stations.shape[0], -1, -1) + if stations.shape[-1] != candidates.shape[-1] or stations.shape[0] != candidates.shape[0]: + raise ValueError( + f"station_locations {tuple(stations.shape)} and candidate_locations {tuple(candidates.shape)} do not match." + ) + distance = torch.cdist(stations, candidates) # (B, S, K) + return torch.stack([distance / float(vp), distance / float(vs)], dim=-1) + + +def eqnet_candidate_grid( + x_range: Tuple[float, float], + y_range: Tuple[float, float], + spacing: float = 4.0, + depth: float = 0.0, +) -> torch.Tensor: + """Candidate hypocentres ``(candidates, 3)`` on a horizontal grid (km), the paper's ~4 km search.""" + xs = torch.arange(float(x_range[0]), float(x_range[1]) + 1e-9, float(spacing)) + ys = torch.arange(float(y_range[0]), float(y_range[1]) + 1e-9, float(spacing)) + grid_x, grid_y = torch.meshgrid(xs, ys, indexing="ij") + return torch.stack([grid_x.flatten(), grid_y.flatten(), torch.full_like(grid_x.flatten(), float(depth))], dim=-1) + + +def geometric_median(points: torch.Tensor, iterations: int = 200, eps: float = 1e-7) -> torch.Tensor: + """Geometric median of ``(n, d)`` points (Weiszfeld's algorithm).""" + points = points.double() + estimate = points.mean(dim=0) + for _ in range(int(iterations)): + distance = torch.linalg.vector_norm(points - estimate, dim=1).clamp_min(eps) + weights = 1.0 / distance + update = (points * weights[:, None]).sum(dim=0) / weights.sum() + if torch.linalg.vector_norm(update - estimate) < eps: + estimate = update + break + estimate = update + return estimate + + +class EQNet(nn.Module, WaveformPicker): + """EQNet: multi-station phase picking and event detection. + + Input contract (``forward``): + + - ``waveforms``: ``(batch, stations, 3, samples)`` three-component windows (E, N, Z at 100 Hz), + standardised per station and channel (:meth:`annotate` does it for raw windows). Pad missing + stations with zeros and mark them in ``station_mask``. + - ``travel_times`` (optional): ``(batch, stations, candidates, 2)`` P and S travel times in seconds + from each station to each candidate hypocentre, e.g. :func:`eqnet_travel_times` of station and + candidate coordinates (:func:`eqnet_candidate_grid`) or a table from any velocity model. + - ``station_mask`` (optional): ``(batch, stations)`` booleans, ``False`` = padded station (left out of + the stack). + + Output: a dict with ``"phase"``, ``(batch, stations, 2, 16 * T)`` P / S activations (``T`` feature + samples, ``samples / 32`` when ``samples`` is a multiple of 32; output sample ``j`` is input sample + ``2 j``), and, with ``travel_times``, ``"event"``, ``(batch, candidates, T)`` event activations over + origin time (feature sample ``t`` is input sample ``32 t``). Probabilities by default, logits with + ``logits=True`` (what :class:`EQNetLoss` takes). + + Single-station picking (the STEAD benchmark of the paper, ``earthquake.picking``): :meth:`annotate` + takes ``(n, 3, samples)`` and returns ``(n, 2, samples // 2)`` P / S probabilities; + :meth:`extract_picks` returns peaks above 0.5. :meth:`extract_events` turns event activations into + origin times and locations. + """ + + sampling_rate = 100.0 + component_order = "ENZ" + output_names = ("P", "S") + phase_channels = {"P": 0, "S": 1} + + def __init__(self, in_channels: int = 3, sampling_rate: float = 100.0, candidate_chunk: int = 256): + super().__init__() + if int(in_channels) < 1 or float(sampling_rate) <= 0 or int(candidate_chunk) < 1: + raise ValueError("EQNet needs positive in_channels, sampling_rate and candidate_chunk.") + self.in_channels = int(in_channels) + self.sampling_rate = float(sampling_rate) + self.candidate_chunk = int(candidate_chunk) + self.backbone = EQNetBackbone(self.in_channels) + self.p_picker = PhasePickingHead(64) + self.s_picker = PhasePickingHead(64) + self.event_detector = EventDetectionHead(128) + + @property + def feature_rate(self) -> float: + return self.sampling_rate / FEATURE_STRIDE + + def features(self, waveforms: torch.Tensor) -> torch.Tensor: + """Backbone features ``(batch, stations, 128, T)`` of ``(batch, stations, 3, samples)`` waveforms.""" + if waveforms.ndim != 4 or waveforms.shape[2] != self.in_channels: + raise ValueError( + f"EQNet expects waveforms shaped (batch, stations, {self.in_channels}, samples), " + f"got shape {tuple(waveforms.shape)}." + ) + batch, stations = waveforms.shape[:2] + features = self.backbone(waveforms.reshape(batch * stations, *waveforms.shape[2:])) + return features.reshape(batch, stations, *features.shape[1:]) + + def detect( + self, + features: torch.Tensor, + travel_times: torch.Tensor, + station_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """Event logits ``(batch, candidates, T)``: shift-and-stack, then the event detection network. + + In evaluation mode candidates are processed in chunks of ``candidate_chunk`` to bound memory; in + training mode all candidates form one batch (batch-normalisation statistics then cover them all). + """ + batch, stations = features.shape[:2] + if travel_times.ndim != 4 or travel_times.shape[:2] != (batch, stations) or travel_times.shape[-1] != 2: + raise ValueError( + f"travel_times must be shaped ({batch}, {stations}, candidates, 2), got shape {tuple(travel_times.shape)}." + ) + if station_mask is not None and tuple(station_mask.shape) != (batch, stations): + raise ValueError(f"station_mask must be shaped ({batch}, {stations}), got shape {tuple(station_mask.shape)}.") + candidates = travel_times.shape[2] + chunk = candidates if self.training else self.candidate_chunk + logits = [] + for start in range(0, candidates, chunk): + stacked = shift_and_stack(features, travel_times[:, :, start : start + chunk], self.feature_rate, station_mask) + count = stacked.shape[1] + out = self.event_detector(stacked.reshape(batch * count, *stacked.shape[2:])) + logits.append(out.reshape(batch, count, -1)) + return torch.cat(logits, dim=1) + + def forward( + self, + waveforms: torch.Tensor, + travel_times: Optional[torch.Tensor] = None, + station_mask: Optional[torch.Tensor] = None, + logits: bool = False, + ) -> Dict[str, torch.Tensor]: + features = self.features(waveforms) + batch, stations = features.shape[:2] + flat = features.reshape(batch * stations, *features.shape[2:]) + phase = torch.stack([self.p_picker(flat[:, :64]), self.s_picker(flat[:, 64:])], dim=1) + outputs = {"phase": phase.reshape(batch, stations, 2, -1)} + if travel_times is not None: + outputs["event"] = self.detect(features, travel_times, station_mask) + if not logits: + outputs = {key: torch.sigmoid(value) for key, value in outputs.items()} + return outputs + + def annotate(self, waveforms: torch.Tensor) -> torch.Tensor: + """P / S probabilities of raw windows: ``(n, 3, samples)`` -> ``(n, 2, samples // 2)`` (single + stations) or ``(batch, stations, 3, samples)`` -> ``(batch, stations, 2, samples // 2)``. Each + station's window is standardised per channel first (mean removed, divided by the standard + deviation, as the official EQNet and PhaseNet readers do).""" + single = waveforms.ndim == 3 + if single: + waveforms = waveforms.unsqueeze(1) + if waveforms.ndim != 4: + raise ValueError( + f"EQNet.annotate expects (n, 3, samples) or (batch, stations, 3, samples), got shape {tuple(waveforms.shape)}." + ) + batch, stations, channels, samples = waveforms.shape + normalised = std_normalize(waveforms.reshape(batch * stations, channels, samples)) + phase = self(normalised.reshape(batch, stations, channels, samples))["phase"][..., : samples // PICK_STRIDE] + return phase[:, 0] if single else phase + + def extract_picks( + self, + annotations: torch.Tensor, + p_threshold: float = 0.5, + s_threshold: float = 0.5, + min_distance_s: float = 0.5, + **kwargs, + ) -> List[TracePicks]: + """Peaks above the threshold (0.5 in the paper) of ``(n, 2, length)`` P / S activations, at least + ``min_distance_s`` apart (the PhaseNet rule; the paper gives no distance). Pick samples are in + input samples (``2 j``).""" + from ..metrics.picking import peak_picks + + if kwargs: + raise TypeError(f"Unexpected EQNet pick parameters: {sorted(kwargs)}.") + if annotations.ndim != 3 or annotations.shape[1] != 2: + raise ValueError(f"extract_picks expects (n, 2, length) activations, got shape {tuple(annotations.shape)}.") + thresholds = as_sequence({"P": p_threshold, "S": s_threshold}, ("P", "S")) + distance = max(1, int(round(min_distance_s * self.sampling_rate / PICK_STRIDE))) + values = annotations.detach().cpu().double().numpy() + picks: List[TracePicks] = [] + for trace in values: + picks.append( + { + phase: [(PICK_STRIDE * index, probability) for index, probability in peak_picks(trace[channel], thresholds[phase], distance)] + for phase, channel in self.phase_channels.items() + } + ) + return picks + + def extract_events( + self, + event_activation: torch.Tensor, + candidate_locations: torch.Tensor, + threshold: float = 0.5, + top_k: int = 20, + min_distance_s: float = 2.0, + ) -> List[List[Dict[str, object]]]: + """Events from ``(batch, candidates, T)`` activations (paper, Section 2.2): origin times are the + peaks above ``threshold`` of the maximum over candidates, at least ``min_distance_s`` apart (not + given in the paper); each location is the geometric median of the ``top_k`` (20) candidates with + the highest activation at that time. Returns per batch item a list of + ``{"time": seconds, "sample": input sample, "probability": p, "location": [x, y, z]}``.""" + from ..metrics.picking import peak_picks + + if event_activation.ndim != 3: + raise ValueError(f"extract_events expects (batch, candidates, T) activations, got shape {tuple(event_activation.shape)}.") + candidates = torch.as_tensor(candidate_locations).double().cpu() + if candidates.ndim != 2 or candidates.shape[0] != event_activation.shape[1]: + raise ValueError( + f"candidate_locations must be shaped ({event_activation.shape[1]}, dims), got shape {tuple(candidates.shape)}." + ) + distance = max(1, int(round(min_distance_s * self.feature_rate))) + activation = event_activation.detach().cpu().double() + events: List[List[Dict[str, object]]] = [] + for item in activation: + found = [] + for index, probability in peak_picks(item.max(dim=0).values.numpy(), threshold, distance): + t = int(index) + top = torch.argsort(item[:, t], descending=True)[: int(top_k)] + found.append( + { + "time": t / self.feature_rate, + "sample": FEATURE_STRIDE * t, + "probability": probability, + "location": geometric_median(candidates[top]).tolist(), + } + ) + events.append(found) + return events + + +class EQNetLoss(nn.Module): + """Equations (1)-(4): ``lambda_P L_P + lambda_S L_S + lambda_EQ L_EQ``, binary cross-entropies summed + over time (mean over stations / candidates and batch), all weights 1 in the paper. + + ``outputs`` are EQNet logits (``forward(..., logits=True)``); ``phase_targets`` match + ``outputs["phase"]`` ``(batch, stations, 2, L)`` and ``event_targets`` match ``outputs["event"]`` + ``(batch, candidates, T)``. The paper's targets are truncated Gaussians around the manual picks + (width 1 s) and the origin time at the true location (width 2 s), with negative sampling of other + candidate locations. + """ + + def __init__(self, weights: Tuple[float, float, float] = (1.0, 1.0, 1.0)): + super().__init__() + self.weights = tuple(float(w) for w in weights) + + def forward( + self, + outputs: Dict[str, torch.Tensor], + phase_targets: torch.Tensor, + event_targets: Optional[torch.Tensor] = None, + station_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + phase = outputs["phase"] + if phase.shape != phase_targets.shape: + raise ValueError(f"phase_targets must be shaped {tuple(phase.shape)}, got shape {tuple(phase_targets.shape)}.") + terms = F.binary_cross_entropy_with_logits(phase, phase_targets, reduction="none").sum(dim=-1) # (B, S, 2) + if station_mask is not None: + mask = station_mask.to(terms.dtype).unsqueeze(-1) + per_phase = (terms * mask).sum(dim=(0, 1)) / mask.sum(dim=(0, 1)).clamp_min(1.0) + else: + per_phase = terms.mean(dim=(0, 1)) + loss = self.weights[0] * per_phase[0] + self.weights[1] * per_phase[1] + if event_targets is not None: + event = outputs["event"] + if event.shape != event_targets.shape: + raise ValueError(f"event_targets must be shaped {tuple(event.shape)}, got shape {tuple(event_targets.shape)}.") + event_loss = F.binary_cross_entropy_with_logits(event, event_targets, reduction="none").sum(dim=-1).mean() + loss = loss + self.weights[2] * event_loss + return loss + + +_OLD_ARGUMENTS = {"hidden_dim", "num_heads", "num_layers", "dropout"} def eqnet_builder( - task: str, + task: str = "picking", in_channels: int = 3, - hidden_dim: int = 48, - num_heads: int = 4, - num_layers: int = 2, - dropout: float = 0.1, + sampling_rate: float = 100.0, + candidate_chunk: int = 256, **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("EQNet only supports regression-style phase picking outputs.") - return EQNet( - in_channels=in_channels, - hidden_dim=hidden_dim, - num_heads=num_heads, - num_layers=num_layers, - dropout=dropout, - ) - - -__all__ = ["EQNet", "eqnet_builder"] +) -> EQNet: + """EQNet for ``task="picking"`` or ``task="detection"`` (the same multi-task network).""" + kwargs.pop("name", None) + old = sorted(set(kwargs) & _OLD_ARGUMENTS) + if old: + raise TypeError( + f"EQNet no longer takes {old}: the former transformer stand-in was replaced by the paper's ResNet " + "network with picking heads, shift-and-stack and event detection." + ) + if kwargs: + raise TypeError(f"Unexpected EQNet arguments: {sorted(kwargs)}.") + if task.lower() not in {"picking", "detection"}: + raise ValueError(f"EQNet supports task='picking' or 'detection', got {task!r}.") + return EQNet(in_channels=in_channels, sampling_rate=sampling_rate, candidate_chunk=candidate_chunk) + + +__all__ = [ + "BasicBlock1d", + "EQNet", + "EQNetBackbone", + "EQNetLoss", + "EventDetectionHead", + "PhasePickingHead", + "eqnet_builder", + "eqnet_candidate_grid", + "eqnet_travel_times", + "geometric_median", + "shift_and_stack", +] diff --git a/pyhazards/models/eqtransformer.py b/pyhazards/models/eqtransformer.py index e33ef726..8049931a 100644 --- a/pyhazards/models/eqtransformer.py +++ b/pyhazards/models/eqtransformer.py @@ -1,68 +1,779 @@ +"""EQTransformer: simultaneous earthquake detection and P/S phase picking. + +Mousavi, Ellsworth, Zhu, Chuang & Beroza, "Earthquake transformer—an attentive deep-learning model +for simultaneous earthquake detection and phase picking", Nature Communications 11, 3952 (2020), +https://doi.org/10.1038/s41467-020-17591-w. + +Port of the official Keras code, smousavi05/EQTransformer at commit +``a589da6504b11df8341fe1dc859a025f49955409`` (MIT License, Copyright (c) 2020-2025 S. Mostafa +Mousavi): the network built by ``cred2`` and its custom layers ``SeqSelfAttention``, ``FeedForward`` +and ``LayerNormalization`` in ``EQTransformer/core/EqT_utils.py``, and the pick post-processing of the +official tester (``picker`` in the same file). The three custom layers are, as their docstrings say, +modified from CyberZHG's keras-self-attention (MIT License, Copyright (c) 2018 PoW), +keras-position-wise-feed-forward and keras-layer-normalization (MIT License, Copyright (c) 2018 Zhao HG). + +The architecture follows the graphs stored in the two released models, which differ from the +defaults of ``cred2`` at the pinned commit: + +- ``variant="original"``: ``ModelsAndSampleData/EqT_original_model.h5`` ("the one in the paper"): + two BiLSTM blocks, dropout rate 0.2 everywhere, 371,639 trainable parameters; +- ``variant="conservative"``: ``ModelsAndSampleData/EqT_model_conservative.h5`` (fewer false + positives, saved by Keras 2.2.4): three BiLSTM blocks, dropout rate 0.1, LSTMs with the Keras 2.2 + defaults ``recurrent_activation="hard_sigmoid"`` and ``implementation=1``, 376,423 trainable + parameters. + +Encoder: seven Conv1D ('same', ReLU) + MaxPooling1D(2, 'same') layers with 8, 16, 16, 32, 32, 64, 64 +filters and kernels 11, 9, 7, 7, 5, 5, 3 (6000 -> 47 samples); seven residual CNN blocks (BN, ReLU, +SpatialDropout1D, Conv1D, twice, plus the input; kernels 3, 3, 3, 3, 2, 3, 2); BiLSTM blocks +(Bidirectional LSTM(16), 1x1 Conv1D(16), BN); two transformer blocks (additive self-attention, add, +layer norm, feed-forward(128), add, layer norm). Decoders: the detection decoder reads the encoder +output; the P and S decoders first apply an LSTM(16) and a local self-attention of width 3. Each +decoder is seven UpSampling1D(2) + Conv1D ('same', ReLU) steps (64, 64, 32, 32, 16, 16, 8 filters, +kernels 3, 5, 5, 7, 7, 9, 11; Cropping1D(1, 1) before the fourth conv), followed by Conv1D(1, 11) +with a sigmoid. + +Changes made for PyHazards (outputs are unchanged): + +- PyTorch layout ``(batch, channels, samples)``: input ``(batch, 3, 6000)`` with components in the + order E, N, Z of STEAD (the training data), output ``(batch, 3, 6000)`` with the detection, P and S + probabilities stacked along dim 1 (the Keras model returns three ``(batch, 6000, 1)`` tensors). +- The Keras LSTM is reimplemented (one bias vector, gates i, f, c, o, sigmoid recurrent activation, + input and recurrent dropout masks fixed over time), so parameter counts equal the Keras ones. +- SpatialDropout1D is called with ``training=True`` in the released graphs, i.e. it is active at + inference as well (Monte Carlo dropout). Here it is active in train mode, and in eval mode only with + ``mc_dropout=True``; the default eval output is deterministic. +- BatchNorm keeps the running-statistics update of the Keras version that trained each model + (:class:`KerasBatchNorm1d`); normalisation itself is unchanged. +- :meth:`EQTransformer.extract_picks` / :meth:`EQTransformer.extract_detections` port ``picker``; + :func:`load_eqtransformer_keras_weights` reads the released ``.h5`` files with h5py. +""" + from __future__ import annotations +import math +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F + +from ._pretrained import cached_download +from ._seismic import KerasBatchNorm1d, TracePicks, WaveformPicker, check_waveforms, std_normalize + +KERAS_EPSILON = 1e-7 # keras.backend.epsilon() +LAYER_NORM_EPSILON = KERAS_EPSILON * KERAS_EPSILON # LayerNormalization default (9.999999999999998e-15) +TRUNCATED_NORMAL_STD = 0.87962566103423978 # std of a unit normal truncated at +-2 + +ENCODER_FILTERS = (8, 16, 16, 32, 32, 64, 64) +ENCODER_KERNELS = (11, 9, 7, 7, 5, 5, 3) +RES_CNN_KERNELS = (3, 3, 3, 3, 2, 3, 2) # cred2: 5 blocks of kernel 3, blocks 4 and 5 followed by kernel 2 +DECODER_FILTERS = tuple(reversed(ENCODER_FILTERS)) +DECODER_KERNELS = tuple(reversed(ENCODER_KERNELS)) +DECODER_CROP_STEP = 3 +LSTM_UNITS = 16 +ATTENTION_UNITS = 32 +FEED_FORWARD_UNITS = 128 +IN_SAMPLES = 6000 + +EQTRANSFORMER_VARIANTS: Dict[str, Dict[str, Any]] = { + # EqT_original_model.h5 (Keras 2.3.0): the paper model. + "original": { + "lstm_blocks": 2, + "drop_rate": 0.2, + "recurrent_activation": "sigmoid", + "lstm_implementation": 2, + "bn_zero_debias": False, # Keras 2.3.0 moving averages + "loss_weights": (0.05, 0.40, 0.55), + }, + # EqT_model_conservative.h5 (Keras 2.2.4). + "conservative": { + "lstm_blocks": 3, + "drop_rate": 0.1, + "recurrent_activation": "hard_sigmoid", + "lstm_implementation": 1, + "bn_zero_debias": True, # Keras 2.2.4 moving averages + "loss_weights": (0.02, 0.40, 0.58), + }, +} + +_WEIGHTS_COMMIT = "a589da6504b11df8341fe1dc859a025f49955409" +EQTRANSFORMER_WEIGHTS: Dict[str, Dict[str, Any]] = { + "original": { + "filename": "EqT_original_model.h5", + "urls": ( + f"https://raw.githubusercontent.com/smousavi05/EQTransformer/{_WEIGHTS_COMMIT}/ModelsAndSampleData/EqT_original_model.h5", + ), + "sha256": "07b3ffc8065164ece44a367b145b0db66e25586d89269ec4d8c340c34966d452", + "license": "MIT", + }, + "conservative": { + "filename": "EqT_model_conservative.h5", + "urls": ( + f"https://raw.githubusercontent.com/smousavi05/EQTransformer/{_WEIGHTS_COMMIT}/ModelsAndSampleData/EqT_model_conservative.h5", + ), + "sha256": "0a9179fd40f9cda4fbc5372dd5f660bc35e69620d91dd7bdffe7f65baf7bd99b", + "license": "MIT", + }, +} + + +def _glorot_normal_(tensor: torch.Tensor, fan_in: int, fan_out: int) -> torch.Tensor: + """Keras ``glorot_normal``: truncated normal (+-2 std) with std ``sqrt(2 / (fan_in + fan_out))``.""" + std = math.sqrt(1.0 / ((fan_in + fan_out) / 2.0)) / TRUNCATED_NORMAL_STD + with torch.no_grad(): + return nn.init.trunc_normal_(tensor, mean=0.0, std=std, a=-2.0 * std, b=2.0 * std) -class EQTransformer(nn.Module): - """Compact sequence model for joint earthquake phase picking.""" +class KerasConv1d(nn.Conv1d): + """Conv1D with stride 1 and Keras 'same' padding (an even kernel pads one sample more on the right). + + Initialised like Keras: ``glorot_uniform`` kernel, zero bias. + """ + + def __init__(self, in_channels: int, out_channels: int, kernel_size: int): + super().__init__(in_channels, out_channels, kernel_size, padding=0) + self._pad = ((kernel_size - 1) // 2, kernel_size - 1 - (kernel_size - 1) // 2) + + def reset_parameters(self) -> None: + nn.init.xavier_uniform_(self.weight) + nn.init.zeros_(self.bias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return super().forward(F.pad(x, self._pad)) + + +def _spatial_dropout(x: torch.Tensor, rate: float, active: bool) -> torch.Tensor: + """Keras SpatialDropout1D on ``(batch, channels, samples)``: whole channels are dropped.""" + if not active or rate <= 0.0: + return x + return F.dropout1d(x, p=rate, training=True) + + +def _max_pool_same(x: torch.Tensor) -> torch.Tensor: + # MaxPooling1D(2, padding='same'): ceil(L / 2) outputs, the last window may be partial. + return F.max_pool1d(x, kernel_size=2, stride=2, ceil_mode=True) + + +def _hard_sigmoid(x: torch.Tensor) -> torch.Tensor: + """Keras 2.x ``hard_sigmoid``: ``clip(0.2 * x + 0.5, 0, 1)``.""" + return torch.clamp(0.2 * x + 0.5, 0.0, 1.0) + + +class KerasLSTM(nn.Module): + """Keras ``LSTM(units, return_sequences=True)`` on ``(batch, time, features)``. + + One bias vector, gate order (i, f, c, o), tanh activation and ``recurrent_activation`` "sigmoid" + (Keras >= 2.3 default, paper model) or "hard_sigmoid" (Keras 2.2 default, conservative model). In + train mode, ``dropout`` and ``recurrent_dropout`` multiply the inputs and the previous hidden state + by masks drawn once per sequence: one mask shared by the four gates with ``implementation=2``, one + per gate with ``implementation=1`` (the stored setting of each released model). Weights keep the + Keras names and layouts: ``kernel`` ``(features, 4 * units)``, ``recurrent_kernel`` + ``(units, 4 * units)``, ``bias`` ``(4 * units,)``. + """ def __init__( self, - in_channels: int = 3, - hidden_dim: int = 48, - num_layers: int = 2, - dropout: float = 0.1, + input_size: int, + units: int, + dropout: float = 0.0, + recurrent_dropout: float = 0.0, + recurrent_activation: str = "sigmoid", + implementation: int = 2, ): super().__init__() - self.encoder = nn.Sequential( - nn.Conv1d(in_channels, hidden_dim, kernel_size=11, padding=5), - nn.ReLU(), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=7, padding=3), - nn.ReLU(), + if recurrent_activation not in ("sigmoid", "hard_sigmoid"): + raise ValueError(f"Unsupported recurrent_activation {recurrent_activation!r}.") + if implementation not in (1, 2): + raise ValueError(f"Keras LSTM implementation must be 1 or 2, got {implementation}.") + self.units = units + self.dropout = dropout + self.recurrent_dropout = recurrent_dropout + self.recurrent_activation = recurrent_activation + self.implementation = implementation + self.kernel = nn.Parameter(torch.empty(input_size, 4 * units)) + self.recurrent_kernel = nn.Parameter(torch.empty(units, 4 * units)) + self.bias = nn.Parameter(torch.empty(4 * units)) + self.reset_parameters() + + def reset_parameters(self) -> None: + # Keras: glorot_uniform kernel, orthogonal recurrent kernel, zero bias with unit_forget_bias. + nn.init.xavier_uniform_(self.kernel) + nn.init.orthogonal_(self.recurrent_kernel) + with torch.no_grad(): + self.bias.zero_() + self.bias[self.units : 2 * self.units] = 1.0 + + @staticmethod + def _mask(shape: Tuple[int, ...], rate: float, reference: torch.Tensor) -> torch.Tensor: + keep = 1.0 - rate + return torch.bernoulli(torch.full(shape, keep, dtype=reference.dtype, device=reference.device)) / keep + + def forward(self, x: torch.Tensor, reverse: bool = False) -> torch.Tensor: + batch, steps, features = x.shape + units = self.units + gates = 4 if self.implementation == 1 else 1 + activation = torch.sigmoid if self.recurrent_activation == "sigmoid" else _hard_sigmoid + input_mask = recurrent_mask = None + if self.training and 0.0 < self.dropout < 1.0: + input_mask = self._mask((gates, batch, 1, features), self.dropout, x) + if self.training and 0.0 < self.recurrent_dropout < 1.0: + recurrent_mask = self._mask((gates, batch, units), self.recurrent_dropout, x) + if input_mask is None: + projected = torch.matmul(x, self.kernel) + self.bias # (batch, time, 4 * units) + else: + kernels = self.kernel.view(features, 4, units) + parts = [ + torch.matmul(x * input_mask[g if gates == 4 else 0], kernels[:, g]) for g in range(4) + ] + projected = torch.cat(parts, dim=-1) + self.bias + recurrent = self.recurrent_kernel.view(units, 4, units) + h = x.new_zeros(batch, units) + c = x.new_zeros(batch, units) + outputs: List[torch.Tensor] = [x.new_empty(0)] * steps + order = range(steps - 1, -1, -1) if reverse else range(steps) + for t in order: + if recurrent_mask is None: + z = projected[:, t] + torch.matmul(h, self.recurrent_kernel) + else: + z = projected[:, t] + torch.cat( + [torch.matmul(h * recurrent_mask[g if gates == 4 else 0], recurrent[:, g]) for g in range(4)], + dim=-1, + ) + i = activation(z[:, :units]) + f = activation(z[:, units : 2 * units]) + c = f * c + i * torch.tanh(z[:, 2 * units : 3 * units]) + h = activation(z[:, 3 * units :]) * torch.tanh(c) + outputs[t] = h + return torch.stack(outputs, dim=1) + + +class SeqSelfAttention(nn.Module): + """Additive self-attention of ``EqT_utils.SeqSelfAttention`` on ``(batch, time, features)``. + + ``e[t, t'] = Wa^T tanh(Wt^T x_t + Wx^T x_t' + bh) + ba``; the weights are ``exp(e - max_t' e)``, + multiplied by a local window mask when ``attention_width`` is set (``t - w // 2 <= t' < + t - w // 2 + w``) and divided by their sum plus ``1e-7``. As in the reference, the maximum is taken + over the whole row before the window mask is applied. Returns ``sum_t' a[t, t'] x_t'``. + """ + + def __init__(self, features: int, units: int = ATTENTION_UNITS, attention_width: Optional[int] = None): + super().__init__() + self.attention_width = attention_width + self.Wt = nn.Parameter(torch.empty(features, units)) + self.Wx = nn.Parameter(torch.empty(features, units)) + self.bh = nn.Parameter(torch.zeros(units)) + self.Wa = nn.Parameter(torch.empty(units, 1)) + self.ba = nn.Parameter(torch.zeros(1)) + self.reset_parameters() + + def reset_parameters(self) -> None: + features, units = self.Wt.shape + _glorot_normal_(self.Wt, features, units) + _glorot_normal_(self.Wx, features, units) + _glorot_normal_(self.Wa, units, 1) + nn.init.zeros_(self.bh) + nn.init.zeros_(self.ba) + + def forward(self, x: torch.Tensor, return_attention: bool = False): + steps = x.shape[1] + q = torch.matmul(x, self.Wt).unsqueeze(2) + k = torch.matmul(x, self.Wx).unsqueeze(1) + h = torch.tanh(q + k + self.bh) + e = (torch.matmul(h, self.Wa) + self.ba).squeeze(-1) # (batch, time, time) + e = torch.exp(e - e.max(dim=-1, keepdim=True).values) + if self.attention_width is not None: + index = torch.arange(steps, device=x.device) + lower = (index - self.attention_width // 2).unsqueeze(-1) + upper = lower + self.attention_width + window = (lower <= index.unsqueeze(0)) & (index.unsqueeze(0) < upper) + e = e * window.to(e.dtype) + a = e / (e.sum(dim=-1, keepdim=True) + KERAS_EPSILON) + v = torch.matmul(a, x) + return (v, a) if return_attention else v + + +class FeedForward(nn.Module): + """Position-wise feed-forward layer of ``EqT_utils.FeedForward`` (ReLU, dropout in train mode).""" + + def __init__(self, features: int, units: int = FEED_FORWARD_UNITS, dropout_rate: float = 0.0): + super().__init__() + self.dropout_rate = dropout_rate + self.W1 = nn.Parameter(torch.empty(features, units)) + self.b1 = nn.Parameter(torch.zeros(units)) + self.W2 = nn.Parameter(torch.empty(units, features)) + self.b2 = nn.Parameter(torch.zeros(features)) + self.reset_parameters() + + def reset_parameters(self) -> None: + features, units = self.W1.shape + _glorot_normal_(self.W1, features, units) + _glorot_normal_(self.W2, units, features) + nn.init.zeros_(self.b1) + nn.init.zeros_(self.b2) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = F.relu(torch.matmul(x, self.W1) + self.b1) + if self.training and 0.0 < self.dropout_rate < 1.0: + h = F.dropout(h, p=self.dropout_rate, training=True) + return torch.matmul(h, self.W2) + self.b2 + + +class LayerNormalization(nn.Module): + """``EqT_utils.LayerNormalization``: ``(x - mean) / sqrt(var + 1e-14) * gamma + beta`` over features.""" + + def __init__(self, features: int, epsilon: float = LAYER_NORM_EPSILON): + super().__init__() + self.epsilon = epsilon + self.gamma = nn.Parameter(torch.ones(features)) + self.beta = nn.Parameter(torch.zeros(features)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + mean = x.mean(dim=-1, keepdim=True) + variance = (x - mean).pow(2).mean(dim=-1, keepdim=True) + return (x - mean) / torch.sqrt(variance + self.epsilon) * self.gamma + self.beta + + +class ResCNNBlock(nn.Module): + """``_block_CNN_1``: ``x + conv2(drop(relu(bn2(conv1(drop(relu(bn1(x))))))))``.""" + + def __init__(self, channels: int, kernel_size: int, zero_debias: bool = False): + super().__init__() + self.bn1 = KerasBatchNorm1d(channels, zero_debias) + self.conv1 = KerasConv1d(channels, channels, kernel_size) + self.bn2 = KerasBatchNorm1d(channels, zero_debias) + self.conv2 = KerasConv1d(channels, channels, kernel_size) + + def forward(self, x: torch.Tensor, drop_rate: float, dropout_active: bool) -> torch.Tensor: + h = self.conv1(_spatial_dropout(F.relu(self.bn1(x)), drop_rate, dropout_active)) + h = self.conv2(_spatial_dropout(F.relu(self.bn2(h)), drop_rate, dropout_active)) + return x + h + + +class BiLSTMBlock(nn.Module): + """``_block_BiLSTM``: Bidirectional(LSTM(16)) (outputs concatenated), 1x1 Conv1D(16), BN.""" + + def __init__(self, input_size: int, units: int, drop_rate: float, zero_debias: bool = False, **lstm_options: Any): + super().__init__() + self.forward_lstm = KerasLSTM(input_size, units, drop_rate, drop_rate, **lstm_options) + self.backward_lstm = KerasLSTM(input_size, units, drop_rate, drop_rate, **lstm_options) + self.conv = KerasConv1d(2 * units, units, 1) + self.bn = KerasBatchNorm1d(units, zero_debias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # (batch, time, features) -> (batch, time, units) + h = torch.cat([self.forward_lstm(x), self.backward_lstm(x, reverse=True)], dim=-1) + return self.bn(self.conv(h.transpose(1, 2))).transpose(1, 2) + + +class TransformerBlock(nn.Module): + """``_transformer``: self-attention, add, layer norm, feed-forward, add, layer norm.""" + + def __init__(self, features: int, drop_rate: float): + super().__init__() + self.attention = SeqSelfAttention(features) + self.norm1 = LayerNormalization(features) + self.feed_forward = FeedForward(features, FEED_FORWARD_UNITS, drop_rate) + self.norm2 = LayerNormalization(features) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm1(x + self.attention(x)) + return self.norm2(h + self.feed_forward(h)) + + +class Decoder(nn.Module): + """``_decoder``: seven UpSampling1D(2) + Conv1D('same', ReLU) steps, Cropping1D(1, 1) before step 4.""" + + def __init__(self, in_channels: int): + super().__init__() + channels = [in_channels, *DECODER_FILTERS] + self.convs = nn.ModuleList( + KerasConv1d(channels[i], channels[i + 1], DECODER_KERNELS[i]) for i in range(len(DECODER_FILTERS)) ) - self.temporal = nn.LSTM( - input_size=hidden_dim, - hidden_size=hidden_dim, - num_layers=num_layers, - batch_first=True, - bidirectional=True, - dropout=dropout if num_layers > 1 else 0.0, + + def forward(self, x: torch.Tensor) -> torch.Tensor: + for step, conv in enumerate(self.convs): + x = torch.repeat_interleave(x, 2, dim=-1) + if step == DECODER_CROP_STEP: + x = x[..., 1:-1] + x = F.relu(conv(x)) + return x + + +def _output_length(samples: int) -> int: + length = samples + for _ in ENCODER_FILTERS: + length = math.ceil(length / 2) + for step in range(len(DECODER_FILTERS)): + length *= 2 + if step == DECODER_CROP_STEP: + length -= 2 + return length + + +class EQTransformer(nn.Module, WaveformPicker): + """EQTransformer (Mousavi et al., 2020), the released Keras models in PyTorch. + + ``forward`` maps normalised waveforms ``(batch, 3, 6000)`` (60 s at 100 Hz, components E, N, Z) + to ``(batch, 3, 6000)`` probabilities: detection, P and S (``logits=True`` returns the values + before the sigmoid). :meth:`annotate` applies the official per-trace normalisation first. + """ + + sampling_rate = 100.0 + component_order = "ENZ" + output_names = ("detection", "P", "S") + phase_channels = {"P": 1, "S": 2} + detection_channel = 0 + + def __init__( + self, + variant: str = "original", + in_channels: int = 3, + drop_rate: Optional[float] = None, + mc_dropout: bool = False, + ): + super().__init__() + if variant not in EQTRANSFORMER_VARIANTS: + raise ValueError(f"Unknown EQTransformer variant {variant!r}; expected one of {sorted(EQTRANSFORMER_VARIANTS)}.") + spec = EQTRANSFORMER_VARIANTS[variant] + self.variant = variant + self.in_channels = int(in_channels) + self.lstm_blocks = int(spec["lstm_blocks"]) + self.drop_rate = float(spec["drop_rate"] if drop_rate is None else drop_rate) + self.mc_dropout = bool(mc_dropout) + lstm_options = { + "recurrent_activation": spec["recurrent_activation"], + "implementation": spec["lstm_implementation"], + } + + channels = [self.in_channels, *ENCODER_FILTERS] + self.encoder = nn.ModuleList( + KerasConv1d(channels[i], channels[i + 1], ENCODER_KERNELS[i]) for i in range(len(ENCODER_FILTERS)) ) - self.attention = nn.Linear(2 * hidden_dim, 1) - self.head = nn.Sequential( - nn.Linear(2 * hidden_dim, hidden_dim), - nn.ReLU(), - nn.Linear(hidden_dim, 2), + width = ENCODER_FILTERS[-1] + zero_debias = bool(spec["bn_zero_debias"]) + self.res_cnn = nn.ModuleList(ResCNNBlock(width, kernel, zero_debias) for kernel in RES_CNN_KERNELS) + self.bilstm = nn.ModuleList( + BiLSTMBlock(width if i == 0 else LSTM_UNITS, LSTM_UNITS, self.drop_rate, zero_debias, **lstm_options) + for i in range(self.lstm_blocks) ) + self.transformer_d0 = TransformerBlock(LSTM_UNITS, self.drop_rate) + self.transformer_d = TransformerBlock(LSTM_UNITS, self.drop_rate) + self.decoder_d = Decoder(LSTM_UNITS) + self.detector = KerasConv1d(DECODER_FILTERS[-1], 1, 11) + self.lstm_p = KerasLSTM(LSTM_UNITS, LSTM_UNITS, self.drop_rate, self.drop_rate, **lstm_options) + self.attention_p = SeqSelfAttention(LSTM_UNITS, ATTENTION_UNITS, attention_width=3) + self.decoder_p = Decoder(LSTM_UNITS) + self.picker_p = KerasConv1d(DECODER_FILTERS[-1], 1, 11) + self.lstm_s = KerasLSTM(LSTM_UNITS, LSTM_UNITS, self.drop_rate, self.drop_rate, **lstm_options) + self.attention_s = SeqSelfAttention(LSTM_UNITS, ATTENTION_UNITS, attention_width=3) + self.decoder_s = Decoder(LSTM_UNITS) + self.picker_s = KerasConv1d(DECODER_FILTERS[-1], 1, 11) - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("EQTransformer expects inputs shaped (batch, channels, length).") - encoded = self.encoder(x).transpose(1, 2) - temporal, _ = self.temporal(encoded) - weights = torch.softmax(self.attention(temporal), dim=1) - pooled = torch.sum(weights * temporal, dim=1) - return self.head(pooled) + def encode(self, x: torch.Tensor) -> torch.Tensor: + """Encoder output ``(batch, 47, 16)`` (time-major, as the Keras ``layer_normalization_4``).""" + h = x + for conv in self.encoder: + h = _max_pool_same(F.relu(conv(h))) + dropout_active = self.training or self.mc_dropout + for block in self.res_cnn: + h = block(h, self.drop_rate, dropout_active) + s = h.transpose(1, 2) + for block in self.bilstm: + s = block(s) + return self.transformer_d(self.transformer_d0(s)) + + def forward(self, x: torch.Tensor, logits: bool = False) -> torch.Tensor: + check_waveforms(x, self.in_channels, "EQTransformer") + if _output_length(x.shape[-1]) != x.shape[-1]: + raise ValueError( + f"EQTransformer expects waveforms shaped (batch, {self.in_channels}, {IN_SAMPLES}) " + f"(60 s at 100 Hz); got shape {tuple(x.shape)}." + ) + encoded = self.encode(x) + detection = self.detector(self.decoder_d(encoded.transpose(1, 2))) + p = self.picker_p(self.decoder_p(self.attention_p(self.lstm_p(encoded)).transpose(1, 2))) + s = self.picker_s(self.decoder_s(self.attention_s(self.lstm_s(encoded)).transpose(1, 2))) + out = torch.cat([detection, p, s], dim=1) + return out if logits else torch.sigmoid(out) + + def annotate(self, waveforms: torch.Tensor, mc_samples: int = 1) -> torch.Tensor: + """Official preprocessing (``normalize(data, 'std')``) and forward; mean of ``mc_samples`` passes. + + With ``mc_samples > 1`` the passes are drawn with the SpatialDropout1D of the residual blocks + active, as the official tester does with ``estimate_uncertainty=True``. + """ + x = std_normalize(waveforms) + if mc_samples <= 1: + return self(x) + previous = self.mc_dropout + self.mc_dropout = True + try: + return torch.stack([self(x) for _ in range(int(mc_samples))]).mean(dim=0) + finally: + self.mc_dropout = previous + + def extract_detections( + self, + annotations: torch.Tensor, + detection_threshold: float = 0.2, + p_threshold: float = 0.1, + s_threshold: float = 0.1, + ) -> List[List[Tuple[int, int, float]]]: + """Events reported by the official tester: ``(on, off, mean detection probability)`` per trace. + + These are the ``matches`` of ``EqT_utils.picker``: detection triggers of at least 10 samples + that have a P or an S pick (the tester's ``number_of_detections``). + """ + return [ + [(on, event["off"], event["detection_probability"]) for on, event in events] + for events in self._match(annotations, detection_threshold, p_threshold, s_threshold) + ] + + def extract_picks( + self, + annotations: torch.Tensor, + detection_threshold: float = 0.2, + p_threshold: float = 0.1, + s_threshold: float = 0.1, + all_events: bool = False, + ) -> List[TracePicks]: + """P and S picks per trace with the official tester's ``picker`` (``EqT_utils.py``). + + Defaults are the thresholds of the official ``tester()`` (detection 0.2, P 0.1, S 0.1). Like the + tester's output table, only the first detected event of each trace is reported unless + ``all_events=True``. Probabilities are rounded to three decimals, as in the reference. + """ + picks: List[TracePicks] = [] + for events in self._match(annotations, detection_threshold, p_threshold, s_threshold): + trace: TracePicks = {"P": [], "S": []} + for _, event in events if all_events else events[:1]: + for phase in ("P", "S"): + if event[phase] is not None: + trace[phase].append(event[phase]) + picks.append(trace) + return picks + + @staticmethod + def _match(annotations: torch.Tensor, detection_threshold: float, p_threshold: float, s_threshold: float): + """``EqT_utils.picker`` without uncertainties: per trace, a list of ``(on, event)``.""" + from ..metrics.picking import detect_peaks, trigger_onset + + if annotations.ndim != 3 or annotations.shape[1] != 3: + raise ValueError( + f"Expected EQTransformer annotations shaped (batch, 3, samples), got {tuple(annotations.shape)}." + ) + values = annotations.detach().cpu().numpy() # keep the dtype: the reference rounds float32 values + results = [] + for yh1, yh2, yh3 in values: + detection = trigger_onset(yh1, detection_threshold, detection_threshold) + # Probabilities are rounded to three decimals in the array's dtype, as the reference does + # before choosing the most probable P. + p_picks = {int(i): np.round(yh2[int(i)], 3) for i in detect_peaks(yh2, mph=p_threshold, mpd=1) if i} + s_picks = {int(i): np.round(yh3[int(i)], 3) for i in detect_peaks(yh3, mph=s_threshold, mpd=1) if i} + events = [] + for on, off in detection: + on, off = int(on), int(off) + if off - on < 10: + continue + with np.errstate(invalid="ignore"): + probability = round(float(np.round(np.mean(yh1[on:off]), 3)), 3) + s_candidates = [s for s in s_picks if on < s < off] + s_pick = s_candidates[0] if s_candidates else None # the earliest S inside the window + if s_pick: + p_candidates = [p for p in p_picks if on - 100 < p < s_pick - 10] + else: + p_candidates = [p for p in p_picks if on - 100 < p < off] + p_pick, best = None, 0 + for p in p_candidates: # the most probable P (the first one on ties) + if p_picks[p] > best: + p_pick, best = p, p_picks[p] + if s_pick or p_pick: + events.append( + ( + on, + { + "off": off, + "detection_probability": probability, + "P": None if p_pick is None else (float(p_pick), round(float(p_picks[p_pick]), 3)), + "S": None if s_pick is None else (float(s_pick), round(float(s_picks[s_pick]), 3)), + }, + ) + ) + results.append(events) + return results + + +def keras_weight_map(lstm_blocks: int) -> Dict[str, Tuple[str, str]]: + """``{pytorch state-dict key: (Keras layer name, Keras weight name)}`` for a released model. + + Keras numbers unnamed layers per class in creation order (``cred2``): encoder convs 1-7, residual + convs 8-21 and batch norms 1-14, the BiLSTM blocks' 1x1 convs and batch norms, then the detection, + P and S decoders' convs; the two decoder LSTMs come after the bidirectional ones. + """ + mapping: Dict[str, Tuple[str, str]] = {} + + def conv(prefix: str, layer: str) -> None: + mapping[f"{prefix}.weight"] = (layer, "kernel") + mapping[f"{prefix}.bias"] = (layer, "bias") + + def bn(prefix: str, layer: str) -> None: + for torch_name, keras_name in (("weight", "gamma"), ("bias", "beta"), ("running_mean", "moving_mean"), ("running_var", "moving_variance")): + mapping[f"{prefix}.{torch_name}"] = (layer, keras_name) + + def lstm(prefix: str, layer: str, inner: str) -> None: + for name in ("kernel", "recurrent_kernel", "bias"): + mapping[f"{prefix}.{name}"] = (layer, f"{inner}{name}") + + conv_id, bn_id = 0, 0 + for i in range(len(ENCODER_FILTERS)): + conv_id += 1 + conv(f"encoder.{i}", f"conv1d_{conv_id}") + for i in range(len(RES_CNN_KERNELS)): + bn_id += 1 + bn(f"res_cnn.{i}.bn1", f"batch_normalization_{bn_id}") + conv_id += 1 + conv(f"res_cnn.{i}.conv1", f"conv1d_{conv_id}") + bn_id += 1 + bn(f"res_cnn.{i}.bn2", f"batch_normalization_{bn_id}") + conv_id += 1 + conv(f"res_cnn.{i}.conv2", f"conv1d_{conv_id}") + for i in range(lstm_blocks): + layer = f"bidirectional_{i + 1}" + lstm(f"bilstm.{i}.forward_lstm", layer, f"forward_lstm_{i + 1}/") + lstm(f"bilstm.{i}.backward_lstm", layer, f"backward_lstm_{i + 1}/") + conv_id += 1 + conv(f"bilstm.{i}.conv", f"conv1d_{conv_id}") + bn_id += 1 + bn(f"bilstm.{i}.bn", f"batch_normalization_{bn_id}") + for block, attention, norms, feed_forward in ( + ("transformer_d0", "attentionD0", (1, 2), 1), + ("transformer_d", "attentionD", (3, 4), 2), + ): + for name in ("Wt", "Wx", "bh", "Wa", "ba"): + mapping[f"{block}.attention.{name}"] = (attention, f"{attention}_Add_{name}") + for norm, index in zip(("norm1", "norm2"), norms): + mapping[f"{block}.{norm}.gamma"] = (f"layer_normalization_{index}", "gamma") + mapping[f"{block}.{norm}.beta"] = (f"layer_normalization_{index}", "beta") + for name in ("W1", "b1", "W2", "b2"): + mapping[f"{block}.feed_forward.{name}"] = (f"feed_forward_{feed_forward}", f"feed_forward_{feed_forward}_{name}") + for decoder in ("decoder_d", "decoder_p", "decoder_s"): + for i in range(len(DECODER_FILTERS)): + conv_id += 1 + conv(f"{decoder}.convs.{i}", f"conv1d_{conv_id}") + conv("detector", "detector") + conv("picker_p", "picker_P") + conv("picker_s", "picker_S") + for offset, branch in ((1, "p"), (2, "s")): + lstm(f"lstm_{branch}", f"lstm_{lstm_blocks + offset}", "") + for name in ("Wt", "Wx", "bh", "Wa", "ba"): + key = "attentionP" if branch == "p" else "attentionS" + mapping[f"attention_{branch}.{name}"] = (key, f"{key}_Add_{name}") + return mapping + + +def read_keras_h5_weights(path: Union[str, Path]) -> Dict[Tuple[str, str], np.ndarray]: + """All weights of a Keras HDF5 model file as ``{(layer, weight name without ':0'): array}``.""" + import h5py + + weights: Dict[Tuple[str, str], np.ndarray] = {} + with h5py.File(str(path), "r") as handle: + group = handle["model_weights"] if "model_weights" in handle else handle + for raw_layer in group.attrs["layer_names"]: + layer = raw_layer.decode() if isinstance(raw_layer, bytes) else str(raw_layer) + for raw_name in group[layer].attrs["weight_names"]: + name = raw_name.decode() if isinstance(raw_name, bytes) else str(raw_name) + short = name.split(":")[0] + short = short[len(layer) + 1 :] if short.startswith(layer + "/") else short + weights[(layer, short)] = np.asarray(group[layer][name]) + return weights + + +def keras_state_dict(model: EQTransformer, path: Union[str, Path]) -> Dict[str, torch.Tensor]: + """State dict of ``model`` filled from a released Keras ``.h5`` file (every Keras weight used once).""" + weights = read_keras_h5_weights(path) + mapping = keras_weight_map(model.lstm_blocks) + state = model.state_dict() + expected = {key for key in state if not key.endswith("num_batches_tracked")} + if set(mapping) != expected: + raise RuntimeError(f"Weight map does not cover the model: {sorted(expected ^ set(mapping))}") + used = set() + converted: Dict[str, torch.Tensor] = {} + for key, (layer, name) in mapping.items(): + if (layer, name) not in weights: + raise KeyError(f"{path}: Keras weight {layer}/{name} not found (variant {model.variant!r}?)") + value = torch.from_numpy(np.array(weights[(layer, name)], dtype=np.float32)) + if name == "kernel" and value.ndim == 3: + value = value.permute(2, 1, 0) # Conv1D (width, in, out) -> (out, in, width) + if tuple(value.shape) != tuple(state[key].shape): + raise ValueError(f"{layer}/{name}: shape {tuple(value.shape)} does not match {key} {tuple(state[key].shape)}") + converted[key] = value.contiguous() + used.add((layer, name)) + unused = set(weights) - used + if unused: + raise ValueError(f"{path}: Keras weights not used by the port: {sorted(unused)}") + for key, value in state.items(): + if key.endswith("num_batches_tracked"): + converted[key] = value + return converted + + +def eqtransformer_weights_path(name: str) -> Path: + """Local path of an official model (``"original"`` or ``"conservative"``), downloaded on first use.""" + if name not in EQTRANSFORMER_WEIGHTS: + raise ValueError(f"Unknown EQTransformer weights {name!r}; expected one of {sorted(EQTRANSFORMER_WEIGHTS)}.") + spec = EQTRANSFORMER_WEIGHTS[name] + return cached_download("eqtransformer", spec["filename"], spec["urls"], spec["sha256"]) + + +def load_eqtransformer_keras_weights(model: EQTransformer, source: Union[str, Path]) -> EQTransformer: + """Load a released Keras model (``"original"``, ``"conservative"`` or a path to an ``.h5``) strictly.""" + path = eqtransformer_weights_path(str(source)) if str(source) in EQTRANSFORMER_WEIGHTS else Path(source) + model.load_state_dict(keras_state_dict(model, path), strict=True) + return model def eqtransformer_builder( task: str, + variant: str = "original", in_channels: int = 3, - hidden_dim: int = 48, - num_layers: int = 2, - dropout: float = 0.1, - **kwargs, + pretrained: Optional[Union[bool, str, Path]] = None, + mc_dropout: bool = False, + **kwargs: Any, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("EQTransformer only supports regression-style phase picking outputs.") - return EQTransformer( - in_channels=in_channels, - hidden_dim=hidden_dim, - num_layers=num_layers, - dropout=dropout, - ) - - -__all__ = ["EQTransformer", "eqtransformer_builder"] + """EQTransformer for ``task="picking"``: ``(batch, 3, 6000)`` -> ``(batch, 3, 6000)`` probabilities. + + ``variant``: ``"original"`` (paper model, default) or ``"conservative"``. ``pretrained``: ``True`` + (the released weights of ``variant``), ``"original"`` / ``"conservative"`` (must equal ``variant``) + or a path to a Keras ``.h5`` file of the same variant. ``mc_dropout=True`` keeps the residual + blocks' SpatialDropout1D active in eval mode, as in the released Keras graphs. + """ + kwargs.pop("name", None) + if kwargs: + raise TypeError(f"eqtransformer_builder got unexpected arguments: {sorted(kwargs)}") + if task.lower() != "picking": + raise ValueError(f"eqtransformer supports task='picking', got {task!r}.") + if variant not in EQTRANSFORMER_VARIANTS: + raise ValueError(f"Unknown EQTransformer variant {variant!r}; expected one of {sorted(EQTRANSFORMER_VARIANTS)}.") + model = EQTransformer(variant=variant, in_channels=in_channels, mc_dropout=mc_dropout) + if pretrained is not None and pretrained is not False: + if int(in_channels) != 3: + raise ValueError("The released EQTransformer weights need in_channels=3.") + source = variant if pretrained is True else pretrained + if str(source) in EQTRANSFORMER_WEIGHTS and str(source) != variant: + raise ValueError(f"Weights {source!r} belong to variant {source!r}, but variant={variant!r}.") + load_eqtransformer_keras_weights(model, source) + return model + + +__all__ = [ + "EQTRANSFORMER_VARIANTS", + "EQTRANSFORMER_WEIGHTS", + "EQTransformer", + "KerasBatchNorm1d", + "eqtransformer_builder", + "eqtransformer_weights_path", + "keras_state_dict", + "keras_weight_map", + "load_eqtransformer_keras_weights", +] diff --git a/pyhazards/models/firecastnet.py b/pyhazards/models/firecastnet.py index 0812f9dd..168a4858 100644 --- a/pyhazards/models/firecastnet.py +++ b/pyhazards/models/firecastnet.py @@ -1,72 +1,712 @@ +"""FireCastNet: seasonal wildfire forecasting with GraphCast on an icosahedral multi-mesh. + +Port of Michail et al., "FireCastNet: Earth-as-a-Graph for Seasonal Fire Prediction", Scientific +Reports 16:1006 (2025), doi:10.1038/s41598-025-30645-7, arXiv:2502.01550. Official code: +https://github.com/SeasFire/firecastnet (PyTorch + Lightning + DGL), checked at commit +``dc0d131be7f0638e3a84c16817e7bc9be454e53e``. + +The model has three stages (paper Sec. 4): a cube embedding (``Conv3d`` with kernel and stride +``T x 4 x 4`` plus LayerNorm) that turns ``T`` 8-day steps of a 0.25-degree grid into 64 features +on a 1-degree grid; a GraphCast encoder-processor-decoder between that grid and an icosahedral +multi-mesh (12 message-passing layers, hidden size 64); and a sub-pixel up-sampling +(``PixelShuffle(4)``) of 16 features per 1-degree cell back to the 0.25-degree grid. + +Provenance and licenses +----------------------- +- ``MeshGraphMLP``, ``MeshGraphEdgeMLPConcat``, ``GraphCastEncoderEmbedder``, + ``GraphCastDecoderEmbedder``, ``MeshGraphEncoder``, ``MeshGraphDecoder``, ``MeshProcessorBlock`` + and ``GraphCastMeshProcessor`` are ported from SeasFire/firecastnet + ``seasfire/backbones/graphcast/gnn_layers/*.py`` and ``graph_cast_mesh_processor.py``, whose + headers read ``SPDX-License-Identifier: Apache-2.0``, Copyright (c) 2023 - 2024 NVIDIA + CORPORATION & AFFILIATES (derived from NVIDIA Modulus). Licensed under the Apache License 2.0 + (http://www.apache.org/licenses/LICENSE-2.0). Changes: DGL message passing is replaced by + ``index_select`` / ``index_add_`` over edge-index buffers, and only the code paths without a + time dimension are kept. +- ``GraphCastNet`` follows NVIDIA Modulus v0.5.0 ``modulus/models/graphcast/graph_cast_net.py`` + (Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES, Apache-2.0), with the module order used by + FireCastNet. Graph construction lives in :mod:`pyhazards.models.firecastnet_graph`. +- The cube embedding, the up-sampling, the static latitude/longitude channels and the overall + wiring (``FireCastNet``) are written from the paper. The rest of the official repository has no + licence; it is used only as a test oracle (``tests/oracle/test_firecastnet_oracle.py``) and is not + copied here. + +Parameter names follow the official ``GraphCastCubeNet``, so official checkpoints load with +``strict=True`` after removing the LightningModule prefix (see :func:`load_official_checkpoint`). +""" + from __future__ import annotations +import re +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union + import torch import torch.nn as nn +from torch import Tensor + +from .firecastnet_graph import FireCastNetGraph, build_graph, deg2rad, icospheres, latlon_grid, load_icospheres + +OFFICIAL_INPUT_VARIABLES = ( + "mslp", + "tp", + "vpd", + "sst", + "t2m_mean", + "ssrd", + "swvl1", + "lst_day", + "ndvi", + "pop_dens", + "lsm", +) + +_Edges = Tuple[Tensor, Tensor, int] # (src index, dst index, number of destination nodes) + + +def _concat_efeat(efeat: Tensor, nfeat: Union[Tensor, Tuple[Tensor, Tensor]], edges: _Edges) -> Tensor: + """Concatenate edge, source-node and destination-node features per edge (in that order).""" + src_feat, dst_feat = (nfeat, nfeat) if isinstance(nfeat, Tensor) else nfeat + src, dst, _ = edges + return torch.cat((efeat, src_feat.index_select(0, src), dst_feat.index_select(0, dst)), dim=1) + + +def _aggregate_and_concat(efeat: Tensor, dst_nfeat: Tensor, edges: _Edges, aggregation: str) -> Tensor: + """Sum (or mean) edge features into their destination nodes, then append the node features.""" + _, dst, num_dst = edges + agg = efeat.new_zeros((num_dst, efeat.size(1))).index_add_(0, dst, efeat) + if aggregation == "mean": + degree = torch.bincount(dst, minlength=num_dst).clamp(min=1).to(agg.dtype) + agg = agg / degree.unsqueeze(1) + elif aggregation != "sum": + raise RuntimeError("Not a valid aggregation!") + return torch.cat((agg, dst_nfeat), dim=-1) + + +class MeshGraphMLP(nn.Module): + """Linear layers with SiLU in between and an optional LayerNorm after the last one.""" + + def __init__( + self, + input_dim: int, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: Optional[int] = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + activation_fn = nn.SiLU() if activation_fn is None else activation_fn + if hidden_layers is not None: + layers = [nn.Linear(input_dim, hidden_dim), activation_fn] + self.hidden_layers = hidden_layers + for _ in range(hidden_layers - 1): + layers += [nn.Linear(hidden_dim, hidden_dim), activation_fn] + layers.append(nn.Linear(hidden_dim, output_dim)) + self.norm_type = norm_type + if norm_type is not None: + if norm_type != "LayerNorm": + raise ValueError(f"norm_type must be 'LayerNorm' or None, got {norm_type!r}") + layers.append(nn.LayerNorm(output_dim)) + self.model = nn.Sequential(*layers) + else: + self.model = nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + return self.model(x) + + +class MeshGraphEdgeMLPConcat(MeshGraphMLP): + """Edge MLP on the concatenation of edge, source-node and destination-node features.""" + + def __init__( + self, + efeat_dim: int = 512, + src_dim: int = 512, + dst_dim: int = 512, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 2, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__(efeat_dim + src_dim + dst_dim, output_dim, hidden_dim, hidden_layers, activation_fn, norm_type) + + def forward(self, efeat: Tensor, nfeat: Union[Tensor, Tuple[Tensor, Tensor]], edges: _Edges) -> Tensor: + return self.model(_concat_efeat(efeat, nfeat, edges)) + + +class GraphCastEncoderEmbedder(nn.Module): + """Embeds grid-node, mesh-node, mesh-edge and grid2mesh-edge input features.""" + + def __init__( + self, + input_dim_grid_nodes: int = 10, + input_dim_mesh_nodes: int = 3, + input_dim_edges: int = 4, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + mlp = dict(output_dim=output_dim, hidden_dim=hidden_dim, hidden_layers=hidden_layers, activation_fn=activation_fn, norm_type=norm_type) + self.grid_node_mlp = MeshGraphMLP(input_dim=input_dim_grid_nodes, **mlp) + self.mesh_node_mlp = MeshGraphMLP(input_dim=input_dim_mesh_nodes, **mlp) + self.mesh_edge_mlp = MeshGraphMLP(input_dim=input_dim_edges, **mlp) + self.grid2mesh_edge_mlp = MeshGraphMLP(input_dim=input_dim_edges, **mlp) + + def forward(self, grid_nfeat: Tensor, mesh_nfeat: Tensor, g2m_efeat: Tensor, mesh_efeat: Tensor): + return ( + self.grid_node_mlp(grid_nfeat), + self.mesh_node_mlp(mesh_nfeat), + self.grid2mesh_edge_mlp(g2m_efeat), + self.mesh_edge_mlp(mesh_efeat), + ) + + +class GraphCastDecoderEmbedder(nn.Module): + """Embeds mesh2grid edge features.""" + + def __init__( + self, + input_dim_edges: int = 4, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + self.mesh2grid_edge_mlp = MeshGraphMLP( + input_dim=input_dim_edges, + output_dim=output_dim, + hidden_dim=hidden_dim, + hidden_layers=hidden_layers, + activation_fn=activation_fn, + norm_type=norm_type, + ) + + def forward(self, m2g_efeat: Tensor) -> Tensor: + return self.mesh2grid_edge_mlp(m2g_efeat) + + +class MeshGraphEncoder(nn.Module): + """Grid -> mesh message passing: updates the mesh nodes, and the grid nodes by a residual MLP.""" + + def __init__( + self, + aggregation: str = "sum", + input_dim_src_nodes: int = 512, + input_dim_dst_nodes: int = 512, + input_dim_edges: int = 512, + output_dim_src_nodes: int = 512, + output_dim_dst_nodes: int = 512, + output_dim_edges: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + self.aggregation = aggregation + mlp = dict(hidden_dim=hidden_dim, hidden_layers=hidden_layers, activation_fn=activation_fn, norm_type=norm_type) + self.edge_mlp = MeshGraphEdgeMLPConcat( + efeat_dim=input_dim_edges, src_dim=input_dim_src_nodes, dst_dim=input_dim_dst_nodes, output_dim=output_dim_edges, **mlp + ) + self.src_node_mlp = MeshGraphMLP(input_dim=input_dim_src_nodes, output_dim=output_dim_src_nodes, **mlp) + self.dst_node_mlp = MeshGraphMLP(input_dim=input_dim_dst_nodes + output_dim_edges, output_dim=output_dim_dst_nodes, **mlp) + + def forward(self, g2m_efeat: Tensor, grid_nfeat: Tensor, mesh_nfeat: Tensor, edges: _Edges) -> Tuple[Tensor, Tensor]: + efeat = self.edge_mlp(g2m_efeat, (grid_nfeat, mesh_nfeat), edges) + cat_feat = _aggregate_and_concat(efeat, mesh_nfeat, edges, self.aggregation) + mesh_nfeat = mesh_nfeat + self.dst_node_mlp(cat_feat) + grid_nfeat = grid_nfeat + self.src_node_mlp(grid_nfeat) + return grid_nfeat, mesh_nfeat + + +class MeshGraphDecoder(nn.Module): + """Mesh -> grid message passing with a residual update of the grid nodes.""" + + def __init__( + self, + aggregation: str = "sum", + input_dim_src_nodes: int = 512, + input_dim_dst_nodes: int = 512, + input_dim_edges: int = 512, + output_dim_dst_nodes: int = 512, + output_dim_edges: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + self.aggregation = aggregation + mlp = dict(hidden_dim=hidden_dim, hidden_layers=hidden_layers, activation_fn=activation_fn, norm_type=norm_type) + self.edge_mlp = MeshGraphEdgeMLPConcat( + efeat_dim=input_dim_edges, src_dim=input_dim_src_nodes, dst_dim=input_dim_dst_nodes, output_dim=output_dim_edges, **mlp + ) + self.node_mlp = MeshGraphMLP(input_dim=input_dim_dst_nodes + output_dim_edges, output_dim=output_dim_dst_nodes, **mlp) + + def forward(self, m2g_efeat: Tensor, grid_nfeat: Tensor, mesh_nfeat: Tensor, edges: _Edges) -> Tensor: + efeat = self.edge_mlp(m2g_efeat, (mesh_nfeat, grid_nfeat), edges) + cat_feat = _aggregate_and_concat(efeat, grid_nfeat, edges, self.aggregation) + return self.node_mlp(cat_feat) + grid_nfeat + + +class MeshProcessorBlock(nn.Module): + """One multi-mesh message-passing layer: residual edge update, then residual node update.""" + + def __init__( + self, + aggregation: str = "sum", + input_dim_nodes: int = 512, + input_dim_edges: int = 512, + output_dim_nodes: int = 512, + output_dim_edges: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + self.aggregation = aggregation + self.input_dim_nodes = input_dim_nodes + self.output_dim_nodes = output_dim_nodes + self.input_dim_edges = input_dim_edges + self.output_dim_edges = output_dim_edges + mlp = dict(hidden_dim=hidden_dim, hidden_layers=hidden_layers, activation_fn=activation_fn, norm_type=norm_type) + self.edge_mlp = MeshGraphMLP(input_dim=2 * input_dim_nodes + input_dim_edges, output_dim=output_dim_edges, **mlp) + self.node_mlp = MeshGraphMLP(input_dim=input_dim_nodes + output_dim_edges, output_dim=output_dim_nodes, **mlp) + + def forward(self, efeat: Tensor, nfeat: Tensor, edges: _Edges) -> Tuple[Tensor, Tensor]: + efeat_new = self.edge_mlp(_concat_efeat(efeat, nfeat, edges)) + if self.input_dim_edges == self.output_dim_edges: + efeat_new = efeat_new + efeat + nfeat_new = self.node_mlp(_aggregate_and_concat(efeat_new, nfeat, edges, self.aggregation)) + if self.input_dim_nodes == self.output_dim_nodes: + nfeat_new = nfeat_new + nfeat + return efeat_new, nfeat_new + + +class GraphCastMeshProcessor(nn.Module): + """A stack of :class:`MeshProcessorBlock` layers on the multi-mesh.""" + + def __init__( + self, + aggregation: str = "sum", + processor_layers: int = 16, + input_dim_nodes: int = 512, + input_dim_edges: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + self.has_time_dim = False + self.hidden_dim = hidden_dim + self.processor_layers = nn.ModuleList( + MeshProcessorBlock( + aggregation, input_dim_nodes, input_dim_edges, input_dim_nodes, input_dim_edges, hidden_dim, hidden_layers, activation_fn, norm_type + ) + for _ in range(processor_layers) + ) + self.num_processor_layers = len(self.processor_layers) + + def forward(self, efeat: Tensor, nfeat: Tensor, edges: _Edges) -> Tuple[Tensor, Tensor]: + for layer in self.processor_layers: + efeat, nfeat = layer(efeat, nfeat, edges) + return efeat, nfeat + + +class GraphCastNet(nn.Module): + """GraphCast encoder-processor-decoder on fixed grid/mesh graphs. + + Takes grid-node features ``(num_grid_nodes, input_dim_grid_nodes)`` and returns + ``(num_grid_nodes, output_dim_grid_nodes)``. The graphs are kept as non-persistent buffers, so + they follow ``.to(device)`` but are not part of the ``state_dict``. + """ + + def __init__( + self, + graph: FireCastNetGraph, + input_dim_grid_nodes: int = 10, + input_dim_mesh_nodes: int = 3, + input_dim_edges: int = 4, + output_dim_grid_nodes: int = 1, + processor_layers: int = 4, + hidden_layers: int = 1, + hidden_dim: int = 512, + aggregation: str = "sum", + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__() + if aggregation not in {"sum", "mean"}: + raise ValueError(f"aggregation must be 'sum' or 'mean', got {aggregation!r}") + if processor_layers <= 2: + raise ValueError("Expected at least 3 processor layers") + self.input_dim_grid_nodes = input_dim_grid_nodes + self.num_grid_nodes = graph.num_grid_nodes + self.num_mesh_nodes = graph.num_mesh_nodes + for name in ("mesh_src", "mesh_dst", "g2m_src", "g2m_dst", "m2g_src", "m2g_dst"): + self.register_buffer(name, getattr(graph, name).long(), persistent=False) + for name in ("mesh_edata", "mesh_ndata", "g2m_edata", "m2g_edata"): + self.register_buffer(name, getattr(graph, name).float(), persistent=False) + + activation_fn = nn.SiLU() + common = dict(hidden_dim=hidden_dim, hidden_layers=hidden_layers, activation_fn=activation_fn, norm_type=norm_type) + self.encoder_embedder = GraphCastEncoderEmbedder( + input_dim_grid_nodes=input_dim_grid_nodes, + input_dim_mesh_nodes=input_dim_mesh_nodes, + input_dim_edges=input_dim_edges, + output_dim=hidden_dim, + **common, + ) + self.encoder = MeshGraphEncoder( + aggregation=aggregation, + input_dim_src_nodes=hidden_dim, + input_dim_dst_nodes=hidden_dim, + input_dim_edges=hidden_dim, + output_dim_src_nodes=hidden_dim, + output_dim_dst_nodes=hidden_dim, + output_dim_edges=hidden_dim, + **common, + ) + processor = dict(aggregation=aggregation, input_dim_nodes=hidden_dim, input_dim_edges=hidden_dim, **common) + self.processor_encoder = GraphCastMeshProcessor(processor_layers=1, **processor) + self.processor = GraphCastMeshProcessor(processor_layers=processor_layers - 2, **processor) + self.processor_decoder = GraphCastMeshProcessor(processor_layers=1, **processor) + self.decoder_embedder = GraphCastDecoderEmbedder(input_dim_edges=input_dim_edges, output_dim=hidden_dim, **common) + self.decoder = MeshGraphDecoder( + aggregation=aggregation, + input_dim_src_nodes=hidden_dim, + input_dim_dst_nodes=hidden_dim, + input_dim_edges=hidden_dim, + output_dim_dst_nodes=hidden_dim, + output_dim_edges=hidden_dim, + **common, + ) + self.finale = MeshGraphMLP( + input_dim=hidden_dim, + output_dim=output_dim_grid_nodes, + hidden_dim=hidden_dim, + hidden_layers=hidden_layers, + activation_fn=activation_fn, + norm_type=None, + ) + + def forward(self, grid_nfeat: Tensor) -> Tensor: + if grid_nfeat.ndim != 2 or grid_nfeat.shape != (self.num_grid_nodes, self.input_dim_grid_nodes): + raise ValueError( + "GraphCastNet expects grid node features of shape " + f"({self.num_grid_nodes}, {self.input_dim_grid_nodes}), got {tuple(grid_nfeat.shape)}." + ) + g2m = (self.g2m_src, self.g2m_dst, self.num_mesh_nodes) + mesh = (self.mesh_src, self.mesh_dst, self.num_mesh_nodes) + m2g = (self.m2g_src, self.m2g_dst, self.num_grid_nodes) + + grid_emb, mesh_emb, g2m_emb, mesh_edge_emb = self.encoder_embedder( + grid_nfeat, self.mesh_ndata.to(grid_nfeat), self.g2m_edata.to(grid_nfeat), self.mesh_edata.to(grid_nfeat) + ) + grid_encoded, mesh_encoded = self.encoder(g2m_emb, grid_emb, mesh_emb, g2m) + mesh_efeat, mesh_nfeat = self.processor_encoder(mesh_edge_emb, mesh_encoded, mesh) + mesh_efeat, mesh_nfeat = self.processor(mesh_efeat, mesh_nfeat, mesh) + _, mesh_nfeat = self.processor_decoder(mesh_efeat, mesh_nfeat, mesh) + m2g_emb = self.decoder_embedder(self.m2g_edata.to(grid_nfeat)) + grid_decoded = self.decoder(m2g_emb, grid_encoded, mesh_nfeat, m2g) + return self.finale(grid_decoded) + + +class CubeConv3d(nn.Module): + """Space-time cube embedding: non-overlapping ``Conv3d`` patches, then LayerNorm. + + As in the official configuration the LayerNorm normalises over the whole embedded cube + ``(C', T', H', W')`` of one sample, with an elementwise affine transform of that shape. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + origin_shape: Tuple[int, int, int], + kernel_size: Tuple[int, int, int], + use_layer_norm: bool = True, + ): + super().__init__() + self.conv_3d = nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, stride=kernel_size) + embedded = tuple(size // patch for size, patch in zip(origin_shape, kernel_size)) + self.layer_norm = nn.LayerNorm((out_channels, *embedded)) if use_layer_norm else None + + def forward(self, x: Tensor) -> Tensor: + out = self.conv_3d(x) + if self.layer_norm is not None: + out = self.layer_norm(out) + return out + + +def _official_levels(path: str) -> Optional[Tuple[int, ...]]: + match = re.fullmatch(r"icospheres_(\d+(?:_\d+)*)\.json(?:\.gz)?", Path(path).name) + return tuple(int(level) for level in match.group(1).split("_")) if match else None class FireCastNet(nn.Module): - """Compact encoder-decoder wildfire spread network.""" + """FireCastNet for one latitude/longitude window (global by default). + + Input ``(batch, timeseries_len, in_channels, n_lat, n_lon)``: ``timeseries_len`` 8-day steps of + ``in_channels`` standardised variables on the grid given by ``sp_res`` and the cell-centre + bounds (latitudes from north to south, longitudes from west to east). The official models use + the 10 SeasFire inputs plus the land-sea mask (:data:`OFFICIAL_INPUT_VARIABLES`) on the global + 0.25-degree grid (720 x 1440). ``cos(lat)``, ``sin(lon)`` and ``cos(lon)`` are appended + internally when ``lat_lon_static_data`` is true. + + Output: logits ``(batch, output_dim_grid_nodes // r**2, n_lat, n_lon)`` with ``r`` the patch + size, i.e. one burned-area logit (or regression value) per cell with the default 16 outputs. + + The mesh is either the icospheres of ``mesh_levels`` (default 0-6, as in the paper) or a mesh + file in the official layout given by ``icospheres_graph_path`` (for example a LAM mesh). + """ def __init__( self, - in_channels: int = 12, - hidden_dim: int = 32, - out_channels: int = 1, - dropout: float = 0.1, + in_channels: int = 11, + timeseries_len: int = 24, + mesh_levels: Sequence[int] = (0, 1, 2, 3, 4, 5, 6), + icospheres_graph_path: Optional[Union[str, Path]] = None, + sp_res: float = 0.25, + max_lat: float = 89.875, + min_lat: float = -89.875, + max_lon: float = 179.875, + min_lon: float = -179.875, + lat_lon_static_data: bool = True, + embed_cube_width: int = 4, + embed_cube_height: int = 4, + embed_cube_time: Optional[int] = None, + embed_cube_dim: int = 64, + embed_cube_layer_norm: bool = True, + embed_cube_sp_res: Optional[float] = None, + embed_cube_max_lat: Optional[float] = None, + embed_cube_min_lat: Optional[float] = None, + embed_cube_max_lon: Optional[float] = None, + embed_cube_min_lon: Optional[float] = None, + output_dim_grid_nodes: int = 16, + input_dim_mesh_nodes: int = 3, + input_dim_edges: int = 4, + processor_layers: int = 12, + hidden_layers: int = 1, + hidden_dim: int = 64, + aggregation: str = "sum", + norm_type: Optional[str] = "LayerNorm", ): super().__init__() - if in_channels <= 0: - raise ValueError(f"in_channels must be positive, got {in_channels}") - if hidden_dim <= 0: - raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") - if out_channels <= 0: - raise ValueError(f"out_channels must be positive, got {out_channels}") - if not 0.0 <= dropout < 1.0: - raise ValueError(f"dropout must be in [0, 1), got {dropout}") + for name, value in (("in_channels", in_channels), ("timeseries_len", timeseries_len), ("embed_cube_dim", embed_cube_dim)): + if int(value) <= 0: + raise ValueError(f"{name} must be positive, got {value}") + embed_cube_time = timeseries_len if embed_cube_time is None else int(embed_cube_time) + if embed_cube_time != timeseries_len: + raise ValueError( + "embed_cube_time must equal timeseries_len: the official recurrent processor used when the cube " + f"embedding keeps a time dimension is not ported (got {embed_cube_time} and {timeseries_len})." + ) + if embed_cube_width != embed_cube_height: + raise ValueError("embed_cube_width and embed_cube_height must be equal (sub-pixel up-sampling).") + patch = int(embed_cube_width) + if output_dim_grid_nodes % (patch * patch) != 0: + raise ValueError(f"output_dim_grid_nodes must be a multiple of {patch * patch}, got {output_dim_grid_nodes}") self.in_channels = int(in_channels) - self.encoder = nn.Sequential( - nn.Conv2d(in_channels, hidden_dim, kernel_size=3, padding=1), - nn.GELU(), - nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, padding=1), - nn.GELU(), + self.timeseries_len = int(timeseries_len) + self.out_channels = output_dim_grid_nodes // (patch * patch) + + # Input grid (0.25 degree by default) and the grid of the embedded cube, on which the graph lives. + self.latitudes, self.longitudes = latlon_grid(sp_res, max_lat, min_lat, max_lon, min_lon) + offset = sp_res * (patch - 1) / 2 + g_sp_res = sp_res * patch if embed_cube_sp_res is None else embed_cube_sp_res + g_max_lat = max_lat - offset if embed_cube_max_lat is None else embed_cube_max_lat + g_min_lat = min_lat + offset if embed_cube_min_lat is None else embed_cube_min_lat + g_max_lon = max_lon - offset if embed_cube_max_lon is None else embed_cube_max_lon + g_min_lon = min_lon + offset if embed_cube_min_lon is None else embed_cube_min_lon + self.graph_latitudes, self.graph_longitudes = latlon_grid(g_sp_res, g_max_lat, g_min_lat, g_max_lon, g_min_lon) + self.lat_dim, self.lon_dim = self.latitudes.numel(), self.longitudes.numel() + self.graph_lat_dim, self.graph_lon_dim = self.graph_latitudes.numel(), self.graph_longitudes.numel() + if (self.lat_dim // patch, self.lon_dim // patch) != (self.graph_lat_dim, self.graph_lon_dim): + raise ValueError( + f"the {self.lat_dim}x{self.lon_dim} input grid embeds to {self.lat_dim // patch}x{self.lon_dim // patch} " + f"cells, but the graph grid has shape {self.graph_lat_dim}x{self.graph_lon_dim}" + ) + + if icospheres_graph_path is not None: + meshes = load_icospheres(icospheres_graph_path) + else: + meshes = icospheres(mesh_levels) + graph = build_graph(self.graph_latitudes, self.graph_longitudes, meshes) + + self.lat_lon_static_data = bool(lat_lon_static_data) + static = None + if self.lat_lon_static_data: + cos_lat = torch.cos(deg2rad(self.latitudes)).view(-1, 1).expand(self.lat_dim, self.lon_dim) + sin_lon = torch.sin(deg2rad(self.longitudes)).view(1, -1).expand(self.lat_dim, self.lon_dim) + cos_lon = torch.cos(deg2rad(self.longitudes)).view(1, -1).expand(self.lat_dim, self.lon_dim) + static = torch.stack((cos_lat, sin_lon, cos_lon)) + self.register_buffer("static_data", static, persistent=False) + grid_channels = self.in_channels + (3 if self.lat_lon_static_data else 0) + + # Module creation order follows the reference (GraphCastNet, then the cube embedding) so that + # the same torch.manual_seed gives the same initial weights. + self._net = GraphCastNet( + graph, + input_dim_grid_nodes=embed_cube_dim, + input_dim_mesh_nodes=input_dim_mesh_nodes, + input_dim_edges=input_dim_edges, + output_dim_grid_nodes=output_dim_grid_nodes, + processor_layers=processor_layers, + hidden_layers=hidden_layers, + hidden_dim=hidden_dim, + aggregation=aggregation, + norm_type=norm_type, ) - self.decoder = nn.Sequential( - nn.Conv2d(hidden_dim, hidden_dim, kernel_size=3, padding=1), - nn.GELU(), - nn.Dropout2d(dropout) if dropout > 0 else nn.Identity(), - nn.Conv2d(hidden_dim, out_channels, kernel_size=1), + self._downsample = CubeConv3d( + grid_channels, + embed_cube_dim, + (self.timeseries_len, self.lat_dim, self.lon_dim), + (embed_cube_time, patch, patch), + use_layer_norm=embed_cube_layer_norm, ) + self._upsample = nn.PixelShuffle(patch) + + def forward(self, x: Tensor) -> Tensor: + expected = (self.timeseries_len, self.in_channels, self.lat_dim, self.lon_dim) + if x.ndim != 5 or tuple(x.shape[1:]) != expected: + raise ValueError( + "FireCastNet expects input shape (batch, timeseries_len, in_channels, n_lat, n_lon) = " + f"(B, {', '.join(map(str, expected))}), got {tuple(x.shape)}." + ) + batch, steps = x.size(0), x.size(1) + x = x.transpose(1, 2) # (B, C, T, H, W), the layout of the reference model + if self.static_data is not None: + static = self.static_data.to(x)[None, :, None].expand(batch, -1, steps, -1, -1) + x = torch.cat((x, static), dim=1) + else: + x = x.contiguous() + x = self._downsample(x) # (B, C', 1, H', W') + logits = [] + for sample in x: + nodes = sample[:, 0].reshape(sample.size(0), -1).permute(1, 0) # (H' * W', C') + out = self._net(nodes) + logits.append(out.view(self.graph_lat_dim, self.graph_lon_dim, -1).permute(2, 0, 1)) + return self._upsample(torch.stack(logits)) + + +# Defaults of the official FireCastNetLit, used for keys missing from a checkpoint's hyper_parameters. +_LIGHTNING_DEFAULTS: Dict[str, Any] = dict( + icospheres_graph_path="icospheres/icospheres_0_1_2_3.json.gz", + sp_res=0.25, + max_lat=89.875, + min_lat=-89.875, + max_lon=179.875, + min_lon=-179.875, + lat_lon_static_data=True, + embed_cube=False, + embed_cube_width=4, + embed_cube_height=4, + embed_cube_time=1, + embed_cube_dim=128, + embed_cube_layer_norm=True, + embed_cube_sp_res=1.0, + embed_cube_max_lat=89.5, + embed_cube_min_lat=-89.5, + embed_cube_max_lon=179.5, + embed_cube_min_lon=-179.5, + timeseries_len=1, + input_dim_grid_nodes=11, + output_dim_grid_nodes=1, + input_dim_mesh_nodes=3, + input_dim_edges=4, + processor_layers=8, + hidden_layers=1, + hidden_dim=64, + aggregation="sum", + norm_type="LayerNorm", + do_concat_trick=False, +) +_MODEL_HPARAMS = ( + "sp_res", "max_lat", "min_lat", "max_lon", "min_lon", "lat_lon_static_data", "embed_cube_width", + "embed_cube_height", "embed_cube_time", "embed_cube_dim", "embed_cube_layer_norm", "embed_cube_sp_res", + "embed_cube_max_lat", "embed_cube_min_lat", "embed_cube_max_lon", "embed_cube_min_lon", + "output_dim_grid_nodes", "input_dim_mesh_nodes", "input_dim_edges", "processor_layers", + "hidden_layers", "hidden_dim", "aggregation", "norm_type", +) + + +def lightning_state_dict_to_firecastnet(state_dict: Mapping[str, Tensor]) -> Dict[str, Tensor]: + """Map a ``FireCastNetLit`` checkpoint ``state_dict`` to :class:`FireCastNet` keys. + + The network weights sit under the LightningModule attribute ``_net``, so ``_net.`` + becomes ````. Data-derived buffers of the LightningModule (``_lsm_mask``, the loss's + ``_criterion.pixel_weights``) are not network weights and are dropped. + """ + return {key[len("_net."):]: value for key, value in state_dict.items() if key.startswith("_net.")} + + +def load_official_checkpoint( + path: Union[str, Path], + icospheres_graph_path: Optional[Union[str, Path]] = None, + map_location: Union[str, torch.device] = "cpu", +) -> FireCastNet: + """Build :class:`FireCastNet` from an official checkpoint and load its weights (``strict=True``). - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 4: + The configuration comes from the checkpoint's ``hyper_parameters``. Meshes named + ``icospheres_.json.gz`` are regenerated; any other mesh (the LAM meshes) must be given + as a local file in ``icospheres_graph_path``. + """ + checkpoint = torch.load(path, map_location=map_location, weights_only=True) + hparams: Dict[str, Any] = {**_LIGHTNING_DEFAULTS, **checkpoint.get("hyper_parameters", {})} + if not hparams["embed_cube"]: + raise ValueError("only checkpoints with embed_cube=True (FireCastNet) are supported") + if hparams.get("embed_cube_vit_enable") or hparams.get("embed_cube_ltae_enable"): + raise ValueError("ViT / L-TAE cube embedders are not ported") + if hparams["do_concat_trick"]: + raise ValueError("do_concat_trick=True is not ported") + kwargs: Dict[str, Any] = {key: hparams[key] for key in _MODEL_HPARAMS} + if icospheres_graph_path is not None: + kwargs["icospheres_graph_path"] = icospheres_graph_path + else: + levels = _official_levels(str(hparams["icospheres_graph_path"])) + if levels is None: raise ValueError( - "FireCastNet expects input shape (batch, channels, height, width), " - f"got {tuple(x.shape)}." + f"mesh {hparams['icospheres_graph_path']!r} is not a regular icosphere set; pass icospheres_graph_path" ) - if x.size(1) != self.in_channels: - raise ValueError(f"FireCastNet expected in_channels={self.in_channels}, got {x.size(1)}.") - encoded = self.encoder(x) - return self.decoder(encoded) + kwargs["mesh_levels"] = levels + model = FireCastNet(in_channels=hparams["input_dim_grid_nodes"], timeseries_len=hparams["timeseries_len"], **kwargs) + model.load_state_dict(lightning_state_dict_to_firecastnet(checkpoint["state_dict"]), strict=True) + return model def firecastnet_builder( task: str, - in_channels: int = 12, - hidden_dim: int = 32, - out_channels: int = 1, - dropout: float = 0.1, - **kwargs, + in_channels: int = 11, + timeseries_len: int = 24, + checkpoint: Optional[Union[str, Path]] = None, + **kwargs: Any, ) -> nn.Module: - _ = kwargs + """Build FireCastNet; ``checkpoint`` loads an official ``.ckpt`` (its configuration wins).""" + kwargs.pop("name", None) if task.lower() not in {"segmentation", "regression"}: - raise ValueError(f"firecastnet supports task='segmentation' or 'regression', got {task!r}.") - return FireCastNet( - in_channels=in_channels, - hidden_dim=hidden_dim, - out_channels=out_channels, - dropout=dropout, - ) + raise ValueError(f"firecastnet supports task='segmentation' (burned-area presence) or 'regression', got {task!r}.") + if checkpoint is not None: + return load_official_checkpoint(checkpoint, icospheres_graph_path=kwargs.get("icospheres_graph_path")) + if "mesh_levels" in kwargs: + kwargs["mesh_levels"] = tuple(kwargs["mesh_levels"]) + return FireCastNet(in_channels=in_channels, timeseries_len=timeseries_len, **kwargs) -__all__ = ["FireCastNet", "firecastnet_builder"] +__all__ = [ + "CubeConv3d", + "FireCastNet", + "GraphCastNet", + "OFFICIAL_INPUT_VARIABLES", + "firecastnet_builder", + "lightning_state_dict_to_firecastnet", + "load_official_checkpoint", +] diff --git a/pyhazards/models/firecastnet_graph.py b/pyhazards/models/firecastnet_graph.py new file mode 100644 index 00000000..1c355ea0 --- /dev/null +++ b/pyhazards/models/firecastnet_graph.py @@ -0,0 +1,386 @@ +"""Icosahedral multi-mesh and grid/mesh graphs for FireCastNet, in plain PyTorch (no DGL). + +FireCastNet (Michail et al., Scientific Reports 2025) runs a GraphCast encoder-processor-decoder +between a regular latitude/longitude grid and an icosahedral multi-mesh. This module builds the +three graphs it needs as ``(src, dst)`` index tensors plus their input features: + +- the multi-mesh: union of the edges of icospheres of several refinement levels, made + bidirectional, on the vertices of the finest level; +- grid -> mesh: each grid node to its 4 nearest mesh vertices, kept when closer than 0.6 times + the longest edge of the finest icosphere; +- mesh -> grid: each grid node from its single nearest mesh vertex. + +Provenance and licenses +----------------------- +- The coordinate helpers (``latlon2xyz``, ``xyz2latlon``, ``geospatial_rotation``, + ``azimuthal_angle``, ``polar_angle``), ``edge_features``, ``node_features`` and the multi-mesh / + grid-to-mesh construction are ported from NVIDIA Modulus v0.5.0 + (``modulus/utils/graphcast/graph_utils.py`` and ``modulus/utils/graphcast/graph.py``), + Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES, licensed under the Apache License 2.0 + (http://www.apache.org/licenses/LICENSE-2.0). Changes: DGL graphs are replaced by index + tensors, the scikit-learn KD-tree by a SciPy KD-tree with exact float64 re-ranking, and the + mesh-to-grid graph links each grid node to its single nearest mesh vertex as FireCastNet does + (Modulus links the three vertices of the nearest face). +- ``icosphere`` reimplements the icosphere layout of PyMesh ``generate_icosphere``, which produced + the official ``icospheres/*.json.gz`` files of FireCastNet: midpoint subdivision of the flat + icosahedron (new vertices numbered in order of first use, faces split as + ``[a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]``) followed by a single projection of all + vertices onto the unit sphere. The oracle test checks that the generated meshes equal those files. +""" + +from __future__ import annotations + +import gzip +import json +import math +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Mapping, Sequence, Tuple, Union + +import numpy as np +import torch +from torch import Tensor + +_PHI = (1.0 + math.sqrt(5.0)) / 2.0 + +# Regular icosahedron (12 vertices, 20 faces) in the layout used by PyMesh's generate_icosphere. +_ICOSAHEDRON_VERTICES = np.array( + [ + [-1.0, _PHI, 0.0], + [1.0, _PHI, 0.0], + [-1.0, -_PHI, 0.0], + [1.0, -_PHI, 0.0], + [0.0, -1.0, _PHI], + [0.0, 1.0, _PHI], + [0.0, -1.0, -_PHI], + [0.0, 1.0, -_PHI], + [_PHI, 0.0, -1.0], + [_PHI, 0.0, 1.0], + [-_PHI, 0.0, -1.0], + [-_PHI, 0.0, 1.0], + ], + dtype=np.float64, +) +_ICOSAHEDRON_FACES = np.array( + [ + [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], + [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], + [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], + [5, 4, 9], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], + ], + dtype=np.int64, +) + + +def _subdivide(vertices: np.ndarray, faces: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Split every triangle into four at its edge midpoints (no projection).""" + midpoint: Dict[Tuple[int, int], int] = {} + edges: List[Tuple[int, int]] = [] + base = len(vertices) + + def mid(a: int, b: int) -> int: + key = (a, b) if a < b else (b, a) + index = midpoint.get(key) + if index is None: + index = base + len(edges) + midpoint[key] = index + edges.append(key) + return index + + new_faces = np.empty((4 * len(faces), 3), dtype=np.int64) + for i, (a, b, c) in enumerate(faces.tolist()): + ab, bc, ca = mid(a, b), mid(b, c), mid(c, a) + new_faces[4 * i : 4 * i + 4] = [[a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]] + pairs = np.asarray(edges, dtype=np.int64) + midpoints = 0.5 * (vertices[pairs[:, 0]] + vertices[pairs[:, 1]]) + return np.concatenate((vertices, midpoints)), new_faces + + +def icosphere(level: int) -> Tuple[np.ndarray, np.ndarray]: + """Unit icosphere after ``level`` refinements: float64 vertices ``(V, 3)``, int64 faces ``(F, 3)``. + + Level ``k`` has ``10 * 4**k + 2`` vertices and ``20 * 4**k`` faces; the vertices of level ``k`` + are the first vertices of every finer level. + """ + if level < 0: + raise ValueError(f"icosphere level must be >= 0, got {level}") + vertices, faces = _ICOSAHEDRON_VERTICES, _ICOSAHEDRON_FACES + for _ in range(level): + vertices, faces = _subdivide(vertices, faces) + return vertices / np.linalg.norm(vertices, axis=1, keepdims=True), faces.copy() + + +def icospheres(levels: Sequence[int] = (0, 1, 2, 3, 4, 5, 6)) -> Dict[str, np.ndarray]: + """Icospheres of the given refinement levels in the layout of FireCastNet's icosphere files. + + Keys are ``order_{i}_vertices`` / ``order_{i}_faces`` with ``i = 0 .. len(levels) - 1`` in the + given order, as in ``icospheres/icospheres_0_1_2_3_4_5_6.json.gz``. + """ + levels = [int(level) for level in levels] + if not levels: + raise ValueError("at least one icosphere level is required") + if any(b <= a for a, b in zip(levels, levels[1:])): + raise ValueError(f"icosphere levels must be strictly increasing, got {levels}") + out: Dict[str, np.ndarray] = {} + vertices, faces = _ICOSAHEDRON_VERTICES, _ICOSAHEDRON_FACES + current = 0 + for order, level in enumerate(levels): + while current < level: + vertices, faces = _subdivide(vertices, faces) + current += 1 + out[f"order_{order}_vertices"] = vertices / np.linalg.norm(vertices, axis=1, keepdims=True) + out[f"order_{order}_faces"] = faces.copy() + return out + + +def load_icospheres(path: Union[str, Path]) -> Dict[str, np.ndarray]: + """Read a mesh file in FireCastNet's icosphere JSON layout (``.json`` or ``.json.gz``). + + This is how the local-area-modelling (LAM) meshes of the official repository are used. + """ + path = Path(path) + opener = gzip.open if path.suffix == ".gz" else open + with opener(path, "rt") as handle: + raw = json.load(handle) + return {key: np.asarray(value) for key, value in raw.items() if re.fullmatch(r"order_\d+_(vertices|faces)", key)} + + +def mesh_levels(meshes: Mapping[str, np.ndarray]) -> int: + """Number of refinement levels (``order_{i}_faces`` entries) in an icosphere mapping.""" + count = 0 + while f"order_{count}_faces" in meshes: + count += 1 + if count == 0 or f"order_{count - 1}_vertices" not in meshes: + raise ValueError("icosphere mapping needs order_0_faces ... order_{k}_faces and order_{k}_vertices") + return count + + +# --- coordinate helpers (ported from NVIDIA Modulus graph_utils, Apache-2.0) ------------------- + + +def deg2rad(deg: Tensor) -> Tensor: + return deg * np.pi / 180 + + +def rad2deg(rad: Tensor) -> Tensor: + return rad * 180 / np.pi + + +def latlon2xyz(latlon: Tensor, radius: float = 1, unit: str = "deg") -> Tensor: + """``(N, 2)`` latitude/longitude to ``(N, 3)`` Cartesian coordinates on a sphere.""" + if unit == "deg": + latlon = deg2rad(latlon) + elif unit != "rad": + raise ValueError("Not a valid unit") + lat, lon = latlon[:, 0], latlon[:, 1] + x = radius * torch.cos(lat) * torch.cos(lon) + y = radius * torch.cos(lat) * torch.sin(lon) + z = radius * torch.sin(lat) + return torch.stack((x, y, z), dim=1) + + +def xyz2latlon(xyz: Tensor, radius: float = 1, unit: str = "deg") -> Tensor: + """``(N, 3)`` Cartesian coordinates to ``(N, 2)`` latitude/longitude.""" + lat = torch.arcsin(xyz[:, 2] / radius) + lon = torch.arctan2(xyz[:, 1], xyz[:, 0]) + if unit == "deg": + return torch.stack((rad2deg(lat), rad2deg(lon)), dim=1) + if unit == "rad": + return torch.stack((lat, lon), dim=1) + raise ValueError("Not a valid unit") + + +def geospatial_rotation(invar: Tensor, theta: Tensor, axis: str) -> Tensor: + """Rotate ``(N, 3)`` points by per-point angles ``theta`` (radians) about ``axis`` (right-hand rule).""" + invar = torch.unsqueeze(invar, -1) + rotation = torch.zeros((theta.size(0), 3, 3), dtype=invar.dtype) + cos = torch.cos(theta) + sin = torch.sin(theta) + if axis == "x": + rotation[:, 0, 0] += 1.0 + rotation[:, 1, 1] += cos + rotation[:, 1, 2] -= sin + rotation[:, 2, 1] += sin + rotation[:, 2, 2] += cos + elif axis == "y": + rotation[:, 0, 0] += cos + rotation[:, 0, 2] += sin + rotation[:, 1, 1] += 1.0 + rotation[:, 2, 0] -= sin + rotation[:, 2, 2] += cos + elif axis == "z": + rotation[:, 0, 0] += cos + rotation[:, 0, 1] -= sin + rotation[:, 1, 0] += sin + rotation[:, 1, 1] += cos + rotation[:, 2, 2] += 1.0 + else: + raise ValueError("Invalid axis") + return torch.matmul(rotation, invar).squeeze(-1) + + +def azimuthal_angle(lon: Tensor) -> Tensor: + return torch.where(lon >= 0.0, 2 * np.pi - lon, -lon) + + +def polar_angle(lat: Tensor) -> Tensor: + return torch.where(lat >= 0.0, lat, 2 * np.pi + lat) + + +def edge_features(src_pos: Tensor, dst_pos: Tensor, src: Tensor, dst: Tensor, normalize: bool = True) -> Tensor: + """GraphCast edge features: source-minus-destination displacement in the destination's local frame. + + Both endpoints are rotated so that the destination lands on ``(1, 0, 0)``; the features are the + rotated displacement and its length, divided by the longest displacement of the graph. + """ + src_pos, dst_pos = src_pos[src.long()], dst_pos[dst.long()] + dst_latlon = xyz2latlon(dst_pos, unit="rad") + dst_lat, dst_lon = dst_latlon[:, 0], dst_latlon[:, 1] + theta_azimuthal = azimuthal_angle(dst_lon) + theta_polar = polar_angle(dst_lat) + src_pos = geospatial_rotation(src_pos, theta=theta_azimuthal, axis="z") + dst_pos = geospatial_rotation(dst_pos, theta=theta_azimuthal, axis="z") + src_pos = geospatial_rotation(src_pos, theta=theta_polar, axis="y") + dst_pos = geospatial_rotation(dst_pos, theta=theta_polar, axis="y") + disp = src_pos - dst_pos + disp_norm = torch.linalg.norm(disp, dim=-1, keepdim=True) + if normalize: + max_disp_norm = torch.max(disp_norm) + return torch.cat((disp / max_disp_norm, disp_norm / max_disp_norm), dim=-1) + return torch.cat((disp, disp_norm), dim=-1) + + +def node_features(pos: Tensor) -> Tensor: + """GraphCast mesh-node features ``(cos(lat), sin(lon), cos(lon))``. + + As in the reference code, latitude and longitude are taken in degrees and passed to the + trigonometric functions without conversion to radians. + """ + latlon = xyz2latlon(pos) + lat, lon = latlon[:, 0], latlon[:, 1] + return torch.stack((torch.cos(lat), torch.sin(lon), torch.cos(lon)), dim=-1) + + +# --- graph construction ------------------------------------------------------------------------- + + +def latlon_grid(sp_res: float, max_lat: float, min_lat: float, max_lon: float, min_lon: float) -> Tuple[Tensor, Tensor]: + """Cell-centre latitudes (north to south) and longitudes (west to east) as float32 tensors.""" + latitudes = torch.from_numpy(np.arange(max_lat, min_lat - (sp_res / 2), -sp_res, dtype=np.float32)) + longitudes = torch.from_numpy(np.arange(min_lon, max_lon + (sp_res / 2), sp_res, dtype=np.float32)) + return latitudes, longitudes + + +def _nearest_vertices(queries: Tensor, points: Tensor, k: int) -> Tuple[Tensor, Tensor]: + """Exact k nearest ``points`` of every query (float64 Euclidean distance), sorted by distance. + + A SciPy KD-tree proposes candidates; the final order uses the directly computed distance + ``sqrt(dx^2 + dy^2 + dz^2)`` (the formula of the scikit-learn KD-tree used by the reference), + with ties broken by vertex index. + """ + from scipy.spatial import cKDTree + + queries = queries.to(torch.float64) + points = points.to(torch.float64) + n_candidates = min(points.size(0), k + 8) + _, candidates = cKDTree(points.numpy()).query(queries.numpy(), k=n_candidates) + candidates = torch.from_numpy(np.asarray(candidates, dtype=np.int64).reshape(queries.size(0), n_candidates)) + candidates, _ = candidates.sort(dim=1) + diff = queries[:, None, :] - points[candidates] + sq = diff[..., 0] * diff[..., 0] + diff[..., 1] * diff[..., 1] + diff[..., 2] * diff[..., 2] + order = sq.argsort(dim=1, stable=True)[:, :k] + return torch.sqrt(sq.gather(1, order)), candidates.gather(1, order) + + +@dataclass +class FireCastNetGraph: + """Edge indices (int64) and float32 input features of the three FireCastNet graphs.""" + + mesh_src: Tensor + mesh_dst: Tensor + mesh_edata: Tensor + mesh_ndata: Tensor + g2m_src: Tensor + g2m_dst: Tensor + g2m_edata: Tensor + m2g_src: Tensor + m2g_dst: Tensor + m2g_edata: Tensor + num_grid_nodes: int + num_mesh_nodes: int + + +def build_graph(latitudes: Tensor, longitudes: Tensor, meshes: Mapping[str, np.ndarray]) -> FireCastNetGraph: + """Build the multi-mesh, grid->mesh and mesh->grid graphs for a latitude/longitude grid. + + Grid nodes are numbered row-major over ``(latitude, longitude)``; mesh nodes are the vertices of + the finest level in ``meshes`` (an :func:`icospheres` / :func:`load_icospheres` mapping). + """ + max_order = mesh_levels(meshes) - 1 + vertices = np.asarray(meshes[f"order_{max_order}_vertices"], dtype=np.float64) + finest_faces = np.asarray(meshes[f"order_{max_order}_faces"], dtype=np.int64) + num_mesh = vertices.shape[0] + mesh_pos = torch.tensor(vertices, dtype=torch.float32) + + # Multi-mesh: every face contributes (a, b), (b, c), (c, a); the union over all levels is made + # bidirectional and simple, with edges sorted by (src, dst). + faces = np.concatenate([np.asarray(meshes[f"order_{i}_faces"], dtype=np.int64) for i in range(max_order + 1)]) + if faces.min() < 0 or faces.max() >= num_mesh: + raise ValueError("icosphere faces must index the vertices of the finest level") + src = faces[:, [0, 1, 2]].reshape(-1) + dst = faces[:, [1, 2, 0]].reshape(-1) + pairs = np.unique(np.concatenate((src * num_mesh + dst, dst * num_mesh + src))) + mesh_src = torch.from_numpy(pairs // num_mesh) + mesh_dst = torch.from_numpy(pairs % num_mesh) + + # Grid nodes on the unit sphere (float32, as the reference computes them). + grid = torch.stack(torch.meshgrid(latitudes, longitudes, indexing="ij"), dim=-1) + grid_flat = grid.permute(2, 0, 1).reshape(2, -1).permute(1, 0) + grid_pos = latlon2xyz(grid_flat) + num_grid = grid_pos.size(0) + + # Grid -> mesh: up to 4 nearest vertices within 0.6 x the longest edge of the finest level. + edge_len = max( + np.max(np.linalg.norm(vertices[finest_faces[:, a]] - vertices[finest_faces[:, b]], axis=1)) + for a, b in ((0, 1), (0, 2), (1, 2)) + ) + distances, neighbours = _nearest_vertices(grid_pos, torch.from_numpy(vertices), k=min(4, num_mesh)) + keep = distances <= 0.6 * edge_len + g2m_src = torch.arange(num_grid).unsqueeze(1).expand_as(neighbours)[keep] + g2m_dst = neighbours[keep] + + # Mesh -> grid: the nearest mesh vertex of every grid node. + _, nearest = _nearest_vertices(grid_pos, torch.from_numpy(vertices), k=1) + m2g_src = nearest[:, 0] + m2g_dst = torch.arange(num_grid) + + return FireCastNetGraph( + mesh_src=mesh_src, + mesh_dst=mesh_dst, + mesh_edata=edge_features(mesh_pos, mesh_pos, mesh_src, mesh_dst), + mesh_ndata=node_features(mesh_pos), + g2m_src=g2m_src, + g2m_dst=g2m_dst, + g2m_edata=edge_features(grid_pos, mesh_pos, g2m_src, g2m_dst), + m2g_src=m2g_src, + m2g_dst=m2g_dst, + m2g_edata=edge_features(mesh_pos, grid_pos, m2g_src, m2g_dst), + num_grid_nodes=num_grid, + num_mesh_nodes=num_mesh, + ) + + +__all__ = [ + "FireCastNetGraph", + "build_graph", + "edge_features", + "icosphere", + "icospheres", + "latlon2xyz", + "latlon_grid", + "load_icospheres", + "mesh_levels", + "node_features", + "xyz2latlon", +] diff --git a/pyhazards/models/forefire.py b/pyhazards/models/forefire.py deleted file mode 100644 index b9b6f565..00000000 --- a/pyhazards/models/forefire.py +++ /dev/null @@ -1,66 +0,0 @@ -from __future__ import annotations - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class ForeFireAdapter(nn.Module): - """Lightweight deterministic spread adapter inspired by simulator-style fronts.""" - - def __init__( - self, - in_channels: int = 12, - out_channels: int = 1, - diffusion_steps: int = 2, - ): - super().__init__() - if in_channels <= 0: - raise ValueError(f"in_channels must be positive, got {in_channels}") - if out_channels != 1: - raise ValueError(f"ForeFireAdapter only supports out_channels=1, got {out_channels}") - if diffusion_steps <= 0: - raise ValueError(f"diffusion_steps must be positive, got {diffusion_steps}") - self.in_channels = int(in_channels) - self.diffusion_steps = int(diffusion_steps) - kernel = torch.tensor( - [[0.05, 0.15, 0.05], [0.15, 0.20, 0.15], [0.05, 0.15, 0.05]], - dtype=torch.float32, - ).view(1, 1, 3, 3) - self.register_buffer("spread_kernel", kernel) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 4: - raise ValueError( - "ForeFireAdapter expects input shape (batch, channels, height, width), " - f"got {tuple(x.shape)}." - ) - if x.size(1) != self.in_channels: - raise ValueError(f"ForeFireAdapter expected in_channels={self.in_channels}, got {x.size(1)}.") - state = torch.sigmoid(x[:, :1]) - fuel = torch.sigmoid(x[:, 1:2]) - wind = torch.tanh(x[:, 2:3]).abs() - for _ in range(self.diffusion_steps): - neighborhood = F.conv2d(state, self.spread_kernel, padding=1) - state = torch.clamp(0.45 * state + 0.4 * neighborhood + 0.1 * fuel + 0.05 * wind, 0.0, 1.0) - return state - - -def forefire_builder( - task: str, - in_channels: int = 12, - out_channels: int = 1, - diffusion_steps: int = 2, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() not in {"segmentation", "regression"}: - raise ValueError(f"forefire supports task='segmentation' or 'regression', got {task!r}.") - return ForeFireAdapter( - in_channels=in_channels, - out_channels=out_channels, - diffusion_steps=diffusion_steps, - ) - - -__all__ = ["ForeFireAdapter", "forefire_builder"] diff --git a/pyhazards/models/fourcastnet_tc.py b/pyhazards/models/fourcastnet_tc.py deleted file mode 100644 index 4230d095..00000000 --- a/pyhazards/models/fourcastnet_tc.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import torch -import torch.nn as nn - - -class FourCastNetTC(nn.Module): - """Experimental wrapper-style FourCastNet storm adapter.""" - - def __init__( - self, - input_dim: int = 8, - history: int = 6, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - ): - super().__init__() - self.history = int(history) - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.net = nn.Sequential( - nn.Linear(self.history * input_dim, hidden_dim), - nn.GELU(), - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("FourCastNetTC expects inputs shaped (batch, history, features).") - if x.size(1) != self.history: - raise ValueError(f"FourCastNetTC expected history={self.history}, got {x.size(1)}.") - preds = self.net(x.reshape(x.size(0), -1)) - return preds.view(x.size(0), self.horizon, self.output_dim) - - -def fourcastnet_tc_builder( - task: str, - input_dim: int = 8, - history: int = 6, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("FourCastNetTC only supports regression for track/intensity forecasting.") - return FourCastNetTC( - input_dim=input_dim, - history=history, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - dropout=dropout, - ) - - -__all__ = ["FourCastNetTC", "fourcastnet_tc_builder"] diff --git a/pyhazards/models/google_flood_forecasting.py b/pyhazards/models/google_flood_forecasting.py index f3722272..136a721b 100644 --- a/pyhazards/models/google_flood_forecasting.py +++ b/pyhazards/models/google_flood_forecasting.py @@ -1,92 +1,570 @@ +"""Google flood-forecasting LSTM: hindcast / forecast LSTMs with masked-mean input embeddings and a CMAL head. + +Port of ``googlehydrology/modelzoo/mean_embedding_forecast_lstm.py`` (``MeanEmbeddingForecastLSTM``), +``fc.py`` (``FC``), ``head.py`` (``CMAL``, ``Regression``) and ``utils/lstm_utils.py`` (``lstm_init``) of +google-research/flood-forecasting at commit cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1 +(https://github.com/google-research/flood-forecasting, Apache License 2.0, Copyright 2025 Google LLC; +googlehydrology is a fork of NeuralHydrology, BSD-3-Clause). Changes: plain constructor arguments instead +of the googlehydrology ``Config``; the data-assimilation hooks (``assimilation_overrides``, +``return_embeddings``) and the hot-start state files (``save_state`` / ``load_state_from_disk``) are not +ported; inputs may also be given as tensors whose columns follow the configured feature order. + +This is the model of Google's released FloodHub weights (Gauch et al., "How to deal w___ missing input +data", HESS 29:6221-6235, 2025), the successor of the hindcast/forecast LSTM of Nearing et al. (Nature +627:559-563, 2024). Static attributes are embedded by an FC network; every dynamic input group (one +weather product, e.g. ``hres``, ``graphcast``, ``imerg``, ``cpc``) is embedded together with the static +embedding by its own FC network, and the group embeddings are averaged with a NaN-aware mean, so a +missing product is skipped. A hindcast LSTM runs over the averaged hindcast embedding; a forecast LSTM +runs over the averaged forecast embedding plus the hindcast LSTM's outputs. The CMAL head gives, for +every time step, a mixture of ``n_distributions`` asymmetric Laplace distributions (``mu``, ``b``, +``tau``, ``pi``). Steps from the first one with no valid input on are NaN, as in the reference. + +``pretrained=True`` downloads the released ``model_epoch110.pt`` (13.6 MB, pinned commit and sha256; +covered by the repository's Apache-2.0 licence) into the torch hub cache and loads it with +``strict=True`` after stripping the ``_orig_mod.`` prefix that ``torch.compile`` added. The release +expects inputs normalised with its ``scaler.zarr`` (not read by PyHazards). +""" + from __future__ import annotations +import hashlib +from pathlib import Path +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union + +import numpy as np import torch import torch.nn as nn +LSTM_IH_XAVIER = "lstm-ih-xavier" +LSTM_HH_ORTHOGONAL = "lstm-hh-orthogonal" +FC_XAVIER = "fc-xavier" + +FLOODHUB_STATIC_ATTRIBUTES = [ + "p_mean", "pet_mean_ERA5_LAND", "aridity_ERA5_LAND", "frac_snow", "moisture_index_ERA5_LAND", + "seasonality_ERA5_LAND", "high_prec_freq", "high_prec_dur", "low_prec_freq", "low_prec_dur", + "aet_mm_syr", "ari_ix_sav", "crp_pc_sse", "ele_mt_sav", "ero_kh_sav", "for_pc_sse", "gdp_ud_ssu", + "gla_pc_sse", "glc_pc_s01", "glc_pc_s02", "glc_pc_s03", "glc_pc_s04", "glc_pc_s06", "glc_pc_s07", + "glc_pc_s08", "glc_pc_s09", "glc_pc_s10", "glc_pc_s11", "glc_pc_s12", "glc_pc_s13", "glc_pc_s14", + "glc_pc_s15", "glc_pc_s16", "glc_pc_s17", "glc_pc_s18", "glc_pc_s19", "glc_pc_s20", "glc_pc_s21", + "glc_pc_s22", "hft_ix_s09", "hft_ix_s93", "inu_pc_slt", "inu_pc_smn", "inu_pc_smx", "ire_pc_sse", + "kar_pc_sse", "lka_pc_sse", "nli_ix_sav", "pac_pc_sse", "pet_mm_syr", "pnv_pc_s01", "pnv_pc_s02", + "pnv_pc_s03", "pnv_pc_s04", "pnv_pc_s05", "pnv_pc_s06", "pnv_pc_s07", "pnv_pc_s08", "pnv_pc_s09", + "pnv_pc_s10", "pnv_pc_s11", "pnv_pc_s12", "pnv_pc_s13", "pnv_pc_s14", "pnv_pc_s15", "ppd_pk_sav", + "pre_mm_syr", "prm_pc_sse", "rdd_mk_sav", "snw_pc_syr", "swc_pc_syr", "tmp_dc_syr", "urb_pc_sse", + "wet_pc_s01", "wet_pc_s02", "wet_pc_s03", "wet_pc_s04", "wet_pc_s05", "wet_pc_s06", "wet_pc_s07", + "wet_pc_s08", "wet_pc_s09", "wet_pc_sg1", "wet_pc_sg2", +] +_HRES = [ + "hres_surface_net_solar_radiation", + "hres_surface_net_thermal_radiation", + "hres_surface_pressure", + "hres_temperature_2m", + "hres_total_precipitation", +] +_GRAPHCAST = ["graphcast_temperature_2m", "graphcast_total_precipitation"] + +# pretrained-models/google-floodhub-settings-110-epochs/config.yml at the pinned commit. +FLOODHUB_CONFIG: Dict[str, Any] = { + "static_attributes": FLOODHUB_STATIC_ATTRIBUTES, + "hindcast_inputs": {"hres": _HRES, "graphcast": _GRAPHCAST, "imerg": ["imerg_precipitation"], "cpc": ["cpc_precipitation"]}, + "forecast_inputs": {"hres": _HRES, "graphcast": _GRAPHCAST}, + "seq_length": 365, + "lead_time": 7, + "hidden_size": 512, + "statics_embedding": {"hiddens": [100, 100, 20], "activation": ["tanh", "tanh", "linear"], "dropout": 0.0}, + "hindcast_embedding": {"hiddens": [100, 20], "activation": ["tanh", "linear"], "dropout": 0.0}, + "forecast_embedding": {"hiddens": [20, 20, 20, 20], "activation": ["tanh", "tanh", "tanh", "linear"], "dropout": 0.0}, + "head": "cmal", + "n_distributions": 3, + "n_targets": 1, + "output_dropout": 0.4, + "initial_forget_bias": 3.0, + "weight_init_opts": [LSTM_IH_XAVIER, LSTM_HH_ORTHOGONAL, FC_XAVIER], +} + +FLOODHUB_WEIGHTS = { + "url": ( + "https://raw.githubusercontent.com/google-research/flood-forecasting/" + "cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1/pretrained-models/google-floodhub-settings-110-epochs/" + "model_epoch110.pt" + ), + "sha256": "90280f0687a5a95006580164c243be6f8551580f772be26247c8b0ef3d53fdba", + "filename": "google_floodhub_settings_110_epochs_model_epoch110.pt", +} + + +def _unique(features: Iterable[str]) -> List[str]: + return list(dict.fromkeys(features)) + + +def _embedding_spec(spec: Mapping[str, Any], label: str) -> Dict[str, Any]: + if spec is None: + raise ValueError(f"{label} embedding specification is required.") + hiddens = [int(h) for h in spec.get("hiddens", [])] + if not hiddens: + raise ValueError(f"{label} embedding needs at least one entry in 'hiddens'.") + activation = spec.get("activation", "tanh") + activation = list(activation) if isinstance(activation, (list, tuple)) else [activation] * len(hiddens) + if len(activation) != len(hiddens): + raise ValueError(f"{label} embedding: hiddens and activation layers must match.") + if spec.get("type", "fc").lower() != "fc": + raise ValueError(f"{label} embedding type {spec.get('type')!r} not supported (only 'fc').") + return {"hiddens": hiddens, "activation": activation, "dropout": float(spec.get("dropout", 0.0))} + + +class FC(nn.Module): + """googlehydrology ``FC``: Linear / activation / Dropout blocks and a linear output layer. + + Initialisation: uniform(-sqrt(3 / n_in), sqrt(3 / n_in)) weights, or, with ``xavier_init``, + ``xavier_uniform_`` with gain sqrt(3 / n_in) (the reference passes that bound as the gain); zero bias. + """ + + def __init__(self, input_size: int, hidden_sizes: Sequence[int], activation: Union[str, Sequence[str]] = "tanh", + dropout: float = 0.0, xavier_init: bool = False): + super().__init__() + self._xavier_init = xavier_init + if len(hidden_sizes) == 0: + raise ValueError("hidden_sizes must at least have one entry to create a fully-connected net.") + self.output_size = hidden_sizes[-1] + hidden_sizes = list(hidden_sizes[:-1]) + if isinstance(activation, str): + activations = [self._get_activation(activation)] * len(hidden_sizes) + else: + activations = [self._get_activation(e) for e in activation] + layers: List[nn.Module] = [] + if hidden_sizes: + for i, hidden_size in enumerate(hidden_sizes): + layers.append(nn.Linear(input_size if i == 0 else hidden_sizes[i - 1], hidden_size)) + layers.append(activations[i]) + layers.append(nn.Dropout(p=dropout)) + layers.append(nn.Linear(hidden_sizes[-1], self.output_size)) + else: + layers.append(nn.Linear(input_size, self.output_size)) + self.net = nn.Sequential(*layers) + self._reset_parameters() + + @staticmethod + def _get_activation(name: str) -> nn.Module: + activations = {"tanh": nn.Tanh, "sigmoid": nn.Sigmoid, "relu": nn.ReLU, "linear": nn.Identity} + if name.lower() not in activations: + raise ValueError(f"{name} currently not supported as activation in this class") + return activations[name.lower()]() + + def _reset_parameters(self) -> None: + for layer in self.net: + if isinstance(layer, nn.Linear): + n_in = layer.weight.shape[1] + gain = np.sqrt(3 / n_in) + if self._xavier_init: + nn.init.xavier_uniform_(layer.weight, gain) + else: + nn.init.uniform_(layer.weight, -gain, gain) + nn.init.constant_(layer.bias, val=0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.net(x) + + +class CMAL(nn.Module): + """Countable mixture of asymmetric Laplacians (Klotz et al., HESS 2022): ``mu``, ``b``, ``tau``, ``pi``.""" + + def __init__(self, n_in: int, n_out: int, n_hidden: int = 100, n_distributions: Optional[int] = None): + super().__init__() + self.fc1 = nn.Linear(n_in, n_hidden) + self.fc2 = nn.Linear(n_hidden, n_out) + self.n_distributions = n_distributions + self._softplus = torch.nn.Softplus(2) + self._eps = 1e-5 + + def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: + h = torch.relu(self.fc1(x)) + h = self.fc2(h) + m_latent, b_latent, t_latent, p_latent = h.chunk(4, dim=-1) + m = m_latent + b = self._softplus(b_latent) + self._eps + t = (1 - self._eps) * torch.sigmoid(t_latent) + self._eps + p = (1 - self._eps) * torch.softmax(p_latent, dim=-1) + self._eps + return {"mu": m, "b": b, "tau": t, "pi": p} + + def point_prediction(self, outputs: Mapping[str, torch.Tensor]) -> torch.Tensor: + """Mean of the predicted mixture, ``(batch, time, n_targets)``.""" + mu, b, tau, pi = (outputs[k] for k in ("mu", "b", "tau", "pi")) + n_distributions = self.n_distributions or mu.shape[-1] + shape = (*mu.shape[:-1], -1, n_distributions) + mu, b, tau, pi = (e.reshape(shape) for e in (mu, b, tau, pi)) + pi = pi / pi.sum(dim=-1, keepdim=True) + tau = torch.clamp(tau, min=1e-6, max=1.0 - 1e-6) + means = mu + b * (1 - 2 * tau) / (tau * (1 - tau)) + return torch.sum(pi * means, dim=-1) + + +class RegressionHead(nn.Module): + """googlehydrology ``Regression`` head (single linear layer, optional ReLU / Softplus).""" + + def __init__(self, n_in: int, n_out: int, activation: str = "linear"): + super().__init__() + layers: List[nn.Module] = [nn.Linear(n_in, n_out)] + if activation != "linear": + if activation.lower() == "relu": + layers.append(nn.ReLU()) + elif activation.lower() == "softplus": + layers.append(nn.Softplus()) + else: + raise ValueError(f"output_activation must be 'linear', 'relu' or 'softplus', got {activation!r}.") + self.net = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: + return {"y_hat": self.net(x)} + + def point_prediction(self, outputs: Mapping[str, torch.Tensor]) -> torch.Tensor: + return outputs["y_hat"] + + +def lstm_init(lstms: Iterable[nn.LSTM], forget_bias: Optional[float], weight_opts: Iterable[str]) -> None: + """Forget-gate bias of ``bias_hh``, Xavier ``weight_ih`` and orthogonal ``weight_hh`` (as configured).""" + weight_opts = set(weight_opts) + with torch.no_grad(): + for lstm in lstms: + for name, param in lstm.named_parameters(): + if forget_bias is not None and name.startswith("bias_hh_"): + param.data[slice(lstm.hidden_size, 2 * lstm.hidden_size)] = forget_bias + elif "weight_ih" in name and LSTM_IH_XAVIER in weight_opts: + nn.init.xavier_uniform_(param) + elif "weight_hh" in name and LSTM_HH_ORTHOGONAL in weight_opts: + nn.init.orthogonal_(param) + class GoogleFloodForecasting(nn.Module): - """Sequence baseline for streamflow-style flood forecasting.""" + """``MeanEmbeddingForecastLSTM`` of googlehydrology (see the module docstring). + + Inputs: ``x_s`` (batch, n_static); ``x_d_hindcast`` and ``x_d_forecast``, each either a dict of + per-feature tensors (batch, time, 1), as googlehydrology passes them, or one tensor (batch, time, + n_features) with the columns in the order of :attr:`hindcast_features` / :attr:`forecast_features`. + Hindcast series have at most ``seq_length + lead_time`` steps (they are NaN-padded to that length) and + forecast series exactly ``seq_length + lead_time``. When every group is shared between hindcast and + forecast and ``lead_time == 0``, ``{"x_d": ..., "x_s": ...}`` feeds both (PyHazards streamflow layout). + Output: the head's dict, e.g. ``mu``, ``b``, ``tau``, ``pi`` of shape (batch, seq_length + lead_time, + n_targets * n_distributions). + """ def __init__( self, - input_dim: int = 2, - hidden_dim: int = 64, - out_dim: int = 1, - history: int = 4, - dropout: float = 0.1, + static_attributes: Union[int, Sequence[str]], + hindcast_inputs: Mapping[str, Sequence[str]], + forecast_inputs: Mapping[str, Sequence[str]], + seq_length: int = 365, + lead_time: int = 7, + hidden_size: int = 512, + statics_embedding: Optional[Mapping[str, Any]] = None, + hindcast_embedding: Optional[Mapping[str, Any]] = None, + forecast_embedding: Optional[Mapping[str, Any]] = None, + head: str = "cmal", + n_distributions: int = 3, + n_targets: int = 1, + output_dropout: float = 0.4, + initial_forget_bias: Optional[float] = 3.0, + weight_init_opts: Sequence[str] = (LSTM_IH_XAVIER, LSTM_HH_ORTHOGONAL, FC_XAVIER), + output_activation: str = "linear", ): super().__init__() - if input_dim <= 0: - raise ValueError(f"input_dim must be positive, got {input_dim}") - if hidden_dim <= 0: - raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") - if out_dim <= 0: - raise ValueError(f"out_dim must be positive, got {out_dim}") - if history <= 0: - raise ValueError(f"history must be positive, got {history}") - if not 0.0 <= dropout < 1.0: - raise ValueError(f"dropout must be in [0, 1), got {dropout}") - - self.history = int(history) - self.proj = nn.Linear(input_dim, hidden_dim) - self.temporal = nn.TransformerEncoder( - nn.TransformerEncoderLayer( - d_model=hidden_dim, - nhead=4, - dim_feedforward=hidden_dim * 2, - dropout=dropout, - batch_first=True, - activation="gelu", - ), - num_layers=2, + if isinstance(static_attributes, int): + static_attributes = [f"static_{i}" for i in range(static_attributes)] + self.static_attributes = list(static_attributes) + if not self.static_attributes: + raise ValueError("Cannot create embedding layer with input size 0: static attributes are required.") + self.hindcast_inputs_grouped = {str(k): _unique(v) for k, v in hindcast_inputs.items()} + self.forecast_inputs_grouped = {str(k): _unique(v) for k, v in forecast_inputs.items()} + if not self.hindcast_inputs_grouped or not self.forecast_inputs_grouped: + raise ValueError("hindcast_inputs and forecast_inputs each need at least one feature group.") + self.shared_groups = [g for g in self.hindcast_inputs_grouped if g in self.forecast_inputs_grouped] + for group in self.shared_groups: + if self.hindcast_inputs_grouped[group] != self.forecast_inputs_grouped[group]: + raise ValueError(f"Same features must be defined in forecast and hindcast for group={group!r}.") + self.hindcast_features = _unique(f for g in self.hindcast_inputs_grouped.values() for f in g) + self.forecast_features = _unique(f for g in self.forecast_inputs_grouped.values() for f in g) + if int(seq_length) <= 0 or int(lead_time) < 0 or int(hidden_size) <= 0: + raise ValueError("seq_length and hidden_size must be positive and lead_time >= 0.") + self.seq_length = int(seq_length) + self.lead_time = int(lead_time) + self.hidden_size = int(hidden_size) + self.weight_init_opts = list(weight_init_opts) + unknown = set(self.weight_init_opts) - {LSTM_IH_XAVIER, LSTM_HH_ORTHOGONAL, FC_XAVIER} + if unknown: + raise ValueError(f"unsupported weight_init_opts: {sorted(unknown)}") + statics = _embedding_spec(statics_embedding or FLOODHUB_CONFIG["statics_embedding"], "statics") + hindcast = _embedding_spec(hindcast_embedding or FLOODHUB_CONFIG["hindcast_embedding"], "hindcast") + forecast = _embedding_spec(forecast_embedding or FLOODHUB_CONFIG["forecast_embedding"], "forecast") + self.head_type = head.lower() + if self.head_type not in ("cmal", "regression"): + raise ValueError(f"head must be 'cmal' or 'regression', got {head!r}.") + output_size = int(n_targets) * (4 * int(n_distributions) if self.head_type == "cmal" else 1) + + # Same creation order as the reference (initialisation draws from the RNG in this order). + self.static_embedding_fc = self._create_fc(statics, len(self.static_attributes)) + static_size = self.static_embedding_fc.output_size + self.hindcast_embeddings_fc = nn.ModuleDict( + { + name: self._create_fc(hindcast, len(features) + static_size) + for name, features in self.hindcast_inputs_grouped.items() + if name not in self.shared_groups + } + ) + self.forecast_embeddings_fc = nn.ModuleDict( + { + name: self._create_fc(forecast, len(features) + static_size) + for name, features in self.forecast_inputs_grouped.items() + if name not in self.shared_groups + } ) - self.head = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim), - nn.GELU(), - nn.Dropout(dropout), - nn.Linear(hidden_dim, out_dim), + self.shared_embeddings_fc = nn.ModuleDict( + { + name: self._create_fc(forecast, len(self.forecast_inputs_grouped[name]) + static_size) + for name in self.shared_groups + } + ) + if hindcast["hiddens"][-1] != forecast["hiddens"][-1] and self.shared_groups: + raise ValueError("Shared groups feed the hindcast mean, so hindcast and forecast embeddings must have the same size.") + self.hindcast_lstm = nn.LSTM( + input_size=static_size + hindcast["hiddens"][-1], hidden_size=self.hidden_size, batch_first=True + ) + self.forecast_lstm = nn.LSTM( + input_size=static_size + forecast["hiddens"][-1] + self.hidden_size, + hidden_size=self.hidden_size, + batch_first=True, + ) + self.dropout = nn.Dropout(p=output_dropout) + if self.head_type == "cmal": + self.head = CMAL(n_in=self.hidden_size, n_out=output_size, n_hidden=100, n_distributions=int(n_distributions)) + else: + self.head = RegressionHead(n_in=self.hidden_size, n_out=output_size, activation=output_activation) + lstm_init([self.hindcast_lstm, self.forecast_lstm], initial_forget_bias, self.weight_init_opts) + + def _create_fc(self, spec: Mapping[str, Any], input_size: int) -> FC: + if input_size <= 0: + raise ValueError("Cannot create embedding layer with input size 0") + return FC( + input_size=input_size, + hidden_sizes=spec["hiddens"], + activation=spec["activation"], + dropout=spec["dropout"], + xavier_init=FC_XAVIER in self.weight_init_opts, ) - def forward(self, batch) -> torch.Tensor: - if not isinstance(batch, dict) or "x" not in batch: - raise ValueError("GoogleFloodForecasting expects a mapping input with key 'x'.") - x = batch["x"] - if x.ndim != 4: + # -- inputs --------------------------------------------------------------------------------------- + def _group_tensors(self, data: Any, features: List[str], grouped: Dict[str, List[str]], label: str): + if isinstance(data, Mapping): + missing = [f for g in grouped.values() for f in g if f not in data] + if missing: + raise ValueError(f"x_d_{label} is missing features {missing}.") + return {name: torch.cat([data[f] for f in feats], dim=-1) for name, feats in grouped.items()} + if not isinstance(data, torch.Tensor) or data.ndim != 3 or data.shape[-1] != len(features): + shape = tuple(data.shape) if isinstance(data, torch.Tensor) else type(data).__name__ raise ValueError( - "GoogleFloodForecasting expects input shape (batch, history, nodes, features), " - f"got {tuple(x.shape)}." + f"x_d_{label} must be a dict of (batch, time, 1) tensors or a tensor of shape " + f"(batch, time, {len(features)}) with columns {features}; got {shape}." ) - if x.size(1) != self.history: - raise ValueError(f"GoogleFloodForecasting expected history={self.history}, got {x.size(1)}.") - encoded = self.proj(x) - temporal = encoded.permute(0, 2, 1, 3).reshape(-1, self.history, encoded.size(-1)) - hidden = self.temporal(temporal)[:, -1] - preds = self.head(hidden) - return preds.view(x.size(0), x.size(2), -1) + index = {f: i for i, f in enumerate(features)} + return {name: data[..., [index[f] for f in feats]] for name, feats in grouped.items()} + + def _forward_data(self, data: Mapping[str, Any]): + if not isinstance(data, Mapping) or "x_s" not in data: + raise ValueError("GoogleFloodForecasting expects a mapping with 'x_s' and the dynamic inputs.") + if "x_d" in data and "x_d_hindcast" not in data and "x_d_forecast" not in data: + if self.lead_time != 0 or self.hindcast_inputs_grouped != self.forecast_inputs_grouped: + raise ValueError( + "'x_d' (streamflow layout) needs lead_time=0 and identical hindcast and forecast groups; " + "pass x_d_hindcast and x_d_forecast instead." + ) + hindcast_data = forecast_data = data["x_d"] + else: + if "x_d_hindcast" not in data or "x_d_forecast" not in data: + raise ValueError("GoogleFloodForecasting expects 'x_d_hindcast' and 'x_d_forecast'.") + hindcast_data, forecast_data = data["x_d_hindcast"], data["x_d_forecast"] + x_s = data["x_s"] + if not isinstance(x_s, torch.Tensor) or x_s.ndim != 2 or x_s.shape[1] != len(self.static_attributes): + shape = tuple(x_s.shape) if isinstance(x_s, torch.Tensor) else type(x_s).__name__ + raise ValueError(f"x_s must have shape (batch, {len(self.static_attributes)}), got {shape}.") + hindcast = self._group_tensors(hindcast_data, self.hindcast_features, self.hindcast_inputs_grouped, "hindcast") + forecast = self._group_tensors(forecast_data, self.forecast_features, self.forecast_inputs_grouped, "forecast") + total = self.seq_length + self.lead_time + for name, tensor in hindcast.items(): + if name not in self.shared_groups and (tensor.shape[0] != x_s.shape[0] or tensor.shape[1] > total): + raise ValueError(f"Hindcast group {name!r} must have shape (batch, <= {total}, ...), got {tuple(tensor.shape)}.") + for name, tensor in forecast.items(): + if tensor.shape[0] != x_s.shape[0] or tensor.shape[1] != total: + raise ValueError( + f"Forecast group {name!r} must have shape (batch, seq_length + lead_time = {total}, ...), " + f"got {tuple(tensor.shape)}." + ) + return x_s, hindcast, forecast + + # -- forward (reference logic) --------------------------------------------------------------------- + def forward(self, data: Mapping[str, Any]) -> Dict[str, torch.Tensor]: + x_s, hindcast_features, forecast_features = self._forward_data(data) + static_embedding = self.static_embedding_fc(x_s) + mean_hindcast_embedding, mean_forecast_embedding = self._calc_mean_embeddings( + hindcast_features, forecast_features, static_embedding + ) + hindcast_missing = self._missing_steps(mean_hindcast_embedding) + forecast_missing = hindcast_missing | self._missing_steps(mean_forecast_embedding) + hindcast_state = self._calc_lstm(self.hindcast_lstm, mean_hindcast_embedding, static_embedding) + forecast_state = self._calc_lstm( + self.forecast_lstm, mean_forecast_embedding, static_embedding, other_inputs=hindcast_state + ) + return { + key: value.masked_fill(forecast_missing, float("nan")) + for key, value in self.head(self.dropout(forecast_state)).items() + } + + def point_prediction(self, outputs: Mapping[str, torch.Tensor]) -> torch.Tensor: + """Deterministic prediction ``(batch, time, n_targets)`` (the CMAL mixture mean).""" + return self.head.point_prediction(outputs) + + def _calc_mean_embeddings(self, hindcast_features, forecast_features, static_embedding): + def embed(networks: nn.ModuleDict, features: Dict[str, torch.Tensor], append_nan: bool) -> List[torch.Tensor]: + return [ + self._calc_dynamic_embedding(fc, features[name], static_embedding, append_nan) + for name, fc in networks.items() + ] + + hindcast = embed(self.hindcast_embeddings_fc, hindcast_features, append_nan=True) + forecast = embed(self.forecast_embeddings_fc, forecast_features, append_nan=False) + shared = embed(self.shared_embeddings_fc, forecast_features, append_nan=False) # shared use forecast data + return self._masked_mean(hindcast + shared), self._masked_mean(forecast + shared) + + @staticmethod + def _append_static_embedding(embedding: torch.Tensor, static_embedding: torch.Tensor) -> torch.Tensor: + repeated = static_embedding.unsqueeze(1).repeat(1, embedding.shape[1], 1) + return torch.cat([embedding, repeated], dim=-1) + + def _add_nan_padding(self, embedding: torch.Tensor) -> torch.Tensor: + padding = torch.full( + (embedding.shape[0], self.seq_length + self.lead_time - embedding.shape[1], embedding.shape[2]), + np.nan, + device=embedding.device, + ) + return torch.cat([embedding, padding], dim=1) + + @staticmethod + def _masked_mean(tensors: List[torch.Tensor]) -> torch.Tensor: + merged = torch.cat([e.unsqueeze(-1) for e in tensors], dim=-1) + return torch.nanmean(merged, dim=-1) + + def _calc_dynamic_embedding(self, network: nn.Module, dynamic_data: torch.Tensor, + static_embedding: torch.Tensor, append_nan: bool) -> torch.Tensor: + # Steps with missing inputs are zeroed before the network and set back to NaN afterwards. + nan_mask = torch.isnan(dynamic_data).any(dim=-1, keepdim=True) + dynamic_data = dynamic_data.masked_fill(nan_mask, 0.0) + output = network(self._append_static_embedding(dynamic_data, static_embedding)) + output = output.masked_fill(nan_mask, float("nan")) + if append_nan: + output = self._add_nan_padding(output) + return output + + @staticmethod + def _missing_steps(masked_mean_embedding: torch.Tensor) -> torch.Tensor: + """Steps with no valid input and every step after the first such step, (batch, time, 1).""" + missing = torch.isnan(masked_mean_embedding).any(dim=-1, keepdim=True) + return torch.cummax(missing.to(torch.int8), dim=1).values.bool() + + def _calc_lstm(self, lstm: nn.LSTM, masked_mean_embeddings: torch.Tensor, static_embedding: torch.Tensor, + other_inputs: Optional[torch.Tensor] = None) -> torch.Tensor: + if other_inputs is not None: + masked_mean_embeddings = torch.cat([masked_mean_embeddings, other_inputs], dim=-1) + lstm_inputs = self._append_static_embedding(masked_mean_embeddings, static_embedding) + lstm_inputs = lstm_inputs.nan_to_num(nan=0.0) # missing steps are zero-filled; outputs masked later + output, _ = lstm(input=lstm_inputs) + return output + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def floodhub_checkpoint_path(cache_dir: Optional[Union[str, Path]] = None) -> Path: + """Local copy of the released FloodHub weights, downloaded (and sha256-checked) on first use.""" + root = Path(cache_dir) if cache_dir is not None else Path(torch.hub.get_dir()) / "checkpoints" + path = root / FLOODHUB_WEIGHTS["filename"] + if path.exists() and _sha256(path) == FLOODHUB_WEIGHTS["sha256"]: + return path + root.mkdir(parents=True, exist_ok=True) + torch.hub.download_url_to_file(FLOODHUB_WEIGHTS["url"], str(path), hash_prefix=FLOODHUB_WEIGHTS["sha256"], progress=False) + return path + + +def load_floodhub_state_dict(path: Optional[Union[str, Path]] = None) -> Dict[str, torch.Tensor]: + """State dict of the released model (``_orig_mod.`` prefix of the compiled model removed).""" + path = floodhub_checkpoint_path() if path is None else Path(path) + state = torch.load(path, map_location="cpu", weights_only=True) + prefix = "_orig_mod." + return {(key[len(prefix):] if key.startswith(prefix) else key): value for key, value in state.items()} + + +def _streamflow_config(n_dynamic: int, n_static: int) -> Dict[str, Any]: + features = [f"x_d_{i}" for i in range(int(n_dynamic))] + return { + **FLOODHUB_CONFIG, + "static_attributes": int(n_static), + "hindcast_inputs": {"x_d": features}, + "forecast_inputs": {"x_d": features}, + "lead_time": 0, + } def google_flood_forecasting_builder( task: str, - input_dim: int = 2, - hidden_dim: int = 64, - out_dim: int = 1, - history: int = 4, - dropout: float = 0.1, - **kwargs, + config: Optional[str] = "floodhub", + pretrained: bool = False, + weights_path: Optional[Union[str, Path]] = None, + n_dynamic: int = 5, + n_static: int = 27, + **overrides: Any, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError( - "google_flood_forecasting only supports task='regression', " - f"got {task!r}." - ) - return GoogleFloodForecasting( - input_dim=input_dim, - hidden_dim=hidden_dim, - out_dim=out_dim, - history=history, - dropout=dropout, - ) + """Build the model. + + ``config="floodhub"``: the released FloodHub model (84 static attributes; hindcast groups hres, + graphcast, imerg, cpc; forecast groups hres, graphcast; 365 + 7 days; hidden size 512; CMAL with 3 + components; 3,402,832 parameters). ``config="streamflow"``: the same architecture with one shared + group of ``n_dynamic`` daily inputs, ``n_static`` attributes and ``lead_time=0``, so it reads the + PyHazards streamflow layout ``{"x_d", "x_s"}`` (a PyHazards adaptation, not a Google configuration). + ``config=None``: everything from ``overrides``. Keyword ``overrides`` replace configuration entries + (``hidden_size``, ``seq_length``, embedding specs, ...). ``pretrained=True`` (or ``weights_path``) + loads the released weights with ``strict=True``. + """ + overrides.pop("name", None) + if task.lower() not in ("regression", "streamflow"): + raise ValueError(f"google_flood_forecasting supports task='regression' (streamflow), got {task!r}.") + if config == "floodhub": + cfg = dict(FLOODHUB_CONFIG) + elif config == "streamflow": + cfg = _streamflow_config(n_dynamic, n_static) + elif config is None: + cfg = {} + else: + raise ValueError(f"config must be 'floodhub', 'streamflow' or None, got {config!r}.") + unknown = set(overrides) - set(FLOODHUB_CONFIG) - {"output_activation"} + if unknown: + raise ValueError(f"Unexpected arguments for google_flood_forecasting: {sorted(unknown)}") + cfg.update(overrides) + model = GoogleFloodForecasting(**cfg) + if pretrained or weights_path is not None: + model.load_state_dict(load_floodhub_state_dict(weights_path), strict=True) + return model -__all__ = ["GoogleFloodForecasting", "google_flood_forecasting_builder"] +__all__ = [ + "CMAL", + "FC", + "FLOODHUB_CONFIG", + "FLOODHUB_STATIC_ATTRIBUTES", + "FLOODHUB_WEIGHTS", + "GoogleFloodForecasting", + "floodhub_checkpoint_path", + "google_flood_forecasting_builder", + "load_floodhub_state_dict", + "lstm_init", +] diff --git a/pyhazards/models/gpd.py b/pyhazards/models/gpd.py index bb034f49..b993ddb5 100644 --- a/pyhazards/models/gpd.py +++ b/pyhazards/models/gpd.py @@ -1,50 +1,304 @@ +"""Generalized Phase Detection (GPD): a P / S / noise classifier for 4-s three-component windows. + +Ross, Meier, Hauksson & Heaton, "Generalized Seismic Phase Detection with Deep Learning", +Bull. Seismol. Soc. Am. 108(5A):2894-2901, 2018 (https://doi.org/10.1785/0120180080, arXiv:1805.01075). + +Port of the official release interseismic/generalized-phase-detection at commit +``ea81ef17d204797de6a99d277fd2b9407fc77df7`` (MIT License, Copyright (c) 2018 Zachary E. Ross): +the network is the Keras 2.2.2 ``Sequential`` stored in ``model_pol.json`` (whose weights are +``model_pol_best.hdf5``), and :meth:`GPD.annotate` / :meth:`GPD.extract_picks` follow the sliding-window +picker of ``gpd_predict.py``. + +Network (input: 400 samples = 4 s at 100 Hz, channels N, E, Z): four blocks of ``Conv1D`` ('same' +padding; 32 / 64 / 128 / 256 filters, kernels 21 / 15 / 11 / 9) + ``BatchNormalization`` + ReLU + +``MaxPooling1D(2)``, ``Flatten`` (25 x 256), two ``Dense(200)`` + ``BatchNormalization`` + ReLU, and +``Dense(3)`` + softmax over the classes (P, S, noise). 1,741,003 trainable parameters. + +Choices that differ from a literal transcription, without changing the network's numbers: + +- Inputs are ``(batch, channels, samples)``; Keras uses ``(batch, samples, channels)``. Keras' + ``Flatten`` is time-major on ``(25, 256)``, so the feature map is transposed before flattening and + ``dense_1`` keeps the Keras row order (its kernel loads with a plain transpose). +- BatchNorm (:class:`KerasBatchNorm1d`) reproduces Keras 2.2.2 with the TensorFlow backend, the + version that trained the released weights: ``eps=1e-3``; in training, outputs use the batch mean and + biased variance (as PyTorch), but the moving statistics are updated with the variance scaled by + ``n / (n - 1 - eps)`` and with TensorFlow's zero-debiased moving average (decay 0.99), so the first + update replaces the stored statistics by the batch's. PyTorch's ``BatchNorm1d`` would instead use + ``n / (n - 1)`` and a plain exponential average. +- Module names are the Keras layer names of ``model_pol.json`` (``conv1d_1``, ``batch_normalization_1``, + ..., ``dense_3``), so every Keras weight has an obvious counterpart (:func:`load_gpd_keras_weights`). +- Initialisation follows Keras: Glorot-uniform kernels (``VarianceScaling(1, fan_avg, uniform)`` in the + JSON), zero biases, BatchNorm ``gamma=1, beta=0``. Random draws cannot match TensorFlow's. +- The release wraps the network in Keras' multi-GPU ``Lambda``/``Concatenate`` layers; they only split + the batch across GPUs and are not ported. +""" + from __future__ import annotations +import re +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Union + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F + +from ._pretrained import cached_download +from ._seismic import KerasBatchNorm1d, TracePicks, WaveformPicker + +_REPO = "interseismic/generalized-phase-detection" +_COMMIT = "ea81ef17d204797de6a99d277fd2b9407fc77df7" +# Official weights (MIT, in the repository). Downloaded on first use, never bundled. +GPD_WEIGHTS: Dict[str, Dict[str, object]] = { + "original": { + "filename": "model_pol_best.hdf5", + "urls": (f"https://raw.githubusercontent.com/{_REPO}/{_COMMIT}/model_pol_best.hdf5",), + "sha256": "b6f1980f64c4e816d43759af7a54c93c1ec9dd3ad56793ce6a09aad66adf3868", + "license": "MIT", + }, +} -class GPD(nn.Module): - """Simple CNN baseline for generalized phase detection style picking.""" +_CONV_SPECS = ((32, 21), (64, 15), (128, 11), (256, 9)) +_DENSE_UNITS = 200 - def __init__(self, in_channels: int = 3, hidden_dim: int = 32, dropout: float = 0.1): + +class GPD(nn.Module, WaveformPicker): + """GPD window classifier: ``(batch, 3, 400)`` waveforms -> ``(batch, 3)`` P / S / noise probabilities. + + Inputs are 4-s windows at 100 Hz in the channel order N, E, Z, each scaled by its maximum absolute + amplitude (as :meth:`annotate` does). ``forward(x, logits=True)`` returns the values before the + softmax. + """ + + sampling_rate = 100.0 + component_order = "NEZ" + output_names = ("P", "S", "noise") + phase_channels = {"P": 0, "S": 1} + window_samples = 400 + pick_offset = 200 # gpd_predict.py: a window's pick time is its centre (half_dur = 2 s) + + def __init__(self, in_channels: int = 3, classes: int = 3): super().__init__() - self.features = nn.Sequential( - nn.Conv1d(in_channels, hidden_dim, kernel_size=9, padding=4), - nn.ReLU(), - nn.MaxPool1d(kernel_size=2), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=7, padding=3), - nn.ReLU(), - nn.MaxPool1d(kernel_size=2), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=5, padding=2), - nn.ReLU(), - nn.AdaptiveAvgPool1d(1), - ) - self.head = nn.Sequential( - nn.Flatten(), - nn.Dropout(dropout), - nn.Linear(hidden_dim, hidden_dim), - nn.ReLU(), - nn.Linear(hidden_dim, 2), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("GPD expects inputs shaped (batch, channels, length).") - return self.head(self.features(x)) + if in_channels <= 0 or classes <= 0: + raise ValueError(f"in_channels and classes must be positive, got {in_channels} and {classes}.") + self.in_channels = int(in_channels) + self.classes = int(classes) + channels = self.in_channels + for index, (filters, kernel) in enumerate(_CONV_SPECS, start=1): + setattr(self, f"conv1d_{index}", nn.Conv1d(channels, filters, kernel, padding=kernel // 2)) + setattr(self, f"batch_normalization_{index}", KerasBatchNorm1d(filters, zero_debias=True)) + channels = filters + flat = (self.window_samples // 2 ** len(_CONV_SPECS)) * channels # 25 x 256 = 6400 + self.dense_1 = nn.Linear(flat, _DENSE_UNITS) + self.batch_normalization_5 = KerasBatchNorm1d(_DENSE_UNITS, zero_debias=True) + self.dense_2 = nn.Linear(_DENSE_UNITS, _DENSE_UNITS) + self.batch_normalization_6 = KerasBatchNorm1d(_DENSE_UNITS, zero_debias=True) + self.dense_3 = nn.Linear(_DENSE_UNITS, self.classes) + self.reset_parameters() + + def reset_parameters(self) -> None: + """Keras initialisation: Glorot-uniform kernels, zero biases, BatchNorm ones / zeros.""" + for module in self.modules(): + if isinstance(module, (nn.Conv1d, nn.Linear)): + nn.init.xavier_uniform_(module.weight) + nn.init.zeros_(module.bias) + elif isinstance(module, nn.BatchNorm1d): + module.reset_parameters() + + def forward(self, x: torch.Tensor, logits: bool = False) -> torch.Tensor: + if x.ndim != 3 or x.shape[1] != self.in_channels or x.shape[2] != self.window_samples: + raise ValueError( + f"GPD expects windows shaped (batch, {self.in_channels}, {self.window_samples}) " + f"(channels N, E, Z at 100 Hz), got shape {tuple(x.shape)}." + ) + for index in range(1, len(_CONV_SPECS) + 1): + conv = getattr(self, f"conv1d_{index}") + norm = getattr(self, f"batch_normalization_{index}") + x = F.max_pool1d(torch.relu(norm(conv(x))), 2) + x = x.transpose(1, 2).flatten(1) # Keras Flatten on (time, channels) + x = torch.relu(self.batch_normalization_5(self.dense_1(x))) + x = torch.relu(self.batch_normalization_6(self.dense_2(x))) + x = self.dense_3(x) + return x if logits else torch.softmax(x, dim=-1) + + def sliding_windows(self, waveforms: torch.Tensor, stride: int = 10) -> torch.Tensor: + """``(batch, n_windows, channels, 400)`` windows, each divided by its max absolute amplitude. + + ``gpd_predict.py``: ``sliding_window(data, 400, stepsize=n_shift)`` per channel and + ``tr_win / max(|tr_win|)`` over channels and samples. An all-zero window (where the official + code divides by zero and returns NaN) is left at zero. + """ + if waveforms.ndim != 3 or waveforms.shape[1] != self.in_channels: + raise ValueError( + f"GPD.annotate expects waveforms shaped (batch, {self.in_channels}, samples), " + f"got shape {tuple(waveforms.shape)}." + ) + if waveforms.shape[-1] < self.window_samples: + raise ValueError( + f"GPD.annotate needs at least {self.window_samples} samples, got shape {tuple(waveforms.shape)}." + ) + if int(stride) < 1: + raise ValueError(f"stride must be a positive number of samples, got {stride}.") + windows = waveforms.unfold(-1, self.window_samples, int(stride)).transpose(1, 2) + scale = windows.abs().amax(dim=(-2, -1), keepdim=True) + return windows / torch.where(scale == 0, torch.ones_like(scale), scale) + + def annotate(self, waveforms: torch.Tensor, stride: int = 10, batch_size: int = 3000) -> torch.Tensor: + """Sliding-window class probabilities ``(batch, 3, n_windows)`` of ``(batch, 3, samples)`` traces. + + Window ``i`` covers samples ``[i * stride, i * stride + 400)`` and is assigned to its centre, + sample ``i * stride + 200``. Windows are normalised in the input's dtype and then cast to the + model's dtype (``gpd_predict.py`` normalises in float64 and Keras casts to float32). Filtering + (3-20 Hz band-pass in ``gpd_predict.py``) is left to the caller. + """ + windows = self.sliding_windows(waveforms, stride=stride) + batch, n_windows = windows.shape[:2] + flat = windows.reshape(batch * n_windows, self.in_channels, self.window_samples) + flat = flat.to(self.dense_3.weight.dtype) + outputs = [self(flat[start : start + batch_size]) for start in range(0, flat.shape[0], int(batch_size))] + probabilities = torch.cat(outputs) if outputs else flat.new_zeros((0, self.classes)) + return probabilities.reshape(batch, n_windows, self.classes).transpose(1, 2) + + def extract_picks( + self, + annotations: Union[torch.Tensor, np.ndarray], + min_proba: float = 0.95, + trigger_off: float = 0.1, + stride: int = 10, + ) -> List[TracePicks]: + """Picks from :meth:`annotate` output with the ``gpd_predict.py`` rule. + + Per phase: ``trigger_onset(prob, min_proba, 0.1)`` over the window sequence; triggers with + ``on == off`` are skipped; the pick is the window with the highest probability in + ``prob[on:off]`` (``off`` excluded, as in the official slice), placed at + ``window * stride + 200``. ``min_proba`` defaults to the repository's 0.95 (the paper reports + detections at 0.98). Thresholds are compared in the dtype of the probabilities, as NumPy does + for the official float32 Keras outputs. + """ + from ..metrics.picking import trigger_onset + + values = annotations.detach().cpu().numpy() if isinstance(annotations, torch.Tensor) else np.asarray(annotations) + if values.ndim != 3 or values.shape[1] < max(self.phase_channels.values()) + 1: + raise ValueError( + f"GPD.extract_picks expects annotations shaped (batch, {self.classes}, n_windows), " + f"got shape {values.shape}." + ) + picks: List[TracePicks] = [] + for trace in values: + trace_picks: TracePicks = {} + for phase, channel in self.phase_channels.items(): + prob = trace[channel] + on_threshold = float(np.asarray(min_proba, dtype=prob.dtype)) + off_threshold = float(np.asarray(trigger_off, dtype=prob.dtype)) + phase_picks = [] + for on, off in trigger_onset(prob, on_threshold, off_threshold): + if off == on: + continue + window = int(np.argmax(prob[on:off])) + int(on) + phase_picks.append((float(window * int(stride) + self.pick_offset), float(prob[window]))) + trace_picks[phase] = phase_picks + picks.append(trace_picks) + return picks + + +_KERAS_NAME = re.compile( + r"^(?P(conv1d|batch_normalization|dense)_\d+)(_\d+)?/(?Pkernel|bias|gamma|beta|moving_mean|moving_variance):0$" +) +_WEIGHT_TARGETS = { + "kernel": "weight", + "bias": "bias", + "gamma": "weight", + "beta": "bias", + "moving_mean": "running_mean", + "moving_variance": "running_var", +} + + +def _keras_weight_arrays(path: Union[str, Path]) -> Dict[str, np.ndarray]: + import h5py + + arrays: Dict[str, np.ndarray] = {} + with h5py.File(path, "r") as handle: + root = handle["model_weights"] if "model_weights" in handle else handle + + def visit(name, obj): + if isinstance(obj, h5py.Dataset): + arrays[name] = np.asarray(obj) + + root.visititems(visit) + return arrays + + +def load_gpd_keras_weights(model: GPD, path: Union[str, Path]) -> GPD: + """Load a Keras GPD weight file (``model_pol_best.hdf5``) into ``model``; every tensor must match. + + Keras names (``sequential_1/conv1d_1_1/kernel:0``, ``.../batch_normalization_1_1/moving_mean:0``, + ...) map to the module of the same Keras layer name; ``Conv1D`` kernels ``(k, in, out)`` and + ``Dense`` kernels ``(in, out)`` are transposed to PyTorch layouts. + """ + state = model.state_dict() + expected = {key for key in state if not key.endswith("num_batches_tracked")} + loaded: Dict[str, torch.Tensor] = {} + for name, array in _keras_weight_arrays(path).items(): + match = _KERAS_NAME.match("/".join(name.split("/")[-2:])) + if match is None: + raise ValueError(f"Unexpected tensor {name!r} in {path}.") + key = f"{match.group('layer')}.{_WEIGHT_TARGETS[match.group('weight')]}" + if key not in expected: + raise ValueError(f"Keras tensor {name!r} has no counterpart ({key!r}) in GPD.") + tensor = torch.from_numpy(np.ascontiguousarray(array)) + if match.group("weight") == "kernel": + tensor = tensor.permute(2, 1, 0) if tensor.ndim == 3 else tensor.t() + if tuple(tensor.shape) != tuple(state[key].shape): + raise ValueError(f"{name!r} has shape {tuple(array.shape)}, which does not fit {key!r} {tuple(state[key].shape)}.") + if key in loaded: + raise ValueError(f"{path} holds more than one tensor for {key!r}.") + loaded[key] = tensor.to(state[key].dtype).contiguous() + missing = sorted(expected - set(loaded)) + if missing: + raise ValueError(f"{path} lacks tensors for {missing}.") + model.load_state_dict({**{k: v for k, v in state.items() if k.endswith("num_batches_tracked")}, **loaded}, strict=True) + return model + + +def gpd_weights_path(name: str = "original") -> Path: + """Local path of the official weights (downloaded and checked against the pinned sha256).""" + if name not in GPD_WEIGHTS: + raise ValueError(f"Unknown GPD weights {name!r}; expected one of {sorted(GPD_WEIGHTS)}.") + spec = GPD_WEIGHTS[name] + return cached_download("gpd", str(spec["filename"]), tuple(spec["urls"]), str(spec["sha256"])) def gpd_builder( task: str, in_channels: int = 3, - hidden_dim: int = 32, - dropout: float = 0.1, + pretrained: Optional[Union[bool, str, Path]] = None, **kwargs, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("GPD only supports regression-style phase picking outputs.") - return GPD(in_channels=in_channels, hidden_dim=hidden_dim, dropout=dropout) + """GPD (Ross et al. 2018). ``task``: ``"classification"`` or ``"picking"`` (the same model). + + ``forward`` classifies ``(batch, 3, 400)`` windows; :meth:`GPD.annotate` and + :meth:`GPD.extract_picks` pick longer traces with the official sliding window. ``pretrained``: + ``True`` / ``"original"`` for the released weights (``model_pol_best.hdf5``, MIT) or a path to a + Keras weight file of the same network. + """ + kwargs.pop("name", None) + if kwargs: + raise TypeError(f"gpd_builder got unexpected arguments {sorted(kwargs)}.") + if task.lower() not in ("classification", "picking"): + raise ValueError(f"gpd supports task='classification' or 'picking', got {task!r}.") + model = GPD(in_channels=in_channels) + if pretrained is not None and pretrained is not False: + if int(in_channels) != 3: + raise ValueError(f"The released GPD weights need in_channels=3, got {in_channels}.") + if pretrained is True or str(pretrained) in GPD_WEIGHTS: + path = gpd_weights_path("original" if pretrained is True else str(pretrained)) + else: + path = Path(pretrained) + load_gpd_keras_weights(model, path) + return model -__all__ = ["GPD", "gpd_builder"] +__all__ = ["GPD", "GPD_WEIGHTS", "KerasBatchNorm1d", "gpd_builder", "gpd_weights_path", "load_gpd_keras_weights"] diff --git a/pyhazards/models/graphcast_tc.py b/pyhazards/models/graphcast_tc.py deleted file mode 100644 index f61fb445..00000000 --- a/pyhazards/models/graphcast_tc.py +++ /dev/null @@ -1,67 +0,0 @@ -from __future__ import annotations - -import torch -import torch.nn as nn - - -class GraphCastTC(nn.Module): - """Experimental wrapper-style GraphCast storm adapter.""" - - def __init__( - self, - input_dim: int = 8, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - num_layers: int = 2, - num_heads: int = 4, - dropout: float = 0.1, - ): - super().__init__() - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.proj = nn.Linear(input_dim, hidden_dim) - encoder_layer = nn.TransformerEncoderLayer( - d_model=hidden_dim, - nhead=num_heads, - dim_feedforward=2 * hidden_dim, - dropout=dropout, - batch_first=True, - ) - self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) - self.head = nn.Linear(hidden_dim, self.horizon * self.output_dim) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("GraphCastTC expects inputs shaped (batch, history, features).") - encoded = self.encoder(self.proj(x)) - preds = self.head(encoded.mean(dim=1)) - return preds.view(x.size(0), self.horizon, self.output_dim) - - -def graphcast_tc_builder( - task: str, - input_dim: int = 8, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - num_layers: int = 2, - num_heads: int = 4, - dropout: float = 0.1, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("GraphCastTC only supports regression for track/intensity forecasting.") - return GraphCastTC( - input_dim=input_dim, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - num_layers=num_layers, - num_heads=num_heads, - dropout=dropout, - ) - - -__all__ = ["GraphCastTC", "graphcast_tc_builder"] diff --git a/pyhazards/models/hurricast.py b/pyhazards/models/hurricast.py index 0c24cfde..6c6cd418 100644 --- a/pyhazards/models/hurricast.py +++ b/pyhazards/models/hurricast.py @@ -1,67 +1,863 @@ +"""Hurricast (HUML): multimodal 24-hour tropical cyclone intensity and track forecasts. + +Paper: L. Boussioux, C. Zeng, T. Guenais and D. Bertsimas, "Hurricane Forecasting: A Novel Multimodal +Machine Learning Framework", Weather and Forecasting 37(6), 817-831 (2022), doi:10.1175/WAF-D-21-0091.1 +(preprint arXiv 2011.06125). + +The official repository (github.com/leobix/hurricast) has no LICENSE file (its README claims MIT and +links a LICENSE that does not exist), so this module is written from the paper (Section 3 and Appendix +A1) and the configuration values of the released code; the official code is used only as a test +oracle (tests/oracle/test_hurricast_oracle.py) and is never copied. Module and parameter names follow +the official ``ExperimentalHurricast`` so that its state dicts load with ``strict=True`` into +:class:`HurricastEncoderDecoder` (``Hurricast.network``), and parameters are created in the official +order, so the same seed gives the same initial weights. + +Hurricast forecasts one 24-hour lead time in three steps: + +1. **Feature extraction.** For 8 three-hourly time steps (t-21 h ... t), the nine ERA5 maps (u, v and + geopotential z at 225, 500 and 700 hPa, 25 x 25 degrees at 1 degree around the storm) of every step + go through a CNN encoder (three 3 x 3 convolutions with BatchNorm and ReLU, two 2 x 2 max poolings, + then dense layers) to a 128-d embedding. The 14 statistical features of the step are concatenated in + front of it and the 8-step sequence goes through a decoder: a Transformer (2 layers, 2 heads, model + width 142, feed-forward 128, sinusoidal positional encoding, mean pooling over time, tanh) or a + recurrent decoder. A linear layer predicts the standardised 24-hour intensity (``c = 1``) or the + latitude / longitude displacement (``c = 2``); the network is trained with MSE plus an L2 penalty and + then frozen. +2. **Fusion.** The decoder output (everything but the last linear layer) is the reanalysis embedding. + It is appended to the flattened statistical data of the 8 steps. +3. **Forecast.** One XGBoost regressor per target (intensity; latitude displacement; longitude + displacement) is trained on these vectors. + +:class:`Hurricast` holds both stages: ``network`` (a :class:`HurricastEncoderDecoder`) and ``xgboost`` +(a :class:`pyhazards.models.classical.EstimatorModule`). ``predictor="network"`` uses the network's +own linear head instead of XGBoost; ``use_embeddings=False`` gives HUML-(stat, xgb), XGBoost on the +statistical data alone. + +Paper and released code disagree in places; the released code is followed where it is the only +executable reference (it is what the oracle verifies) and the differences are listed in the model card: +the code's CNN has dense layers 4096 -> 576 -> 256 -> 128 (the paper's Fig. A1 shows 576 -> 128); the +code concatenates ``[statistics, embedding]`` (the paper writes ``[embedding, statistics]``); the paper's +GRU decoder (two unidirectional layers, all 8 hidden states concatenated, fully connected +1024-512-128-c) is not in the released code, whose recurrent presets are bidirectional LSTM / GRU / +RNN decoders reading the last hidden state (``lstm_config*``); the paper lists 31 statistical +features per step, the code's feature table has 30 (:data:`HURRICAST_STAT_FEATURES`) and the network +reads the first 14 (``d_model = 142 = 128 + 14``). +""" + from __future__ import annotations +import copy +import math +from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F +# --------------------------------------------------------------------------------------------------- +# Inputs -class Hurricast(nn.Module): - """Compact storm-track and intensity baseline for Wave 2 vertical slices.""" +#: The 30 statistical features of one time step, in the column order of the official feature tables +#: (``names`` in notebooks/Compute_results_*_Round2.ipynb). ``cat_*`` columns are categorical: the +#: day-of-year encoding, the Saffir-Simpson category value, and one-hot basin (``AN`` is IBTrACS' North +#: Atlantic ``NA``) and storm nature. ``STORM_DISPLACEMENT_X`` / ``_Y`` are the latitude / longitude +#: change (degrees) since the previous 3-hour step. +HURRICAST_STAT_FEATURES: Tuple[str, ...] = ( + "LAT", "LON", "WMO_WIND", "WMO_PRES", "DIST2LAND", + "STORM_SPEED", "cat_cos_day", "cat_sign_day", "COS_STORM_DIR", "SIN_STORM_DIR", + "COS_LAT", "SIN_LAT", "COS_LON", "SIN_LON", "cat_storm_category", "cat_basin_AN", + "cat_basin_EP", "cat_basin_NI", "cat_basin_SA", + "cat_basin_SI", "cat_basin_SP", "cat_basin_WP", "cat_nature_DS", "cat_nature_ET", + "cat_nature_MX", "cat_nature_NR", "cat_nature_SS", "cat_nature_TS", + "STORM_DISPLACEMENT_X", "STORM_DISPLACEMENT_Y", +) +#: The encoder-decoder reads the first 14 statistical features of every step (``x_stat[:, :, :14]``). +HURRICAST_NETWORK_STAT_FEATURES = 14 +#: Reanalysis channels of one step: u, v, z (official variable order) at 225, 500, 700 hPa. +HURRICAST_MAP_CHANNELS: Tuple[str, ...] = tuple(f"{var}{level}" for var in ("u", "v", "z") for level in (225, 500, 700)) +HURRICAST_WINDOW = 8 # 8 steps of 3 hours: t-21 h ... t +HURRICAST_GRID = 25 # 25 x 25 one-degree pixels + +# --------------------------------------------------------------------------------------------------- +# Configuration presets of the released code (scripts/config.py). Values only; the networks below are +# written from the paper. ``transformer_config`` is the paper's Appendix A1c decoder. + +_CNN_LAYOUT = ( + ("conv", 64), + ("conv", 64), + ("maxpool", None), + ("conv", 256), + ("maxpool", None), + ("flatten", 256 * 4 * 4), + ("linear", 576), + ("linear", 256), + ("fc", 128), +) + +ENCODER_CONFIGS: Dict[str, Dict[str, Any]] = { + # One CNN over the 9 maps of a step. + "full_encoder_config": {"n_in": 9, "n_out": 128, "hidden_configuration": _CNN_LAYOUT}, + # Three CNNs (u maps, v maps, z maps) and a linear layer that recombines their outputs. + "split_encoder_config": {"n_in": 3, "n_out": 128, "hidden_configuration": _CNN_LAYOUT}, +} + +DECODER_CONFIGS: Dict[str, Tuple[str, Dict[str, Any]]] = { + "transformer_config": ("transformer", {"n_in": 142, "n_head": 2, "dim_feedforward": 128, "num_layers": 2, "dropout": 0.0, "window_size": None, "n_out_unroll": None, "max_len_pe": 10, "pool_method": "default", "activation": "tanh"}), + "transformer_config_4": ("transformer", {"n_in": 142, "n_head": 2, "dim_feedforward": 128, "num_layers": 4, "dropout": 0.0, "window_size": None, "n_out_unroll": None, "max_len_pe": 10, "pool_method": "default", "activation": "tanh"}), + "transformer_config_68": ("transformer", {"n_in": 142, "n_head": 1, "dim_feedforward": 64, "num_layers": 1, "dropout": 0.0, "window_size": None, "n_out_unroll": None, "max_len_pe": 10, "pool_method": "default", "activation": "tanh"}), + "transformer_config_noviz": ("transformer", {"n_in": 10, "n_head": 2, "dim_feedforward": 512, "num_layers": 6, "dropout": 0.2, "window_size": None, "n_out_unroll": None, "max_len_pe": 10, "pool_method": "default", "activation": "tanh"}), + "lstm_config": ("recurrent", {"n_in": 142, "hidden_dim": 128, "rnn_num_layers": 2, "N_OUT": 128, "rnn_type": "lstm", "dropout": 0.1, "activation_fn": "tanh", "bidir": True}), + "lstm_config_4layers": ("recurrent", {"n_in": 142, "hidden_dim": 128, "rnn_num_layers": 4, "N_OUT": 128, "rnn_type": "gru", "dropout": 0.1, "activation_fn": "tanh", "bidir": True}), + "lstm_config_best_dis": ("recurrent", {"n_in": 142, "hidden_dim": 128, "rnn_num_layers": 4, "N_OUT": 128, "rnn_type": "gru", "dropout": 0.1, "activation_fn": "tanh", "bidir": True}), + "lstm_config_test_dis": ("recurrent", {"n_in": 142, "hidden_dim": 128, "rnn_num_layers": 2, "N_OUT": 128, "rnn_type": "rnn", "dropout": 0.1, "activation_fn": "tanh", "bidir": True}), +} + +#: XGBoost hyperparameters: the defaults of ``train_xgb_track`` / ``train_xgb_intensity`` in the official +#: scripts/run_embeddings.py. The paper gives only ranges (depth 6-9, 100-300 trees, learning rate +#: 0.03-0.15, subsample 0.6-0.9, column sampling 0.7-1, minimum child weight 1-5); these lie inside them. +HURRICAST_XGBOOST_PARAMS: Dict[str, Any] = { + "max_depth": 8, + "n_estimators": 140, + "learning_rate": 0.15, + "subsample": 0.7, + "min_child_weight": 5, +} + +#: Training settings of the encoder-decoder from the paper (Appendix A3c): Adam, batch 64, L2 weight 0.01, +#: learning rate 1e-3 for intensity and 4e-4 for track; best validation after about 30 epochs. +HURRICAST_TRAINING = { + "batch_size": 64, + "l2_reg": 0.01, + "learning_rate": {"intensity": 1e-3, "displacement": 4e-4}, + "epochs": 30, +} + +TARGETS = {"intensity": 1, "displacement": 2} + + +# --------------------------------------------------------------------------------------------------- +# Network + + +class HurricastCNNEncoder(nn.Module): + """CNN that maps the reanalysis maps of one time step ``(batch, n_in, 25, 25)`` to ``(batch, n_out)``. + + ``hidden_configuration`` lists the cells in order: ``("conv", c)`` is a 3 x 3 convolution (stride 1, + no padding) with ``c`` channels, BatchNorm and ReLU; ``("maxpool", None)`` a 2 x 2 max pooling with + stride 2; ``("flatten", n)`` flattens to ``n`` features; ``("linear", n)`` a dense layer with + BatchNorm and ReLU; ``("fc", n)`` a plain dense layer. All modules sit in ``layers``. + """ + + def __init__( + self, + n_in: int, + n_out: int, + hidden_configuration: Sequence[Tuple[str, Optional[int]]], + kernel_size: int = 3, + stride: int = 1, + padding: int = 0, + groups: int = 1, + pool_kernel_size: int = 2, + pool_stride: int = 2, + pool_padding: int = 0, + ): + super().__init__() + self.n_in = int(n_in) + self.n_out = int(n_out) + self.hidden_configuration = tuple(tuple(cell) for cell in hidden_configuration) + layers: List[nn.Module] = [] + width = self.n_in + for kind, size in self.hidden_configuration: + if kind == "conv": + layers += [nn.Conv2d(width, size, kernel_size, stride=stride, padding=padding, groups=groups, bias=True), nn.BatchNorm2d(size), nn.ReLU()] + elif kind == "maxpool": + layers.append(nn.MaxPool2d(pool_kernel_size, stride=pool_stride, padding=pool_padding)) + elif kind == "flatten": + layers.append(nn.Flatten()) + elif kind == "linear": + layers += [nn.Linear(width, size), nn.BatchNorm1d(size), nn.ReLU()] + elif kind == "fc": + layers.append(nn.Linear(width, size)) + else: + raise ValueError(f"unknown CNN cell {kind!r}; use conv, maxpool, flatten, linear or fc") + if size is not None: + width = int(size) + if width != self.n_out: + raise ValueError(f"the last cell gives {width} features, expected n_out={self.n_out}") + self.layers = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.layers(x) + + +class _PositionalEncoding(nn.Module): + """Sinusoidal position encoding, ``P[i, 2j] = sin(i / 10000^(2j/d))``, ``P[i, 2j+1] = cos(...)``, then dropout.""" + + def __init__(self, d_model: int, dropout: float, max_len: int = 5000): + super().__init__() + self.dropout = nn.Dropout(p=dropout) + pe = torch.zeros(max_len, d_model) + position = torch.arange(0, max_len).unsqueeze(1) + div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) + pe[:, 0::2] = torch.sin(position * div_term) + pe[:, 1::2] = torch.cos(position * div_term) + self.register_buffer("pe", pe.unsqueeze(0)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.dropout(x + self.pe[:, : x.size(1)]) + + +def _activation(name: str): + if name == "relu": + return F.relu + if name == "tanh": + return torch.tanh + raise ValueError(f"activation must be 'relu' or 'tanh', got {name!r}") + + +class HurricastTransformerDecoder(nn.Module): + """Transformer decoder: positional encoding, ``num_layers`` post-norm encoder layers, pooling, activation. + + Input ``(batch, T, n_in)``; output ``(batch, n_in)`` (``pool_method`` ``"default"`` / ``"mean"``: + mean over time; ``"unroll"``: a linear layer on the flattened sequence, output ``n_out_unroll``). + """ def __init__( self, - input_dim: int = 8, - hidden_dim: int = 64, - num_layers: int = 2, - horizon: int = 5, - output_dim: int = 3, + n_in: int = 512, + n_head: int = 4, + dim_feedforward: int = 2048, + num_layers: int = 6, dropout: float = 0.1, + window_size: Optional[int] = None, + n_out_unroll: Optional[int] = None, + max_len_pe: int = 10, + pool_method: str = "default", + activation: str = "tanh", + ): + super().__init__() + self.n_in = int(n_in) + self.n_head = int(n_head) + self.num_layers = int(num_layers) + self.dim_feedforward = int(dim_feedforward) + self.dropout = float(dropout) + self.window_size = window_size + self.n_out_unroll = n_out_unroll + layer = nn.TransformerEncoderLayer(d_model=self.n_in, nhead=self.n_head, dim_feedforward=self.dim_feedforward, dropout=self.dropout) + # The nested-tensor fast path only applies to padded batch-first input; it never changes outputs here. + self.transformer_layers = nn.TransformerEncoder(layer, num_layers=self.num_layers, enable_nested_tensor=False) + if pool_method not in ("default", "mean", "unroll"): + raise ValueError("pool_method must be 'default', 'mean' or 'unroll'") + self.pool_method = pool_method + if pool_method == "unroll": + if n_out_unroll is None or window_size is None: + raise ValueError("pool_method='unroll' needs window_size and n_out_unroll") + self.pool_linear = nn.Linear(int(window_size) * self.n_in, int(n_out_unroll)) + self.activation = activation + self.activation_fn = _activation(activation) + self.max_len_pe = int(max_len_pe) + self.pe = _PositionalEncoding(self.n_in, self.dropout, max_len=self.max_len_pe) + self.N_OUT = int(n_out_unroll) if pool_method == "unroll" else self.n_in + + def forward(self, x: torch.Tensor, xgb: bool = False): + out = self.pe(x) + out = self.transformer_layers(out.transpose(0, 1)).transpose(0, 1) # sequence-first inside + sequence = out + pooled = self.pool_linear(out.flatten(start_dim=1)) if self.pool_method == "unroll" else out.mean(1) + pooled = self.activation_fn(pooled) + return (pooled, sequence) if xgb else pooled + + +class HurricastRecurrentDecoder(nn.Module): + """Recurrent decoder of the released code (``ExpLSTM``): a bidirectional LSTM / GRU / RNN over the + sequence; the last layer's final forward and backward states go through a linear layer and an activation. + + Input ``(batch, T, n_in)``; output ``(batch, N_OUT)``. + """ + + def __init__( + self, + n_in: int, + hidden_dim: int, + rnn_num_layers: int, + N_OUT: int, + rnn_type: str = "gru", + dropout: float = 0.0, + activation_fn: str = "tanh", + bidir: bool = True, ): super().__init__() - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.encoder = nn.LSTM( - input_dim, - hidden_dim, - num_layers=num_layers, + cells = {"lstm": nn.LSTM, "gru": nn.GRU, "rnn": nn.RNN} + if rnn_type not in cells: + raise ValueError(f"rnn_type must be one of {sorted(cells)}, got {rnn_type!r}") + if not bidir: + raise ValueError("the recurrent decoder reads the last forward and backward states; it needs bidir=True") + self.n_in = int(n_in) + self.hidden_dim = int(hidden_dim) + self.rnn_num_layers = int(rnn_num_layers) + self.N_OUT = int(N_OUT) + self.rnn_type = rnn_type + self.bidir = bool(bidir) + self.dropout = float(dropout) + self.activation = activation_fn + self.rnn = cells[rnn_type]( + input_size=self.n_in, + hidden_size=self.hidden_dim, + num_layers=self.rnn_num_layers, + bidirectional=self.bidir, batch_first=True, - dropout=dropout if num_layers > 1 else 0.0, + dropout=self.dropout, + ) + self.fc = nn.Linear(self.hidden_dim * (1 + int(self.bidir)), self.N_OUT) + self.activation_fn = _activation(activation_fn) + + def forward(self, x: torch.Tensor, xgb: bool = False): + _, hidden = self.rnn(x) + if self.rnn_type == "lstm": + hidden = hidden[0] + out = self.activation_fn(self.fc(torch.cat((hidden[-2], hidden[-1]), dim=1))) + return (out, hidden) if xgb else out + + +class HurricastEncoderDecoder(nn.Module): + """The Hurricast encoder-decoder network (the official ``ExperimentalHurricast``). + + ``forward(x_stat, x_viz)`` takes ``x_stat`` ``(batch, T, n_stat)`` standardised statistical features + (14 for the paper's configuration) and ``x_viz`` ``(batch, T, 9, 25, 25)`` standardised reanalysis + maps and returns ``(batch, n_pred)``, the standardised 24-hour intensity (``n_pred = 1``) or latitude / + longitude displacement (``n_pred = 2``). Without an encoder (``encoder_config=None``) or with + ``x_viz=None`` the decoder reads ``x_stat`` alone; with ``no_stat=True`` it reads the map embeddings + alone. :meth:`get_embeddings` returns the decoder output, the input of the last linear layer. + """ + + def __init__( + self, + n_pred: int, + decoder_config: Mapping[str, Any], + encoder_config: Optional[Mapping[str, Any]] = None, + decoder_name: str = "transformer", + split_cnns: bool = False, + no_stat: bool = False, + ): + super().__init__() + self.n_pred = int(n_pred) + self.no_stat = bool(no_stat) + self.split_cnns = bool(split_cnns) + self.encoder_config = dict(encoder_config) if encoder_config is not None else None + self.decoder_name = decoder_name + self.decoder_config = dict(decoder_config) + # Creation order of the official network: encoder(s), recombination layer, decoder, predictor. + encoder: Optional[nn.Module] = None + recombine: Optional[nn.Linear] = None + if self.encoder_config is not None: + encoder = HurricastCNNEncoder(**self.encoder_config) + if self.split_cnns: + # Three copies of one initialised CNN (identical initial weights, as in the official code). + encoder = nn.ModuleList([copy.deepcopy(encoder) for _ in range(3)]) + recombine = nn.Linear(3 * self.encoder_config["n_out"], self.encoder_config["n_out"]) + self.encoder = encoder + self.recombine_encoders = recombine + if decoder_name == "transformer": + self.decoder = HurricastTransformerDecoder(**self.decoder_config) + elif decoder_name == "recurrent": + self.decoder = HurricastRecurrentDecoder(**self.decoder_config) + else: + raise ValueError("decoder_name must be 'transformer' or 'recurrent'") + self.predictor = nn.Linear(self.decoder.N_OUT, self.n_pred) + + @property + def embedding_dim(self) -> int: + return int(self.decoder.N_OUT) + + @property + def n_stat(self) -> int: + """Statistical features per step that the decoder expects (0 without statistics).""" + if self.no_stat and self.encoder is not None: + return 0 + width = self.decoder.n_in + if self.encoder is not None: + width -= self.encoder_config["n_out"] + return int(width) + + def _encode_step(self, maps: torch.Tensor) -> torch.Tensor: + if not self.split_cnns: + return self.encoder(maps).unsqueeze(1) + parts = torch.split(maps, 3, dim=1) # (u maps, v maps, z maps) + out = torch.cat([cnn(part) for part, cnn in zip(parts, self.encoder)], -1) + return self.recombine_encoders(out).unsqueeze(1) + + def encode(self, x_viz: torch.Tensor) -> torch.Tensor: + """``(batch, T, channels, 25, 25)`` -> ``(batch, T, 128)``; the CNN runs once per time step.""" + return torch.cat([self._encode_step(step) for step in x_viz.unbind(1)], dim=1) + + def _check(self, x_stat: Optional[torch.Tensor], x_viz: Optional[torch.Tensor]) -> None: + if x_viz is not None and self.encoder is not None: + n_in = self.encoder_config["n_in"] * (3 if self.split_cnns else 1) + if x_viz.ndim != 5 or x_viz.size(2) != n_in: + raise ValueError(f"x_viz must be shaped (batch, T, {n_in}, 25, 25), got shape {tuple(x_viz.shape)}") + uses_stat = x_viz is None or self.encoder is None or not (self.no_stat or x_stat is None) + if uses_stat: + if x_stat is None or x_stat.ndim != 3: + raise ValueError(f"x_stat must be shaped (batch, T, features), got {None if x_stat is None else tuple(x_stat.shape)}") + expected = self.decoder.n_in if (x_viz is None or self.encoder is None) else self.n_stat + if x_stat.size(-1) != expected: + raise ValueError(f"x_stat must have {expected} features per step, got shape {tuple(x_stat.shape)}") + + def fuse(self, x_stat: Optional[torch.Tensor], x_viz: Optional[torch.Tensor] = None) -> torch.Tensor: + """The decoder input: statistics, map embeddings, or ``[statistics, embeddings]`` per step.""" + self._check(x_stat, x_viz) + if x_viz is None or self.encoder is None: + return x_stat + if self.no_stat or x_stat is None: + return self.encode(x_viz) + return torch.cat([x_stat, self.encode(x_viz)], -1) + + def get_embeddings(self, x_stat: Optional[torch.Tensor], x_viz: Optional[torch.Tensor] = None, xgb: bool = False): + """Decoder output ``(batch, embedding_dim)``; with ``xgb=True`` also the decoder's sequence output + (Transformer) or final hidden states (recurrent), as the official ``get_embeddings(..., xgb=True)``.""" + return self.decoder(self.fuse(x_stat, x_viz), xgb=xgb) + + def forward(self, x_stat: Optional[torch.Tensor], x_viz: Optional[torch.Tensor] = None) -> torch.Tensor: + return self.predictor(self.get_embeddings(x_stat, x_viz)) + + +def hurricast_l2_penalty(module: nn.Module) -> torch.Tensor: + """Sum of squares of every parameter whose name contains ``weight`` (the paper's L2 term).""" + terms = [(param**2).sum() for name, param in module.named_parameters() if "weight" in name] + return torch.stack(terms).sum() if terms else torch.zeros(()) + + +def hurricast_training_loss(output: torch.Tensor, target: torch.Tensor, network: nn.Module, l2_reg: float) -> torch.Tensor: + """MSE plus ``2 / batch * l2_reg * sum(W**2)``, the scaling of the official training loop. + + ``output`` and ``target`` must have the same shape (the official loop compared ``(batch, 1)`` intensity + outputs with ``(batch,)`` targets, which broadcasts to ``(batch, batch)``; see the model card). + """ + if output.shape != target.shape: + raise ValueError(f"output shape {tuple(output.shape)} and target shape {tuple(target.shape)} differ") + loss = F.mse_loss(output, target) + if l2_reg > 0: + loss = loss + 2.0 / target.size(0) * l2_reg * hurricast_l2_penalty(network) + return loss + + +# --------------------------------------------------------------------------------------------------- +# XGBoost stage + + +def hurricast_xgboost_columns(window_size: int = HURRICAST_WINDOW, features: Sequence[str] = HURRICAST_STAT_FEATURES) -> List[str]: + """Names of the statistical columns XGBoost reads, in order. + + The official feature table holds the ``features`` of every step, step after step, with a ``_`` + suffix; it keeps a column when its name ends in ``_0`` (the oldest step, t-21 h) or does not start + with ``cat``: all numerical features of every step and the categorical ones of the first step only. + """ + names = [f"{name}_{index // len(features)}" for index, name in enumerate(list(features) * int(window_size))] + return [name for name in names if name.lower()[-2:] == "_0" or name.lower()[:3] != "cat"] + + +def hurricast_xgboost_features( + x_stat: Union[torch.Tensor, np.ndarray], + embeddings: Optional[Union[torch.Tensor, np.ndarray]] = None, + features: Sequence[str] = HURRICAST_STAT_FEATURES, +) -> np.ndarray: + """XGBoost input: the selected statistical columns of ``x_stat`` ``(batch, T, 30)``, then the embeddings.""" + stat = x_stat.detach().cpu().numpy() if isinstance(x_stat, torch.Tensor) else np.asarray(x_stat) + if stat.ndim != 3 or stat.shape[-1] != len(features): + raise ValueError(f"x_stat must be shaped (batch, T, {len(features)}) for the XGBoost stage, got shape {stat.shape}") + window = stat.shape[1] + all_names = [f"{name}_{index // len(features)}" for index, name in enumerate(list(features) * window)] + keep = set(hurricast_xgboost_columns(window, features)) + columns = [i for i, name in enumerate(all_names) if name in keep] + flat = stat.reshape(stat.shape[0], -1)[:, columns] + if embeddings is None: + return flat + emb = embeddings.detach().cpu().numpy() if isinstance(embeddings, torch.Tensor) else np.asarray(embeddings) + return np.concatenate([flat, emb.reshape(emb.shape[0], -1)], axis=1) + + +def _xgboost_estimator(params: Mapping[str, Any], n_targets: int): + from .classical import _import_xgboost + + xgboost = _import_xgboost() + estimator = xgboost.XGBRegressor(**params) + if n_targets == 1: + return estimator + from sklearn.multioutput import MultiOutputRegressor + + # One regressor per target (latitude and longitude displacement), as the official xgb_x / xgb_y. + return MultiOutputRegressor(estimator) + + +# --------------------------------------------------------------------------------------------------- +# Two-stage model + + +def _as_tensor(value: Any) -> torch.Tensor: + return value if isinstance(value, torch.Tensor) else torch.as_tensor(np.asarray(value), dtype=torch.float32) + + +class Hurricast(nn.Module): + """Hurricast forecaster: encoder-decoder embeddings plus XGBoost (or the network's own head). + + Input: a mapping with ``x_stat`` ``(batch, T, 30)`` (the statistical features of + :data:`HURRICAST_STAT_FEATURES`; the network reads the first 14, which must be standardised as for + training), ``x_viz`` ``(batch, T, 9, 25, 25)`` standardised ERA5 maps (not needed for + ``use_embeddings=False``), and for track forecasts ``position`` ``(batch, 2)``, the latitude and + longitude at the forecast time in degrees. + + ``forward`` returns ``(batch, 1)`` intensity 24 hours ahead (in the training targets' unit, knots for + IBTrACS) or ``(batch, 2)`` latitude / longitude displacement over 24 hours (degrees). + ``forecast`` turns them into benchmark forecasts: ``{"intensity": ...}`` or ``{"lat", "lon"}``. + + Train with :meth:`fit` (encoder-decoder by gradient descent, then XGBoost on its embeddings); + :class:`pyhazards.engine.Trainer` refuses ``fit``. The XGBoost stage is not part of ``state_dict()``; + use :meth:`save` / :meth:`load`. The network's parameters are ``network.*`` with the official names. + """ + + def __init__( + self, + target: str = "intensity", + predictor: str = "xgboost", + network: Optional[HurricastEncoderDecoder] = None, + use_embeddings: bool = True, + xgboost_params: Optional[Mapping[str, Any]] = None, + estimator: Any = None, + n_stat_features: int = len(HURRICAST_STAT_FEATURES), + config: Optional[Mapping[str, Any]] = None, + ): + super().__init__() + self.config = dict(config or {}) # builder arguments, used by load() + if target not in TARGETS: + raise ValueError(f"target must be one of {sorted(TARGETS)}, got {target!r}") + if predictor not in ("xgboost", "network"): + raise ValueError("predictor must be 'xgboost' or 'network'") + if predictor == "network" and network is None: + raise ValueError("predictor='network' needs the encoder-decoder network") + if predictor == "xgboost" and use_embeddings and network is None: + raise ValueError("use_embeddings=True needs the encoder-decoder network") + self.target = target + self.n_targets = TARGETS[target] + self.predictor = predictor + self.use_embeddings = bool(use_embeddings) and network is not None + self.n_stat_features = int(n_stat_features) + self.network = network + if network is not None and network.n_pred != self.n_targets: + raise ValueError(f"the network predicts {network.n_pred} values, target {target!r} needs {self.n_targets}") + self.xgboost_params = dict(HURRICAST_XGBOOST_PARAMS if xgboost_params is None else xgboost_params) + self.xgboost = None + if predictor == "xgboost": + from .classical import EstimatorModule + + model = estimator if estimator is not None else _xgboost_estimator(self.xgboost_params, self.n_targets) + self.xgboost = EstimatorModule(model, task="regression", name="hurricast_xgboost") + # Training-target standardisation (the official pipeline fits both stages on standardised targets). + self.register_buffer("target_mean", torch.zeros(self.n_targets)) + self.register_buffer("target_std", torch.ones(self.n_targets)) + + # -- inputs -------------------------------------------------------------------------------------- + def _unpack(self, inputs: Any, x_viz: Optional[torch.Tensor] = None): + if isinstance(inputs, Mapping): + x_stat, x_viz, position = inputs.get("x_stat"), inputs.get("x_viz"), inputs.get("position") + else: + x_stat, position = inputs, None + x_stat = None if x_stat is None else _as_tensor(x_stat).float() + x_viz = None if x_viz is None else _as_tensor(x_viz).float() + if x_stat is None or x_stat.ndim != 3: + raise ValueError(f"Hurricast needs x_stat shaped (batch, T, features), got {None if x_stat is None else tuple(x_stat.shape)}") + if self.predictor == "xgboost" and x_stat.size(-1) != self.n_stat_features: + raise ValueError(f"the XGBoost stage needs x_stat shaped (batch, T, {self.n_stat_features}), got shape {tuple(x_stat.shape)}") + if self.network is not None and self.network.encoder is not None and (self.predictor == "network" or self.use_embeddings) and x_viz is None: + raise ValueError("Hurricast with a map encoder needs x_viz shaped (batch, T, 9, 25, 25)") + return x_stat, x_viz, position + + def _network_stat(self, x_stat: torch.Tensor, x_viz: Optional[torch.Tensor]) -> Optional[torch.Tensor]: + network = self.network + uses_maps = x_viz is not None and network.encoder is not None + width = network.n_stat if uses_maps else network.decoder.n_in + if width == 0: + return None + if x_stat.size(-1) < width: + raise ValueError(f"the network reads {width} statistical features per step, x_stat has shape {tuple(x_stat.shape)}") + return x_stat[..., :width] + + def embeddings(self, inputs: Any) -> torch.Tensor: + """Reanalysis embeddings ``(batch, embedding_dim)`` of the frozen encoder-decoder (always in eval mode).""" + x_stat, x_viz, _ = self._unpack(inputs) + network, was_training = self.network, self.network.training + network.eval() + try: + return network.get_embeddings(self._network_stat(x_stat, x_viz), x_viz) + finally: + network.train(was_training) + + def xgboost_features(self, inputs: Any) -> np.ndarray: + """The vectors XGBoost reads: flattened statistics, then the embeddings (``use_embeddings``).""" + x_stat, _, _ = self._unpack(inputs) + embeddings = None + if self.use_embeddings: + with torch.no_grad(): + embeddings = self.embeddings(inputs) + return hurricast_xgboost_features(x_stat, embeddings) + + # -- targets ------------------------------------------------------------------------------------- + def model_targets(self, inputs: Any, targets: Any) -> torch.Tensor: + """Targets as the model predicts them: intensity ``(N, 1)`` or displacement ``(N, 2)``. + + Track targets may be given as displacement ``(N, 2)`` or as the observed position 24 hours + ahead ``(N, 1, 2)`` (latitude, longitude, the ``tc.track_intensity`` layout), which needs + ``position`` in ``inputs``. + """ + y = _as_tensor(targets).float() + if self.target == "intensity": + return y.reshape(-1, 1) + if y.ndim == 3: + position = inputs.get("position") if isinstance(inputs, Mapping) else None + if position is None or y.shape[1:] != (1, 2): + raise ValueError("track targets (N, 1, 2) need inputs['position'] (N, 2); or pass displacements (N, 2)") + return y[:, 0, :] - _as_tensor(position).float() + if y.ndim != 2 or y.size(1) != 2: + raise ValueError(f"displacement targets must be shaped (N, 2), got shape {tuple(y.shape)}") + return y + + # -- prediction ---------------------------------------------------------------------------------- + def forward(self, inputs: Any) -> torch.Tensor: + x_stat, x_viz, _ = self._unpack(inputs) + if self.predictor == "network": + scaled = self.network(self._network_stat(x_stat, x_viz), x_viz) + else: + scaled = self.xgboost(hurricast_xgboost_features(x_stat, self.embeddings(inputs).detach() if self.use_embeddings else None)) + scaled = scaled.to(self.target_mean.device).reshape(-1, self.n_targets) + return scaled * self.target_std + self.target_mean + + def forecast(self, inputs: Any) -> Dict[str, torch.Tensor]: + """Benchmark forecasts: ``{"intensity": (batch, 1)}`` or ``{"lat", "lon"}`` ``(batch, 1)`` 24 h ahead.""" + out = self.forward(inputs) + if self.target == "intensity": + return {"intensity": out} + position = inputs.get("position") if isinstance(inputs, Mapping) else None + if position is None: + raise ValueError("track forecasts need inputs['position'] (batch, 2): latitude and longitude at the forecast time") + position = _as_tensor(position).to(out) + return {"lat": position[:, :1] + out[:, :1], "lon": position[:, 1:2] + out[:, 1:2]} + + # -- training ------------------------------------------------------------------------------------ + @property + def custom_fit_reason(self) -> str: + return ( + "hurricast trains in two stages (the encoder-decoder by gradient descent on standardised " + "targets, then XGBoost on its frozen embeddings). Use model.fit(inputs, targets, val_inputs, " + "val_targets); Trainer.evaluate and Trainer.predict work on the fitted model." ) - self.head = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim), - nn.ReLU(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), + + def fit( + self, + inputs: Mapping[str, Any], + targets: Any, + val_inputs: Optional[Mapping[str, Any]] = None, + val_targets: Any = None, + train_network: bool = True, + epochs: int = HURRICAST_TRAINING["epochs"], + batch_size: int = HURRICAST_TRAINING["batch_size"], + learning_rate: Optional[float] = None, + l2_reg: float = HURRICAST_TRAINING["l2_reg"], + seed: int = 0, + device: Optional[Union[str, torch.device]] = None, + ) -> "Hurricast": + """Fit the target scaling, the encoder-decoder (``train_network``) and the XGBoost stage. + + Targets are standardised with their training mean and standard deviation. The network is trained + with Adam (learning rate 1e-3 for intensity, 4e-4 for displacement unless ``learning_rate`` is + given), shuffled mini-batches of ``batch_size`` (the last incomplete batch dropped), MSE plus the + L2 term of :func:`hurricast_training_loss`; with validation data the weights of the epoch with the + lowest validation MSE are kept. XGBoost is then fitted on :meth:`xgboost_features`. + """ + y = self.model_targets(inputs, targets) + mean, std = y.mean(0), y.std(0) + std = torch.where(std > 0, std, torch.ones_like(std)) + self.target_mean.copy_(mean) + self.target_std.copy_(std) + scaled = (y - mean) / std + if train_network and self.network is not None: + val = None + if val_inputs is not None and val_targets is not None: + val = (val_inputs, (self.model_targets(val_inputs, val_targets) - mean) / std) + lr = learning_rate if learning_rate is not None else HURRICAST_TRAINING["learning_rate"][self.target] + self.fit_network(inputs, scaled, val=val, epochs=epochs, batch_size=batch_size, learning_rate=lr, l2_reg=l2_reg, seed=seed, device=device) + if self.xgboost is not None: + if self.network is not None: + self.network.eval() + features = self.xgboost_features(inputs) + labels = scaled.numpy() if self.n_targets > 1 else scaled[:, 0].numpy() + self.xgboost.fit(features, labels) + return self + + def fit_network( + self, + inputs: Mapping[str, Any], + scaled_targets: torch.Tensor, + val: Optional[Tuple[Mapping[str, Any], torch.Tensor]] = None, + epochs: int = HURRICAST_TRAINING["epochs"], + batch_size: int = HURRICAST_TRAINING["batch_size"], + learning_rate: float = 1e-3, + l2_reg: float = HURRICAST_TRAINING["l2_reg"], + seed: int = 0, + device: Optional[Union[str, torch.device]] = None, + ) -> List[float]: + """Train the encoder-decoder on standardised targets; returns the validation MSE per epoch.""" + network = self.network + device = torch.device(device) if device is not None else next(network.parameters()).device + network.to(device) + x_stat, x_viz, _ = self._unpack(inputs) + n = x_stat.size(0) + if n < batch_size: + raise ValueError(f"need at least batch_size={batch_size} training samples, got {n}") + optimizer = torch.optim.Adam(network.parameters(), lr=learning_rate) + generator = torch.Generator().manual_seed(int(seed)) + best, best_state, history = float("inf"), None, [] + for _ in range(int(epochs)): + network.train() + order = torch.randperm(n, generator=generator) + for start in range(0, n - batch_size + 1, batch_size): + index = order[start : start + batch_size] + stat = self._network_stat(x_stat[index], x_viz) + maps = None if x_viz is None else x_viz[index].to(device) + out = network(None if stat is None else stat.to(device), maps) + loss = hurricast_training_loss(out, scaled_targets[index].to(device), network, l2_reg) + optimizer.zero_grad() + loss.backward() + optimizer.step() + if val is not None: + network.eval() + v_stat, v_viz, _ = self._unpack(val[0]) + with torch.no_grad(): + stat = self._network_stat(v_stat, v_viz) + pred = network(None if stat is None else stat.to(device), None if v_viz is None else v_viz.to(device)) + mse = float(F.mse_loss(pred.cpu(), val[1].reshape(pred.shape))) + history.append(mse) + if mse < best: + best, best_state = mse, copy.deepcopy(network.state_dict()) + if best_state is not None: + network.load_state_dict(best_state) + network.eval() + return history + + # -- persistence --------------------------------------------------------------------------------- + def save(self, path) -> None: + """Save the network weights, target scaling and fitted XGBoost stage (joblib; trusted files only).""" + import joblib + + joblib.dump( + { + "format": "pyhazards.Hurricast", + "config": self.config, + "state_dict": {k: v.cpu() for k, v in self.state_dict().items()}, + "estimator": None if self.xgboost is None else self.xgboost.estimator, + }, + path, ) - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("Hurricast expects inputs shaped (batch, history, features).") - encoded, _ = self.encoder(x) - last = encoded[:, -1, :] - preds = self.head(last) - return preds.view(x.size(0), self.horizon, self.output_dim) + @classmethod + def load(cls, path) -> "Hurricast": + """Load a model written by :meth:`save` (unpickles the file: only load files you trust).""" + import joblib + + payload = joblib.load(path) + if not isinstance(payload, dict) or payload.get("format") != "pyhazards.Hurricast": + raise ValueError(f"{path} was not written by Hurricast.save") + model = hurricast_builder("regression", estimator=payload["estimator"], **payload["config"]) + model.load_state_dict(payload["state_dict"]) + return model.eval() + + +def hurricast_network( + target: str = "intensity", + decoder_config: str = "transformer_config", + encoder_config: Optional[str] = "full_encoder_config", + no_stat: bool = False, +) -> HurricastEncoderDecoder: + """The official encoder-decoder for a preset of the released code (``scripts/config.py``).""" + if target not in TARGETS: + raise ValueError(f"target must be one of {sorted(TARGETS)}, got {target!r}") + if decoder_config not in DECODER_CONFIGS: + raise ValueError(f"unknown decoder_config {decoder_config!r}; choose from {sorted(DECODER_CONFIGS)}") + if encoder_config is not None and encoder_config not in ENCODER_CONFIGS: + raise ValueError(f"unknown encoder_config {encoder_config!r}; choose from {sorted(ENCODER_CONFIGS)} or None") + decoder_name, decoder_kwargs = DECODER_CONFIGS[decoder_config] + return HurricastEncoderDecoder( + n_pred=TARGETS[target], + decoder_config=decoder_kwargs, + encoder_config=None if encoder_config is None else ENCODER_CONFIGS[encoder_config], + decoder_name=decoder_name, + split_cnns=encoder_config == "split_encoder_config", + no_stat=no_stat, + ) def hurricast_builder( task: str, - input_dim: int = 8, - hidden_dim: int = 64, - num_layers: int = 2, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - **kwargs, + target: str = "intensity", + predictor: str = "xgboost", + decoder_config: str = "transformer_config", + encoder_config: Optional[str] = "full_encoder_config", + no_stat: bool = False, + use_embeddings: bool = True, + xgboost_params: Optional[Mapping[str, Any]] = None, + estimator: Any = None, + **kwargs: Any, ) -> nn.Module: - _ = kwargs + """Hurricast for ``target="intensity"`` or ``"displacement"`` (24-hour track). + + Defaults: HUML-(stat/viz, xgb/cnn/transfo), the paper's best model (CNN encoder, Transformer decoder, + XGBoost with the official defaults). ``predictor="network"`` predicts with the network's linear head; + ``use_embeddings=False`` is HUML-(stat, xgb) (no network). Other keyword arguments (``n_jobs``, ...) + go to ``xgboost.XGBRegressor``. + """ if task.lower() != "regression": - raise ValueError("Hurricast only supports regression for track/intensity forecasting.") + raise ValueError("hurricast is a regression model (24-hour intensity or displacement); use task='regression'.") + kwargs.pop("name", None) + params = dict(HURRICAST_XGBOOST_PARAMS if xgboost_params is None else xgboost_params) + params.update(kwargs) + needs_network = predictor == "network" or use_embeddings + network = hurricast_network(target, decoder_config, encoder_config, no_stat) if needs_network else None + config = { + "target": target, + "predictor": predictor, + "decoder_config": decoder_config, + "encoder_config": encoder_config, + "no_stat": no_stat, + "use_embeddings": use_embeddings, + "xgboost_params": params, + } return Hurricast( - input_dim=input_dim, - hidden_dim=hidden_dim, - num_layers=num_layers, - horizon=horizon, - output_dim=output_dim, - dropout=dropout, + target=target, + predictor=predictor, + network=network, + use_embeddings=use_embeddings, + xgboost_params=params, + estimator=estimator, + config=config, ) -__all__ = ["Hurricast", "hurricast_builder"] +__all__ = [ + "DECODER_CONFIGS", + "ENCODER_CONFIGS", + "HURRICAST_MAP_CHANNELS", + "HURRICAST_NETWORK_STAT_FEATURES", + "HURRICAST_STAT_FEATURES", + "HURRICAST_TRAINING", + "HURRICAST_XGBOOST_PARAMS", + "Hurricast", + "HurricastCNNEncoder", + "HurricastEncoderDecoder", + "HurricastRecurrentDecoder", + "HurricastTransformerDecoder", + "hurricast_builder", + "hurricast_l2_penalty", + "hurricast_network", + "hurricast_training_loss", + "hurricast_xgboost_columns", + "hurricast_xgboost_features", +] diff --git a/pyhazards/models/hydrographnet.py b/pyhazards/models/hydrographnet.py index e3368275..c0b7b244 100644 --- a/pyhazards/models/hydrographnet.py +++ b/pyhazards/models/hydrographnet.py @@ -1,379 +1,615 @@ +"""HydroGraphNet (Taghizadeh et al., Computer-Aided Civil and Infrastructure Engineering 2025). + +HydroGraphNet is the MeshGraphKAN model of NVIDIA PhysicsNeMo: a MeshGraphNet encoder-processor-decoder +whose node encoder is a Fourier Kolmogorov-Arnold network, trained on a water-volume continuity loss +and rolled out autoregressively over an unstructured flood mesh. + +Ported from NVIDIA PhysicsNeMo @ eb7a329c246a48b6fb5acd569eaabeac53f915f7 +(https://github.com/NVIDIA/physicsnemo, Apache-2.0, Copyright (c) 2023 - 2026 NVIDIA CORPORATION & +AFFILIATES): ``physicsnemo/models/meshgraphnet/{meshgraphkan,meshgraphnet}.py``, +``physicsnemo/nn/module/kan_layers.py``, ``physicsnemo/nn/module/gnn_layers/{mesh_graph_mlp, +mesh_edge_block,mesh_node_block,utils}.py`` and the HydroGraphNet example +``examples/weather/flood_modeling/hydrographnet/{utils.py (compute_physics_loss), inference.py +(rollout)}``. The port is plain PyTorch: PhysicsNeMo's PyTorch Geometric graph and ``torch_scatter`` +aggregation are replaced by an ``edge_index`` tensor and ``index_add_``. + +Parameter names, initialisation order and outputs equal PhysicsNeMo's, so PhysicsNeMo state dicts load +with ``strict=True`` (``tests/oracle/test_hydrographnet_oracle.py``). +""" + from __future__ import annotations -from typing import Dict, Optional, Tuple +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +import numpy as np import torch import torch.nn as nn import torch.nn.functional as F +# PhysicsNeMo's ``ACT2FN`` entries without parameters (one module instance is shared by every MLP). +_ACTIVATIONS = { + "relu": lambda: nn.ReLU(), + "leaky_relu": lambda: nn.LeakyReLU(negative_slope=0.1), + "relu6": lambda: nn.ReLU6(), + "elu": lambda: nn.ELU(), + "celu": lambda: nn.CELU(alpha=1.0), + "selu": lambda: nn.SELU(), + "silu": lambda: nn.SiLU(), + "gelu": lambda: nn.GELU(), + "sigmoid": lambda: nn.Sigmoid(), + "logsigmoid": lambda: nn.LogSigmoid(), + "softplus": lambda: nn.Softplus(), + "softsign": lambda: nn.Softsign(), + "tanh": lambda: nn.Tanh(), + "tanhshrink": lambda: nn.Tanhshrink(), + "hardtanh": lambda: nn.Hardtanh(), + "identity": lambda: nn.Identity(), +} + +# HydroGraphNet node features (HydroGraphDataset.create_node_features): 12 static / forcing columns +# followed by the water-depth and volume windows. +HYDROGRAPHNET_STATIC_FEATURES = ( + "x", + "y", + "area", + "elevation", + "slope", + "aspect", + "curvature", + "manning", + "flow_accumulation", + "infiltration", + "inflow", + "precipitation", +) + + +def _activation(name: str) -> nn.Module: + key = str(name).lower() + if key not in _ACTIVATIONS: + raise ValueError(f"Unknown mlp_activation_fn {name!r}; choose one of {sorted(_ACTIVATIONS)}.") + return _ACTIVATIONS[key]() + + +def _edge_index(graph: Any) -> torch.Tensor: + """``(2, num_edges)`` source / destination indices from a tensor or a graph object with ``edge_index``.""" + edge_index = getattr(graph, "edge_index", graph) + if not isinstance(edge_index, torch.Tensor) or edge_index.ndim != 2 or edge_index.shape[0] != 2: + shape = tuple(edge_index.shape) if isinstance(edge_index, torch.Tensor) else type(edge_index).__name__ + raise ValueError(f"edge_index must be a (2, num_edges) tensor of source / destination nodes, got {shape}.") + return edge_index.long() + + +class MeshGraphMLP(nn.Module): + """Linear layers with a shared activation and an optional LayerNorm after the last layer. + + ``hidden_layers=2``: Linear(in, hidden), act, Linear(hidden, hidden), act, Linear(hidden, out), LayerNorm. + """ -class MLP(nn.Module): - def __init__(self, in_dim: int, out_dim: int, hidden_dim: int = 64, dropout: float = 0.0): + def __init__( + self, + input_dim: int, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: Optional[int] = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): super().__init__() - self.layers = nn.Sequential( - nn.Linear(in_dim, hidden_dim), - nn.ReLU(), - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, hidden_dim), - nn.ReLU(), - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, out_dim), - ) + activation_fn = nn.SiLU() if activation_fn is None else activation_fn + if hidden_layers is not None: + layers: List[nn.Module] = [nn.Linear(input_dim, hidden_dim), activation_fn] + self.hidden_layers = hidden_layers + for _ in range(hidden_layers - 1): + layers += [nn.Linear(hidden_dim, hidden_dim), activation_fn] + layers.append(nn.Linear(hidden_dim, output_dim)) + self.norm_type = norm_type + if norm_type is not None: + if norm_type != "LayerNorm": + raise ValueError(f"norm_type must be 'LayerNorm' or None, got {norm_type!r}.") + layers.append(nn.LayerNorm(output_dim)) + self.model = nn.Sequential(*layers) + else: + self.model = nn.Identity() def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.layers(x) + return self.model(x) -class KAN(nn.Module): - """ - Lightweight KAN-style harmonic basis encoder for node features. - """ +class MeshGraphEdgeMLPConcat(MeshGraphMLP): + """Edge MLP on ``cat(edge, source node, destination node)``.""" + + def __init__( + self, + efeat_dim: int = 512, + src_dim: int = 512, + dst_dim: int = 512, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 2, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): + super().__init__(efeat_dim + src_dim + dst_dim, output_dim, hidden_dim, hidden_layers, activation_fn, norm_type) + + def forward(self, efeat: torch.Tensor, nfeat: torch.Tensor, edge_index: torch.Tensor) -> torch.Tensor: + src, dst = edge_index + return self.model(torch.cat((efeat, nfeat[src], nfeat[dst]), dim=1)) - def __init__(self, in_dim: int, harmonics: int = 5, hidden_dim: int = 64): + +class MeshEdgeBlock(nn.Module): + """Residual edge update: ``e + MLP(cat(e, n_src, n_dst))``.""" + + def __init__( + self, + input_dim_nodes: int = 512, + input_dim_edges: int = 512, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): super().__init__() - self.in_dim = in_dim - self.harmonics = harmonics - self.feature_proj = nn.ModuleList( - [nn.Linear(2 * harmonics + 1, hidden_dim) for _ in range(in_dim)] + self.edge_mlp = MeshGraphEdgeMLPConcat( + efeat_dim=input_dim_edges, + src_dim=input_dim_nodes, + dst_dim=input_dim_nodes, + output_dim=output_dim, + hidden_dim=hidden_dim, + hidden_layers=hidden_layers, + activation_fn=activation_fn, + norm_type=norm_type, ) - def forward(self, x: torch.Tensor) -> torch.Tensor: - # x: (B, N, F) - outputs = [] - for i in range(self.in_dim): - xi = x[:, :, i].unsqueeze(-1) - basis = [torch.ones_like(xi)] - for k in range(1, self.harmonics + 1): - basis.append(torch.sin(k * xi)) - basis.append(torch.cos(k * xi)) - basis = torch.cat(basis, dim=-1) - outputs.append(self.feature_proj[i](basis)) - return torch.stack(outputs, dim=0).sum(dim=0) - - -class GNBlock(nn.Module): - """ - Message-passing block with residual edge and node updates. - """ + def forward( + self, efeat: torch.Tensor, nfeat: torch.Tensor, edge_index: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + return self.edge_mlp(efeat, nfeat, edge_index) + efeat, nfeat - def __init__(self, hidden_dim: int, dropout: float = 0.0): + +class MeshNodeBlock(nn.Module): + """Residual node update: ``n + MLP(cat(aggregate(incoming edges), n))``, summing (or averaging) at the destination.""" + + def __init__( + self, + aggregation: str = "sum", + input_dim_nodes: int = 512, + input_dim_edges: int = 512, + output_dim: int = 512, + hidden_dim: int = 512, + hidden_layers: int = 1, + activation_fn: Optional[nn.Module] = None, + norm_type: Optional[str] = "LayerNorm", + ): super().__init__() - self.edge_mlp = MLP(3 * hidden_dim, hidden_dim, hidden_dim, dropout=dropout) - self.node_mlp = MLP(2 * hidden_dim, hidden_dim, hidden_dim, dropout=dropout) + if aggregation not in {"sum", "mean"}: + raise ValueError(f"aggregation must be 'sum' or 'mean', got {aggregation!r}.") + self.aggregation = aggregation + self.node_mlp = MeshGraphMLP( + input_dim=input_dim_nodes + input_dim_edges, + output_dim=output_dim, + hidden_dim=hidden_dim, + hidden_layers=hidden_layers, + activation_fn=activation_fn, + norm_type=norm_type, + ) def forward( - self, - node: torch.Tensor, - edge: torch.Tensor, - senders: torch.Tensor, - receivers: torch.Tensor, + self, efeat: torch.Tensor, nfeat: torch.Tensor, edge_index: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: - sender_feat = node[:, senders, :] - receiver_feat = node[:, receivers, :] + dst = edge_index[1] + # torch_scatter.scatter(efeat, dst, dim=0, dim_size=num_nodes, reduce=aggregation). + aggregated = efeat.new_zeros(nfeat.shape[0], efeat.shape[1]).index_add_(0, dst, efeat) + if self.aggregation == "mean": + count = efeat.new_zeros(nfeat.shape[0]).index_add_(0, dst, efeat.new_ones(dst.shape[0])) + aggregated = aggregated / count.clamp(min=1).unsqueeze(-1) + return efeat, self.node_mlp(torch.cat((aggregated, nfeat), dim=-1)) + nfeat - edge_input = torch.cat([edge, sender_feat, receiver_feat], dim=-1) - edge = edge + self.edge_mlp(edge_input) - agg = torch.zeros_like(node) - agg.index_add_(1, receivers, edge) +class MeshGraphNetProcessor(nn.Module): + """``processor_size`` alternating edge and node blocks (``processor_layers`` = [edge, node, edge, node, ...]).""" - # Degree-normalized aggregation improves stability when graph density changes. - deg = torch.zeros(node.size(1), device=node.device, dtype=node.dtype) - deg.index_add_(0, receivers, torch.ones_like(receivers, dtype=node.dtype)) - agg = agg / deg.clamp(min=1.0).view(1, -1, 1) + def __init__( + self, + processor_size: int = 15, + input_dim_node: int = 128, + input_dim_edge: int = 128, + num_layers_node: int = 2, + num_layers_edge: int = 2, + aggregation: str = "sum", + norm_type: Optional[str] = "LayerNorm", + activation_fn: Optional[nn.Module] = None, + ): + super().__init__() + self.processor_size = processor_size + self.input_dim_node = input_dim_node + self.input_dim_edge = input_dim_edge + activation_fn = nn.ReLU() if activation_fn is None else activation_fn + # As in PhysicsNeMo, every edge block is created before the node blocks (initialisation order). + edge_blocks = [ + MeshEdgeBlock(input_dim_node, input_dim_edge, input_dim_edge, input_dim_edge, num_layers_edge, activation_fn, norm_type) + for _ in range(processor_size) + ] + node_blocks = [ + MeshNodeBlock(aggregation, input_dim_node, input_dim_edge, input_dim_edge, input_dim_edge, num_layers_node, activation_fn, norm_type) + for _ in range(processor_size) + ] + self.processor_layers = nn.ModuleList([block for pair in zip(edge_blocks, node_blocks) for block in pair]) + self.num_processor_layers = len(self.processor_layers) + + def forward(self, node_features: torch.Tensor, edge_features: torch.Tensor, edge_index: torch.Tensor) -> torch.Tensor: + if node_features.ndim != 2 or node_features.shape[1] != self.input_dim_node: + raise ValueError( + f"Expected tensor of shape (N_nodes, {self.input_dim_node}) but got tensor of shape {tuple(node_features.shape)}" + ) + if edge_features.ndim != 2 or edge_features.shape[1] != self.input_dim_edge: + raise ValueError( + f"Expected tensor of shape (N_edges, {self.input_dim_edge}) but got tensor of shape {tuple(edge_features.shape)}" + ) + for layer in self.processor_layers: + edge_features, node_features = layer(edge_features, node_features, edge_index) + return node_features - node_input = torch.cat([node, agg], dim=-1) - node = node + self.node_mlp(node_input) - return node, edge +class KolmogorovArnoldNetwork(nn.Module): + """Fourier KAN layer: ``y_o = sum_i sum_k a_oik cos(k x_i) + b_oik sin(k x_i) + bias_o``, k = 1..num_harmonics.""" -class HydroGraphNet(nn.Module): - """ - PhysicsNeMo-inspired HydroGraphNet: - encoder -> message-passing processor -> residual delta-state decoder. + def __init__(self, input_dim: int, output_dim: int, num_harmonics: int = 5, add_bias: bool = True): + super().__init__() + self.input_dim = input_dim + self.output_dim = output_dim + self.num_harmonics = num_harmonics + self.add_bias = add_bias + # [2, output_dim, input_dim, num_harmonics]: cosine and sine coefficients. + self.fourier_coeffs = nn.Parameter( + torch.randn(2, output_dim, input_dim, num_harmonics) / (np.sqrt(input_dim) * np.sqrt(num_harmonics)) + ) + if self.add_bias: + self.bias = nn.Parameter(torch.zeros(1, output_dim)) - Supports one-step forward prediction and autoregressive rollout. + def forward(self, x: torch.Tensor) -> torch.Tensor: + batch_size = x.size(0) + x = x.view(batch_size, self.input_dim, 1) + k = torch.arange(1, self.num_harmonics + 1, device=x.device).view(1, 1, self.num_harmonics) + y_cos = torch.einsum("bij,oij->bo", torch.cos(k * x), self.fourier_coeffs[0]) + y_sin = torch.einsum("bij,oij->bo", torch.sin(k * x), self.fourier_coeffs[1]) + y = y_cos + y_sin + if self.add_bias: + y = y + self.bias + return y + + +class HydroGraphNet(nn.Module): + """HydroGraphNet: PhysicsNeMo's MeshGraphKAN. + + ``forward(node_features (N, input_dim_nodes), edge_features (E, input_dim_edges), edge_index (2, E))`` + returns ``(N, output_dim)``; for HydroGraphNet the outputs are the normalised changes of water depth + and volume over one 20-minute step. ``edge_index`` holds source (row 0) and destination (row 1) node + indices; messages are summed at the destination. A PyTorch Geometric ``Data`` (anything with an + ``edge_index`` attribute) is accepted in its place, and a single mapping with the keys + ``node_features``, ``edge_features`` and ``edge_index`` (the PyHazards mesh batches) as the only + argument. + + Defaults are the HydroGraphNet configuration (``conf/config.yaml``): 16 node features, 3 edge + features, 2 outputs, hidden width 128, 15 message-passing blocks, 2 hidden layers per MLP, ReLU, + LayerNorm, sum aggregation and 5 harmonics (2,318,722 parameters). """ def __init__( self, - node_in_dim: int, - edge_in_dim: int, - out_dim: int, - hidden_dim: int = 64, - harmonics: int = 5, - num_gn_blocks: int = 5, - state_dim: Optional[int] = None, - rollout_steps: int = 1, - enforce_nonnegative: bool = False, - dropout: float = 0.0, + input_dim_nodes: int = 16, + input_dim_edges: int = 3, + output_dim: int = 2, + processor_size: int = 15, + mlp_activation_fn: str = "relu", + num_layers_node_processor: int = 2, + num_layers_edge_processor: int = 2, + hidden_dim_processor: int = 128, + hidden_dim_node_encoder: int = 128, + num_layers_node_encoder: Optional[int] = 2, + hidden_dim_edge_encoder: int = 128, + num_layers_edge_encoder: Optional[int] = 2, + hidden_dim_node_decoder: int = 128, + num_layers_node_decoder: Optional[int] = 2, + aggregation: str = "sum", + num_harmonics: int = 5, ): super().__init__() - self.node_in_dim = int(node_in_dim) - self.edge_in_dim = int(edge_in_dim) - self.out_dim = int(out_dim) - self.state_dim = int(state_dim) if state_dim is not None else min(2, self.node_in_dim) - self.state_dim = max(1, min(self.state_dim, self.node_in_dim)) - if self.out_dim > self.state_dim: - raise ValueError( - f"out_dim={self.out_dim} cannot exceed residual state_dim={self.state_dim}." - ) - self.rollout_steps = max(1, int(rollout_steps)) - self.enforce_nonnegative = bool(enforce_nonnegative) - - # Encoder - self.node_encoder = KAN( - in_dim=self.node_in_dim, - hidden_dim=hidden_dim, - harmonics=harmonics, + if num_layers_node_encoder is None or num_layers_edge_encoder is None or num_layers_node_decoder is None: + raise ValueError("num_layers_node_encoder, num_layers_edge_encoder and num_layers_node_decoder cannot be None") + self.input_dim_nodes = input_dim_nodes + self.input_dim_edges = input_dim_edges + self.output_dim = output_dim + activation_fn = _activation(mlp_activation_fn) + + self.edge_encoder = MeshGraphMLP( + input_dim_edges, + output_dim=hidden_dim_processor, + hidden_dim=hidden_dim_edge_encoder, + hidden_layers=num_layers_edge_encoder, + activation_fn=activation_fn, + norm_type="LayerNorm", ) - self.edge_encoder = MLP( - in_dim=self.edge_in_dim, - out_dim=hidden_dim, - hidden_dim=hidden_dim, - dropout=dropout, + # MeshGraphKAN builds MeshGraphNet's MLP node encoder and only then replaces it with the KAN; + # creating (and dropping) it keeps the random number stream, and the position of ``node_encoder`` + # in the state dict, identical to PhysicsNeMo's. + self.node_encoder = MeshGraphMLP( + input_dim_nodes, + output_dim=hidden_dim_processor, + hidden_dim=hidden_dim_node_encoder, + hidden_layers=num_layers_node_encoder, + activation_fn=activation_fn, + norm_type="LayerNorm", ) - - # Processor - self.processor = nn.ModuleList( - [GNBlock(hidden_dim=hidden_dim, dropout=dropout) for _ in range(num_gn_blocks)] + self.node_decoder = MeshGraphMLP( + hidden_dim_processor, + output_dim=output_dim, + hidden_dim=hidden_dim_node_decoder, + hidden_layers=num_layers_node_decoder, + activation_fn=activation_fn, + norm_type=None, ) - - # Decoder predicts delta of physically meaningful states. - self.decoder = MLP( - in_dim=hidden_dim, - out_dim=self.state_dim, - hidden_dim=hidden_dim, - dropout=dropout, + self.processor = MeshGraphNetProcessor( + processor_size=processor_size, + input_dim_node=hidden_dim_processor, + input_dim_edge=hidden_dim_processor, + num_layers_node=num_layers_node_processor, + num_layers_edge=num_layers_edge_processor, + aggregation=aggregation, + norm_type="LayerNorm", + activation_fn=activation_fn, ) - - def _edge_index(self, adj: torch.Tensor, batch_size: int) -> Tuple[torch.Tensor, torch.Tensor]: - if adj.dim() == 2: - a = adj - elif adj.dim() == 3: - if adj.size(0) != batch_size: - raise ValueError(f"adj batch size mismatch: got {adj.size(0)}, expected {batch_size}") - a = adj[0] - for i in range(1, batch_size): - if not torch.allclose(adj[i], a): - raise ValueError( - "Per-sample varying adjacency is not supported yet. " - "Provide a shared (N, N) adjacency or identical (B, N, N) adjacency." - ) - else: - raise ValueError("adj must be shaped (N, N) or (B, N, N).") - - a = (a > 0).to(dtype=torch.bool) - a.fill_diagonal_(True) - return a.nonzero(as_tuple=True) - - def _match_edge_dim(self, edge_feat: torch.Tensor) -> torch.Tensor: - # edge_feat: (B, E, F_edge_raw) - f_raw = edge_feat.size(-1) - if f_raw == self.edge_in_dim: - return edge_feat - if f_raw > self.edge_in_dim: - return edge_feat[..., : self.edge_in_dim] - pad = torch.zeros( - edge_feat.size(0), - edge_feat.size(1), - self.edge_in_dim - f_raw, - device=edge_feat.device, - dtype=edge_feat.dtype, + self.node_encoder = KolmogorovArnoldNetwork( + input_dim=input_dim_nodes, + output_dim=hidden_dim_processor, + num_harmonics=num_harmonics, + add_bias=True, ) - return torch.cat([edge_feat, pad], dim=-1) - def _prepare_edge_inputs( - self, - batch: Dict[str, torch.Tensor], - senders: torch.Tensor, - receivers: torch.Tensor, - batch_size: int, - device: torch.device, - dtype: torch.dtype, - ) -> torch.Tensor: - edge_attr = batch.get("edge_attr") - if edge_attr is not None: - edge_attr = edge_attr.to(device=device, dtype=dtype) - if edge_attr.dim() == 2: - edge_attr = edge_attr.unsqueeze(0).expand(batch_size, -1, -1) - elif edge_attr.dim() == 3 and edge_attr.size(0) == 1 and batch_size > 1: - edge_attr = edge_attr.expand(batch_size, -1, -1) - if edge_attr.dim() != 3: - raise ValueError("edge_attr must be shaped (E, F_edge) or (B, E, F_edge).") - if edge_attr.size(1) != senders.numel(): - raise ValueError( - f"edge_attr edge count mismatch: got {edge_attr.size(1)}, expected {senders.numel()}." - ) - return self._match_edge_dim(edge_attr) - - # Derive geometric edge features from coords: [dx, dy, distance] - coords = batch.get("coords") - if coords is None: - edge_feat = torch.zeros(batch_size, senders.numel(), 3, device=device, dtype=dtype) - return self._match_edge_dim(edge_feat) - - coords = coords.to(device=device, dtype=dtype) - if coords.dim() == 2: - coords = coords.unsqueeze(0).expand(batch_size, -1, -1) - elif coords.dim() == 3 and coords.size(0) == 1 and batch_size > 1: - coords = coords.expand(batch_size, -1, -1) - if coords.dim() != 3: - raise ValueError("coords must be shaped (N, 2) or (B, N, 2).") - - src = coords[:, senders, :] - dst = coords[:, receivers, :] - delta = src - dst - dist = torch.norm(delta, dim=-1, keepdim=True) - edge_feat = torch.cat([delta, dist], dim=-1) - return self._match_edge_dim(edge_feat) - - def _one_step( + def forward( self, - node_x: torch.Tensor, - batch: Dict[str, torch.Tensor], + node_features: Union[torch.Tensor, Mapping[str, Any]], + edge_features: Optional[torch.Tensor] = None, + graph: Any = None, ) -> torch.Tensor: - # node_x: (B, N, F) - if node_x.ndim != 3: - raise ValueError(f"Expected node_x with shape (B,N,F), got {tuple(node_x.shape)}") - if node_x.size(-1) < self.state_dim: + if isinstance(node_features, Mapping): + batch = node_features + missing = [key for key in ("node_features", "edge_features", "edge_index") if key not in batch] + if missing: + raise ValueError(f"HydroGraphNet mesh batches need the keys node_features, edge_features and edge_index; missing {missing}.") + node_features, edge_features, graph = batch["node_features"], batch["edge_features"], batch["edge_index"] + if edge_features is None or graph is None: + raise ValueError("HydroGraphNet needs node_features (N, F), edge_features (E, F_edge) and edge_index (2, E).") + if node_features.ndim != 2 or node_features.shape[1] != self.input_dim_nodes: raise ValueError( - f"Input feature dim {node_x.size(-1)} is smaller than state_dim {self.state_dim}." + f"Expected tensor of shape (N_nodes, {self.input_dim_nodes}) but got tensor of shape {tuple(node_features.shape)}" ) - - adj = batch.get("adj") - if adj is None: - raise ValueError("HydroGraphNet requires `adj` in the batch.") - adj = adj.to(device=node_x.device) - - senders, receivers = self._edge_index(adj, batch_size=node_x.size(0)) - - # ---- encoder ---- - node = self.node_encoder(node_x) - edge_in = self._prepare_edge_inputs( - batch=batch, - senders=senders, - receivers=receivers, - batch_size=node.size(0), - device=node.device, - dtype=node.dtype, - ) - edge = self.edge_encoder(edge_in) - - # ---- processor ---- - for gn in self.processor: - node, edge = gn(node, edge, senders, receivers) - - # ---- decoder: residual state update ---- - delta_state = self.decoder(node) # (B, N, state_dim) - prev_state = node_x[..., : self.state_dim] - next_state = prev_state + delta_state - if self.enforce_nonnegative: - next_state = next_state.clamp_min(0.0) - - # Return requested targets from the evolved state. - return next_state[..., : self.out_dim] - - def rollout(self, batch: Dict[str, torch.Tensor], predict_steps: int) -> torch.Tensor: - batch_roll = dict(batch) - batch_roll["predict_steps"] = int(predict_steps) - out = self.forward(batch_roll) - if out.ndim != 4: - raise RuntimeError("rollout expected stacked output with shape (B, S, N, out_dim).") - return out - - def forward(self, batch: Dict[str, torch.Tensor]) -> torch.Tensor: - # batch["x"]: (B, T, N, F) - x = batch["x"] - if x.ndim != 4: + if edge_features.ndim != 2 or edge_features.shape[1] != self.input_dim_edges: raise ValueError( - f"HydroGraphNet expects x shaped (B, T, N, F), got {tuple(x.shape)}" + f"Expected tensor of shape (N_edges, {self.input_dim_edges}) but got tensor of shape {tuple(edge_features.shape)}" ) + edge_index = _edge_index(graph) + if edge_index.shape[1] != edge_features.shape[0]: + raise ValueError( + f"edge_index has {edge_index.shape[1]} edges but edge_features has shape {tuple(edge_features.shape)}." + ) + edge_features = self.edge_encoder(edge_features) + node_features = self.node_encoder(node_features) + x = self.processor(node_features, edge_features, edge_index) + return self.node_decoder(x) - predict_steps = int(batch.get("predict_steps", self.rollout_steps)) - predict_steps = max(1, predict_steps) - - history = x - preds = [] - for _ in range(predict_steps): - node_x = history[:, -1] - y_next = self._one_step(node_x=node_x, batch=batch) # (B, N, out_dim) - preds.append(y_next) - - if predict_steps > 1: - next_frame = history[:, -1].clone() - next_frame[..., : self.out_dim] = y_next - history = torch.cat([history[:, 1:], next_frame.unsqueeze(1)], dim=1) - - if predict_steps == 1: - return preds[0] - return torch.stack(preds, dim=1) + @torch.no_grad() + def rollout( + self, + node_features: torch.Tensor, + edge_features: torch.Tensor, + edge_index: Any, + inflow: torch.Tensor, + precipitation: torch.Tensor, + n_time_steps: int = 2, + n_static: int = 12, + ) -> Dict[str, torch.Tensor]: + """Autoregressive rollout of the HydroGraphNet example (``inference.py``). + + ``node_features`` (N, 12 + 2 * n_time_steps) is the first window of a test hydrograph; ``inflow`` + and ``precipitation`` (rollout_length,) are the normalised forcings from step ``n_time_steps`` on. + Each step predicts the depth / volume change, appends ``last + change`` to the windows (dropping + the oldest), and writes ``inflow[t]`` / ``precipitation[t]`` into columns 10 and 11. Returns the + normalised ``water_depth`` and ``volume`` of every step, ``(rollout_length, N)`` each. + """ + if node_features.ndim != 2 or node_features.shape[1] != n_static + 2 * n_time_steps: + raise ValueError( + f"rollout expects node_features of shape (N_nodes, {n_static + 2 * n_time_steps}), got {tuple(node_features.shape)}." + ) + if inflow.ndim != 1 or precipitation.shape != inflow.shape: + raise ValueError( + f"inflow and precipitation must be 1-D tensors of equal length, got {tuple(inflow.shape)} and {tuple(precipitation.shape)}." + ) + num_nodes = node_features.size(0) + x_iter = node_features.clone() + depths, volumes = [], [] + for t in range(inflow.shape[0]): + static_part = x_iter[:, :n_static] + water_depth_window = x_iter[:, n_static : n_static + n_time_steps] + volume_window = x_iter[:, n_static + n_time_steps : n_static + 2 * n_time_steps] + x_input = torch.cat([static_part, water_depth_window, volume_window], dim=1) + pred = self(x_input, edge_features, edge_index) + new_wd = water_depth_window[:, -1:] + pred[:, 0:1] + new_vol = volume_window[:, -1:] + pred[:, 1:2] + water_depth_updated = torch.cat([water_depth_window[:, 1:], new_wd], dim=1) + volume_updated = torch.cat([volume_window[:, 1:], new_vol], dim=1) + new_flow = inflow[t].unsqueeze(0).expand(num_nodes, 1) + new_precip = precipitation[t].unsqueeze(0).expand(num_nodes, 1) + static_part_updated = static_part.clone() + static_part_updated[:, 10:12] = torch.cat([new_flow, new_precip], dim=1) + x_iter = torch.cat([static_part_updated, water_depth_updated, volume_updated], dim=1) + depths.append(new_wd.squeeze(1)) + volumes.append(new_vol.squeeze(1)) + return {"water_depth": torch.stack(depths), "volume": torch.stack(volumes)} + + +MeshGraphKAN = HydroGraphNet + +PHYSICS_KEYS = ( + "past_volume", + "future_volume", + "avg_inflow", + "avg_precipitation", + "next_inflow", + "next_precip", + "volume_mean", + "volume_std", + "num_nodes", + "area_sum", + "infiltration_area_sum", +) + + +def hydrographnet_physics_loss( + pred: torch.Tensor, + physics_data: Mapping[str, torch.Tensor], + batch: Optional[torch.Tensor] = None, + delta_t: float = 1200.0, +) -> torch.Tensor: + """Volume-continuity loss of the HydroGraphNet example (``compute_physics_loss``). + + For each graph of the batch (``batch`` gives the graph index of every node; ``None`` means one graph) + the predicted total volume ``V_pred = V_past + volume_std * sum(pred[:, 1])`` is compared, in + physical units, with the volume entering over ``delta_t`` seconds: + + ``term1 = relu((V_pred - (V_past + delta_t (avg_inflow + avg_precipitation * A_inf))) / A)^2``, + ``term2 = relu((V_future - V_pred - delta_t (next_inflow + next_precip * A_inf)) / A)^2``, + + with ``V = volume_norm * volume_std + num_nodes * volume_mean``, ``A`` the total cell area and + ``A_inf`` the infiltration-weighted area. Returns the mean of ``term1 + term2`` over graphs. + ``physics_data`` holds one value per graph for each of :data:`PHYSICS_KEYS`. + """ + if pred.ndim != 2 or pred.shape[1] < 2: + raise ValueError(f"pred must have shape (N_nodes, >=2) with the volume change in column 1, got {tuple(pred.shape)}.") + missing = [key for key in PHYSICS_KEYS if key not in physics_data] + if missing: + raise ValueError(f"physics_data is missing {missing}.") + if batch is None: + batch = torch.zeros(pred.shape[0], dtype=torch.long, device=pred.device) + unique_ids = torch.unique(batch) + predicted_diff = pred[:, 1] + physics_losses = [] + for uid in unique_ids: + mask = batch == uid + pred_diff_sum = predicted_diff[mask].sum() + idx = (unique_ids == uid).nonzero(as_tuple=False).item() + values = {key: torch.as_tensor(physics_data[key]).reshape(-1)[idx] for key in PHYSICS_KEYS} + past_volume_denorm = values["past_volume"] * values["volume_std"] + values["num_nodes"] * values["volume_mean"] + future_volume_denorm = values["future_volume"] * values["volume_std"] + values["num_nodes"] * values["volume_mean"] + pred_total_volume = past_volume_denorm + values["volume_std"] * pred_diff_sum + new_precip_term = values["avg_precipitation"] * values["infiltration_area_sum"] + new_next_precip_term = values["next_precip"] * values["infiltration_area_sum"] + term1 = ( + F.relu( + (pred_total_volume - (past_volume_denorm + delta_t * (values["avg_inflow"] + new_precip_term))) + / values["area_sum"] + ) + ** 2 + ) + term2 = ( + F.relu( + (future_volume_denorm - pred_total_volume - delta_t * (values["next_inflow"] + new_next_precip_term)) + / values["area_sum"] + ) + ** 2 + ) + physics_losses.append(term1 + term2) + if physics_losses: + return torch.stack(physics_losses).mean() + return torch.tensor(0.0, device=pred.device) class HydroGraphNetLoss(nn.Module): - """ - Supervised regression loss with optional continuity regularization. + """Training loss of the HydroGraphNet example (``train.py``, ``noise_type: none``). + + ``MSE(pred, target) + physics_loss_weight * hydrographnet_physics_loss(pred, physics_data, batch)``; + the physics term is skipped when ``physics_data`` is ``None`` (``use_physics_loss: false``). Defaults + are the example's ``physics_loss_weight=1.0`` and ``delta_t=1200`` s. Returns the total loss and a + dict of its parts. """ - def __init__(self, supervised_weight: float = 1.0, continuity_weight: float = 0.0): + def __init__(self, physics_loss_weight: float = 1.0, delta_t: float = 1200.0, use_physics_loss: bool = True): super().__init__() - self.supervised_weight = float(supervised_weight) - self.continuity_weight = float(continuity_weight) + self.physics_loss_weight = float(physics_loss_weight) + self.delta_t = float(delta_t) + self.use_physics_loss = bool(use_physics_loss) def forward( self, - preds: torch.Tensor, - targets: torch.Tensor, - prev_state: Optional[torch.Tensor] = None, - cell_area: Optional[torch.Tensor] = None, - ) -> Tuple[torch.Tensor, Dict[str, float]]: - supervised = F.mse_loss(preds, targets) - total = self.supervised_weight * supervised - metrics: Dict[str, float] = {"mse": float(supervised.detach().cpu())} - - if ( - self.continuity_weight > 0 - and prev_state is not None - and cell_area is not None - and preds.size(-1) >= 2 - and prev_state.size(-1) >= 2 - ): - # Approximate local continuity: depth-change * area ~= volume-change - depth_delta = preds[..., 0] - prev_state[..., 0] - volume_delta = preds[..., 1] - prev_state[..., 1] - area = cell_area.to(device=preds.device, dtype=preds.dtype) - if area.dim() == 1: - area = area.unsqueeze(0) - continuity = F.mse_loss(depth_delta * area, volume_delta) - total = total + self.continuity_weight * continuity - metrics["continuity"] = float(continuity.detach().cpu()) - - metrics["total"] = float(total.detach().cpu()) - return total, metrics + pred: torch.Tensor, + target: torch.Tensor, + physics_data: Optional[Mapping[str, torch.Tensor]] = None, + batch: Optional[torch.Tensor] = None, + ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]: + mse_loss = F.mse_loss(pred, target) + loss = mse_loss + parts = {"total_loss": loss, "mse_loss": mse_loss} + if self.use_physics_loss and physics_data is not None: + phy_loss = hydrographnet_physics_loss(pred, physics_data, batch, delta_t=self.delta_t) + loss = loss + self.physics_loss_weight * phy_loss + parts = {"total_loss": loss, "mse_loss": mse_loss, "physics_loss": phy_loss} + return loss, parts def hydrographnet_builder( task: str, - node_in_dim: int, - edge_in_dim: int, - out_dim: int, - **kwargs, + input_dim_nodes: int = 16, + input_dim_edges: int = 3, + output_dim: int = 2, + processor_size: int = 15, + mlp_activation_fn: str = "relu", + num_layers_node_processor: int = 2, + num_layers_edge_processor: int = 2, + hidden_dim_processor: int = 128, + hidden_dim_node_encoder: int = 128, + num_layers_node_encoder: int = 2, + hidden_dim_edge_encoder: int = 128, + num_layers_edge_encoder: int = 2, + hidden_dim_node_decoder: int = 128, + num_layers_node_decoder: int = 2, + aggregation: str = "sum", + num_harmonics: int = 5, + **kwargs: Any, ) -> HydroGraphNet: - if task != "regression": - raise ValueError("HydroGraphNet only supports regression") - + """HydroGraphNet (MeshGraphKAN) at the HydroGraphNet example configuration by default.""" + if task.lower() != "regression": + raise ValueError(f"HydroGraphNet only supports task='regression', got {task!r}.") + kwargs.pop("name", None) + if kwargs: + raise ValueError(f"Unknown HydroGraphNet arguments: {sorted(kwargs)}.") return HydroGraphNet( - node_in_dim=node_in_dim, - edge_in_dim=edge_in_dim, - out_dim=out_dim, - hidden_dim=kwargs.get("hidden_dim", 64), - harmonics=kwargs.get("harmonics", 5), - num_gn_blocks=kwargs.get("num_gn_blocks", 5), - state_dim=kwargs.get("state_dim"), - rollout_steps=kwargs.get("rollout_steps", 1), - enforce_nonnegative=kwargs.get("enforce_nonnegative", False), - dropout=kwargs.get("dropout", 0.0), + input_dim_nodes=input_dim_nodes, + input_dim_edges=input_dim_edges, + output_dim=output_dim, + processor_size=processor_size, + mlp_activation_fn=mlp_activation_fn, + num_layers_node_processor=num_layers_node_processor, + num_layers_edge_processor=num_layers_edge_processor, + hidden_dim_processor=hidden_dim_processor, + hidden_dim_node_encoder=hidden_dim_node_encoder, + num_layers_node_encoder=num_layers_node_encoder, + hidden_dim_edge_encoder=hidden_dim_edge_encoder, + num_layers_edge_encoder=num_layers_edge_encoder, + hidden_dim_node_decoder=hidden_dim_node_decoder, + num_layers_node_decoder=num_layers_node_decoder, + aggregation=aggregation, + num_harmonics=num_harmonics, ) -__all__ = ["HydroGraphNet", "HydroGraphNetLoss", "hydrographnet_builder"] +__all__ = [ + "HYDROGRAPHNET_STATIC_FEATURES", + "HydroGraphNet", + "HydroGraphNetLoss", + "KolmogorovArnoldNetwork", + "MeshGraphKAN", + "PHYSICS_KEYS", + "hydrographnet_builder", + "hydrographnet_physics_loss", +] diff --git a/pyhazards/models/logistic_regression.py b/pyhazards/models/logistic_regression.py new file mode 100644 index 00000000..3ca31e57 --- /dev/null +++ b/pyhazards/models/logistic_regression.py @@ -0,0 +1,61 @@ +"""Per-pixel logistic regression over a local neighbourhood. + +WildfireSpreadTS (Gerard et al., NeurIPS 2023 D&B, ``src/models/LogisticRegression.py``, MIT) +implements its logistic-regression baseline as a single ``Conv2d(C, 1, kernel_size=3, padding=1)``: +every output pixel is a linear function of the ``3 x 3 x C`` input window followed by a sigmoid +in the loss. Next Day Wildfire Spread (Huot et al., IEEE TGRS 2022) fits the same model with +scikit-learn on the 3 x 3 neighbourhood of each pixel; only the fitting procedure differs. +""" + +from __future__ import annotations + +import torch +import torch.nn as nn + + +class PixelLogisticRegression(nn.Module): + """Linear ``kernel_size x kernel_size`` window classifier returning logits. + + Accepts ``(batch, channels, height, width)`` or ``(batch, time, channels, height, width)``; + the latter is flattened to ``time * channels`` input channels, as in WildfireSpreadTS. + """ + + def __init__(self, in_channels: int, out_channels: int = 1, kernel_size: int = 3): + super().__init__() + if in_channels <= 0: + raise ValueError(f"in_channels must be positive, got {in_channels}") + if kernel_size <= 0 or kernel_size % 2 == 0: + raise ValueError(f"kernel_size must be a positive odd integer, got {kernel_size}") + self.in_channels = int(in_channels) + self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 5: + x = x.flatten(start_dim=1, end_dim=2) + if x.ndim != 4: + raise ValueError( + "PixelLogisticRegression expects input shape (batch, channels, height, width) or " + f"(batch, time, channels, height, width), got {tuple(x.shape)}." + ) + if x.size(1) != self.in_channels: + raise ValueError(f"PixelLogisticRegression expected {self.in_channels} channels, got {x.size(1)}.") + return self.conv(x) + + +def logistic_regression_builder( + task: str, + in_channels: int, + out_channels: int = 1, + history: int = 1, + kernel_size: int = 3, + **kwargs, +) -> nn.Module: + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"logistic_regression supports task='segmentation', got {task!r}.") + if history <= 0: + raise ValueError(f"history must be positive, got {history}") + return PixelLogisticRegression(in_channels * history, out_channels, kernel_size) + + +__all__ = ["PixelLogisticRegression", "logistic_regression_builder"] diff --git a/pyhazards/models/monai_blocks.py b/pyhazards/models/monai_blocks.py new file mode 100644 index 00000000..643e2fde --- /dev/null +++ b/pyhazards/models/monai_blocks.py @@ -0,0 +1,425 @@ +"""MONAI building blocks shared by the ``unetr`` and ``swin_unetr`` ports. + +Ported from MONAI 1.3.2 (Apache License 2.0, Copyright (c) MONAI Consortium): +``monai/networks/blocks/dynunet_block.py`` (``get_conv_layer``, ``UnetResBlock``, +``UnetBasicBlock``, ``UnetOutBlock``), ``monai/networks/blocks/unetr_block.py`` +(``UnetrBasicBlock``, ``UnetrPrUpBlock``, ``UnetrUpBlock``), ``monai/networks/blocks/mlp.py`` +(``MLPBlock``), ``monai/networks/layers/drop_path.py`` (``DropPath``) and +``monai/networks/layers/utils.py`` (``get_norm_layer``). The blocks are rewritten in plain +PyTorch with MONAI's module names and creation order, so MONAI state dicts load with +``strict=True`` and a given seed gives the same initial weights. Only the options that UNETR and +SwinUNETR use are supported: normalisation ``"batch"`` or ``"instance"`` (optionally as a +``(name, kwargs)`` tuple), LeakyReLU(0.01) activations and no dropout in the convolution blocks. + +``trunc_normal_`` is MONAI's ``monai.networks.layers.trunc_normal_``, which uses the same +inverse-CDF algorithm as timm 0.4.12, so it is shared with :mod:`pyhazards.models.swin_blocks`. +""" + +from __future__ import annotations + +from typing import Any, Dict, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn + +from .attention_unet import Convolution +from .swin_blocks import trunc_normal_ + +IntOrSeq = Union[int, Sequence[int]] +NormSpec = Union[str, Tuple[str, Dict[str, Any]]] + +_BATCH_NORM = {1: nn.BatchNorm1d, 2: nn.BatchNorm2d, 3: nn.BatchNorm3d} +_INSTANCE_NORM = {1: nn.InstanceNorm1d, 2: nn.InstanceNorm2d, 3: nn.InstanceNorm3d} + + +def as_tuple(value: IntOrSeq, dims: int, name: str) -> Tuple[int, ...]: + """``monai.utils.ensure_tuple_rep`` for ints, with a ``ValueError`` for wrong lengths.""" + if isinstance(value, (int, np.integer)): + return (int(value),) * dims + values = tuple(int(v) for v in value) + if len(values) != dims: + raise ValueError(f"{name} must be an int or have {dims} entries, got {value!r}") + return values + + +def get_norm_layer(name: NormSpec, spatial_dims: int, channels: int) -> nn.Module: + """``monai.networks.layers.get_norm_layer`` for batch and instance norm.""" + if isinstance(name, str): + norm_name, norm_args = name, {} + elif isinstance(name, (tuple, list)) and len(name) == 2 and isinstance(name[0], str): + norm_name, norm_args = name[0], dict(name[1]) + else: + raise ValueError(f"norm_name must be 'batch', 'instance' or (name, kwargs), got {name!r}") + norm_name = norm_name.lower() + if norm_name == "batch": + return _BATCH_NORM[spatial_dims](**{"num_features": channels, **norm_args}) + if norm_name == "instance": + return _INSTANCE_NORM[spatial_dims](**{"num_features": channels, **norm_args}) + raise ValueError(f"norm_name must be 'batch' or 'instance', got {name!r}") + + +def check_norm_name(name: NormSpec) -> None: + get_norm_layer(name, 1, 1) + + +def get_padding(kernel_size: IntOrSeq, stride: IntOrSeq) -> IntOrSeq: + kernel = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = (kernel - stride_np + 1) / 2 + if np.min(padding_np) < 0: + raise ValueError("padding value should not be negative, please change the kernel size and/or stride.") + padding = tuple(int(p) for p in padding_np) + return padding if len(padding) > 1 else padding[0] + + +def get_output_padding(kernel_size: IntOrSeq, stride: IntOrSeq, padding: IntOrSeq) -> IntOrSeq: + kernel = np.atleast_1d(kernel_size) + stride_np = np.atleast_1d(stride) + padding_np = np.atleast_1d(padding) + out_padding_np = 2 * padding_np + stride_np - kernel + if np.min(out_padding_np) < 0: + raise ValueError("out_padding value should not be negative, please change the kernel size and/or stride.") + out_padding = tuple(int(p) for p in out_padding_np) + return out_padding if len(out_padding) > 1 else out_padding[0] + + +def get_conv_layer( + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq = 3, + stride: IntOrSeq = 1, + bias: bool = False, + is_transposed: bool = False, +) -> Convolution: + """``monai.networks.blocks.dynunet_block.get_conv_layer`` without act/norm/dropout. + + Every call in UNETR and SwinUNETR builds a bare (transposed) convolution; MONAI's default + ``bias=False`` is kept. + """ + padding = get_padding(kernel_size, stride) + output_padding = get_output_padding(kernel_size, stride, padding) if is_transposed else None + return Convolution( + spatial_dims, + in_channels, + out_channels, + strides=stride, + kernel_size=kernel_size, + act=None, + norm=None, + dropout=None, + bias=bias, + conv_only=True, + is_transposed=is_transposed, + padding=padding, + output_padding=output_padding, + ) + + +def _leaky_relu() -> nn.Module: + # MONAI's default act_name ("leakyrelu", {"inplace": True, "negative_slope": 0.01}). + return nn.LeakyReLU(negative_slope=0.01, inplace=True) + + +class UnetResBlock(nn.Module): + """Residual ``conv -> norm -> lrelu -> conv -> norm (+ 1x1 projection)`` block (MONAI).""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq, + stride: IntOrSeq, + norm_name: NormSpec, + ): + super().__init__() + self.conv1 = get_conv_layer(spatial_dims, in_channels, out_channels, kernel_size=kernel_size, stride=stride) + self.conv2 = get_conv_layer(spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1) + self.lrelu = _leaky_relu() + self.norm1 = get_norm_layer(norm_name, spatial_dims, out_channels) + self.norm2 = get_norm_layer(norm_name, spatial_dims, out_channels) + self.downsample = in_channels != out_channels + if not np.all(np.atleast_1d(stride) == 1): + self.downsample = True + if self.downsample: + self.conv3 = get_conv_layer(spatial_dims, in_channels, out_channels, kernel_size=1, stride=stride) + self.norm3 = get_norm_layer(norm_name, spatial_dims, out_channels) + + def forward(self, inp: torch.Tensor) -> torch.Tensor: + residual = inp + out = self.conv1(inp) + out = self.norm1(out) + out = self.lrelu(out) + out = self.conv2(out) + out = self.norm2(out) + if hasattr(self, "conv3"): + residual = self.conv3(residual) + if hasattr(self, "norm3"): + residual = self.norm3(residual) + out += residual + out = self.lrelu(out) + return out + + +class UnetBasicBlock(nn.Module): + """``conv -> norm -> lrelu -> conv -> norm -> lrelu`` block (MONAI).""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq, + stride: IntOrSeq, + norm_name: NormSpec, + ): + super().__init__() + self.conv1 = get_conv_layer(spatial_dims, in_channels, out_channels, kernel_size=kernel_size, stride=stride) + self.conv2 = get_conv_layer(spatial_dims, out_channels, out_channels, kernel_size=kernel_size, stride=1) + self.lrelu = _leaky_relu() + self.norm1 = get_norm_layer(norm_name, spatial_dims, out_channels) + self.norm2 = get_norm_layer(norm_name, spatial_dims, out_channels) + + def forward(self, inp: torch.Tensor) -> torch.Tensor: + out = self.lrelu(self.norm1(self.conv1(inp))) + return self.lrelu(self.norm2(self.conv2(out))) + + +class UnetOutBlock(nn.Module): + """1x1 output convolution with bias (MONAI).""" + + def __init__(self, spatial_dims: int, in_channels: int, out_channels: int): + super().__init__() + self.conv = get_conv_layer(spatial_dims, in_channels, out_channels, kernel_size=1, stride=1, bias=True) + + def forward(self, inp: torch.Tensor) -> torch.Tensor: + return self.conv(inp) + + +class UnetrBasicBlock(nn.Module): + """UNETR encoder block: a :class:`UnetResBlock` or :class:`UnetBasicBlock` named ``layer``.""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq, + stride: IntOrSeq, + norm_name: NormSpec, + res_block: bool = False, + ): + super().__init__() + block = UnetResBlock if res_block else UnetBasicBlock + self.layer = block( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + norm_name=norm_name, + ) + + def forward(self, inp: torch.Tensor) -> torch.Tensor: + return self.layer(inp) + + +class UnetrPrUpBlock(nn.Module): + """UNETR projection-upsampling block: one transposed convolution, then ``num_layer`` more. + + With ``conv_block=True`` each extra up-sampling is followed by a residual or basic block. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + num_layer: int, + kernel_size: IntOrSeq, + stride: IntOrSeq, + upsample_kernel_size: IntOrSeq, + norm_name: NormSpec, + conv_block: bool = False, + res_block: bool = False, + ): + super().__init__() + upsample_stride = upsample_kernel_size + self.transp_conv_init = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=upsample_kernel_size, + stride=upsample_stride, + is_transposed=True, + ) + + def _up() -> Convolution: + return get_conv_layer( + spatial_dims, + out_channels, + out_channels, + kernel_size=upsample_kernel_size, + stride=upsample_stride, + is_transposed=True, + ) + + if conv_block: + block = UnetResBlock if res_block else UnetBasicBlock + self.blocks = nn.ModuleList( + [ + nn.Sequential( + _up(), + block( + spatial_dims=spatial_dims, + in_channels=out_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + norm_name=norm_name, + ), + ) + for _ in range(num_layer) + ] + ) + else: + self.blocks = nn.ModuleList([_up() for _ in range(num_layer)]) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.transp_conv_init(x) + for blk in self.blocks: + x = blk(x) + return x + + +class UnetrUpBlock(nn.Module): + """UNETR decoder block: transposed convolution, concatenation with the skip, conv block.""" + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + kernel_size: IntOrSeq, + upsample_kernel_size: IntOrSeq, + norm_name: NormSpec, + res_block: bool = False, + ): + super().__init__() + upsample_stride = upsample_kernel_size + self.transp_conv = get_conv_layer( + spatial_dims, + in_channels, + out_channels, + kernel_size=upsample_kernel_size, + stride=upsample_stride, + is_transposed=True, + ) + block = UnetResBlock if res_block else UnetBasicBlock + self.conv_block = block( + spatial_dims, + out_channels + out_channels, + out_channels, + kernel_size=kernel_size, + stride=1, + norm_name=norm_name, + ) + + def forward(self, inp: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: + out = self.transp_conv(inp) + out = torch.cat((out, skip), dim=1) + return self.conv_block(out) + + +class MLPBlock(nn.Module): + """``Linear -> GELU -> Dropout -> Linear -> Dropout`` (MONAI ``MLPBlock``). + + ``dropout_mode="vit"`` uses two dropout modules, ``"swin"`` reuses the first one. + """ + + def __init__(self, hidden_size: int, mlp_dim: int, dropout_rate: float = 0.0, dropout_mode: str = "vit"): + super().__init__() + if not 0 <= dropout_rate <= 1: + raise ValueError("dropout_rate should be between 0 and 1.") + mlp_dim = mlp_dim or hidden_size + self.linear1 = nn.Linear(hidden_size, mlp_dim) + self.linear2 = nn.Linear(mlp_dim, hidden_size) + self.fn = nn.GELU() + self.drop1 = nn.Dropout(dropout_rate) + if dropout_mode == "vit": + self.drop2 = nn.Dropout(dropout_rate) + elif dropout_mode == "swin": + self.drop2 = self.drop1 + else: + raise ValueError(f"dropout_mode should be 'vit' or 'swin', got {dropout_mode!r}") + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.drop1(self.fn(self.linear1(x))) + return self.drop2(self.linear2(x)) + + +class DropPath(nn.Module): + """Per-sample stochastic depth (MONAI ``DropPath``: Bernoulli mask, scaled by the keep rate).""" + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): + super().__init__() + if not 0 <= drop_prob <= 1: + raise ValueError("Drop path prob should be between 0 and 1.") + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class TemporalReadout: + """Mixin for 3D networks over ``(time, H, W)`` fed with PyHazards' ``(B, T, C, H, W)`` layout. + + Subclasses call :meth:`_to_network_layout` before the network and :meth:`_read_out` after it. + With ``time_reduction="mean"`` (TS-SatFire's prediction script, ``outputs.mean(2)``) the + logits are averaged over time to ``(B, classes, H, W)``; ``"none"`` keeps + ``(B, classes, T, H, W)``. + """ + + time_reduction: str + + def _set_time_reduction(self, time_reduction: str) -> None: + if time_reduction not in {"mean", "none"}: + raise ValueError(f"time_reduction must be 'mean' or 'none', got {time_reduction!r}") + self.time_reduction = time_reduction + + @staticmethod + def _to_network_layout(x: torch.Tensor, name: str) -> torch.Tensor: + if x.ndim != 5: + raise ValueError( + f"{name} expects input shape (batch, time, channels, height, width), got {tuple(x.shape)}." + ) + return x.transpose(1, 2).contiguous() + + def _read_out(self, out: torch.Tensor) -> torch.Tensor: + return out.mean(2) if self.time_reduction == "mean" else out + + +__all__ = [ + "DropPath", + "MLPBlock", + "TemporalReadout", + "UnetBasicBlock", + "UnetOutBlock", + "UnetResBlock", + "UnetrBasicBlock", + "UnetrPrUpBlock", + "UnetrUpBlock", + "get_conv_layer", + "get_norm_layer", + "trunc_normal_", +] diff --git a/pyhazards/models/neuralhydrology_ealstm.py b/pyhazards/models/neuralhydrology_ealstm.py index 4dcac1fd..20d7e753 100644 --- a/pyhazards/models/neuralhydrology_ealstm.py +++ b/pyhazards/models/neuralhydrology_ealstm.py @@ -1,75 +1,150 @@ +"""Entity-Aware LSTM (EA-LSTM) of Kratzert et al. (HESS 2019), as implemented in NeuralHydrology. + +Port of NeuralHydrology ``neuralhydrology/modelzoo/ealstm.py`` (``EALSTM``, ``_DynamicGates``) and +``head.py`` (``Regression``) at commit ea94a40 (https://github.com/neuralhydrology/neuralhydrology, +BSD-3-Clause, Copyright (c) 2021, NeuralHydrology), which is the same network as the paper code +(kratzert/ealstm_regional_modeling, ``papercode/ealstm.py``, Apache-2.0). + +The input gate is computed once from the static catchment attributes, ``i = sigmoid(W_s x_s + b_s)``, +and used at every step; the forget, output and cell gates come from the dynamic inputs and the previous +hidden state (``f, o, g`` chunks of ``h W_hh + x W_ih + b``): +``c_t = sigmoid(f) * c_{t-1} + i * tanh(g)``, ``h_t = sigmoid(o) * tanh(c_t)``. +Parameter names (``input_gate.*``, ``dynamic_gates.weight_ih/weight_hh/bias``, ``head.net.0.*``), +initialisation (orthogonal ``weight_ih``, identity-tiled ``weight_hh``, zero bias with the forget slice +set to ``initial_forget_bias``) and the order of creation follow the reference. Official Kratzert et al. +(2019) checkpoints load after :func:`~pyhazards.models.neuralhydrology_lstm.convert_kratzert2019_state_dict`. +""" + from __future__ import annotations -from typing import Any +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Tuple, Union import torch import torch.nn as nn +from .neuralhydrology_lstm import Regression, load_kratzert2019_state_dict, streamflow_inputs + + +class _DynamicGates(nn.Module): + """Forget, output and cell gates of the EA-LSTM (``_DynamicGates`` of the reference).""" + + def __init__(self, input_size: int, hidden_size: int, initial_forget_bias: Optional[float]): + super().__init__() + self.hidden_size = hidden_size + self.initial_forget_bias = initial_forget_bias + self.weight_ih = nn.Parameter(torch.empty(input_size, 3 * hidden_size)) + self.weight_hh = nn.Parameter(torch.empty(hidden_size, 3 * hidden_size)) + self.bias = nn.Parameter(torch.empty(3 * hidden_size)) + self._reset_parameters() + + def _reset_parameters(self) -> None: + nn.init.orthogonal_(self.weight_ih.data) + self.weight_hh.data = torch.eye(self.hidden_size).repeat(1, 3) + nn.init.constant_(self.bias.data, val=0) + if self.initial_forget_bias is not None: + self.bias.data[: self.hidden_size] = self.initial_forget_bias -def _streamflow_inputs(batch: Any) -> torch.Tensor: - x = batch["x"] if isinstance(batch, dict) else batch - if x.ndim != 4: - raise ValueError("EA-LSTM expects inputs shaped (batch, history, nodes, features).") - return x + def forward(self, h: torch.Tensor, x_d: torch.Tensor) -> torch.Tensor: + return h @ self.weight_hh + x_d @ self.weight_ih + self.bias class NeuralHydrologyEALSTM(nn.Module): - """Entity-aware LSTM style streamflow baseline.""" + """EA-LSTM with a regression head. + + ``forward({"x_d": (B, T, n_dynamic), "x_s": (B, n_static)})`` returns ``y_hat`` (B, T, n_targets) and + the hidden and cell states of every step, ``h_n`` and ``c_n`` (B, T, hidden_size), like the reference. + """ def __init__( self, - input_dim: int = 2, - hidden_dim: int = 64, - num_layers: int = 1, - out_dim: int = 1, - dropout: float = 0.1, + n_dynamic: int = 5, + n_static: int = 27, + hidden_size: int = 256, + n_targets: int = 1, + output_dropout: float = 0.4, + initial_forget_bias: Optional[float] = 5.0, + output_activation: str = "linear", ): super().__init__() - self.hidden_dim = int(hidden_dim) - self.out_dim = int(out_dim) - self.dynamic_encoder = nn.LSTM( - input_size=input_dim, - hidden_size=hidden_dim, - num_layers=num_layers, - batch_first=True, - dropout=dropout if num_layers > 1 else 0.0, - ) - self.static_gate = nn.Sequential( - nn.Linear(input_dim, hidden_dim), - nn.Sigmoid(), - ) - self.head = nn.Linear(hidden_dim, self.out_dim) - - def forward(self, batch: Any) -> torch.Tensor: - x = _streamflow_inputs(batch) - bsz, history, nodes, features = x.shape - series = x.permute(0, 2, 1, 3).reshape(bsz * nodes, history, features) - encoded, _ = self.dynamic_encoder(series) - static_features = series.mean(dim=1) - gated = encoded[:, -1] * self.static_gate(static_features) - preds = self.head(gated) - return preds.view(bsz, nodes, self.out_dim) + for label, value in ( + ("n_dynamic", n_dynamic), + ("n_static", n_static), + ("hidden_size", hidden_size), + ("n_targets", n_targets), + ): + if int(value) <= 0: + raise ValueError(f"{label} must be positive (the EA-LSTM input gate needs static inputs), got {value}.") + if not 0.0 <= output_dropout < 1.0: + raise ValueError(f"output_dropout must be in [0, 1), got {output_dropout}.") + self.n_dynamic = int(n_dynamic) + self.n_static = int(n_static) + self._hidden_size = int(hidden_size) + # Reference order: InputLayer (no parameters), input gate, dynamic gates, dropout, head. + self.input_gate = nn.Linear(self.n_static, self._hidden_size) + self.dynamic_gates = _DynamicGates(self.n_dynamic, self._hidden_size, initial_forget_bias) + self.dropout = nn.Dropout(p=output_dropout) + self.head = Regression(n_in=self._hidden_size, n_out=int(n_targets), activation=output_activation) + + def _cell(self, x: torch.Tensor, i: torch.Tensor, states: Tuple[torch.Tensor, torch.Tensor]): + h_0, c_0 = states + gates = self.dynamic_gates(h_0, x) + f, o, g = gates.chunk(3, 1) + c_1 = torch.sigmoid(f) * c_0 + i * torch.tanh(g) + h_1 = torch.sigmoid(o) * torch.tanh(c_1) + return h_1, c_1 + + def forward(self, batch: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + x_d, x_s = streamflow_inputs(batch, self.n_dynamic, self.n_static, "NeuralHydrologyEALSTM") + x_d = x_d.transpose(0, 1) # [seq_length, batch_size, n_features] + h_t = x_d.new_zeros(x_d.shape[1], self._hidden_size) + c_t = x_d.new_zeros(x_d.shape[1], self._hidden_size) + h_n, c_n = [], [] + i = torch.sigmoid(self.input_gate(x_s)) # computed once: the inputs are static + for x_dt in x_d: + h_t, c_t = self._cell(x_dt, i, (h_t, c_t)) + h_n.append(h_t) + c_n.append(c_t) + h_n = torch.stack(h_n, 0).transpose(0, 1) + c_n = torch.stack(c_n, 0).transpose(0, 1) + pred = {"h_n": h_n, "c_n": c_n} + pred.update(self.head(self.dropout(h_n))) + return pred def neuralhydrology_ealstm_builder( task: str, - input_dim: int = 2, - hidden_dim: int = 64, - num_layers: int = 1, - out_dim: int = 1, - dropout: float = 0.1, - **kwargs, + n_dynamic: int = 5, + n_static: int = 27, + hidden_size: int = 256, + n_targets: int = 1, + output_dropout: float = 0.4, + initial_forget_bias: Optional[float] = 5.0, + output_activation: str = "linear", + checkpoint: Optional[Union[str, Path]] = None, + **kwargs: Any, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("NeuralHydrologyEALSTM only supports regression for streamflow forecasting.") - return NeuralHydrologyEALSTM( - input_dim=input_dim, - hidden_dim=hidden_dim, - num_layers=num_layers, - out_dim=out_dim, - dropout=dropout, + """Build the EA-LSTM; defaults are the Kratzert et al. (2019) configuration (5 dynamic, 27 static, 256). + + ``checkpoint`` is an official 2019 EA-LSTM ``model_epoch30.pt``, loaded with ``strict=True``. + """ + kwargs.pop("name", None) + if kwargs: + raise ValueError(f"Unexpected arguments for neuralhydrology_ealstm: {sorted(kwargs)}") + if task.lower() not in ("regression", "streamflow"): + raise ValueError(f"neuralhydrology_ealstm supports task='regression' (streamflow), got {task!r}.") + model = NeuralHydrologyEALSTM( + n_dynamic=n_dynamic, + n_static=n_static, + hidden_size=hidden_size, + n_targets=n_targets, + output_dropout=output_dropout, + initial_forget_bias=initial_forget_bias, + output_activation=output_activation, ) + if checkpoint is not None: + model.load_state_dict(load_kratzert2019_state_dict(checkpoint), strict=True) + return model __all__ = ["NeuralHydrologyEALSTM", "neuralhydrology_ealstm_builder"] diff --git a/pyhazards/models/neuralhydrology_lstm.py b/pyhazards/models/neuralhydrology_lstm.py index f353caf8..2e7c885b 100644 --- a/pyhazards/models/neuralhydrology_lstm.py +++ b/pyhazards/models/neuralhydrology_lstm.py @@ -1,68 +1,214 @@ +"""NeuralHydrology LSTM (``CudaLSTM``): the regional rainfall-runoff LSTM with static catchment inputs. + +Port of NeuralHydrology ``neuralhydrology/modelzoo/cudalstm.py`` (``CudaLSTM``), ``head.py`` +(``Regression``) and the input concatenation of ``inputlayer.py`` at commit ea94a40 +(https://github.com/neuralhydrology/neuralhydrology, BSD-3-Clause, Copyright (c) 2021, NeuralHydrology). + +The model is a single-layer ``nn.LSTM`` over daily inputs, where the static catchment attributes ``x_s`` +are concatenated to the dynamic inputs ``x_d`` at every time step (Kratzert et al., HESS 2019, "LSTM +with static inputs"; the LSTM rainfall-runoff model itself is Kratzert et al., HESS 2018), followed by +dropout and a linear regression head applied to every time step. Parameter names (``lstm.*``, +``head.net.0.*``), initialisation order and the forget-gate bias initialisation of the reference are kept, +so NeuralHydrology state dicts load with ``strict=True`` and the same seed gives the same weights. + +:func:`convert_kratzert2019_state_dict` maps the official checkpoints of Kratzert et al. (2019) (written by +``papercode/lstm.py`` of kratzert/ealstm_regional_modeling, Apache-2.0: one bias vector, gate order f, i, +o, g, transposed weights) onto this layout. +""" + from __future__ import annotations -from typing import Any +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Tuple, Union import torch import torch.nn as nn -def _streamflow_inputs(batch: Any) -> torch.Tensor: - x = batch["x"] if isinstance(batch, dict) else batch - if x.ndim != 4: - raise ValueError("NeuralHydrology-style models expect inputs shaped (batch, history, nodes, features).") - return x +def streamflow_inputs(batch: Any, n_dynamic: int, n_static: int, model_name: str) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """``x_d`` (batch, time, n_dynamic) and ``x_s`` (batch, n_static) from a streamflow batch mapping.""" + if not isinstance(batch, Mapping) or "x_d" not in batch: + raise ValueError( + f"{model_name} expects a mapping with 'x_d' of shape (batch, time, n_dynamic) and, with static " + "attributes, 'x_s' of shape (batch, n_static)." + ) + x_d = batch["x_d"] + if not isinstance(x_d, torch.Tensor) or x_d.ndim != 3 or x_d.shape[-1] != n_dynamic: + shape = tuple(x_d.shape) if isinstance(x_d, torch.Tensor) else type(x_d).__name__ + raise ValueError(f"{model_name} expects x_d of shape (batch, time, {n_dynamic}), got {shape}.") + x_s = batch.get("x_s") + if n_static: + if not isinstance(x_s, torch.Tensor) or x_s.ndim != 2 or tuple(x_s.shape) != (x_d.shape[0], n_static): + shape = tuple(x_s.shape) if isinstance(x_s, torch.Tensor) else None + raise ValueError(f"{model_name} expects x_s of shape ({x_d.shape[0]}, {n_static}), got {shape}.") + elif x_s is not None and x_s.numel(): + raise ValueError(f"{model_name} was built without static attributes (n_static=0) but received x_s.") + else: + x_s = None + return x_d, x_s + + +class Regression(nn.Module): + """NeuralHydrology's single-layer regression head (``head.Regression``).""" + + def __init__(self, n_in: int, n_out: int, activation: str = "linear"): + super().__init__() + layers = [nn.Linear(n_in, n_out)] + if activation != "linear": + if activation.lower() == "relu": + layers.append(nn.ReLU()) + elif activation.lower() == "softplus": + layers.append(nn.Softplus()) + else: + raise ValueError(f"output_activation must be 'linear', 'relu' or 'softplus', got {activation!r}.") + self.net = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]: + return {"y_hat": self.net(x)} class NeuralHydrologyLSTM(nn.Module): - """Adapter-style LSTM streamflow baseline.""" + """``CudaLSTM`` of NeuralHydrology with a regression head. + + ``forward({"x_d": (B, T, n_dynamic), "x_s": (B, n_static)})`` returns, like the reference, + ``y_hat`` (B, T, n_targets), ``lstm_output`` (B, T, hidden_size), ``h_n`` and ``c_n`` (B, 1, hidden_size). + """ def __init__( self, - input_dim: int = 2, - hidden_dim: int = 64, - num_layers: int = 2, - out_dim: int = 1, - dropout: float = 0.1, + n_dynamic: int = 5, + n_static: int = 27, + hidden_size: int = 256, + n_targets: int = 1, + output_dropout: float = 0.4, + initial_forget_bias: Optional[float] = 5.0, + output_activation: str = "linear", ): super().__init__() - self.out_dim = int(out_dim) - self.encoder = nn.LSTM( - input_size=input_dim, - hidden_size=hidden_dim, - num_layers=num_layers, - batch_first=True, - dropout=dropout if num_layers > 1 else 0.0, + for label, value in (("n_dynamic", n_dynamic), ("hidden_size", hidden_size), ("n_targets", n_targets)): + if int(value) <= 0: + raise ValueError(f"{label} must be positive, got {value}.") + if int(n_static) < 0: + raise ValueError(f"n_static must be >= 0, got {n_static}.") + if not 0.0 <= output_dropout < 1.0: + raise ValueError(f"output_dropout must be in [0, 1), got {output_dropout}.") + self.n_dynamic = int(n_dynamic) + self.n_static = int(n_static) + self.hidden_size = int(hidden_size) + self.initial_forget_bias = initial_forget_bias + # Reference order: InputLayer (no parameters without embedding networks), LSTM, dropout, head. + self.lstm = nn.LSTM(input_size=self.n_dynamic + self.n_static, hidden_size=self.hidden_size) + self.dropout = nn.Dropout(p=output_dropout) + self.head = Regression(n_in=self.hidden_size, n_out=int(n_targets), activation=output_activation) + self._reset_parameters() + + def _reset_parameters(self) -> None: + if self.initial_forget_bias is not None: + self.lstm.bias_hh_l0.data[self.hidden_size: 2 * self.hidden_size] = self.initial_forget_bias + + def forward(self, batch: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + x_d, x_s = streamflow_inputs(batch, self.n_dynamic, self.n_static, "NeuralHydrologyLSTM") + x = x_d.transpose(0, 1) # [seq_length, batch_size, n_features], as the reference InputLayer + if x_s is not None: + x = torch.cat([x, x_s.unsqueeze(0).repeat(x.shape[0], 1, 1)], dim=-1) + lstm_output, (h_n, c_n) = self.lstm(input=x) + lstm_output = lstm_output.transpose(0, 1) + h_n = h_n.transpose(0, 1) + c_n = c_n.transpose(0, 1) + pred = {"lstm_output": lstm_output, "h_n": h_n, "c_n": c_n} + pred.update(self.head(self.dropout(lstm_output))) + return pred + + +def _reorder_gates(tensor: torch.Tensor, hidden_size: int, order: Tuple[int, ...]) -> torch.Tensor: + chunks = tensor.split(hidden_size, dim=0) + return torch.cat([chunks[i] for i in order], dim=0) + + +def convert_kratzert2019_state_dict(state_dict: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + """Official Kratzert et al. (2019) checkpoint -> state dict of this module or the EA-LSTM port. + + LSTM checkpoints (``lstm.weight_ih`` (in, 4H), ``lstm.weight_hh`` (H, 4H), ``lstm.bias`` (4H), gates + f, i, o, g) become ``nn.LSTM`` tensors (gates i, f, g, o; the single bias goes to ``bias_ih_l0`` and + ``bias_hh_l0`` is zero). EA-LSTM checkpoints (with ``lstm.weight_sh``) keep their gate layout (f, o, g, + as in NeuralHydrology); ``weight_sh`` (S, H) becomes ``input_gate.weight`` (H, S). ``fc.*`` becomes + ``head.net.0.*``. + """ + state = dict(state_dict) + out: Dict[str, torch.Tensor] = { + "head.net.0.weight": state["fc.weight"], + "head.net.0.bias": state["fc.bias"], + } + if "lstm.weight_sh" in state: + out.update( + { + "input_gate.weight": state["lstm.weight_sh"].t().contiguous(), + "input_gate.bias": state["lstm.bias_s"], + "dynamic_gates.weight_ih": state["lstm.weight_ih"], + "dynamic_gates.weight_hh": state["lstm.weight_hh"], + "dynamic_gates.bias": state["lstm.bias"], + } ) - self.head = nn.Linear(hidden_dim, self.out_dim) + return out + hidden = state["lstm.weight_hh"].shape[0] + order = (1, 0, 3, 2) # (f, i, o, g) -> (i, f, g, o) + out.update( + { + "lstm.weight_ih_l0": _reorder_gates(state["lstm.weight_ih"].t(), hidden, order).contiguous(), + "lstm.weight_hh_l0": _reorder_gates(state["lstm.weight_hh"].t(), hidden, order).contiguous(), + "lstm.bias_ih_l0": _reorder_gates(state["lstm.bias"], hidden, order).contiguous(), + "lstm.bias_hh_l0": torch.zeros_like(state["lstm.bias"]), + } + ) + return out - def forward(self, batch: Any) -> torch.Tensor: - x = _streamflow_inputs(batch) - bsz, history, nodes, features = x.shape - series = x.permute(0, 2, 1, 3).reshape(bsz * nodes, history, features) - encoded, _ = self.encoder(series) - preds = self.head(encoded[:, -1]) - return preds.view(bsz, nodes, self.out_dim) + +def load_kratzert2019_state_dict(path: Union[str, Path]) -> Dict[str, torch.Tensor]: + """Read a ``model_epoch30.pt`` of the official 2019 runs (HydroShare, CC BY 4.0) and convert it.""" + return convert_kratzert2019_state_dict(torch.load(path, map_location="cpu", weights_only=True)) def neuralhydrology_lstm_builder( task: str, - input_dim: int = 2, - hidden_dim: int = 64, - num_layers: int = 2, - out_dim: int = 1, - dropout: float = 0.1, - **kwargs, + n_dynamic: int = 5, + n_static: int = 27, + hidden_size: int = 256, + n_targets: int = 1, + output_dropout: float = 0.4, + initial_forget_bias: Optional[float] = 5.0, + output_activation: str = "linear", + checkpoint: Optional[Union[str, Path]] = None, + **kwargs: Any, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("NeuralHydrologyLSTM only supports regression for streamflow forecasting.") - return NeuralHydrologyLSTM( - input_dim=input_dim, - hidden_dim=hidden_dim, - num_layers=num_layers, - out_dim=out_dim, - dropout=dropout, + """Build the LSTM; defaults are the Kratzert et al. (2019) "LSTM with static inputs" configuration. + + ``checkpoint`` is an official 2019 ``model_epoch30.pt`` (LSTM with or without static inputs), + converted with :func:`convert_kratzert2019_state_dict` and loaded with ``strict=True``. + """ + kwargs.pop("name", None) + if kwargs: + raise ValueError(f"Unexpected arguments for neuralhydrology_lstm: {sorted(kwargs)}") + if task.lower() not in ("regression", "streamflow"): + raise ValueError(f"neuralhydrology_lstm supports task='regression' (streamflow), got {task!r}.") + model = NeuralHydrologyLSTM( + n_dynamic=n_dynamic, + n_static=n_static, + hidden_size=hidden_size, + n_targets=n_targets, + output_dropout=output_dropout, + initial_forget_bias=initial_forget_bias, + output_activation=output_activation, ) + if checkpoint is not None: + model.load_state_dict(load_kratzert2019_state_dict(checkpoint), strict=True) + return model -__all__ = ["NeuralHydrologyLSTM", "neuralhydrology_lstm_builder"] +__all__ = [ + "NeuralHydrologyLSTM", + "Regression", + "convert_kratzert2019_state_dict", + "load_kratzert2019_state_dict", + "neuralhydrology_lstm_builder", + "streamflow_inputs", +] diff --git a/pyhazards/models/pangu_tc.py b/pyhazards/models/pangu_tc.py deleted file mode 100644 index 9335c263..00000000 --- a/pyhazards/models/pangu_tc.py +++ /dev/null @@ -1,63 +0,0 @@ -from __future__ import annotations - -import torch -import torch.nn as nn - - -class PanguTC(nn.Module): - """Experimental wrapper-style Pangu-Weather storm adapter.""" - - def __init__( - self, - input_dim: int = 8, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - ): - super().__init__() - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.temporal = nn.Sequential( - nn.Conv1d(input_dim, hidden_dim, kernel_size=5, padding=2), - nn.GELU(), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1), - nn.GELU(), - ) - self.head = nn.Sequential( - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, hidden_dim), - nn.GELU(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("PanguTC expects inputs shaped (batch, history, features).") - encoded = self.temporal(x.transpose(1, 2)).mean(dim=-1) - preds = self.head(encoded) - return preds.view(x.size(0), self.horizon, self.output_dim) - - -def pangu_tc_builder( - task: str, - input_dim: int = 8, - hidden_dim: int = 96, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("PanguTC only supports regression for track/intensity forecasting.") - return PanguTC( - input_dim=input_dim, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - dropout=dropout, - ) - - -__all__ = ["PanguTC", "pangu_tc_builder"] diff --git a/pyhazards/models/phasenet.py b/pyhazards/models/phasenet.py index eb3197bb..45b48e6e 100644 --- a/pyhazards/models/phasenet.py +++ b/pyhazards/models/phasenet.py @@ -1,46 +1,316 @@ +"""PhaseNet: a deep-neural-network-based seismic arrival-time picking method. + +Zhu & Beroza, Geophysical Journal International 216(1):261-273 (2019), doi:10.1093/gji/ggy423 +(arXiv 1803.03211). + +Port of the official TensorFlow code, AI4EPS/PhaseNet at commit +``62005c6195638f88d077f8870ea895971062715a``: ``phasenet/model.py`` (``UNet``, ``crop_and_concat``, +``ModelConfig``), ``phasenet/data_reader.py`` (``normalize``) and ``phasenet/util.py`` +(``detect_peaks_thread``). MIT License, Copyright (c) 2021 Weiqiang Zhu. + +The network is a 1-D U-Net over three-component waveforms ``(batch, 3, samples)`` that returns +per-sample probabilities of noise, P and S (softmax over the three classes). With the released +configuration (``model/190703-214543/config.log``: depths 5, filters_root 8, kernel 7, pool 4) the +channel widths are 8, 16, 32, 64, 128 and the model has 268,443 trainable parameters. The paper's +Figure 5 shows widths 8, 11, 16, 22, 32 and no batch normalisation; the port follows the code and the +released checkpoint, which use 8-128 with batch normalisation. + +Implementation notes: + +- Module and parameter names mirror the TensorFlow variable scopes (``Input/input_conv``, + ``DownConv_/down_conv1_``, ``UpConv_/up_conv0_``, ``Output/output_conv``, ...), so a + TensorFlow variable ``A/b/kernel`` becomes the PyTorch parameter ``A.b.weight`` (see + :func:`state_dict_from_tf_checkpoint`). +- TensorFlow ``"same"`` padding is reproduced exactly, including its asymmetric split for the stride-4 + convolutions (more padding on the right) and the ``"same"`` transposed convolutions (output length + ``stride * input``); skip connections crop the up-sampled branch at offset ``(n_up - n_skip) // 2`` + like ``crop_and_concat``. Any input length works, as in the official code. +- Batch normalisation uses TensorFlow's defaults (epsilon 1e-3, moving-average momentum 0.99, i.e. + PyTorch momentum 0.01). Weights are initialised like the reference (Glorot-uniform kernels + ``VarianceScaling(1.0, "fan_avg", "uniform")``, zero biases); TensorFlow's random draws cannot be + reproduced in PyTorch. +""" + from __future__ import annotations +import math +from pathlib import Path +from typing import Dict, List, Optional, Union + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F +from ._pretrained import cached_download +from ._seismic import TracePicks, WaveformPicker, as_sequence, check_waveforms, picks_from_peaks, std_normalize +from ._tf_checkpoint import read_tf_checkpoint -class PhaseNet(nn.Module): - """Lightweight phase-picking network for synthetic waveform smoke runs.""" +# Official checkpoint model/190703-214543 (config.log above), raw files pinned to the reference commit. +_PHASENET_RAW = "https://raw.githubusercontent.com/AI4EPS/PhaseNet/62005c6195638f88d077f8870ea895971062715a/model/190703-214543/" +PHASENET_WEIGHTS: Dict[str, Dict[str, object]] = { + "original": { + "checkpoint": "model_95.ckpt", + "files": { + "model_95.ckpt.index": "f96b553b76be4ebae9a455eaf8d83cfa8c0e110f06cfba958de2568e5b6b2780", + "model_95.ckpt.data-00000-of-00001": "9ee2c15dd78fb15de45a55ad64a446f1a0ced152ba4ac5c506d82b9194da85b4", + }, + "license": "MIT (AI4EPS/PhaseNet)", + }, +} + + +def _tf_same_padding(length: int, kernel_size: int, stride: int) -> tuple: + out = math.ceil(length / stride) + total = max((out - 1) * stride + kernel_size - length, 0) + return total // 2, total - total // 2 - def __init__(self, in_channels: int = 3, hidden_dim: int = 32): - super().__init__() - self.encoder = nn.Sequential( - nn.Conv1d(in_channels, hidden_dim, kernel_size=9, padding=4), - nn.ReLU(), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=7, padding=3), - nn.ReLU(), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=5, padding=2), - nn.ReLU(), - ) - self.head = nn.Sequential( - nn.AdaptiveAvgPool1d(1), - nn.Flatten(), - nn.Linear(hidden_dim, hidden_dim), - nn.ReLU(), - nn.Linear(hidden_dim, 2), - ) + +class _TFConv1d(nn.Conv1d): + """``tf.compat.v1.layers.conv2d`` with ``padding="same"`` on ``(batch, channels, samples)``.""" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + left, right = _tf_same_padding(x.shape[-1], self.kernel_size[0], self.stride[0]) + return F.conv1d(F.pad(x, (left, right)), self.weight, self.bias, self.stride) + + +class _TFConvTranspose1d(nn.ConvTranspose1d): + """``tf.compat.v1.layers.conv2d_transpose`` with ``padding="same"`` (output ``stride * length``).""" def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("PhaseNet expects inputs shaped (batch, channels, length).") - return self.head(self.encoder(x)) + length = x.shape[-1] * self.stride[0] + left, _ = _tf_same_padding(length, self.kernel_size[0], self.stride[0]) + full = F.conv_transpose1d(x, self.weight, self.bias, self.stride) + return full[..., left : left + length] + + +def _tf_batch_norm(channels: int) -> nn.BatchNorm1d: + return nn.BatchNorm1d(channels, eps=1e-3, momentum=0.01) + + +def _glorot_uniform_(weight: torch.Tensor, fan_in: int, fan_out: int) -> None: + limit = math.sqrt(6.0 / (fan_in + fan_out)) + with torch.no_grad(): + weight.uniform_(-limit, limit) + + +class PhaseNet(nn.Module, WaveformPicker): + """PhaseNet U-Net: ``(batch, in_channels, samples)`` waveforms -> ``(batch, classes, samples)``. + + ``forward`` returns softmax probabilities of (noise, P, S); ``forward(x, logits=True)`` returns + the pre-softmax output that the official cross-entropy loss uses. :meth:`annotate` adds the + official per-window normalisation, :meth:`extract_picks` the official peak picking. + """ + + sampling_rate = 100.0 + component_order = "ENZ" + output_names = ("noise", "P", "S") + phase_channels = {"P": 1, "S": 2} + + def __init__( + self, + in_channels: int = 3, + classes: int = 3, + depths: int = 5, + filters_root: int = 8, + kernel_size: int = 7, + pool_size: int = 4, + drop_rate: float = 0.0, + ): + super().__init__() + for label, value in (("in_channels", in_channels), ("classes", classes), ("depths", depths), + ("filters_root", filters_root), ("kernel_size", kernel_size), ("pool_size", pool_size)): + if int(value) < 1: + raise ValueError(f"PhaseNet {label} must be positive, got {value}.") + if not 0.0 <= drop_rate < 1.0: + raise ValueError(f"PhaseNet drop_rate must be in [0, 1), got {drop_rate}.") + self.in_channels = int(in_channels) + self.classes = int(classes) + self.depths = int(depths) + self.filters_root = int(filters_root) + self.kernel_size = int(kernel_size) + self.pool_size = int(pool_size) + self.drop_rate = float(drop_rate) + k, s = self.kernel_size, self.pool_size + + # Modules are created in the order of the TensorFlow graph (UNet.add_prediction_op). + inputs = nn.Module() + inputs.add_module("input_conv", _TFConv1d(in_channels, filters_root, k, bias=True)) + inputs.add_module("input_bn", _tf_batch_norm(filters_root)) + self.add_module("Input", inputs) + for depth in range(self.depths): + filters = int(2**depth * filters_root) + previous = filters_root if depth == 0 else int(2 ** (depth - 1) * filters_root) + block = nn.Module() + block.add_module(f"down_conv1_{depth + 1}", _TFConv1d(previous, filters, k, bias=False)) + block.add_module(f"down_bn1_{depth + 1}", _tf_batch_norm(filters)) + if depth < self.depths - 1: + block.add_module(f"down_conv3_{depth + 1}", _TFConv1d(filters, filters, k, stride=s, bias=False)) + block.add_module(f"down_bn3_{depth + 1}", _tf_batch_norm(filters)) + self.add_module(f"DownConv_{depth}", block) + for depth in range(self.depths - 2, -1, -1): + filters = int(2**depth * filters_root) + block = nn.Module() + block.add_module(f"up_conv0_{depth + 1}", _TFConvTranspose1d(2 * filters, filters, k, stride=s, bias=False)) + block.add_module(f"up_bn0_{depth + 1}", _tf_batch_norm(filters)) + block.add_module(f"up_conv1_{depth + 1}", _TFConv1d(2 * filters, filters, k, bias=False)) + block.add_module(f"up_bn1_{depth + 1}", _tf_batch_norm(filters)) + self.add_module(f"UpConv_{depth}", block) + outputs = nn.Module() + outputs.add_module("output_conv", _TFConv1d(filters_root, classes, 1, bias=True)) + self.add_module("Output", outputs) + self.dropout = nn.Dropout(self.drop_rate) + self.reset_parameters() + + def reset_parameters(self) -> None: + """Glorot-uniform kernels (fans of the TensorFlow kernel shape), zero biases, BN 1/0.""" + for module in self.modules(): + if isinstance(module, (_TFConv1d, _TFConvTranspose1d)): + kernel = module.weight.shape[-1] + if isinstance(module, _TFConvTranspose1d): # TF kernel (k, 1, out, in) + fan_in, fan_out = kernel * module.out_channels, kernel * module.in_channels + else: # TF kernel (k, 1, in, out) + fan_in, fan_out = kernel * module.in_channels, kernel * module.out_channels + _glorot_uniform_(module.weight, fan_in, fan_out) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.BatchNorm1d): + module.reset_parameters() + + def _block(self, name: str) -> nn.Module: + return getattr(self, name) + + def _conv_bn_relu(self, x: torch.Tensor, block: nn.Module, conv: str, bn: str) -> torch.Tensor: + x = getattr(block, bn)(getattr(block, conv)(x)) + return self.dropout(F.relu(x)) + + def forward(self, x: torch.Tensor, logits: bool = False) -> torch.Tensor: + check_waveforms(x, self.in_channels, "PhaseNet") + if x.shape[-1] < 1: + raise ValueError("PhaseNet needs at least one sample.") + inputs = self._block("Input") + net = self._conv_bn_relu(x, inputs, "input_conv", "input_bn") + skips: List[torch.Tensor] = [] + for depth in range(self.depths): + block = self._block(f"DownConv_{depth}") + net = self._conv_bn_relu(net, block, f"down_conv1_{depth + 1}", f"down_bn1_{depth + 1}") + skips.append(net) + if depth < self.depths - 1: + net = self._conv_bn_relu(net, block, f"down_conv3_{depth + 1}", f"down_bn3_{depth + 1}") + for depth in range(self.depths - 2, -1, -1): + block = self._block(f"UpConv_{depth}") + net = self._conv_bn_relu(net, block, f"up_conv0_{depth + 1}", f"up_bn0_{depth + 1}") + skip = skips[depth] + offset = (net.shape[-1] - skip.shape[-1]) // 2 + net = torch.cat([skip, net[..., offset : offset + skip.shape[-1]]], dim=1) + net = self._conv_bn_relu(net, block, f"up_conv1_{depth + 1}", f"up_bn1_{depth + 1}") + out = self._block("Output").output_conv(net) + return out if logits else torch.softmax(out, dim=1) + + def annotate(self, waveforms: torch.Tensor) -> torch.Tensor: + """Per-sample (noise, P, S) probabilities of raw windows, normalised like the official reader.""" + return self(std_normalize(waveforms)) + + def extract_picks( + self, + annotations: torch.Tensor, + p_threshold: float = 0.5, + s_threshold: float = 0.5, + min_distance: Optional[int] = None, + **kwargs, + ) -> List[TracePicks]: + """Official peak picking: ``detect_peaks(prob, mph=threshold, mpd=0.5 s)`` for P and S. + + Thresholds 0.5 are the paper's ("peak probabilities above 0.5 are counted as positive picks"); + ``phasenet/util.py`` uses the same 0.5 and ``mpd = 0.5 / dt`` (50 samples at 100 Hz). + """ + if kwargs: + raise TypeError(f"Unexpected PhaseNet pick parameters: {sorted(kwargs)}.") + distance = int(round(0.5 * self.sampling_rate)) if min_distance is None else int(min_distance) + thresholds = as_sequence({"P": p_threshold, "S": s_threshold}, ("P", "S")) + return picks_from_peaks(annotations, self.phase_channels, thresholds, distance) + + +def state_dict_from_tf_checkpoint(variables: Dict[str, np.ndarray]) -> Dict[str, torch.Tensor]: + """PhaseNet state dict from TensorFlow checkpoint variables (optimizer slots are ignored).""" + renames = {"kernel": "weight", "bias": "bias", "gamma": "weight", "beta": "bias", + "moving_mean": "running_mean", "moving_variance": "running_var"} + state: Dict[str, torch.Tensor] = {} + for name, value in variables.items(): + parts = name.split("/") + if len(parts) != 3 or parts[0] not in ("Input", "Output") and not parts[0].startswith(("DownConv_", "UpConv_")): + continue # global_step, beta1_power, ... + if parts[2] not in renames: + continue # Adam slots: /Adam, /Adam_1 have four components + tensor = torch.from_numpy(np.ascontiguousarray(value)) + if parts[2] == "kernel": # (k, 1, in, out) -> (out, in, k); transposed convs: (k, 1, out, in) -> (in, out, k) + tensor = tensor[:, 0].permute(2, 1, 0).contiguous() + key = f"{parts[0]}.{parts[1]}.{renames[parts[2]]}" + state[key] = tensor + if key.endswith(".running_var"): # PyTorch's BatchNorm counter, absent in TensorFlow + state[key[: -len("running_var")] + "num_batches_tracked"] = torch.tensor(0, dtype=torch.long) + return state + + +def phasenet_checkpoint_prefix(name: str = "original") -> Path: + """Local prefix of an official TensorFlow checkpoint, downloaded on first use.""" + if name not in PHASENET_WEIGHTS: + raise ValueError(f"Unknown PhaseNet weights {name!r}; expected one of {sorted(PHASENET_WEIGHTS)}.") + spec = PHASENET_WEIGHTS[name] + path = None + for filename, sha256 in spec["files"].items(): # type: ignore[union-attr] + path = cached_download("phasenet", filename, [_PHASENET_RAW + filename], sha256) + assert path is not None + return path.parent / str(spec["checkpoint"]) + + +def load_phasenet_tf_checkpoint(model: PhaseNet, prefix: Union[str, Path]) -> PhaseNet: + """Load a PhaseNet TensorFlow checkpoint (``.index`` + data file) with ``strict=True``.""" + model.load_state_dict(state_dict_from_tf_checkpoint(read_tf_checkpoint(prefix)), strict=True) + return model def phasenet_builder( task: str, in_channels: int = 3, - hidden_dim: int = 32, + classes: int = 3, + depths: int = 5, + filters_root: int = 8, + kernel_size: int = 7, + pool_size: int = 4, + drop_rate: float = 0.0, + pretrained: Optional[Union[bool, str, Path]] = None, **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("PhaseNet only supports regression-style phase picking outputs.") - return PhaseNet(in_channels=in_channels, hidden_dim=hidden_dim) +) -> PhaseNet: + """PhaseNet for ``task="picking"``. + + ``pretrained``: ``True`` or ``"original"`` loads the official checkpoint ``190703-214543`` (MIT, + downloaded from the pinned repository commit and checked by sha256); a path is read as a + TensorFlow checkpoint prefix (``.../model_95.ckpt``). + """ + kwargs.pop("name", None) + if kwargs: + raise TypeError(f"Unexpected PhaseNet arguments: {sorted(kwargs)}.") + if task.lower() != "picking": + raise ValueError(f"PhaseNet supports task='picking', got {task!r}.") + model = PhaseNet(in_channels, classes, depths, filters_root, kernel_size, pool_size, drop_rate) + if pretrained: + name = "original" if pretrained is True else str(pretrained) + if name in PHASENET_WEIGHTS: + if (in_channels, classes, depths, filters_root, kernel_size, pool_size) != (3, 3, 5, 8, 7, 4): + raise ValueError("The official PhaseNet checkpoint needs the default configuration.") + prefix = phasenet_checkpoint_prefix(name) + else: + prefix = Path(name) + load_phasenet_tf_checkpoint(model, prefix) + return model -__all__ = ["PhaseNet", "phasenet_builder"] +__all__ = [ + "PHASENET_WEIGHTS", + "PhaseNet", + "load_phasenet_tf_checkpoint", + "phasenet_builder", + "phasenet_checkpoint_prefix", + "state_dict_from_tf_checkpoint", +] diff --git a/pyhazards/models/prithvi.py b/pyhazards/models/prithvi.py new file mode 100644 index 00000000..05e9a346 --- /dev/null +++ b/pyhazards/models/prithvi.py @@ -0,0 +1,1118 @@ +"""Prithvi-EO-2.0 masked-autoencoder ViT and the TerraTorch segmentation recipe, in plain PyTorch. + +Ported from the reference code, keeping its module and parameter names so the official checkpoints +load with ``strict=True``: + +- ``prithvi_mae.py`` shipped in the Hugging Face repository ``ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL`` + (revision 63adbd39; Apache License 2.0, Copyright (c) IBM Corp. 2024): ``PatchEmbed``, + ``TemporalEncoder``, ``LocationEncoder``, ``PrithviViT``, ``MAEDecoder``, ``PrithviMAE`` and the + sin/cos position-embedding helpers. The timm ``Block``, ``Attention``, ``Mlp`` and ``DropPath`` it + imports (timm 1.0.15, Apache License 2.0, Copyright (c) Ross Wightman) are re-implemented here with + the same attribute names and initialisation order. +- TerraTorch 0.99.8 (``terratorch/models``; Apache License 2.0, Copyright contributors to the + Terratorch project): necks ``SelectIndices``, ``ReshapeTokensToImage``, + ``LearnedInterpolateToPyramidal``, the ``UNetDecoder`` wrapper, ``SegmentationHead`` and the + ``PixelWiseModel`` forward pass (padding, bilinear rescale, crop). +- segmentation_models_pytorch 0.4.0 (``decoders/unet/decoder.py``, ``base/modules.py``, + ``base/initialization.py``; MIT License, Copyright (c) 2019 Pavel Iakubovskii): ``UnetDecoder``, + ``DecoderBlock``, ``Conv2dReLU`` and ``initialize_decoder``. + +TerraTorch 0.99.8 with smp 0.4.0 is the stack the official Prithvi-EO-2.0-300M-BurnScars checkpoint was +trained with (and the release its demo pins). Later releases (smp >= 0.5) resize the last U-Net decoder +block to the skip resolution instead of upsampling it by two, which changes this model's outputs; this +port keeps the training-time behaviour. + +Pretrained weights are not bundled. :func:`load_pretrained_state_dict` downloads a pinned file from +Hugging Face over plain HTTPS on first use, verifies its sha256 and caches it under +``torch.hub.get_dir()/checkpoints`` (or ``cache_dir``). +""" + +from __future__ import annotations + +import os +import warnings +from collections import OrderedDict +from pathlib import Path +from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +# HLS bands the Prithvi-EO models were pretrained on, in input order (HLS B02, B03, B04, B05/B8A, +# B06/B11, B07/B12), and the pretraining normalisation (HLS digital numbers, reflectance x 10000). +PRITHVI_BANDS = ("BLUE", "GREEN", "RED", "NIR_NARROW", "SWIR_1", "SWIR_2") +PRITHVI_EO_V2_MEAN = (1087.0, 1342.0, 1433.0, 2734.0, 1958.0, 1363.0) +PRITHVI_EO_V2_STD = (2248.0, 2179.0, 2178.0, 1850.0, 1242.0, 1049.0) + +# Encoder configurations of the TerraTorch backbone registry (``prithvi_cfgs``) and the SelectIndices +# used by the official Prithvi-EO-2.0 fine-tuning configs for each size. +PRITHVI_EO_V2_CONFIGS = { + "300m": dict(embed_dim=1024, depth=24, num_heads=16, patch_size=(1, 16, 16), select_indices=(5, 11, 17, 23)), + "600m": dict(embed_dim=1280, depth=32, num_heads=16, patch_size=(1, 14, 14), select_indices=(7, 15, 23, 31)), +} + + +# -------------------------------------------------------------------------------------------------- +# Position embeddings (prithvi_mae.py) +# -------------------------------------------------------------------------------------------------- + + +def get_1d_sincos_pos_embed_from_grid(embed_dim: int, pos: np.ndarray) -> np.ndarray: + """1D sin/cos embedding of ``pos`` (M,) -> (M, embed_dim), computed in float64 like the reference.""" + if embed_dim % 2 != 0: + raise ValueError("embed_dim must be even") + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega + pos = pos.reshape(-1) + out = np.einsum("m,d->md", pos, omega) + return np.concatenate([np.sin(out), np.cos(out)], axis=1) + + +def get_3d_sincos_pos_embed(embed_dim: int, grid_size: Sequence[int], add_cls_token: bool = False) -> np.ndarray: + """3D sin/cos embedding over a (T, H, W) token grid: 6/16 width, 6/16 height, 4/16 time channels.""" + if embed_dim % 16 != 0: + raise ValueError(f"embed_dim must be divisible by 16, got {embed_dim}") + t_size, h_size, w_size = grid_size + w_embed_dim = embed_dim // 16 * 6 + h_embed_dim = embed_dim // 16 * 6 + t_embed_dim = embed_dim // 16 * 4 + w_pos_embed = get_1d_sincos_pos_embed_from_grid(w_embed_dim, np.arange(w_size)) + h_pos_embed = get_1d_sincos_pos_embed_from_grid(h_embed_dim, np.arange(h_size)) + t_pos_embed = get_1d_sincos_pos_embed_from_grid(t_embed_dim, np.arange(t_size)) + w_pos_embed = np.tile(w_pos_embed, (t_size * h_size, 1)) + h_pos_embed = np.tile(np.repeat(h_pos_embed, w_size, axis=0), (t_size, 1)) + t_pos_embed = np.repeat(t_pos_embed, h_size * w_size, axis=0) + pos_embed = np.concatenate((w_pos_embed, h_pos_embed, t_pos_embed), axis=1) + if add_cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def _get_1d_sincos_embed_from_grid_torch(embed_dim: int, pos: torch.Tensor) -> torch.Tensor: + """Torch version of :func:`get_1d_sincos_pos_embed_from_grid` for float ``pos``.""" + omega = torch.arange(embed_dim // 2, dtype=pos.dtype).to(pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega + pos = pos.reshape(-1) + out = torch.einsum("m,d->md", pos, omega) + return torch.cat([torch.sin(out), torch.cos(out)], dim=1) + + +def _init_weights(module: nn.Module) -> None: + if isinstance(module, nn.Linear): + nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + + +def _interpolate_pos_encoding( + pos_embed: torch.Tensor, + grid_size: Sequence[int], + patch_size: Sequence[int], + shape: Sequence[int], + embed_dim: int, +) -> torch.Tensor: + """Recompute the sin/cos table for a new frame count and bicubically resize it to a new grid.""" + t, h, w = shape + t_patches = t // patch_size[0] + h_patches = h // patch_size[1] + w_patches = w // patch_size[2] + if [t_patches, h_patches, w_patches] == list(grid_size): + return pos_embed + if t_patches != grid_size[0]: + new_grid_size = (t_patches, *grid_size[1:]) + new_pos_embed = get_3d_sincos_pos_embed(pos_embed.shape[-1], new_grid_size, add_cls_token=True) + new_pos_embed = torch.from_numpy(new_pos_embed).float().unsqueeze(0).to(pos_embed.device) + else: + new_grid_size = grid_size + new_pos_embed = pos_embed + class_pos_embed, patch_pos_embed = new_pos_embed[:, :1], new_pos_embed[:, 1:] + patch_pos_embed = patch_pos_embed.reshape(*new_grid_size, embed_dim).permute(0, 3, 1, 2) + patch_pos_embed = F.interpolate(patch_pos_embed, size=(h_patches, w_patches), mode="bicubic", align_corners=True) + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).reshape(1, -1, embed_dim) + return torch.cat((class_pos_embed, patch_pos_embed), dim=1) + + +def _to_2tuple(value: Union[int, Sequence[int]]) -> Tuple[int, int]: + if isinstance(value, (tuple, list)): + return tuple(value) # type: ignore[return-value] + return (value, value) + + +def _as_float(coords: torch.Tensor) -> torch.Tensor: + return coords if coords.is_floating_point() else coords.float() + + +# -------------------------------------------------------------------------------------------------- +# Embeddings and transformer block (prithvi_mae.py + timm 1.0.15) +# -------------------------------------------------------------------------------------------------- + + +class PatchEmbed(nn.Module): + """3D patch embedding: a Conv3d whose kernel and stride equal the (t, h, w) patch size.""" + + def __init__( + self, + input_size: Tuple[int, int, int] = (1, 224, 224), + patch_size: Tuple[int, int, int] = (1, 16, 16), + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Optional[type] = None, + flatten: bool = True, + bias: bool = True, + ): + super().__init__() + self.input_size = input_size + self.patch_size = patch_size + self.grid_size = [s // p for s, p in zip(self.input_size, self.patch_size)] + if self.grid_size < [1, 1, 1]: + raise ValueError("Patch size is bigger than input size.") + self.num_patches = self.grid_size[0] * self.grid_size[1] * self.grid_size[2] + self.flatten = flatten + self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + _, _, T, H, W = x.shape + if T / self.patch_size[0] % 1 or H / self.patch_size[1] % 1 or W / self.patch_size[2] % 1: + warnings.warn( + f"Input {tuple(x.shape[-3:])} is not divisible by patch size {self.patch_size}. " + "The border will be ignored, add backbone_padding for pixel-wise tasks." + ) + x = self.proj(x) + if self.flatten: + x = x.flatten(2).transpose(1, 2) + return self.norm(x) + + +class TemporalEncoder(nn.Module): + """Sin/cos encoding of (year, day of year), half of the channels each, times a scale.""" + + def __init__(self, embed_dim: int, trainable_scale: bool = False): + super().__init__() + self.embed_dim = embed_dim + self.year_embed_dim = embed_dim // 2 + self.julian_day_embed_dim = embed_dim - self.year_embed_dim + if trainable_scale: + self.scale = nn.Parameter(torch.full((1,), 0.1)) + else: + self.register_buffer("scale", torch.ones(1)) + + def forward(self, temporal_coords: torch.Tensor, tokens_per_frame: Optional[int] = None) -> torch.Tensor: + shape = temporal_coords.shape[:2] + (-1,) + year = _get_1d_sincos_embed_from_grid_torch(self.year_embed_dim, temporal_coords[:, :, 0].flatten()).reshape( + shape + ) + julian_day = _get_1d_sincos_embed_from_grid_torch( + self.julian_day_embed_dim, temporal_coords[:, :, 1].flatten() + ).reshape(shape) + embedding = self.scale * torch.cat([year, julian_day], dim=-1) + if tokens_per_frame is not None: + embedding = torch.repeat_interleave(embedding, tokens_per_frame, dim=1) + return embedding + + +class LocationEncoder(nn.Module): + """Sin/cos encoding of (latitude, longitude), half of the channels each, times a scale.""" + + def __init__(self, embed_dim: int, trainable_scale: bool = False): + super().__init__() + self.embed_dim = embed_dim + self.lat_embed_dim = embed_dim // 2 + self.lon_embed_dim = embed_dim - self.lat_embed_dim + if trainable_scale: + self.scale = nn.Parameter(torch.full((1,), 0.1)) + else: + self.register_buffer("scale", torch.ones(1)) + + def forward(self, location_coords: torch.Tensor) -> torch.Tensor: + shape = location_coords.shape[:1] + (1, -1) + lat = _get_1d_sincos_embed_from_grid_torch(self.lat_embed_dim, location_coords[:, 0].flatten()).reshape(shape) + lon = _get_1d_sincos_embed_from_grid_torch(self.lon_embed_dim, location_coords[:, 1].flatten()).reshape(shape) + return self.scale * torch.cat([lat, lon], dim=-1) + + +def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor: + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class DropPath(nn.Module): + def __init__(self, drop_prob: float = 0.0): + super().__init__() + self.drop_prob = drop_prob + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return drop_path(x, self.drop_prob, self.training) + + +class Attention(nn.Module): + """timm multi-head self-attention with a fused qkv projection (scaled_dot_product_attention path).""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ): + super().__init__() + if dim % num_heads != 0: + raise ValueError(f"dim ({dim}) must be divisible by num_heads ({num_heads})") + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = nn.Identity() + self.k_norm = nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + x = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0) + x = x.transpose(1, 2).reshape(B, N, C) + return self.proj_drop(self.proj(x)) + + +class Mlp(nn.Module): + def __init__(self, in_features: int, hidden_features: int, drop: float = 0.0): + super().__init__() + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = nn.GELU() + self.drop1 = nn.Dropout(drop) + self.norm = nn.Identity() + self.fc2 = nn.Linear(hidden_features, in_features) + self.drop2 = nn.Dropout(drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.drop2(self.fc2(self.norm(self.drop1(self.act(self.fc1(x)))))) + + +class Block(nn.Module): + """Pre-norm transformer block (timm ``vision_transformer.Block`` without layer scale).""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = False, + drop_path: float = 0.0, + norm_layer: type = nn.LayerNorm, + ): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias) + self.ls1 = nn.Identity() + self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio)) + self.ls2 = nn.Identity() + self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x)))) + x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) + return x + + +# -------------------------------------------------------------------------------------------------- +# Encoder, MAE decoder and MAE (prithvi_mae.py) +# -------------------------------------------------------------------------------------------------- + + +class PrithviViT(nn.Module): + """Prithvi ViT encoder: 3D patch embedding, fixed 3D sin/cos positions, optional time/location codes. + + Input is ``(B, C, T, H, W)``; ``(B, C, H, W)`` is accepted when ``num_frames == 1``. Optional + ``temporal_coords`` are ``(B, T, 2)`` (year, day of year) and ``location_coords`` ``(B, 2)`` + (latitude, longitude); they are used only when ``coords_encoding`` enables them. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int, int]] = (1, 16, 16), + num_frames: int = 1, + in_chans: int = 3, + embed_dim: int = 1024, + depth: int = 24, + num_heads: int = 16, + mlp_ratio: float = 4.0, + norm_layer: type = nn.LayerNorm, + coords_encoding: Optional[Sequence[str]] = None, + coords_scale_learn: bool = False, + drop_path: float = 0.0, + ): + super().__init__() + self.in_chans = in_chans + self.num_frames = num_frames + self.embed_dim = embed_dim + self.img_size = _to_2tuple(img_size) + if isinstance(patch_size, int): + patch_size = (1, patch_size, patch_size) + patch_size = tuple(patch_size) + self.patch_embed = PatchEmbed( + input_size=(num_frames,) + self.img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + ) + self.out_channels = [embed_dim * self.patch_embed.grid_size[0]] * depth + + coords_encoding = list(coords_encoding or []) + self.temporal_encoding = "time" in coords_encoding + self.location_encoding = "location" in coords_encoding + if self.temporal_encoding: + if patch_size[0] != 1: + raise ValueError(f"With temporal encoding, patch_size[0] must be 1, received {patch_size[0]}") + self.temporal_embed_enc = TemporalEncoder(embed_dim, coords_scale_learn) + if self.location_encoding: + self.location_embed_enc = LocationEncoder(embed_dim, coords_scale_learn) + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.register_buffer("pos_embed", torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) + self.blocks = nn.ModuleList( + [ + Block(embed_dim, num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer, drop_path=drop_path) + for _ in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + self.initialize_weights() + + def initialize_weights(self) -> None: + pos_embed = get_3d_sincos_pos_embed(self.pos_embed.shape[-1], self.patch_embed.grid_size, add_cls_token=True) + self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) + w = self.patch_embed.proj.weight.data + nn.init.xavier_uniform_(w.view([w.shape[0], -1])) + nn.init.normal_(self.cls_token, std=0.02) + self.apply(_init_weights) + + def _validate(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 4 and self.patch_embed.input_size[0] == 1: + x = x.unsqueeze(2) + if x.ndim != 5: + layout = "(B, C, T, H, W)" + (" or (B, C, H, W)" if self.num_frames == 1 else "") + raise ValueError(f"PrithviViT expects input of shape {layout}, got shape {tuple(x.shape)}") + if x.shape[1] != self.in_chans: + raise ValueError( + f"PrithviViT expects {self.in_chans} channels in dim 1 of (B, C, T, H, W), got shape {tuple(x.shape)}" + ) + p = self.patch_embed.patch_size + if x.shape[2] < p[0] or x.shape[3] < p[1] or x.shape[4] < p[2]: + raise ValueError(f"Input shape {tuple(x.shape)} is smaller than the patch size {p}") + return x + + def _add_coords( + self, + x: torch.Tensor, + temporal_coords: Optional[torch.Tensor], + location_coords: Optional[torch.Tensor], + ) -> torch.Tensor: + batch, num_tokens = x.shape[0], x.shape[1] + if self.temporal_encoding and temporal_coords is not None: + temporal_coords = _as_float(temporal_coords) + num_tokens_per_frame = num_tokens // self.num_frames + if ( + temporal_coords.ndim != 3 + or temporal_coords.shape[0] != batch + or temporal_coords.shape[2] != 2 + or temporal_coords.shape[1] * num_tokens_per_frame != num_tokens + ): + raise ValueError( + "temporal_coords must have shape (B, T, 2) with (year, day of year) per frame and " + f"T = num_frames = {self.num_frames}; got shape {tuple(temporal_coords.shape)}" + ) + x = x + self.temporal_embed_enc(temporal_coords, num_tokens_per_frame) + if self.location_encoding and location_coords is not None: + location_coords = _as_float(location_coords) + if location_coords.ndim != 2 or location_coords.shape != (batch, 2): + raise ValueError( + "location_coords must have shape (B, 2) with (latitude, longitude); " + f"got shape {tuple(location_coords.shape)}" + ) + x = x + self.location_embed_enc(location_coords) + return x + + def random_masking(self, sequence: torch.Tensor, mask_ratio: float, noise: Optional[torch.Tensor] = None): + """Per-sample random masking by argsort of uniform noise (MAE).""" + batch_size, seq_length, dim = sequence.shape + len_keep = int(seq_length * (1 - mask_ratio)) + if noise is None: + noise = torch.rand(batch_size, seq_length, device=sequence.device) + ids_shuffle = torch.argsort(noise, dim=1).to(sequence.device) + ids_restore = torch.argsort(ids_shuffle, dim=1).to(sequence.device) + ids_keep = ids_shuffle[:, :len_keep] + sequence_unmasked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, dim)) + mask = torch.ones([batch_size, seq_length], device=sequence.device) + mask[:, :len_keep] = 0 + mask = torch.gather(mask, dim=1, index=ids_restore) + return sequence_unmasked, mask, ids_restore + + def interpolate_pos_encoding(self, sample_shape: Sequence[int]) -> torch.Tensor: + return _interpolate_pos_encoding( + pos_embed=self.pos_embed, + grid_size=self.patch_embed.grid_size, + patch_size=self.patch_embed.patch_size, + shape=sample_shape, + embed_dim=self.embed_dim, + ) + + def forward( + self, + x: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + mask_ratio: float = 0.75, + ): + """MAE encoder pass: returns (latent of the kept tokens with cls token, mask, ids_restore).""" + x = self._validate(x) + sample_shape = x.shape[-3:] + x = self.patch_embed(x) + pos_embed = self.interpolate_pos_encoding(sample_shape) + x = x + pos_embed[:, 1:, :] + x = self._add_coords(x, temporal_coords, location_coords) + x, mask, ids_restore = self.random_masking(x, mask_ratio) + cls_token = self.cls_token + pos_embed[:, :1, :] + x = torch.cat((cls_token.expand(x.shape[0], -1, -1), x), dim=1) + for block in self.blocks: + x = block(x) + x = self.norm(x) + return x, mask, ids_restore + + def forward_features( + self, + x: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + ) -> List[torch.Tensor]: + """All tokens after every block, ``(B, 1 + T*h*w, D)`` each; only the last one is layer-normed.""" + x = self._validate(x) + sample_shape = x.shape[-3:] + x = self.patch_embed(x) + pos_embed = self.interpolate_pos_encoding(sample_shape) + x = x + pos_embed[:, 1:, :] + x = self._add_coords(x, temporal_coords, location_coords) + cls_token = self.cls_token + pos_embed[:, :1, :] + x = torch.cat((cls_token.expand(x.shape[0], -1, -1), x), dim=1) + out = [] + for block in self.blocks: + x = block(x) + out.append(x.clone()) + out[-1] = self.norm(x) + return out + + +class MAEDecoder(nn.Module): + """Transformer decoder of the Prithvi MAE (reconstructs masked patches).""" + + def __init__( + self, + patch_size: Union[int, Tuple[int, int, int]] = (1, 16, 16), + grid_size: Sequence[int] = (3, 14, 14), + in_chans: int = 3, + encoder_embed_dim: int = 1024, + decoder_embed_dim: int = 512, + depth: int = 8, + num_heads: int = 16, + mlp_ratio: float = 4.0, + norm_layer: type = nn.LayerNorm, + coords_encoding: Optional[Sequence[str]] = None, + coords_scale_learn: bool = False, + ): + super().__init__() + self.decoder_embed = nn.Linear(encoder_embed_dim, decoder_embed_dim, bias=True) + self.decoder_embed_dim = decoder_embed_dim + self.grid_size = list(grid_size) + if isinstance(patch_size, int): + patch_size = (1, patch_size, patch_size) + self.patch_size = tuple(patch_size) + self.num_frames = self.grid_size[0] * self.patch_size[0] + num_patches = self.grid_size[0] * self.grid_size[1] * self.grid_size[2] + + coords_encoding = list(coords_encoding or []) + self.temporal_encoding = "time" in coords_encoding + self.location_encoding = "location" in coords_encoding + if self.temporal_encoding: + self.temporal_embed_dec = TemporalEncoder(decoder_embed_dim, coords_scale_learn) + if self.location_encoding: + self.location_embed_dec = LocationEncoder(decoder_embed_dim, coords_scale_learn) + + self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim)) + self.register_buffer("decoder_pos_embed", torch.zeros(1, num_patches + 1, decoder_embed_dim)) + self.decoder_blocks = nn.ModuleList( + [Block(decoder_embed_dim, num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer) for _ in range(depth)] + ) + self.decoder_norm = norm_layer(decoder_embed_dim) + self.decoder_pred = nn.Linear( + decoder_embed_dim, self.patch_size[0] * self.patch_size[1] * self.patch_size[2] * in_chans, bias=True + ) + self.initialize_weights() + + def initialize_weights(self) -> None: + decoder_pos_embed = get_3d_sincos_pos_embed( + self.decoder_pos_embed.shape[-1], self.grid_size, add_cls_token=True + ) + self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) + nn.init.normal_(self.mask_token, std=0.02) + self.apply(_init_weights) + + def interpolate_pos_encoding(self, sample_shape: Sequence[int]) -> torch.Tensor: + return _interpolate_pos_encoding( + pos_embed=self.decoder_pos_embed, + grid_size=self.grid_size, + patch_size=self.patch_size, + shape=sample_shape, + embed_dim=self.decoder_embed_dim, + ) + + def forward( + self, + hidden_states: torch.Tensor, + ids_restore: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + input_size: Optional[Sequence[int]] = None, + ) -> torch.Tensor: + x = self.decoder_embed(hidden_states) + cls_token = x[:, :1, :] + mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1) + x = torch.cat([x[:, 1:, :], mask_tokens], dim=1) + x = torch.gather(x, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2]).to(x.device)) + decoder_pos_embed = self.interpolate_pos_encoding(input_size[-3:]) + cls_token = cls_token + decoder_pos_embed[:, :1, :] + x = x + decoder_pos_embed[:, 1:, :] + if self.temporal_encoding and temporal_coords is not None: + num_tokens_per_frame = x.shape[1] // self.num_frames + x = x + self.temporal_embed_dec(_as_float(temporal_coords), num_tokens_per_frame) + if self.location_encoding and location_coords is not None: + x = x + self.location_embed_dec(_as_float(location_coords)) + x = torch.cat([cls_token, x], dim=1) + for block in self.decoder_blocks: + x = block(x) + x = self.decoder_norm(x) + pred = self.decoder_pred(x) + return pred[:, 1:, :] + + +class PrithviMAE(nn.Module): + """Prithvi masked autoencoder (encoder + decoder); the released pretraining checkpoints load strictly.""" + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int, int]] = (1, 16, 16), + num_frames: int = 4, + in_chans: int = 6, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + decoder_embed_dim: int = 512, + decoder_depth: int = 8, + decoder_num_heads: int = 16, + mlp_ratio: float = 4.0, + norm_layer: type = nn.LayerNorm, + norm_pix_loss: bool = False, + coords_encoding: Optional[Sequence[str]] = None, + coords_scale_learn: bool = False, + drop_path: float = 0.0, + mask_ratio: float = 0.75, + ): + super().__init__() + self.encoder = PrithviViT( + img_size=img_size, + num_frames=num_frames, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + norm_layer=norm_layer, + coords_encoding=coords_encoding, + coords_scale_learn=coords_scale_learn, + drop_path=drop_path, + ) + self.decoder = MAEDecoder( + patch_size=patch_size, + grid_size=self.encoder.patch_embed.grid_size, + in_chans=in_chans, + encoder_embed_dim=embed_dim, + decoder_embed_dim=decoder_embed_dim, + depth=decoder_depth, + num_heads=decoder_num_heads, + mlp_ratio=mlp_ratio, + norm_layer=norm_layer, + coords_encoding=coords_encoding, + coords_scale_learn=coords_scale_learn, + ) + self.mask_ratio = mask_ratio + self.norm_pix_loss = norm_pix_loss + self.out_channels = self.encoder.out_channels + + def patchify(self, pixel_values: torch.Tensor) -> torch.Tensor: + """(B, C, T, H, W) -> (B, num_patches, pt*ph*pw*C).""" + s, p, q = self.encoder.patch_embed.patch_size + B, C, T, H, W = pixel_values.shape + x = pixel_values.reshape(B, C, T // s, s, H // p, p, W // q, q) + x = x.permute(0, 2, 4, 6, 3, 5, 7, 1) + return x.reshape(B, (T // s) * (H // p) * (W // q), s * p * q * C) + + def unpatchify(self, patchified_pixel_values: torch.Tensor, image_size: Optional[Tuple[int, int]] = None): + """(B, num_patches, pt*ph*pw*C) -> (B, C, T, H, W).""" + s, p, q = self.encoder.patch_embed.patch_size + image_size = _to_2tuple(image_size) if image_size is not None else self.encoder.img_size + h, w = image_size[0] // p, image_size[1] // q + C = self.encoder.in_chans + B, L, _ = patchified_pixel_values.shape + t = L // (h * w) + x = patchified_pixel_values.reshape(B, t, h, w, s, p, q, C) + x = x.permute(0, 7, 1, 4, 2, 5, 3, 6) + return x.reshape(B, C, t * s, h * p, w * q) + + def forward_loss(self, pixel_values: torch.Tensor, pred: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + target = self.patchify(pixel_values) + if self.norm_pix_loss: + mean = target.mean(dim=-1, keepdim=True) + var = target.var(dim=-1, keepdim=True) + target = (target - mean) / (var + 1.0e-6) ** 0.5 + loss = ((pred - target) ** 2).mean(dim=-1) + return (loss * mask).sum() / mask.sum() + + def forward( + self, + pixel_values: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + mask_ratio: Optional[float] = None, + ): + """Returns (reconstruction loss on masked patches, predicted patches, mask).""" + if pixel_values.ndim == 4 and self.encoder.patch_embed.input_size[0] == 1: + pixel_values = pixel_values.unsqueeze(2) + mask_ratio = mask_ratio or self.mask_ratio + latent, mask, ids_restore = self.encoder(pixel_values, temporal_coords, location_coords, mask_ratio) + pred = self.decoder(latent, ids_restore, temporal_coords, location_coords, input_size=pixel_values.shape) + loss = self.forward_loss(pixel_values, pred, mask) + return loss, pred, mask + + def forward_features( + self, + x: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + ) -> List[torch.Tensor]: + return self.encoder.forward_features(x, temporal_coords, location_coords) + + +# -------------------------------------------------------------------------------------------------- +# TerraTorch necks, smp U-Net decoder, segmentation head and pixel-wise model +# -------------------------------------------------------------------------------------------------- + + +class SelectIndices(nn.Module): + """Keep the encoder outputs at ``indices``.""" + + def __init__(self, indices: Sequence[int]): + super().__init__() + self.indices = list(indices) + + def forward(self, features: List[torch.Tensor]) -> List[torch.Tensor]: + return [features[i] for i in self.indices] + + +class ReshapeTokensToImage(nn.Module): + """Tokens ``(B, 1 + t*h*w, E)`` -> feature maps ``(B, t*E, h, w)`` (time folded into channels).""" + + def __init__(self, remove_cls_token: bool = True, effective_time_dim: int = 1): + super().__init__() + self.remove_cls_token = remove_cls_token + self.effective_time_dim = effective_time_dim + + def forward(self, features: List[torch.Tensor], grid_size: Tuple[int, int]) -> List[torch.Tensor]: + h, w = grid_size + t = self.effective_time_dim + out = [] + for x in features: + x_no_token = x[:, 1:, :] if self.remove_cls_token else x + batch, _, embed = x_no_token.shape + x_no_token = x_no_token.reshape(batch, t, h, w, embed).permute(0, 1, 4, 2, 3) + out.append(x_no_token.reshape(batch, t * embed, h, w)) + return out + + +class LearnedInterpolateToPyramidal(nn.Module): + """Turn four same-resolution maps into a 4x / 2x / 1x / 0.5x pyramid with learned up-convolutions.""" + + def __init__(self, channel_list: Sequence[int]): + super().__init__() + if len(channel_list) != 4: + raise ValueError(f"LearnedInterpolateToPyramidal needs exactly 4 feature maps, got {len(channel_list)}") + self.fpn1 = nn.Sequential( + nn.ConvTranspose2d(channel_list[0], channel_list[0] // 2, 2, 2), + nn.BatchNorm2d(channel_list[0] // 2), + nn.GELU(), + nn.ConvTranspose2d(channel_list[0] // 2, channel_list[0] // 4, 2, 2), + ) + self.fpn2 = nn.Sequential(nn.ConvTranspose2d(channel_list[1], channel_list[1] // 2, 2, 2)) + self.fpn3 = nn.Sequential(nn.Identity()) + self.fpn4 = nn.Sequential(nn.MaxPool2d(kernel_size=2, stride=2)) + self.embedding_dim = [channel_list[0] // 4, channel_list[1] // 2, channel_list[2], channel_list[3]] + + def forward(self, features: List[torch.Tensor]) -> List[torch.Tensor]: + return [self.fpn1(features[0]), self.fpn2(features[1]), self.fpn3(features[2]), self.fpn4(features[3])] + + +class Conv2dReLU(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, kernel_size: int, padding: int = 0, stride: int = 1, + use_batchnorm: bool = True): + conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, + bias=not use_batchnorm) + relu = nn.ReLU(inplace=True) + bn = nn.BatchNorm2d(out_channels) if use_batchnorm else nn.Identity() + super().__init__(conv, bn, relu) + + +class SmpAttention(nn.Module): + """smp ``base.modules.Attention`` with ``name=None``: an identity kept for parameter-name parity.""" + + def __init__(self): + super().__init__() + self.attention = nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.attention(x) + + +class DecoderBlock(nn.Module): + """smp 0.4.0 U-Net block: nearest x2 upsampling, concat skip, two conv-BN-ReLU.""" + + def __init__(self, in_channels: int, skip_channels: int, out_channels: int, use_batchnorm: bool = True): + super().__init__() + self.conv1 = Conv2dReLU(in_channels + skip_channels, out_channels, kernel_size=3, padding=1, + use_batchnorm=use_batchnorm) + self.attention1 = SmpAttention() + self.conv2 = Conv2dReLU(out_channels, out_channels, kernel_size=3, padding=1, use_batchnorm=use_batchnorm) + self.attention2 = SmpAttention() + + def forward(self, x: torch.Tensor, skip: Optional[torch.Tensor] = None) -> torch.Tensor: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if skip is not None: + x = torch.cat([x, skip], dim=1) + x = self.attention1(x) + x = self.conv1(x) + x = self.conv2(x) + return self.attention2(x) + + +class UnetDecoder(nn.Module): + """smp 0.4.0 ``UnetDecoder`` (no center block).""" + + def __init__(self, encoder_channels: Sequence[int], decoder_channels: Sequence[int], n_blocks: int = 5, + use_batchnorm: bool = True): + super().__init__() + if n_blocks != len(decoder_channels): + raise ValueError(f"Model depth is {n_blocks}, but decoder_channels has {len(decoder_channels)} blocks.") + encoder_channels = list(encoder_channels[1:])[::-1] + head_channels = encoder_channels[0] + in_channels = [head_channels] + list(decoder_channels[:-1]) + skip_channels = list(encoder_channels[1:]) + [0] + self.center = nn.Identity() + self.blocks = nn.ModuleList( + [ + DecoderBlock(in_ch, skip_ch, out_ch, use_batchnorm=use_batchnorm) + for in_ch, skip_ch, out_ch in zip(in_channels, skip_channels, decoder_channels) + ] + ) + + def forward(self, *features: torch.Tensor) -> torch.Tensor: + features = features[1:][::-1] + head, skips = features[0], features[1:] + x = self.center(head) + for i, decoder_block in enumerate(self.blocks): + skip = skips[i] if i < len(skips) else None + x = decoder_block(x, skip) + return x + + +def initialize_decoder(module: nn.Module) -> None: + for m in module.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + +class UNetDecoder(nn.Module): + """TerraTorch ``UNetDecoder``: the smp decoder fed with the first map duplicated as its dropped skip.""" + + def __init__(self, embed_dim: Sequence[int], channels: Sequence[int], use_batchnorm: bool = True): + super().__init__() + if len(embed_dim) != len(channels): + raise ValueError("channels should have the same length as embed_dim") + self.decoder = UnetDecoder( + encoder_channels=[embed_dim[0], *embed_dim], + decoder_channels=channels, + n_blocks=len(channels), + use_batchnorm=use_batchnorm, + ) + initialize_decoder(self.decoder) + self.out_channels = channels[-1] + + def forward(self, x: List[torch.Tensor]) -> torch.Tensor: + x = [x[0].clone(), *x] + return self.decoder(*x) + + +class SegmentationHead(nn.Module): + """TerraTorch segmentation head: optional dropout, then a 1x1 convolution to class logits.""" + + def __init__(self, in_channels: int, num_classes: int, dropout: float = 0.0): + super().__init__() + self.num_classes = num_classes + self.head = nn.Sequential( + nn.Identity(), + nn.Identity() if dropout == 0 else nn.Dropout(dropout), + nn.Conv2d(in_channels=in_channels, out_channels=num_classes, kernel_size=1), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.head(x) + + +class PrithviSegmentation(nn.Module): + """TerraTorch ``EncoderDecoderFactory`` segmentation model on a Prithvi encoder. + + ``encoder`` (PrithviViT) -> ``SelectIndices`` -> ``ReshapeTokensToImage`` -> + ``LearnedInterpolateToPyramidal`` -> ``UNetDecoder`` -> ``SegmentationHead``, as in the official + Prithvi-EO-2.0 burn-scar fine-tune. The input is reflect-padded at the bottom/right to a multiple of + twice the patch size, the logits are bilinearly resized to the padded size and cropped back, so the + output is ``(B, num_classes, H, W)``. + + Submodules are registered in the reference order (``encoder``, ``decoder``, ``head``, ``neck``) but + created in the reference initialisation order (encoder, neck, decoder, head), so that the same seed + gives the same weights as TerraTorch and the Lightning checkpoint (minus its ``model.`` prefix) + loads with ``strict=True``. + """ + + def __init__( + self, + encoder: PrithviViT, + select_indices: Sequence[int], + decoder_channels: Sequence[int] = (512, 256, 128, 64), + num_classes: int = 2, + head_dropout: float = 0.0, + rescale: bool = True, + ): + super().__init__() + if len(select_indices) != 4: + raise ValueError(f"select_indices needs 4 encoder blocks, got {list(select_indices)}") + depth = len(encoder.blocks) + if any(not -depth <= i < depth for i in select_indices): + raise ValueError(f"select_indices {list(select_indices)} out of range for {depth} encoder blocks") + channel_list = [encoder.out_channels[i] for i in select_indices] + time_dim = encoder.patch_embed.grid_size[0] + neck = nn.ModuleList( + [ + SelectIndices(select_indices), + ReshapeTokensToImage(effective_time_dim=time_dim), + LearnedInterpolateToPyramidal(channel_list), + ] + ) + pyramid_channels = [channel_list[0] // 4, channel_list[1] // 2, channel_list[2], channel_list[3]] + decoder = UNetDecoder(pyramid_channels, list(decoder_channels)) + self.encoder = encoder + self.decoder = decoder + self.head = SegmentationHead(decoder.out_channels, num_classes, dropout=head_dropout) + self.neck = neck + self.num_classes = num_classes + self.rescale = rescale + + def forward( + self, + x: torch.Tensor, + temporal_coords: Optional[torch.Tensor] = None, + location_coords: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + num_frames = self.encoder.num_frames + if x.ndim == 4 and num_frames == 1: + x = x.unsqueeze(2) + if x.ndim != 5 or x.shape[2] != num_frames: + raise ValueError( + f"Prithvi segmentation expects input of shape (B, C, T={num_frames}, H, W)" + + (" or (B, C, H, W)" if num_frames == 1 else "") + + f", got shape {tuple(x.shape)}" + ) + height, width = x.shape[-2:] + _, patch_h, patch_w = self.encoder.patch_embed.patch_size + pad_h = (2 * patch_h - height % (2 * patch_h)) % (2 * patch_h) + pad_w = (2 * patch_w - width % (2 * patch_w)) % (2 * patch_w) + if pad_h >= height or pad_w >= width: + raise ValueError( + f"Input shape {tuple(x.shape)} is too small: H and W must exceed the reflect padding to a " + f"multiple of {2 * patch_h}x{2 * patch_w}" + ) + if pad_h or pad_w: + x = torch.stack([F.pad(img, (0, pad_w, 0, pad_h), mode="reflect") for img in x]) + padded_size = x.shape[-2:] + grid_size = (padded_size[0] // patch_h, padded_size[1] // patch_w) + + features = self.encoder.forward_features(x, temporal_coords, location_coords) + features = self.neck[0](features) + features = self.neck[1](features, grid_size) + features = self.neck[2](features) + mask = self.head(self.decoder([f.clone() for f in features])) + if self.rescale and mask.shape[-2:] != padded_size: + mask = F.interpolate(mask, size=padded_size, mode="bilinear") + return mask[..., :height, :width] + + +# -------------------------------------------------------------------------------------------------- +# Pretrained weights (downloaded on demand, never bundled) +# -------------------------------------------------------------------------------------------------- + + +class PretrainedWeights(NamedTuple): + """A checkpoint file in a Hugging Face model repository, pinned by revision and sha256.""" + + repo_id: str + revision: str + filename: str + sha256: str + num_bytes: int + + @property + def url(self) -> str: + endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/") + return f"{endpoint}/{self.repo_id}/resolve/{self.revision}/{self.filename}" + + +PRITHVI_WEIGHTS: Dict[str, PretrainedWeights] = { + "prithvi_eo_v2_300_burnscars": PretrainedWeights( + repo_id="ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars", + revision="a3f2c410e45b8ac7417976614528a872f024d831", + filename="Prithvi_EO_V2_300M_BurnScars.pt", + sha256="0c5f9334be9a75c9006387ab8f3dc05a55ea7fb5ef7956717316be57c62954d3", + num_bytes=1297798380, + ), + "prithvi_eo_v2_300_tl": PretrainedWeights( + repo_id="ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL", + revision="63adbd39c271da4c42f447e69b1a7c91a338cdc9", + filename="Prithvi_EO_V2_300M_TL.pt", + sha256="3629cedfbb350faafcb0dac902ae0d3c927e25ce8d9e0024aa1276ec66956ddb", + num_bytes=1326660716, + ), + "prithvi_eo_v2_600_tl": PretrainedWeights( + repo_id="ibm-nasa-geospatial/Prithvi-EO-2.0-600M-TL", + revision="3d72adc6dfc4cc3862bf4f41da8c83db267193c9", + filename="Prithvi_EO_V2_600M_TL.pt", + sha256="7b92c53b0204a76bb775bd8930f045e05776251caa8c83f7367ed0b75b594702", + num_bytes=2638217218, + ), +} + + +def download_weights(spec: PretrainedWeights, cache_dir: Optional[Union[str, Path]] = None, progress: bool = True) -> Path: + """Download ``spec`` over HTTPS into the cache (once) and return the local path. + + The file is checked against the pinned sha256 while downloading. ``cache_dir`` defaults to + ``torch.hub.get_dir()/checkpoints``; ``HF_ENDPOINT`` selects a Hugging Face mirror. + """ + root = Path(cache_dir) if cache_dir is not None else Path(torch.hub.get_dir()) / "checkpoints" + target = root / spec.repo_id.replace("/", "--") / spec.revision / spec.filename + if target.exists() and target.stat().st_size == spec.num_bytes: + return target + target.parent.mkdir(parents=True, exist_ok=True) + torch.hub.download_url_to_file(spec.url, str(target), hash_prefix=spec.sha256, progress=progress) + return target + + +def load_pretrained_state_dict( + name: str, + weights_path: Optional[Union[str, Path]] = None, + cache_dir: Optional[Union[str, Path]] = None, +) -> "OrderedDict[str, torch.Tensor]": + """State dict of a pinned Prithvi checkpoint, from ``weights_path`` or downloaded on demand. + + Lightning checkpoints (fine-tuned models) are unwrapped to their ``state_dict``. + """ + if name not in PRITHVI_WEIGHTS: + raise ValueError(f"Unknown Prithvi weights {name!r}; available: {sorted(PRITHVI_WEIGHTS)}") + path = Path(weights_path) if weights_path is not None else download_weights(PRITHVI_WEIGHTS[name], cache_dir) + state = torch.load(path, map_location="cpu", weights_only=True) + if "state_dict" in state and isinstance(state["state_dict"], dict): + state = state["state_dict"] + return OrderedDict(state) + + +def finetuned_state_dict_to_model(state: Dict[str, torch.Tensor]) -> "OrderedDict[str, torch.Tensor]": + """TerraTorch task checkpoint -> :class:`PrithviSegmentation` keys (drop the ``model.`` prefix).""" + return OrderedDict((key[len("model."):], value) for key, value in state.items() if key.startswith("model.")) + + +def mae_state_dict_to_encoder(state: Dict[str, torch.Tensor], encoder: PrithviViT) -> "OrderedDict[str, torch.Tensor]": + """Pretraining (PrithviMAE) checkpoint -> :class:`PrithviViT` keys, as TerraTorch's filter does. + + Keeps ``encoder.*`` without the prefix and drops the MAE decoder. ``pos_embed`` is a fixed sin/cos + table that depends on ``num_frames``, so the encoder's own table replaces the checkpoint's. + """ + out = OrderedDict() + for key, value in state.items(): + if not key.startswith("encoder."): + continue + key = key[len("encoder."):] + if (not encoder.temporal_encoding and "temporal_embed" in key) or ( + not encoder.location_encoding and "location_embed" in key + ): + continue + out[key] = encoder.pos_embed.detach().clone() if key == "pos_embed" else value + return out + + +__all__ = [ + "PRITHVI_BANDS", + "PRITHVI_EO_V2_CONFIGS", + "PRITHVI_EO_V2_MEAN", + "PRITHVI_EO_V2_STD", + "PRITHVI_WEIGHTS", + "LearnedInterpolateToPyramidal", + "MAEDecoder", + "PretrainedWeights", + "PrithviMAE", + "PrithviSegmentation", + "PrithviViT", + "ReshapeTokensToImage", + "SegmentationHead", + "SelectIndices", + "UNetDecoder", + "download_weights", + "finetuned_state_dict_to_model", + "get_3d_sincos_pos_embed", + "load_pretrained_state_dict", + "mae_state_dict_to_encoder", +] diff --git a/pyhazards/models/prithvi_burnscars.py b/pyhazards/models/prithvi_burnscars.py new file mode 100644 index 00000000..e3bb4732 --- /dev/null +++ b/pyhazards/models/prithvi_burnscars.py @@ -0,0 +1,139 @@ +"""Prithvi-EO-2.0-300M-BurnScars: burn-scar segmentation of single HLS scenes. + +The official fine-tune (Hugging Face ``ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars``, Apache-2.0) +of the Prithvi-EO-2.0-300M encoder (Szwarcman et al., arXiv:2412.02732) on the HLS Burn Scars dataset, +built with TerraTorch from ``burn_scars_config.yaml``: + + backbone prithvi_eo_v2_300 (ViT-L/16, 1 frame, 6 HLS bands) + necks SelectIndices[5, 11, 17, 23] -> ReshapeTokensToImage -> LearnedInterpolateToPyramidal + decoder UNetDecoder [512, 256, 128, 64] -> SegmentationHead (2 classes: not burned, burn scar) + +The modules are the plain-PyTorch port in :mod:`pyhazards.models.prithvi` (TerraTorch 0.99.8 and +``prithvi_mae.py``, Apache-2.0; smp 0.4.0, MIT). Inputs are HLS surface reflectance (0-1) of bands +B, G, R, NIR (narrow), SWIR 1, SWIR 2, standardised with :data:`BURN_SCARS_MEAN` / :data:`BURN_SCARS_STD`, +with input shape ``(B, 6, H, W)`` or ``(B, 6, 1, H, W)`` (other shapes raise ``ValueError``); the +official chips are 512 x 512. The output is ``(B, 2, H, W)`` logits. +""" + +from __future__ import annotations + +from typing import Optional, Sequence + +import torch.nn as nn + +from .prithvi import ( + PRITHVI_BANDS, + PrithviSegmentation, + PrithviViT, + finetuned_state_dict_to_model, + load_pretrained_state_dict, +) + +# Data normalisation of the official fine-tune (burn_scars_config.yaml, reflectance units). +BURN_SCARS_BANDS = PRITHVI_BANDS +BURN_SCARS_MEAN = ( + 0.033349706741586264, + 0.05701185520536176, + 0.05889748132001316, + 0.2323245113436119, + 0.1972854853760658, + 0.11944914225186566, +) +BURN_SCARS_STD = ( + 0.02269135568823774, + 0.026807560223070237, + 0.04004109844362779, + 0.07791732423672691, + 0.08708738838140137, + 0.07241979477437814, +) +BURN_SCARS_CLASSES = ("Not burned", "Burn scar") + +_OFFICIAL = dict( + in_channels=6, + num_classes=2, + img_size=224, + patch_size=16, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4.0, + select_indices=(5, 11, 17, 23), + decoder_channels=(512, 256, 128, 64), +) + + +def prithvi_burnscars_builder( + task: str, + pretrained: bool = False, + weights_path: Optional[str] = None, + cache_dir: Optional[str] = None, + in_channels: int = 6, + num_classes: int = 2, + img_size: int = 224, + patch_size: int = 16, + embed_dim: int = 1024, + depth: int = 24, + num_heads: int = 16, + mlp_ratio: float = 4.0, + select_indices: Sequence[int] = (5, 11, 17, 23), + decoder_channels: Sequence[int] = (512, 256, 128, 64), + drop_path: float = 0.0, + **kwargs, +) -> nn.Module: + """Build the burn-scar model; ``pretrained=True`` loads the official checkpoint (1.3 GB download). + + ``weights_path`` loads a local copy of ``Prithvi_EO_V2_300M_BurnScars.pt`` instead of downloading. + The architecture arguments exist for small test configurations; the official weights need the + defaults. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"prithvi_burnscars supports task='segmentation', got {task!r}.") + arch = dict( + in_channels=in_channels, + num_classes=num_classes, + img_size=img_size, + patch_size=patch_size, + embed_dim=embed_dim, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + select_indices=tuple(select_indices), + decoder_channels=tuple(decoder_channels), + ) + load = pretrained or weights_path is not None + if load and arch != _OFFICIAL: + changed = sorted(k for k in arch if arch[k] != _OFFICIAL[k]) + raise ValueError(f"The official burn-scar weights need the default architecture; changed: {changed}") + encoder = PrithviViT( + img_size=img_size, + patch_size=(1, patch_size, patch_size), + num_frames=1, + in_chans=in_channels, + embed_dim=embed_dim, + depth=depth, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + drop_path=drop_path, + ) + model = PrithviSegmentation( + encoder, + select_indices=select_indices, + decoder_channels=decoder_channels, + num_classes=num_classes, + ) + if load: + state = load_pretrained_state_dict("prithvi_eo_v2_300_burnscars", weights_path=weights_path, cache_dir=cache_dir) + model.load_state_dict(finetuned_state_dict_to_model(state), strict=True) + return model + + +__all__ = [ + "BURN_SCARS_BANDS", + "BURN_SCARS_CLASSES", + "BURN_SCARS_MEAN", + "BURN_SCARS_STD", + "PrithviSegmentation", + "prithvi_burnscars_builder", +] diff --git a/pyhazards/models/prithvi_eo_2_tl.py b/pyhazards/models/prithvi_eo_2_tl.py new file mode 100644 index 00000000..e637df7c --- /dev/null +++ b/pyhazards/models/prithvi_eo_2_tl.py @@ -0,0 +1,110 @@ +"""Prithvi-EO-2.0-TL encoder (time + location embeddings) with the official burn-scar segmentation head. + +Prithvi-EO-2.0 (Szwarcman et al., arXiv:2412.02732) is a multi-temporal ViT masked autoencoder pretrained +on 4.2M HLS samples. The TL variants add sin/cos encodings of acquisition time (year, day of year) and +location (latitude, longitude), each multiplied by a learned scale, to the patch tokens. The encoder is +the plain-PyTorch port of the official ``prithvi_mae.py`` in :mod:`pyhazards.models.prithvi` +(Apache-2.0, IBM); ``pretrained=True`` loads the released MAE checkpoint +(``ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL`` or ``-600M-TL``) into it. + +PyHazards builders return a task model, so the encoder is wrapped in the segmentation recipe of the +official Prithvi-EO-2.0 burn-scar fine-tune (TerraTorch ``EncoderDecoderFactory``: SelectIndices at +the official per-size indices -> ReshapeTokensToImage -> LearnedInterpolateToPyramidal -> UNetDecoder +[512, 256, 128, 64] -> SegmentationHead). Only the encoder is pretrained; the neck, decoder and head are +randomly initialised and must be fine-tuned. With ``num_frames = T > 1`` the tokens of all frames are +stacked along channels (``effective_time_dim = T``), as in the official multi-temporal configs. + +Input shape is ``(B, C, T, H, W)`` (``(B, C, H, W)`` when ``num_frames == 1``), with optional +``temporal_coords`` ``(B, T, 2)`` and ``location_coords`` ``(B, 2)``; other shapes raise ``ValueError``. +The output is ``(B, num_classes, H, W)`` logits. Use ``model.encoder.forward_features`` for the raw +encoder tokens. +""" + +from __future__ import annotations + +from typing import Optional, Sequence + +import torch.nn as nn + +from .prithvi import ( + PRITHVI_EO_V2_CONFIGS, + PrithviSegmentation, + PrithviViT, + load_pretrained_state_dict, + mae_state_dict_to_encoder, +) + +TL_WEIGHTS = {"300m": "prithvi_eo_v2_300_tl", "600m": "prithvi_eo_v2_600_tl"} + + +def prithvi_eo_2_tl_builder( + task: str, + variant: str = "300m", + pretrained: bool = False, + weights_path: Optional[str] = None, + cache_dir: Optional[str] = None, + in_channels: int = 6, + num_classes: int = 2, + num_frames: int = 1, + img_size: int = 224, + select_indices: Optional[Sequence[int]] = None, + decoder_channels: Sequence[int] = (512, 256, 128, 64), + head_dropout: float = 0.0, + drop_path: float = 0.0, + embed_dim: Optional[int] = None, + depth: Optional[int] = None, + num_heads: Optional[int] = None, + patch_size: Optional[int] = None, + **kwargs, +) -> nn.Module: + """Build a Prithvi-EO-2.0-TL segmentation model. + + ``variant`` is ``"300m"`` (ViT-L/16) or ``"600m"`` (ViT-H/14). ``pretrained=True`` downloads the + variant's pretraining checkpoint (1.3 GB / 2.6 GB) and loads its encoder weights; + ``weights_path`` loads a local copy instead. ``embed_dim``, ``depth``, ``num_heads`` and + ``patch_size`` override the variant for small untrained test configurations. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"prithvi_eo_2_tl supports task='segmentation', got {task!r}.") + if variant not in PRITHVI_EO_V2_CONFIGS: + raise ValueError(f"variant must be one of {sorted(PRITHVI_EO_V2_CONFIGS)}, got {variant!r}") + cfg = dict(PRITHVI_EO_V2_CONFIGS[variant]) + overrides = dict(embed_dim=embed_dim, depth=depth, num_heads=num_heads) + overrides = {k: v for k, v in overrides.items() if v is not None} + if patch_size is not None: + overrides["patch_size"] = (1, patch_size, patch_size) + load = pretrained or weights_path is not None + if load and (overrides or in_channels != 6 or img_size != 224): + raise ValueError( + "The official TL weights need the variant's architecture with 6 input bands and img_size=224; " + f"got overrides {sorted(overrides)}, in_channels={in_channels}, img_size={img_size}" + ) + cfg.update(overrides) + encoder = PrithviViT( + img_size=img_size, + patch_size=cfg["patch_size"], + num_frames=num_frames, + in_chans=in_channels, + embed_dim=cfg["embed_dim"], + depth=cfg["depth"], + num_heads=cfg["num_heads"], + mlp_ratio=4.0, + coords_encoding=["time", "location"], + coords_scale_learn=True, + drop_path=drop_path, + ) + model = PrithviSegmentation( + encoder, + select_indices=cfg["select_indices"] if select_indices is None else select_indices, + decoder_channels=decoder_channels, + num_classes=num_classes, + head_dropout=head_dropout, + ) + if load: + state = load_pretrained_state_dict(TL_WEIGHTS[variant], weights_path=weights_path, cache_dir=cache_dir) + model.encoder.load_state_dict(mae_state_dict_to_encoder(state, model.encoder), strict=True) + return model + + +__all__ = ["PrithviSegmentation", "PrithviViT", "prithvi_eo_2_tl_builder"] diff --git a/pyhazards/models/rainformer.py b/pyhazards/models/rainformer.py new file mode 100644 index 00000000..0ccb75f2 --- /dev/null +++ b/pyhazards/models/rainformer.py @@ -0,0 +1,547 @@ +"""Rainformer: local/global feature-balanced U-shaped network for radar nowcasting. + +Architecture paper: Bai, Sun, Zhang, Song and Chen, "Rainformer: Features Extraction Balanced +Network for Radar-Based Precipitation Nowcasting", IEEE Geoscience and Remote Sensing Letters 19, +2022 (doi:10.1109/LGRS.2022.3162882). Wildfire usage: the Sim2Real-Fire benchmark (Li et al., +NeurIPS 2024 Datasets and Benchmarks) reports it as its strongest fire-forecasting baseline. + +The official code (github.com/Zjut-MultimediaPlus/Rainformer) has no license, so this module is +written from the paper and from permissively licensed parts; the official code is used only as a +test oracle (tests/oracle/test_rainformer_oracle.py). Module and parameter names +match the official ``Net`` so its state dicts (including the released KNMI checkpoint) load with +``strict=True``, and modules are created in the same order, so the same seed gives the same +initial weights. + +Attribution: + +- ``Residual``, ``PreNorm``, ``FeedForward``, the shifted-window masks, the relative-position + table, ``WindowAttention`` and ``SwinBlock`` are ported from berniwal/swin-transformer-pytorch + ``swin_transformer_pytorch/swin_transformer.py`` at commit + ``c921ebf914c6ea9734bb260ada395e3746c85402`` (MIT License, Copyright (c) 2021 Bernhard Walser), + the Swin implementation the official Rainformer builds on; the einops rearrangements are + written as reshapes and permutes. +- The channel and spatial attention of the local branch follow CBAM (Woo et al., ECCV 2018), as + the Rainformer paper states; the gate fusion unit, patch merging/expanding and the U-shaped + stage layout are written from the Rainformer paper (Sec. II-B to II-D). + +Behaviour of the official code that is kept (it changes outputs or parameter counts): + +- every window attention is followed by a channel attention (``ca``) with separate average- and + max-pool MLPs, and the relative position bias is one table shared by all heads; +- the gate fusion unit computes ``Z * g + R * l`` from ``Z, R = sigmoid(LN(conv(cat(g, l))))``; + the paper's extra convolutions of ``g`` and ``l`` (``conv_2``, ``conv_3``) exist, are counted + and initialised, but are never applied; +- the LayerNorms of the gate fusion unit normalise over ``(channels, height, width)``, so the + parameter count depends on the input size; the official code hard-codes the stage sizes for + 288x288 inputs, PyHazards derives them from ``img_size``; +- decoder blocks use an MLP width of only twice their channel count (``4 * hidden``, with + ``2 * hidden`` channels); +- inside a stage, every (window block, shifted block, CNN, CASA, gate) group reads the stage input + and only the last group's output is kept. With the reference ``layers=(2, 2, 2, 2)`` each stage + has one group; larger ``layers`` add groups whose outputs are discarded (as in the reference). +""" + +from __future__ import annotations + +from typing import Sequence, Union + +import torch +import torch.nn as nn + +from .swin_blocks import to_2tuple + + +# --------------------------------------------------------------------------- Swin parts (MIT) + + +class Residual(nn.Module): + def __init__(self, fn: nn.Module): + super().__init__() + self.fn = fn + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.fn(x) + x + + +class PreNorm(nn.Module): + def __init__(self, dim: int, fn: nn.Module): + super().__init__() + self.norm = nn.LayerNorm(dim) + self.fn = fn + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.fn(self.norm(x)) + + +class FeedForward(nn.Module): + def __init__(self, dim: int, hidden_dim: int): + super().__init__() + self.net = nn.Sequential(nn.Linear(dim, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.net(x) + + +def create_mask(window_size: int, displacement: int, upper_lower: bool, left_right: bool) -> torch.Tensor: + """``-inf`` between window positions that come from different sides of the cyclic shift.""" + mask = torch.zeros(window_size ** 2, window_size ** 2) + cut = displacement * window_size + if upper_lower: + mask[-cut:, :-cut] = float("-inf") + mask[:-cut, -cut:] = float("-inf") + if left_right: + mask = mask.view(window_size, window_size, window_size, window_size) + mask[:, -displacement:, :, :-displacement] = float("-inf") + mask[:, :-displacement, :, -displacement:] = float("-inf") + mask = mask.view(window_size ** 2, window_size ** 2) + return mask + + +def get_relative_distances(window_size: int) -> torch.Tensor: + coords = torch.stack( + torch.meshgrid(torch.arange(window_size), torch.arange(window_size), indexing="ij"), dim=-1 + ).reshape(-1, 2) + return coords[None, :, :] - coords[:, None, :] + + +class WindowChannelAttention(nn.Module): + """Channel attention on channels-last features with separate average- and max-pool MLPs.""" + + def __init__(self, input_channels: int, reduction_ratio: int = 16): + super().__init__() + self.input_channels = input_channels + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.max_pool = nn.AdaptiveMaxPool2d(1) + middle = input_channels // reduction_ratio + if middle < 10: + middle = input_channels + self.MLP1 = nn.Sequential(nn.Flatten(), nn.Linear(input_channels, middle), nn.ReLU(), nn.Linear(middle, input_channels)) + self.MLP2 = nn.Sequential(nn.Flatten(), nn.Linear(input_channels, middle), nn.ReLU(), nn.Linear(middle, input_channels)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x.permute(0, 3, 1, 2) + weights = torch.sigmoid(self.MLP1(self.avg_pool(x)) + self.MLP2(self.max_pool(x))) + return (x * weights[:, :, None, None]).permute(0, 2, 3, 1) + + +class WindowAttention(nn.Module): + """(Shifted) window multi-head self-attention on ``(B, H, W, C)`` features.""" + + def __init__(self, dim: int, heads: int, head_dim: int, shifted: bool, window_size: int, relative_pos_embedding: bool): + super().__init__() + inner_dim = head_dim * heads + self.heads = heads + self.head_dim = head_dim + self.scale = head_dim ** -0.5 + self.window_size = window_size + self.relative_pos_embedding = relative_pos_embedding + self.shifted = shifted + if shifted: + self.displacement = window_size // 2 + # Parameters without gradient (not buffers), as in the reference: same state-dict keys + # and the same parameter count. + self.upper_lower_mask = nn.Parameter( + create_mask(window_size, self.displacement, upper_lower=True, left_right=False), requires_grad=False + ) + self.left_right_mask = nn.Parameter( + create_mask(window_size, self.displacement, upper_lower=False, left_right=True), requires_grad=False + ) + self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False) + if relative_pos_embedding: + self.register_buffer("relative_indices", get_relative_distances(window_size) + window_size - 1, persistent=False) + self.pos_embedding = nn.Parameter(torch.randn(2 * window_size - 1, 2 * window_size - 1)) + else: + self.pos_embedding = nn.Parameter(torch.randn(window_size ** 2, window_size ** 2)) + self.to_out = nn.Linear(inner_dim, dim) + self.ca = WindowChannelAttention(dim) + + def _to_windows(self, t: torch.Tensor, nw_h: int, nw_w: int) -> torch.Tensor: + b, w = t.shape[0], self.window_size + t = t.reshape(b, nw_h, w, nw_w, w, self.heads, self.head_dim) + return t.permute(0, 5, 1, 3, 2, 4, 6).reshape(b, self.heads, nw_h * nw_w, w * w, self.head_dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.shifted: + x = torch.roll(x, shifts=(-self.displacement, -self.displacement), dims=(1, 2)) + b, n_h, n_w, _ = x.shape + w = self.window_size + nw_h, nw_w = n_h // w, n_w // w + q, k, v = (self._to_windows(t, nw_h, nw_w) for t in self.to_qkv(x).chunk(3, dim=-1)) + + dots = torch.einsum("bhwid,bhwjd->bhwij", q, k) * self.scale + if self.relative_pos_embedding: + dots = dots + self.pos_embedding[self.relative_indices[:, :, 0], self.relative_indices[:, :, 1]] + else: + dots = dots + self.pos_embedding + if self.shifted: + dots[:, :, -nw_w:] += self.upper_lower_mask # last row of windows + dots[:, :, nw_w - 1 :: nw_w] += self.left_right_mask # last column of windows + out = torch.einsum("bhwij,bhwjd->bhwid", dots.softmax(dim=-1), v) + + out = out.reshape(b, self.heads, nw_h, nw_w, w, w, self.head_dim) + out = out.permute(0, 2, 4, 3, 5, 1, 6).reshape(b, n_h, n_w, self.heads * self.head_dim) + out = self.to_out(out) + if self.shifted: + out = torch.roll(out, shifts=(self.displacement, self.displacement), dims=(1, 2)) + return self.ca(out) + + +class SwinBlock(nn.Module): + def __init__(self, dim: int, heads: int, head_dim: int, mlp_dim: int, shifted: bool, window_size: int, relative_pos_embedding: bool): + super().__init__() + self.attention_block = Residual( + PreNorm(dim, WindowAttention(dim, heads, head_dim, shifted, window_size, relative_pos_embedding)) + ) + self.mlp_block = Residual(PreNorm(dim, FeedForward(dim=dim, hidden_dim=mlp_dim))) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.mlp_block(self.attention_block(x)) + + +# --------------------------------------------------------------------------- local branch and gate + + +class DoubleConv(nn.Module): + def __init__(self, in_channel: int, out_channel: int): + super().__init__() + self.conv = nn.Sequential( + nn.Conv2d(in_channel, out_channel, kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(out_channel), + nn.ReLU(True), + nn.Conv2d(out_channel, out_channel, kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(out_channel), + nn.ReLU(True), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv(x) + + +class ChannelAttention(nn.Module): + """CBAM channel attention: a shared MLP on average- and max-pooled channels.""" + + def __init__(self, input_channels: int, reduction_ratio: int = 16): + super().__init__() + self.input_channels = input_channels + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.max_pool = nn.AdaptiveMaxPool2d(1) + middle = input_channels // reduction_ratio + if middle <= 0: + middle = input_channels + self.MLP = nn.Sequential(nn.Flatten(), nn.Linear(input_channels, middle), nn.ReLU(), nn.Linear(middle, input_channels)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + weights = torch.sigmoid(self.MLP(self.avg_pool(x)) + self.MLP(self.max_pool(x))) + return x * weights[:, :, None, None] + + +class SpatialAttention(nn.Module): + """CBAM spatial attention: 3x3 convolution of the channel mean and max, BatchNorm, sigmoid.""" + + def __init__(self, kernel_size: int = 3): + super().__init__() + self.conv = nn.Conv2d(2, 1, kernel_size=kernel_size, padding=kernel_size // 2, bias=False) + self.bn = nn.BatchNorm2d(1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + pooled = torch.cat([x.mean(dim=1, keepdim=True), x.max(dim=1, keepdim=True)[0]], dim=1) + return x * torch.sigmoid(self.bn(self.conv(pooled))) + + +class CASA(nn.Module): + def __init__(self, in_channel: int): + super().__init__() + self.ca = ChannelAttention(in_channel) + self.sa = SpatialAttention() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.sa(self.ca(x)) + + +class GateFusionUnit(nn.Module): + """GFU: gates ``Z`` (global) and ``R`` (local) from the concatenated features.""" + + def __init__(self, channel: int, h_w: Sequence[int]): + super().__init__() + height, width = h_w + self.conv_1 = nn.Sequential( + nn.Conv2d(channel * 2, channel * 2, kernel_size=3, stride=1, padding=1), + nn.LayerNorm([channel * 2, height, width]), + ) + # conv_2 / conv_3 are built by the reference but not used in its forward pass. + self.conv_2 = nn.Sequential( + nn.Conv2d(channel, channel, kernel_size=3, stride=1, padding=1), nn.LayerNorm([channel, height, width]) + ) + self.conv_3 = nn.Sequential( + nn.Conv2d(channel * 2, channel, kernel_size=3, stride=1, padding=1), nn.LayerNorm([channel, height, width]) + ) + self.leaky_relu = nn.LeakyReLU(0.2) + + def forward(self, g: torch.Tensor, l: torch.Tensor) -> torch.Tensor: + z, r = torch.chunk(self.conv_1(torch.cat((g, l), dim=1)), 2, dim=1) + return torch.sigmoid(z) * g + torch.sigmoid(r) * l + + +# --------------------------------------------------------------------------- stages + + +class PatchMerging(nn.Module): + """Space-to-depth by ``downscaling_factor`` and a linear projection (channels last out).""" + + def __init__(self, in_channels: int, out_channels: int, downscaling_factor: int): + super().__init__() + self.downscaling_factor = downscaling_factor + self.linear = nn.Linear(in_channels * downscaling_factor ** 2, out_channels) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, c, h, w = x.shape + f = self.downscaling_factor + x = x.reshape(b, c, h // f, f, w // f, f).permute(0, 1, 3, 5, 2, 4) + return self.linear(x.reshape(b, c * f * f, h // f, w // f).permute(0, 2, 3, 1)) + + +class PatchExpanding(nn.Module): + """Depth-to-space by ``upscaling_factor`` and a linear projection (channels last out).""" + + def __init__(self, in_channels: int, out_channels: int, upscaling_factor: int): + super().__init__() + self.upscaling_factor = upscaling_factor + self.linear = nn.Linear(in_channels // (upscaling_factor ** 2), out_channels) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, c, h, w = x.shape + f = self.upscaling_factor + new_c = c // (f * f) + x = x.reshape(b, new_c, f, f, h, w).permute(0, 1, 4, 2, 5, 3) + return self.linear(x.reshape(b, new_c, h * f, w * f).permute(0, 2, 3, 1)) + + +def _febm(dim: int, heads: int, head_dim: int, mlp_dim: int, window_size: int, relative_pos_embedding: bool, h_w) -> nn.ModuleList: + """One feature-extraction-balance module: W-MSA and SW-MSA blocks, CNN, CASA and the gate.""" + attention = dict(heads=heads, head_dim=head_dim, mlp_dim=mlp_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) + return nn.ModuleList( + [ + SwinBlock(dim=dim, shifted=False, **attention), + SwinBlock(dim=dim, shifted=True, **attention), + DoubleConv(dim, dim), + CASA(dim), + GateFusionUnit(dim, h_w), + ] + ) + + +def _run_febms(layers: nn.ModuleList, x: torch.Tensor) -> torch.Tensor: + """``x`` channels last; returns channels first. Every group reads ``x``; the last one wins.""" + out = None + for regular_block, shifted_block, cnn, casa, gate in layers: + local_x = casa(cnn(x.permute(0, 3, 1, 2))) + global_x = shifted_block(regular_block(x)).permute(0, 3, 1, 2) + out = gate(global_x, local_x) + return out + + +class StageModule(nn.Module): + """Encoder stage (and the last decoder stage with ``expand=True``): resample, then FEBM.""" + + def __init__(self, in_channels: int, hidden_dimension: int, layers: int, scaling_factor: int, num_heads: int, head_dim: int, window_size: int, relative_pos_embedding: bool, h_w, expand: bool = False): + super().__init__() + if expand: + self.patch_partition = PatchExpanding(in_channels, hidden_dimension, scaling_factor) + else: + self.patch_partition = PatchMerging(in_channels, hidden_dimension, scaling_factor) + self.layers = nn.ModuleList( + [ + _febm(hidden_dimension, num_heads, head_dim, hidden_dimension * 4, window_size, relative_pos_embedding, h_w) + for _ in range(layers // 2) + ] + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return _run_febms(self.layers, self.patch_partition(x)) + + +class StageModuleUp(nn.Module): + """Decoder stage: patch expanding, concatenation with the encoder skip, then FEBM.""" + + def __init__(self, in_channels: int, hidden_dimension: int, layers: int, upscaling_factor: int, num_heads: int, head_dim: int, window_size: int, relative_pos_embedding: bool, h_w): + super().__init__() + self.patch_partition = PatchExpanding(in_channels, hidden_dimension, upscaling_factor) + self.in_channel = in_channels + self.hidden_dimension = hidden_dimension + self.layers = nn.ModuleList( + [ + _febm(hidden_dimension * 2, num_heads, head_dim, hidden_dimension * 4, window_size, relative_pos_embedding, h_w) + for _ in range(layers // 2) + ] + ) + + def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: + x = torch.cat((self.patch_partition(x), skip.permute(0, 2, 3, 1)), dim=-1) + return _run_febms(self.layers, x) + + +def rainformer_stage_sizes(img_size: Union[int, Sequence[int]], downscaling_factors: Sequence[int]) -> list: + """Feature-map sizes ``(h, w)`` of stages 1-8 for an input of ``img_size``. + + Stages 1-4 divide by the downscaling factors, stages 5-7 mirror stages 3-1 and stage 8 is at + the input resolution: 288x288 with (4, 2, 2, 2) gives 72, 36, 18, 9, 18, 36, 72, 288. + """ + h, w = to_2tuple(img_size) + sizes = [] + for factor in downscaling_factors: + if factor <= 0 or h % factor or w % factor: + raise ValueError( + f"Rainformer input size {to_2tuple(img_size)} is not divisible by the downscaling factors " + f"{tuple(downscaling_factors)} (stage {len(sizes) + 1} gets {(h, w)})." + ) + h, w = h // factor, w // factor + sizes.append((h, w)) + return sizes + [sizes[2], sizes[1], sizes[0], to_2tuple(img_size)] + + +class Rainformer(nn.Module): + """Rainformer (official ``Net``): ``input_channel`` frames in, as many frames out. + + Input ``(B, input_channel, H, W)`` (frames stacked as channels, the official layout) or + ``(B, T, C, H, W)`` with ``T * C == input_channel`` (flattened time-major and reshaped back). + """ + + def __init__( + self, + input_channel: int = 9, + hidden_dim: int = 96, + downscaling_factors: Sequence[int] = (4, 2, 2, 2), + layers: Sequence[int] = (2, 2, 2, 2), + heads: Sequence[int] = (3, 6, 12, 24), + head_dim: int = 32, + window_size: int = 9, + relative_pos_embedding: bool = True, + img_size: Union[int, Sequence[int]] = 288, + ): + super().__init__() + d, layers, heads = tuple(downscaling_factors), tuple(layers), tuple(heads) + if len(d) != 4 or len(layers) != 4 or len(heads) != 4: + raise ValueError("Rainformer needs four downscaling_factors, layers and heads (one per encoder stage).") + if any(n < 2 or n % 2 for n in layers): + raise ValueError(f"Rainformer stage layers must be even and >= 2 (regular + shifted block), got {layers}.") + if window_size < 2: + raise ValueError(f"window_size must be >= 2 for shifted windows, got {window_size}.") + if input_channel <= 0 or hidden_dim <= 0: + raise ValueError(f"input_channel and hidden_dim must be positive, got {input_channel} and {hidden_dim}.") + sizes = rainformer_stage_sizes(img_size, d) + for stage, (h, w) in enumerate(sizes, start=1): + if h % window_size or w % window_size: + raise ValueError( + f"Rainformer stage {stage} feature map {(h, w)} (input {to_2tuple(img_size)}) is not divisible by " + f"window_size {window_size}; the official 288x288 setting gives 72/36/18/9 with window 9." + ) + for channels, factor in ((hidden_dim * 8, d[3]), (hidden_dim * 8, d[2]), (hidden_dim * 4, d[1]), (hidden_dim * 2, d[0])): + if channels % (factor * factor): + raise ValueError(f"patch expanding needs {channels} channels divisible by {factor}**2; change hidden_dim.") + self.input_channel = input_channel + self.img_size = to_2tuple(img_size) + self.stage_sizes = sizes + + common = dict(head_dim=head_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) + self.stage1 = StageModule(input_channel, hidden_dim, layers[0], d[0], heads[0], h_w=sizes[0], **common) + self.stage2 = StageModule(hidden_dim, hidden_dim * 2, layers[1], d[1], heads[1], h_w=sizes[1], **common) + self.stage3 = StageModule(hidden_dim * 2, hidden_dim * 4, layers[2], d[2], heads[2], h_w=sizes[2], **common) + self.stage4 = StageModule(hidden_dim * 4, hidden_dim * 8, layers[3], d[3], heads[3], h_w=sizes[3], **common) + self.stage5 = StageModuleUp(hidden_dim * 8, hidden_dim * 4, layers[3], d[3], heads[3], h_w=sizes[4], **common) + self.stage6 = StageModuleUp(hidden_dim * 8, hidden_dim * 2, layers[2], d[2], heads[2], h_w=sizes[5], **common) + self.stage7 = StageModuleUp(hidden_dim * 4, hidden_dim, layers[1], d[1], heads[1], h_w=sizes[6], **common) + self.stage8 = StageModule(hidden_dim * 2, input_channel, layers[0], d[0], heads[0], h_w=sizes[7], expand=True, **common) + + def _check_input(self, x: torch.Tensor) -> None: + layout = None + if x.ndim == 4: + layout = x.shape[1] == self.input_channel + elif x.ndim == 5: + layout = x.shape[1] * x.shape[2] == self.input_channel + if not layout or tuple(x.shape[-2:]) != self.img_size: + raise ValueError( + f"Rainformer expects input shape (batch, {self.input_channel}, {self.img_size[0]}, {self.img_size[1]}) or " + f"(batch, time, channels, {self.img_size[0]}, {self.img_size[1]}) with time * channels = " + f"{self.input_channel}, got {tuple(x.shape)}." + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + self._check_input(x) + frames = x.shape[:3] if x.ndim == 5 else None + if frames is not None: + x = x.flatten(1, 2) + x1 = self.stage1(x) + x2 = self.stage2(x1) + x3 = self.stage3(x2) + x4 = self.stage4(x3) + x5 = self.stage5(x4, x3) + x6 = self.stage6(x5, x2) + x7 = self.stage7(x6, x1) + out = self.stage8(x7) + return out.reshape(*frames, *out.shape[-2:]) if frames is not None else out + + +class RainformerSegmenter(Rainformer): + """PyHazards adaptation for next-step masks: ``(B, T, C, H, W)`` -> logits ``(B, out, H, W)``. + + Runs :class:`Rainformer` and maps the ``C`` channels of the first predicted frame to + ``out_channels`` logits with a 1x1 convolution (``segmentation_head``). The Rainformer + parameters keep their reference names at the top level. + """ + + def __init__(self, in_channels: int, out_channels: int = 1, **kwargs): + super().__init__(**kwargs) + if in_channels <= 0 or self.input_channel % in_channels: + raise ValueError(f"in_channels {in_channels} must divide input_channel {self.input_channel}.") + if out_channels <= 0: + raise ValueError(f"out_channels must be positive, got {out_channels}.") + self.in_channels = in_channels + self.segmentation_head = nn.Conv2d(in_channels, out_channels, kernel_size=1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 5 or x.shape[2] != self.in_channels: + raise ValueError( + f"Rainformer segmentation expects input shape (batch, time, {self.in_channels}, height, width), " + f"got {tuple(x.shape)}." + ) + return self.segmentation_head(super().forward(x)[:, 0]) + + +def rainformer_builder( + task: str, + in_channels: int = 1, + history: int = 9, + img_size: Union[int, Sequence[int]] = 288, + out_channels: int = 1, + hidden_dim: int = 96, + downscaling_factors: Sequence[int] = (4, 2, 2, 2), + layers: Sequence[int] = (2, 2, 2, 2), + heads: Sequence[int] = (3, 6, 12, 24), + head_dim: int = 32, + window_size: int = 9, + relative_pos_embedding: bool = True, + **kwargs, +) -> nn.Module: + """Rainformer with the official KNMI configuration (``train.py``: 9 frames, 288x288). + + ``task="forecasting"``: ``(B, history, in_channels, H, W)`` -> the next ``history`` frames. + ``task="segmentation"``: the same input -> ``(B, out_channels, H, W)`` logits (PyHazards + adaptation, see :class:`RainformerSegmenter`). + """ + _ = kwargs + task = task.lower() + if task not in {"forecasting", "segmentation"}: + raise ValueError(f"rainformer supports task='forecasting' or 'segmentation', got {task!r}.") + if history <= 0 or in_channels <= 0: + raise ValueError(f"history and in_channels must be positive, got {history} and {in_channels}.") + config = dict( + input_channel=history * in_channels, hidden_dim=hidden_dim, downscaling_factors=downscaling_factors, + layers=layers, heads=heads, head_dim=head_dim, window_size=window_size, + relative_pos_embedding=relative_pos_embedding, img_size=img_size, + ) + if task == "segmentation": + return RainformerSegmenter(in_channels=in_channels, out_channels=out_channels, **config) + return Rainformer(**config) + + +__all__ = ["Rainformer", "RainformerSegmenter", "rainformer_builder", "rainformer_stage_sizes"] diff --git a/pyhazards/models/resnet_unet.py b/pyhazards/models/resnet_unet.py new file mode 100644 index 00000000..4f052e6d --- /dev/null +++ b/pyhazards/models/resnet_unet.py @@ -0,0 +1,329 @@ +"""U-Net with a ResNet encoder, equivalent to ``segmentation_models_pytorch.Unet``. + +WildfireSpreadTS (Gerard et al., NeurIPS 2023 D&B) uses ``smp.Unet(encoder_name="resnet18", +encoder_weights=None, in_channels=C, classes=1)`` from segmentation_models_pytorch 0.3.2 +(MIT, Copyright (c) 2019 Pavel Iakubovskii). This module re-implements that network in plain +PyTorch: the torchvision ResNet encoder without its classifier, the smp U-Net decoder +(nearest-neighbour upsampling, two Conv-BN-ReLU per block, no centre block) and the 3x3 +segmentation head, with the same initialisation and the same parameter names, so smp state +dicts load with ``strict=True``. + +Architecture papers: U-Net (Ronneberger et al., MICCAI 2015) and ResNet (He et al., CVPR 2016). +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# ImageNet weights used by smp 0.3.2 (torchvision checkpoints, BSD-3-Clause). +RESNET_IMAGENET_URLS = { + "resnet18": "https://download.pytorch.org/models/resnet18-5c106cde.pth", + "resnet34": "https://download.pytorch.org/models/resnet34-333f7ec4.pth", +} +RESNET_LAYERS = { + "resnet18": (2, 2, 2, 2), + "resnet34": (3, 4, 6, 3), +} + + +class BasicBlock(nn.Module): + expansion = 1 + + def __init__(self, inplanes: int, planes: int, stride: int = 1, downsample: Optional[nn.Module] = None): + super().__init__() + self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.downsample = downsample + + def forward(self, x: torch.Tensor) -> torch.Tensor: + identity = x if self.downsample is None else self.downsample(x) + out = self.relu(self.bn1(self.conv1(x))) + out = self.bn2(self.conv2(out)) + return self.relu(out + identity) + + +class ResNetEncoder(nn.Module): + """torchvision ResNet (BasicBlock variants) without ``avgpool``/``fc``, returning multi-scale features.""" + + def __init__(self, name: str = "resnet18", in_channels: int = 3, depth: int = 5): + super().__init__() + if name not in RESNET_LAYERS: + raise ValueError(f"encoder_name must be one of {sorted(RESNET_LAYERS)}, got {name!r}") + if not 1 <= depth <= 5: + raise ValueError(f"encoder_depth must be in [1, 5], got {depth}") + self.name = name + self.depth = depth + self.in_channels = 3 + self.inplanes = 64 + self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = nn.BatchNorm2d(64) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + layers = RESNET_LAYERS[name] + self.layer1 = self._make_layer(64, layers[0]) + self.layer2 = self._make_layer(128, layers[1], stride=2) + self.layer3 = self._make_layer(256, layers[2], stride=2) + self.layer4 = self._make_layer(512, layers[3], stride=2) + # torchvision builds its 1000-way classifier here and smp deletes it afterwards. Creating and + # dropping it keeps the random-number stream, and therefore seeded initialisation, identical. + nn.Linear(512, 1000) + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + self.out_channels = [3, 64, 64, 128, 256, 512][: depth + 1] + self._output_stride = 32 + self.set_in_channels(in_channels, pretrained=False) + + @property + def output_stride(self) -> int: + return min(self._output_stride, 2**self.depth) + + def load_imagenet_weights(self) -> None: + """Load the torchvision ImageNet checkpoint that smp uses (needs a 3-channel stem).""" + state = torch.hub.load_state_dict_from_url(RESNET_IMAGENET_URLS[self.name], progress=False) + state.pop("fc.weight", None) + state.pop("fc.bias", None) + self.load_state_dict(state) + + def make_dilated(self, output_stride: int) -> None: + """Trade the strides of the last stages for dilation, as smp's ``EncoderMixin.make_dilated``. + + Every convolution of ``layer4`` (output stride 16), or of ``layer3`` and ``layer4`` (output + stride 8), gets stride 1 and dilation 2 / 4, including the first block's convolution and + its 1x1 shortcut (torchvision keeps the previous dilation there; smp does not). + """ + if output_stride == 16: + stages, rates = [self.layer4], [2] + elif output_stride == 8: + stages, rates = [self.layer3, self.layer4], [2, 4] + else: + raise ValueError(f"output_stride must be 8 or 16, got {output_stride}") + self._output_stride = output_stride + for stage, rate in zip(stages, rates): + for module in stage.modules(): + if isinstance(module, nn.Conv2d): + module.stride = (1, 1) + module.dilation = (rate, rate) + kh, _ = module.kernel_size + module.padding = ((kh // 2) * rate, (kh // 2) * rate) # smp uses kh for both axes + + def _make_layer(self, planes: int, blocks: int, stride: int = 1) -> nn.Sequential: + downsample = None + if stride != 1 or self.inplanes != planes: + downsample = nn.Sequential( + nn.Conv2d(self.inplanes, planes, kernel_size=1, stride=stride, bias=False), + nn.BatchNorm2d(planes), + ) + layers = [BasicBlock(self.inplanes, planes, stride, downsample)] + self.inplanes = planes + layers.extend(BasicBlock(self.inplanes, planes) for _ in range(1, blocks)) + return nn.Sequential(*layers) + + def set_in_channels(self, in_channels: int, pretrained: bool) -> None: + """Adapt the stem to ``in_channels`` the way smp does (``patch_first_conv``).""" + if in_channels <= 0: + raise ValueError(f"in_channels must be positive, got {in_channels}") + if in_channels == 3: + return + weight = self.conv1.weight.detach() + self.conv1.in_channels = in_channels + if not pretrained: + self.conv1.weight = nn.Parameter(torch.empty(64, in_channels, *self.conv1.kernel_size)) + self.conv1.reset_parameters() + elif in_channels == 1: + self.conv1.weight = nn.Parameter(weight.sum(1, keepdim=True)) + else: + new_weight = torch.empty(64, in_channels, *self.conv1.kernel_size) + for i in range(in_channels): + new_weight[:, i] = weight[:, i % 3] + self.conv1.weight = nn.Parameter(new_weight * (3 / in_channels)) + self.in_channels = in_channels + self.out_channels[0] = in_channels + + def forward(self, x: torch.Tensor) -> List[torch.Tensor]: + stages = [ + nn.Identity(), + nn.Sequential(self.conv1, self.bn1, self.relu), + nn.Sequential(self.maxpool, self.layer1), + self.layer2, + self.layer3, + self.layer4, + ] + features = [] + for i in range(self.depth + 1): + x = stages[i](x) + features.append(x) + return features + + +class Conv2dReLU(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, use_batchnorm: bool = True): + super().__init__( + nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=not use_batchnorm), + nn.BatchNorm2d(out_channels) if use_batchnorm else nn.Identity(), + nn.ReLU(inplace=True), + ) + + +class DecoderBlock(nn.Module): + def __init__(self, in_channels: int, skip_channels: int, out_channels: int, use_batchnorm: bool = True): + super().__init__() + self.conv1 = Conv2dReLU(in_channels + skip_channels, out_channels, use_batchnorm) + self.conv2 = Conv2dReLU(out_channels, out_channels, use_batchnorm) + + def forward(self, x: torch.Tensor, skip: Optional[torch.Tensor] = None) -> torch.Tensor: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if skip is not None: + x = torch.cat([x, skip], dim=1) + return self.conv2(self.conv1(x)) + + +class UnetDecoder(nn.Module): + def __init__(self, encoder_channels: Sequence[int], decoder_channels: Sequence[int], use_batchnorm: bool = True): + super().__init__() + encoder_channels = list(encoder_channels[1:])[::-1] + head_channels = encoder_channels[0] + in_channels = [head_channels] + list(decoder_channels[:-1]) + skip_channels = list(encoder_channels[1:]) + [0] + self.center = nn.Identity() + self.blocks = nn.ModuleList( + DecoderBlock(in_ch, skip_ch, out_ch, use_batchnorm) + for in_ch, skip_ch, out_ch in zip(in_channels, skip_channels, decoder_channels) + ) + + def forward(self, *features: torch.Tensor) -> torch.Tensor: + features = features[1:][::-1] + skips = features[1:] + x = self.center(features[0]) + for i, block in enumerate(self.blocks): + x = block(x, skips[i] if i < len(skips) else None) + return x + + +class ResNetUNet(nn.Module): + """``smp.Unet`` with a ResNet-18/34 encoder. + + Accepts ``(batch, channels, height, width)``, or ``(batch, time, channels, height, width)`` + which is flattened to ``time * channels`` input channels as WildfireSpreadTS does for its + multi-day U-Net. With ``static_feature_ids``, those per-day features (constant over time) are + kept for the last day only, as WildfireSpreadTS does with ``remove_duplicate_features``. + Height and width must be divisible by ``2 ** encoder_depth``. + """ + + def __init__( + self, + in_channels: int, + classes: int = 1, + encoder_name: str = "resnet18", + encoder_depth: int = 5, + encoder_weights: Optional[str] = None, + decoder_channels: Sequence[int] = (256, 128, 64, 32, 16), + decoder_use_batchnorm: bool = True, + static_feature_ids: Optional[Sequence[int]] = None, + ): + super().__init__() + self.static_feature_ids = None if static_feature_ids is None else tuple(int(i) for i in static_feature_ids) + if len(decoder_channels) != encoder_depth: + raise ValueError( + f"decoder_channels needs {encoder_depth} entries for encoder_depth={encoder_depth}, " + f"got {len(decoder_channels)}." + ) + if classes <= 0: + raise ValueError(f"classes must be positive, got {classes}") + self.encoder = ResNetEncoder(encoder_name, in_channels=3, depth=encoder_depth) + if encoder_weights is not None: + if encoder_weights != "imagenet": + raise ValueError(f"encoder_weights must be None or 'imagenet', got {encoder_weights!r}") + self.encoder.load_imagenet_weights() + self.encoder.set_in_channels(in_channels, pretrained=encoder_weights is not None) + self.in_channels = int(in_channels) + self.output_stride = 2 ** encoder_depth + self.decoder = UnetDecoder(self.encoder.out_channels, decoder_channels, use_batchnorm=decoder_use_batchnorm) + self.segmentation_head = nn.Sequential( + nn.Conv2d(decoder_channels[-1], classes, kernel_size=3, padding=1), + nn.Identity(), + nn.Identity(), + ) + for m in self.decoder.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + for m in self.segmentation_head.modules(): + if isinstance(m, nn.Conv2d): + nn.init.xavier_uniform_(m.weight) + nn.init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 5: + if self.static_feature_ids is None: + x = x.flatten(start_dim=1, end_dim=2) + else: + x = flatten_and_remove_duplicate_features(x, self.static_feature_ids) + if x.ndim != 4: + raise ValueError( + "ResNetUNet expects input shape (batch, channels, height, width) or " + f"(batch, time, channels, height, width), got {tuple(x.shape)}." + ) + if x.size(1) != self.in_channels: + raise ValueError(f"ResNetUNet expected {self.in_channels} input channels, got {x.size(1)}.") + h, w = x.shape[-2:] + if h % self.output_stride or w % self.output_stride: + raise ValueError( + f"ResNetUNet needs height and width divisible by {self.output_stride}, got {(h, w)}." + ) + features = self.encoder(x) + return self.segmentation_head(self.decoder(*features)) + + +def flatten_and_remove_duplicate_features(x: torch.Tensor, static_feature_ids: Sequence[int]) -> torch.Tensor: + """Flatten ``(B, T, C, H, W)`` to channels, keeping static features for the last day only. + + Matches WildfireSpreadTS ``FireSpreadDataset.flatten_and_remove_duplicate_features_``: the + dynamic features of days ``0..T-2`` (day-major), followed by all ``C`` features of the last + day, giving ``(T - 1) * (C - len(static_feature_ids)) + C`` channels. + """ + if x.ndim != 5: + raise ValueError(f"expected input shape (batch, time, channels, height, width), got {tuple(x.shape)}.") + static = set(int(i) for i in static_feature_ids) + dynamic = [i for i in range(x.size(2)) if i not in static] + earlier = x[:, :-1, dynamic].flatten(start_dim=1, end_dim=2) + return torch.cat([earlier, x[:, -1]], dim=1) + + +def resnet18_unet_builder( + task: str, + in_channels: int, + out_channels: int = 1, + history: int = 1, + encoder_name: str = "resnet18", + encoder_weights: Optional[str] = None, + **kwargs, +) -> nn.Module: + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"resnet18_unet supports task='segmentation', got {task!r}.") + if history <= 0: + raise ValueError(f"history must be positive, got {history}") + return ResNetUNet( + in_channels=in_channels * history, + classes=out_channels, + encoder_name=encoder_name, + encoder_weights=encoder_weights, + ) + + +__all__ = ["ResNetEncoder", "ResNetUNet", "flatten_and_remove_duplicate_features", "resnet18_unet_builder"] diff --git a/pyhazards/models/saf_net.py b/pyhazards/models/saf_net.py index 796bcacd..a372b283 100644 --- a/pyhazards/models/saf_net.py +++ b/pyhazards/models/saf_net.py @@ -1,58 +1,180 @@ +"""SAF-Net: spatio-temporal attention fusion network for 24-hour typhoon intensity prediction. + +Paper: G. Xu, K. Lin, X. Li and Y. Ye, "SAF-Net: A spatio-temporal deep learning method for +typhoon intensity prediction", Pattern Recognition Letters 155, 121-127 (2022), +doi:10.1016/j.patrec.2021.11.012. + +The official code (github.com/xuguangning1218/TI_Prediction, ``SAF-Net.ipynb``) has no license, +so this module is written from the paper's description of the network; the notebook and its +released checkpoint (``model_saver/SAF_Net.pkl``) are used only as a test oracle +(tests/oracle/test_saf_net_oracle.py) and are never copied or redistributed. Module and parameter +names follow the official state dict so that the released checkpoint loads with ``strict=True``, +and parameters are created in the same order, so the same seed gives the same initial weights. + +SAF-Net is a wide-and-deep regressor of the maximum sustained wind 24 hours ahead: + +* wide part: 96 hand-crafted CLIPER-style predictors from the CMA best track (current and + past positions, pressures and winds, their 6-hourly changes and derived climatology factors), + MinMax-scaled; +* deep part: ERA-Interim u and v wind on a 31 x 31 storm-centred grid at four pressure levels + (1000, 750, 500, 250 hPa) for four times (t, t-6 h, t-12 h, t-18 h), MinMax-scaled, as a tensor + ``(batch, 2, level, height, width, time)`` with u first; +* each time step runs three convolution stages (3 x 3 convolution with 64 / 128 / 256 channels, + ReLU, 2 x 2 max pooling) shared by a u branch, a v branch and a fused branch. After every stage a + spatial-attention block (1 x 1 conv, BatchNorm, ReLU, 1 x 1 conv, BatchNorm, sigmoid) rescales + the features. Before stages 2 and 3, and after stage 3, the u and v branches are mixed with + learnable weights (``cross_unit``) and merged with the fused branch with learnable weights + (``fuse_unit``); each pair of weights ``(a, b)`` mixes as ``a / (a + b) * x + b / (a + b) * y``; +* the fused 256 x 3 x 3 map of each time step goes through ``fc1`` (no activation); the four + 128-d time features are concatenated after the 96 wide predictors, then ``fc2`` (ReLU) and + ``fc3`` (ReLU) give one MinMax-scaled intensity. + +Behaviour of the official network that is kept because it changes outputs: the fused branch of +stage 3 passes through the stage-3 attention block a second time after the final mix; ``fc1`` has +no activation; the output goes through a ReLU, so predictions of the scaled target are never +negative. +""" + from __future__ import annotations +from typing import Mapping, Optional, Sequence + import torch import torch.nn as nn +import torch.nn.functional as F + +_U, _V = 0, 1 + + +def _spatial_attention(channels: int) -> nn.Sequential: + """1x1 conv - BN - ReLU - 1x1 conv - BN - sigmoid, giving a per-pixel, per-channel gate.""" + return nn.Sequential( + nn.Conv2d(channels, channels, kernel_size=1, padding=0), + nn.BatchNorm2d(channels), + nn.ReLU(inplace=True), + nn.Conv2d(channels, channels, kernel_size=1, padding=0), + nn.BatchNorm2d(channels), + nn.Sigmoid(), + ) + + +def _weighted_mix(weights: torch.Tensor, first: int, second: int, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + total = weights[first] + weights[second] + return weights[first] / total * x + weights[second] / total * y class SAFNet(nn.Module): - """Spatiotemporal intensity-focused storm baseline.""" + """SAF-Net intensity regressor. + + ``forward(wide, deep)`` takes ``wide`` ``(batch, wide_dim)`` and ``deep`` + ``(batch, 2, num_levels, grid_size, grid_size, num_times)`` (u then v; times ordered t, t-6 h, + t-12 h, t-18 h in the paper) and returns ``(batch, 1)``: the MinMax-scaled maximum sustained + wind ``lead`` hours after time t. A mapping ``{"wide": ..., "deep": ...}`` may be passed as + the only argument. + """ def __init__( self, - input_dim: int = 8, + wide_dim: int = 96, + num_times: int = 4, + num_levels: int = 4, + grid_size: int = 31, + channels: Sequence[int] = (64, 128, 256), + time_feature_dim: int = 128, hidden_dim: int = 64, - horizon: int = 5, - dropout: float = 0.1, ): super().__init__() - self.horizon = int(horizon) - self.temporal = nn.Sequential( - nn.Conv1d(input_dim, hidden_dim, kernel_size=3, padding=1), - nn.ReLU(), - nn.Conv1d(hidden_dim, hidden_dim, kernel_size=3, padding=1), - nn.ReLU(), - ) - self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() - self.track_head = nn.Linear(hidden_dim, 2 * self.horizon) - self.intensity_head = nn.Linear(hidden_dim, self.horizon) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("SAFNet expects inputs shaped (batch, history, features).") - encoded = self.temporal(x.transpose(1, 2)).mean(dim=-1) - encoded = self.dropout(encoded) - track = self.track_head(encoded).view(x.size(0), self.horizon, 2) - intensity = self.intensity_head(encoded).view(x.size(0), self.horizon, 1) - return torch.cat([track, intensity], dim=-1) + channels = tuple(int(c) for c in channels) + if len(channels) != 3: + raise ValueError("SAF-Net has exactly three convolution stages; pass three channel widths") + spatial = int(grid_size) + for _ in channels: + spatial //= 2 + if spatial < 1: + raise ValueError(f"grid_size={grid_size} is too small for three 2x2 poolings") + self.wide_dim = int(wide_dim) + self.num_times = int(num_times) + self.num_levels = int(num_levels) + self.grid_size = int(grid_size) + self.channels = channels + self.time_feature_dim = int(time_feature_dim) + + # Creation order follows the official network (attention blocks, mixing weights, + # convolutions, fully connected layers) so that a seed gives the official initial weights. + self.att_block_1 = _spatial_attention(channels[0]) + self.att_block_2 = _spatial_attention(channels[1]) + self.att_block_3 = _spatial_attention(channels[2]) + # Per time step: three (u, v) cross weights and two (fused, cross) fuse weights. + self.cross_unit = nn.Parameter(torch.ones(self.num_times, 6)) + self.fuse_unit = nn.Parameter(torch.ones(self.num_times, 4)) + self.conv1 = nn.Conv2d(self.num_levels, channels[0], kernel_size=3, padding=(1, 1)) + self.pool = nn.MaxPool2d(2, 2) + self.conv2 = nn.Conv2d(channels[0], channels[1], kernel_size=3, padding=(1, 1)) + self.conv3 = nn.Conv2d(channels[1], channels[2], kernel_size=3, padding=(1, 1)) + self.fc1 = nn.Linear(channels[2] * spatial * spatial, self.time_feature_dim) + self.fc2 = nn.Linear(self.wide_dim + self.time_feature_dim * self.num_times, hidden_dim) + self.fc3 = nn.Linear(hidden_dim, 1) + + def _stage(self, index: int, x: torch.Tensor) -> torch.Tensor: + conv = getattr(self, f"conv{index}") + attention = getattr(self, f"att_block_{index}") + features = self.pool(F.relu(conv(x))) + return attention(features) * features + + def _time_step_features(self, u: torch.Tensor, v: torch.Tensor, step: int) -> torch.Tensor: + cross = self.cross_unit[step] + fuse = self.fuse_unit[step] + u = self._stage(1, u) + v = self._stage(1, v) + fused = self._stage(2, _weighted_mix(cross, 0, 1, u, v)) + u = self._stage(2, u) + v = self._stage(2, v) + fused = self._stage(3, _weighted_mix(fuse, 0, 1, fused, _weighted_mix(cross, 2, 3, u, v))) + u = self._stage(3, u) + v = self._stage(3, v) + fused = _weighted_mix(fuse, 2, 3, fused, _weighted_mix(cross, 4, 5, u, v)) + fused = self.att_block_3(fused) * fused + return self.fc1(fused.flatten(1)) + + def _check_inputs(self, wide: torch.Tensor, deep: torch.Tensor) -> None: + expected_deep = (2, self.num_levels, self.grid_size, self.grid_size, self.num_times) + if deep.ndim != 6 or tuple(deep.shape[1:]) != expected_deep: + raise ValueError( + "SAF-Net expects deep inputs shaped (batch, 2 [u, v], {levels}, {size}, {size}, {times}), got {shape}".format( + levels=self.num_levels, size=self.grid_size, times=self.num_times, shape=tuple(deep.shape) + ) + ) + if wide.ndim != 2 or wide.size(1) != self.wide_dim or wide.size(0) != deep.size(0): + raise ValueError( + f"SAF-Net expects wide inputs shaped (batch, {self.wide_dim}) matching the deep batch, got {tuple(wide.shape)}" + ) + + def forward(self, wide, deep: Optional[torch.Tensor] = None) -> torch.Tensor: + if isinstance(wide, Mapping): + wide, deep = wide["wide"], wide["deep"] + if deep is None: + raise ValueError("SAF-Net needs both the wide predictors and the deep wind fields") + self._check_inputs(wide, deep) + time_features = [ + self._time_step_features(deep[:, _U, :, :, :, step], deep[:, _V, :, :, :, step], step) + for step in range(self.num_times) + ] + joined = torch.cat([wide, *time_features], dim=1) + return F.relu(self.fc3(F.relu(self.fc2(joined)))) def saf_net_builder( task: str, - input_dim: int = 8, - hidden_dim: int = 64, - horizon: int = 5, - dropout: float = 0.1, + wide_dim: int = 96, + num_times: int = 4, + num_levels: int = 4, + grid_size: int = 31, **kwargs, ) -> nn.Module: _ = kwargs if task.lower() != "regression": - raise ValueError("SAFNet only supports regression for track/intensity forecasting.") - return SAFNet( - input_dim=input_dim, - hidden_dim=hidden_dim, - horizon=horizon, - dropout=dropout, - ) + raise ValueError("saf_net is a regression model (24-hour intensity); use task='regression'.") + return SAFNet(wide_dim=wide_dim, num_times=num_times, num_levels=num_levels, grid_size=grid_size) __all__ = ["SAFNet", "saf_net_builder"] diff --git a/pyhazards/models/segformer.py b/pyhazards/models/segformer.py new file mode 100644 index 00000000..3de0f1c0 --- /dev/null +++ b/pyhazards/models/segformer.py @@ -0,0 +1,613 @@ +"""SegFormer: a Mix Transformer (MiT) encoder with an all-MLP decode head. + +Xie, Wang, Yu, Anandkumar, Alvarez & Luo, "SegFormer: Simple and Efficient Design for Semantic +Segmentation with Transformers", NeurIPS 2021 (https://arxiv.org/abs/2105.15203). + +Ported to plain PyTorch from Hugging Face transformers 4.57.6, +``src/transformers/models/segformer/modeling_segformer.py`` (Apache-2.0, Copyright 2021 NVIDIA and +The HuggingFace Inc. team). The official NVlabs/SegFormer code is under the NVIDIA Source Code +License (non-commercial use only) and was not used. + +Module and parameter names follow transformers up to 5.8.x (transformers 5.9 renamed them and maps +the old names on load; the checkpoints on the Hub keep the old ones), so: + +- a ``SegformerForSemanticSegmentation`` state dict loads into :class:`SegFormer` with ``strict=True``; +- a ``SegformerModel`` state dict loads into ``SegFormer.segformer`` with ``strict=True``; +- the ImageNet-1k MiT checkpoints ``nvidia/mit-b0`` ... ``nvidia/mit-b5`` (``SegformerForImageClassification``) + load into ``SegFormer.segformer`` with ``strict=True`` once the ``segformer.`` prefix is removed and + the 1000-way ``classifier`` is dropped; :meth:`SegFormer.load_hf_state_dict` does this. + +Weights are initialised as transformers does (PyTorch defaults at construction, then +``SegformerPreTrainedModel._init_weights``, encoder before decode head), so the same seed gives +the same initial weights as ``SegformerForSemanticSegmentation(config)``. + +NVIDIA licenses its SegFormer/MiT weights for non-commercial use only; PyHazards does not bundle +them, and ``encoder_weights="imagenet"`` downloads them from the Hugging Face Hub on request. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# MiT encoder sizes (transformers configs of nvidia/mit-b0..b5, the official mit_b0..b5 classes and +# paper Table 6) and the decode-head width C (256 for the real-time B0/B1, 768 for B2-B5, paper +# Sec. 4.2). All variants share heads (1, 2, 5, 8), reduction ratios (8, 4, 2, 1) and Mix-FFN +# expansion 4; paper Table 6 lists expansion 8 in stages 1-2 of B0-B4, which matches neither the +# released code and weights nor the B1-B5 parameter counts of paper Table 1. +SEGFORMER_VARIANTS: Dict[str, Dict[str, object]] = { + "b0": {"hidden_sizes": (32, 64, 160, 256), "depths": (2, 2, 2, 2), "decoder_hidden_size": 256}, + "b1": {"hidden_sizes": (64, 128, 320, 512), "depths": (2, 2, 2, 2), "decoder_hidden_size": 256}, + "b2": {"hidden_sizes": (64, 128, 320, 512), "depths": (3, 4, 6, 3), "decoder_hidden_size": 768}, + "b3": {"hidden_sizes": (64, 128, 320, 512), "depths": (3, 4, 18, 3), "decoder_hidden_size": 768}, + "b4": {"hidden_sizes": (64, 128, 320, 512), "depths": (3, 8, 27, 3), "decoder_hidden_size": 768}, + "b5": {"hidden_sizes": (64, 128, 320, 512), "depths": (3, 6, 40, 3), "decoder_hidden_size": 768}, +} + +# ImageNet-1k MiT encoders on the Hugging Face Hub: pinned revision and sha256 of pytorch_model.bin. +MIT_IMAGENET_CHECKPOINTS: Dict[str, Tuple[str, str]] = { + "b0": ("80983a413c30d36a39c20203974ae7807835e2b4", "4af8348c2a802bf76115d34797ff5ce1d9f110bb8593c22d9b66d8bd7fa227fc"), + "b1": ("13ddceec4e8bdf401e7cd7acf5aebc526222518c", "980b86b60db37b1b1528086f6c53d253d879e9e09ebe07397b40fd275738a3bf"), + "b2": ("3bb39e8739149c3777d0325349b2a6c32c6413db", "4500b5665471b593e6757e15bcca5034f433fe3902fe8ec2b7230774a57f264f"), + "b3": ("0e0522cf0515903a0d35abc5adc9df78a25fde7c", "5670aa22de1b1848b1d715cc97d8fef77761701dedc8b3d3e44525fd71012896"), + "b4": ("3844ddaa13d9ce98816bacb904688a5284f164af", "1cddf0f9ed0b7f1639a8f5e339c177673685df3e2e3c9575a649eb15bcf68a55"), + "b5": ("40357155205b036cf11b61f132d53d2f8861f170", "a389c0a604458fa205446fd08a2c01b74e6591a5da3e77de668c6ca5cbf75356"), +} + + +def mit_imagenet_url(variant: str) -> str: + revision, _ = MIT_IMAGENET_CHECKPOINTS[variant] + return f"https://huggingface.co/nvidia/mit-{variant}/resolve/{revision}/pytorch_model.bin" + + +@dataclass +class SegformerConfig: + """The fields of ``transformers.SegformerConfig`` that change the network, with its defaults.""" + + num_channels: int = 3 + num_encoder_blocks: int = 4 + depths: Sequence[int] = (2, 2, 2, 2) + sr_ratios: Sequence[int] = (8, 4, 2, 1) + hidden_sizes: Sequence[int] = (32, 64, 160, 256) + patch_sizes: Sequence[int] = (7, 3, 3, 3) + strides: Sequence[int] = (4, 2, 2, 2) + num_attention_heads: Sequence[int] = (1, 2, 5, 8) + mlp_ratios: Sequence[int] = (4, 4, 4, 4) + hidden_dropout_prob: float = 0.0 + attention_probs_dropout_prob: float = 0.0 + classifier_dropout_prob: float = 0.1 + initializer_range: float = 0.02 + drop_path_rate: float = 0.1 + decoder_hidden_size: int = 256 + num_labels: int = 150 + + @classmethod + def from_variant(cls, variant: str, **overrides) -> "SegformerConfig": + key = variant.lower() + if key not in SEGFORMER_VARIANTS: + raise ValueError(f"variant must be one of {sorted(SEGFORMER_VARIANTS)}, got {variant!r}") + return replace(cls(**SEGFORMER_VARIANTS[key]), **overrides) + + +def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor: + """Stochastic depth per sample, drawing the same random numbers as transformers.""" + if drop_prob == 0.0 or not training: + return input + keep_prob = 1 - drop_prob + shape = (input.shape[0],) + (1,) * (input.ndim - 1) + random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device) + random_tensor.floor_() + return input.div(keep_prob) * random_tensor + + +class SegformerDropPath(nn.Module): + def __init__(self, drop_prob: Optional[float] = None) -> None: + super().__init__() + self.drop_prob = drop_prob + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return drop_path(hidden_states, self.drop_prob, self.training) + + def extra_repr(self) -> str: + return f"p={self.drop_prob}" + + +class SegformerOverlapPatchEmbeddings(nn.Module): + """Overlapping patch embedding: strided convolution followed by LayerNorm over channels.""" + + def __init__(self, patch_size: int, stride: int, num_channels: int, hidden_size: int): + super().__init__() + self.proj = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=patch_size // 2) + self.layer_norm = nn.LayerNorm(hidden_size) + + def forward(self, pixel_values: torch.Tensor) -> Tuple[torch.Tensor, int, int]: + embeddings = self.proj(pixel_values) + _, _, height, width = embeddings.shape + embeddings = embeddings.flatten(2).transpose(1, 2) + embeddings = self.layer_norm(embeddings) + return embeddings, height, width + + +class SegformerEfficientSelfAttention(nn.Module): + """Multi-head self-attention whose keys and values are spatially reduced by ``sr_ratio``.""" + + def __init__(self, config: SegformerConfig, hidden_size: int, num_attention_heads: int, sequence_reduction_ratio: int): + super().__init__() + if hidden_size % num_attention_heads != 0: + raise ValueError( + f"The hidden size ({hidden_size}) is not a multiple of the number of attention heads ({num_attention_heads})" + ) + self.hidden_size = hidden_size + self.num_attention_heads = num_attention_heads + self.attention_head_size = hidden_size // num_attention_heads + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(hidden_size, self.all_head_size) + self.key = nn.Linear(hidden_size, self.all_head_size) + self.value = nn.Linear(hidden_size, self.all_head_size) + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + + self.sr_ratio = sequence_reduction_ratio + if sequence_reduction_ratio > 1: + self.sr = nn.Conv2d(hidden_size, hidden_size, kernel_size=sequence_reduction_ratio, stride=sequence_reduction_ratio) + self.layer_norm = nn.LayerNorm(hidden_size) + + def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor: + batch_size, _, _ = hidden_states.shape + query_layer = ( + self.query(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2) + ) + if self.sr_ratio > 1: + num_channels = hidden_states.shape[2] + hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width) + hidden_states = self.sr(hidden_states) + hidden_states = hidden_states.reshape(batch_size, num_channels, -1).permute(0, 2, 1) + hidden_states = self.layer_norm(hidden_states) + key_layer = ( + self.key(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2) + ) + value_layer = ( + self.value(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2) + ) + + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + attention_probs = F.softmax(attention_scores, dim=-1) + attention_probs = self.dropout(attention_probs) + + context_layer = torch.matmul(attention_probs, value_layer) + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + return context_layer.view(context_layer.size()[:-2] + (self.all_head_size,)) + + +class SegformerSelfOutput(nn.Module): + def __init__(self, config: SegformerConfig, hidden_size: int): + super().__init__() + self.dense = nn.Linear(hidden_size, hidden_size) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.dropout(self.dense(hidden_states)) + + +class SegformerAttention(nn.Module): + def __init__(self, config: SegformerConfig, hidden_size: int, num_attention_heads: int, sequence_reduction_ratio: int): + super().__init__() + self.self = SegformerEfficientSelfAttention(config, hidden_size, num_attention_heads, sequence_reduction_ratio) + self.output = SegformerSelfOutput(config, hidden_size=hidden_size) + + def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor: + return self.output(self.self(hidden_states, height, width)) + + +class SegformerDWConv(nn.Module): + """3x3 depth-wise convolution of the Mix-FFN, which supplies positional information.""" + + def __init__(self, dim: int = 768): + super().__init__() + self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) + + def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor: + batch_size, _, num_channels = hidden_states.shape + hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width) + hidden_states = self.dwconv(hidden_states) + return hidden_states.flatten(2).transpose(1, 2) + + +class SegformerMixFFN(nn.Module): + def __init__(self, config: SegformerConfig, in_features: int, hidden_features: int, out_features: Optional[int] = None): + super().__init__() + out_features = out_features or in_features + self.dense1 = nn.Linear(in_features, hidden_features) + self.dwconv = SegformerDWConv(hidden_features) + self.intermediate_act_fn = nn.GELU() + self.dense2 = nn.Linear(hidden_features, out_features) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor: + hidden_states = self.dense1(hidden_states) + hidden_states = self.dwconv(hidden_states, height, width) + hidden_states = self.intermediate_act_fn(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.dense2(hidden_states) + return self.dropout(hidden_states) + + +class SegformerLayer(nn.Module): + """Pre-norm Transformer block: efficient self-attention and Mix-FFN, each with stochastic depth.""" + + def __init__( + self, + config: SegformerConfig, + hidden_size: int, + num_attention_heads: int, + drop_path: float, + sequence_reduction_ratio: int, + mlp_ratio: int, + ): + super().__init__() + self.layer_norm_1 = nn.LayerNorm(hidden_size) + self.attention = SegformerAttention(config, hidden_size, num_attention_heads, sequence_reduction_ratio) + self.drop_path = SegformerDropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.layer_norm_2 = nn.LayerNorm(hidden_size) + self.mlp = SegformerMixFFN(config, in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio)) + + def forward(self, hidden_states: torch.Tensor, height: int, width: int) -> torch.Tensor: + attention_output = self.attention(self.layer_norm_1(hidden_states), height, width) + hidden_states = self.drop_path(attention_output) + hidden_states + mlp_output = self.mlp(self.layer_norm_2(hidden_states), height, width) + return self.drop_path(mlp_output) + hidden_states + + +class SegformerEncoder(nn.Module): + """The four-stage hierarchical Mix Transformer (MiT).""" + + def __init__(self, config: SegformerConfig): + super().__init__() + self.config = config + # Stochastic depth grows linearly over all blocks (torch.linspace, as in transformers). + drop_path_decays = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")] + + self.patch_embeddings = nn.ModuleList( + SegformerOverlapPatchEmbeddings( + patch_size=config.patch_sizes[i], + stride=config.strides[i], + num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1], + hidden_size=config.hidden_sizes[i], + ) + for i in range(config.num_encoder_blocks) + ) + blocks = [] + cur = 0 + for i in range(config.num_encoder_blocks): + if i != 0: + cur += config.depths[i - 1] + blocks.append( + nn.ModuleList( + SegformerLayer( + config, + hidden_size=config.hidden_sizes[i], + num_attention_heads=config.num_attention_heads[i], + drop_path=drop_path_decays[cur + j], + sequence_reduction_ratio=config.sr_ratios[i], + mlp_ratio=config.mlp_ratios[i], + ) + for j in range(config.depths[i]) + ) + ) + self.block = nn.ModuleList(blocks) + self.layer_norm = nn.ModuleList(nn.LayerNorm(config.hidden_sizes[i]) for i in range(config.num_encoder_blocks)) + + def forward(self, pixel_values: torch.Tensor) -> List[torch.Tensor]: + batch_size = pixel_values.shape[0] + hidden_states = pixel_values + all_hidden_states = [] + for embedding_layer, block_layer, norm_layer in zip(self.patch_embeddings, self.block, self.layer_norm): + hidden_states, height, width = embedding_layer(hidden_states) + for block in block_layer: + hidden_states = block(hidden_states, height, width) + hidden_states = norm_layer(hidden_states) + hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous() + all_hidden_states.append(hidden_states) + return all_hidden_states + + +def _init_segformer_weights(module: nn.Module, std: float) -> None: + """``SegformerPreTrainedModel._init_weights`` over every submodule. + + transformers visits modules children-first; only leaf modules carry weights here, and they come + in the same order either way, so the random-number stream is the same. + """ + with torch.no_grad(): + for m in module.modules(): + if isinstance(m, (nn.Linear, nn.Conv2d)): + m.weight.normal_(mean=0.0, std=std) + if m.bias is not None: + m.bias.zero_() + elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): + m.bias.zero_() + m.weight.fill_(1.0) + + +class SegformerModel(nn.Module): + """The MiT encoder wrapped as ``transformers.SegformerModel`` (parameters under ``encoder.``). + + ``forward`` returns the four stage outputs ``(batch, hidden_sizes[i], H / 2**(i+2), W / 2**(i+2))`` + (sizes rounded up). + """ + + def __init__(self, config: SegformerConfig): + super().__init__() + self.config = config + self.encoder = SegformerEncoder(config) + _init_segformer_weights(self, config.initializer_range) + + def forward(self, pixel_values: torch.Tensor) -> List[torch.Tensor]: + return self.encoder(pixel_values) + + +class SegformerMLP(nn.Module): + """Linear embedding of one encoder stage to the decoder width.""" + + def __init__(self, config: SegformerConfig, input_dim: int): + super().__init__() + self.proj = nn.Linear(input_dim, config.decoder_hidden_size) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.proj(hidden_states.flatten(2).transpose(1, 2)) + + +class SegformerDecodeHead(nn.Module): + """All-MLP decoder: unify channels, upsample to 1/4 resolution, fuse, classify.""" + + def __init__(self, config: SegformerConfig): + super().__init__() + self.linear_c = nn.ModuleList( + SegformerMLP(config, input_dim=config.hidden_sizes[i]) for i in range(config.num_encoder_blocks) + ) + # Conv-BN-ReLU: the ConvModule of the original implementation. + self.linear_fuse = nn.Conv2d( + in_channels=config.decoder_hidden_size * config.num_encoder_blocks, + out_channels=config.decoder_hidden_size, + kernel_size=1, + bias=False, + ) + self.batch_norm = nn.BatchNorm2d(config.decoder_hidden_size) + self.activation = nn.ReLU() + self.dropout = nn.Dropout(config.classifier_dropout_prob) + self.classifier = nn.Conv2d(config.decoder_hidden_size, config.num_labels, kernel_size=1) + + def forward(self, encoder_hidden_states: Sequence[torch.Tensor]) -> torch.Tensor: + batch_size = encoder_hidden_states[-1].shape[0] + target_size = encoder_hidden_states[0].size()[2:] + all_hidden_states = [] + for encoder_hidden_state, mlp in zip(encoder_hidden_states, self.linear_c): + height, width = encoder_hidden_state.shape[2], encoder_hidden_state.shape[3] + encoder_hidden_state = mlp(encoder_hidden_state).permute(0, 2, 1).reshape(batch_size, -1, height, width) + encoder_hidden_state = F.interpolate(encoder_hidden_state, size=target_size, mode="bilinear", align_corners=False) + all_hidden_states.append(encoder_hidden_state) + hidden_states = self.linear_fuse(torch.cat(all_hidden_states[::-1], dim=1)) + hidden_states = self.dropout(self.activation(self.batch_norm(hidden_states))) + return self.classifier(hidden_states) + + +StateDict = Mapping[str, torch.Tensor] + + +class SegFormer(nn.Module): + """SegFormer-B0 ... B5 for dense prediction (``transformers.SegformerForSemanticSegmentation``). + + Input ``(batch, channels, height, width)``, or ``(batch, time, channels, height, width)`` which is + flattened to ``time * channels`` input channels (data-level fusion). The decode head predicts at + 1/4 resolution; with ``upsample=True`` (default) the logits are resized bilinearly + (``align_corners=False``) to the input size, as transformers' post-processing and loss do, so + the output is ``(batch, num_labels, height, width)``. :meth:`raw_logits` returns the 1/4 + resolution logits that transformers returns. + """ + + def __init__( + self, + in_channels: int = 3, + num_labels: int = 1, + variant: str = "b2", + encoder_weights: Optional[Union[str, Path]] = None, + upsample: bool = True, + drop_path_rate: float = 0.1, + classifier_dropout_prob: float = 0.1, + hidden_dropout_prob: float = 0.0, + attention_probs_dropout_prob: float = 0.0, + ): + super().__init__() + if in_channels <= 0: + raise ValueError(f"in_channels must be positive, got {in_channels}") + if num_labels <= 0: + raise ValueError(f"num_labels must be positive, got {num_labels}") + self.variant = variant.lower() + self.config = SegformerConfig.from_variant( + self.variant, + num_channels=int(in_channels), + num_labels=int(num_labels), + drop_path_rate=drop_path_rate, + classifier_dropout_prob=classifier_dropout_prob, + hidden_dropout_prob=hidden_dropout_prob, + attention_probs_dropout_prob=attention_probs_dropout_prob, + ) + self.in_channels = int(in_channels) + self.upsample = bool(upsample) + # Same construction and initialisation order as SegformerForSemanticSegmentation.__init__: + # SegformerModel initialises the encoder, then the decode head is built and initialised. + self.segformer = SegformerModel(self.config) + self.decode_head = SegformerDecodeHead(self.config) + _init_segformer_weights(self.decode_head, self.config.initializer_range) + if encoder_weights is not None: + self.load_pretrained_encoder(encoder_weights) + + # -- weights ----------------------------------------------------------------------------------- + + def load_hf_state_dict(self, state_dict: StateDict, strict: bool = True): + """Load a transformers SegFormer state dict, choosing the target from its keys. + + - ``SegformerForSemanticSegmentation`` (``segformer.*`` and ``decode_head.*``): the whole model; + - ``SegformerForImageClassification``, e.g. ``nvidia/mit-b*`` (``segformer.*`` and + ``classifier.*``): the ``segformer.`` prefix is removed, the ImageNet classifier is dropped, + and the rest loads into the encoder; + - ``SegformerModel`` (``encoder.*``): the encoder. + """ + keys = list(state_dict) + if any(key.startswith("decode_head.") for key in keys): + return self.load_state_dict(state_dict, strict=strict) + if any(key.startswith("segformer.") for key in keys): + encoder_state = { + key[len("segformer."):] if key.startswith("segformer.") else key: value + for key, value in state_dict.items() + if not key.startswith("classifier.") + } + return self.segformer.load_state_dict(encoder_state, strict=strict) + return self.segformer.load_state_dict(state_dict, strict=strict) + + def load_pretrained_encoder(self, source: Union[str, Path, StateDict] = "imagenet") -> None: + """Load ImageNet-1k MiT weights into the encoder; the decode head keeps its initialisation. + + ``source`` is ``"imagenet"`` (download ``nvidia/mit-`` from the Hugging Face Hub at a + pinned revision, checked against its sha256 prefix and cached by ``torch.hub``), a local + checkpoint path, or a state dict. Those checkpoints have a 3-channel first patch embedding; + for other ``in_channels`` it is adapted the way segmentation_models_pytorch adapts ImageNet + encoders (``patch_first_conv``): summed over RGB for one channel, otherwise the RGB filters + are repeated cyclically over the input channels and scaled by ``3 / in_channels``. + """ + if isinstance(source, Mapping): + state = dict(source) + elif str(source) == "imagenet": + revision, sha256 = MIT_IMAGENET_CHECKPOINTS[self.variant] + state = torch.hub.load_state_dict_from_url( + mit_imagenet_url(self.variant), + map_location="cpu", + progress=False, + check_hash=True, + file_name=f"nvidia-mit-{self.variant}-{sha256[:8]}.bin", + weights_only=True, + ) + else: + state = load_checkpoint(source) + state = {key[len("segformer."):] if key.startswith("segformer.") else key: value for key, value in state.items()} + state = {key: value for key, value in state.items() if not key.startswith(("classifier.", "decode_head."))} + key = "encoder.patch_embeddings.0.proj.weight" + if key in state: + state[key] = adapt_first_conv_weight(state[key], self.in_channels) + self.segformer.load_state_dict(state, strict=True) + + # -- forward ----------------------------------------------------------------------------------- + + def _check_input(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 5: + x = x.flatten(start_dim=1, end_dim=2) + if x.ndim != 4: + raise ValueError( + "SegFormer expects input shape (batch, channels, height, width) or " + f"(batch, time, channels, height, width), got {tuple(x.shape)}." + ) + if x.size(1) != self.in_channels: + raise ValueError( + f"SegFormer expected {self.in_channels} input channels (time * channels for 5-D input), " + f"got shape {tuple(x.shape)}." + ) + height, width = x.shape[-2:] + for size in (height, width): + for i in range(self.config.num_encoder_blocks): + patch = self.config.patch_sizes[i] + size = (size + 2 * (patch // 2) - patch) // self.config.strides[i] + 1 + if size < self.config.sr_ratios[i]: + raise ValueError( + f"SegFormer input of shape {tuple(x.shape)} is too small: stage {i + 1} has spatial size " + f"{size}, below its key/value reduction ratio {self.config.sr_ratios[i]} " + "(height and width must be at least 29)." + ) + return x + + def raw_logits(self, x: torch.Tensor) -> torch.Tensor: + """Decode-head logits at 1/4 of the input resolution (``SegformerForSemanticSegmentation`` output).""" + x = self._check_input(x) + return self.decode_head(self.segformer(x)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self._check_input(x) + logits = self.decode_head(self.segformer(x)) + if self.upsample: + logits = F.interpolate(logits, size=x.shape[-2:], mode="bilinear", align_corners=False) + return logits + + +def load_checkpoint(path: Union[str, Path]) -> Dict[str, torch.Tensor]: + """Read a Hub checkpoint file (``pytorch_model.bin``, or ``model.safetensors`` if safetensors is installed).""" + path = Path(path).expanduser() + if not path.is_file(): + raise ValueError(f"expected 'imagenet' or an existing checkpoint file, got {str(path)!r}") + if path.suffix == ".safetensors": + try: + from safetensors.torch import load_file + except ImportError as exc: # optional: only needed for .safetensors files + raise ImportError("reading .safetensors checkpoints requires the safetensors package") from exc + return load_file(str(path)) + return torch.load(path, map_location="cpu", weights_only=True) + + +def adapt_first_conv_weight(weight: torch.Tensor, in_channels: int) -> torch.Tensor: + """segmentation_models_pytorch's ``patch_first_conv`` rule for a pretrained RGB convolution.""" + if weight.ndim != 4: + raise ValueError(f"expected a convolution weight of shape (out, in, kh, kw), got {tuple(weight.shape)}") + default = weight.shape[1] + if in_channels == default: + return weight + if default != 3: + raise ValueError(f"can only adapt a 3-channel convolution, got weight shape {tuple(weight.shape)}") + if in_channels == 1: + return weight.sum(1, keepdim=True) + index = torch.tensor([i % default for i in range(in_channels)]) + return weight[:, index] * (default / in_channels) + + +def segformer_builder( + task: str, + in_channels: int, + out_channels: int = 1, + variant: str = "b2", + history: int = 1, + encoder_weights: Optional[Union[str, Path]] = None, + upsample: bool = True, + drop_path_rate: float = 0.1, + classifier_dropout_prob: float = 0.1, + **kwargs, +) -> nn.Module: + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"segformer supports task='segmentation', got {task!r}.") + if history <= 0: + raise ValueError(f"history must be positive, got {history}") + return SegFormer( + in_channels=in_channels * history, + num_labels=out_channels, + variant=variant, + encoder_weights=encoder_weights, + upsample=upsample, + drop_path_rate=drop_path_rate, + classifier_dropout_prob=classifier_dropout_prob, + ) + + +__all__ = [ + "MIT_IMAGENET_CHECKPOINTS", + "SEGFORMER_VARIANTS", + "SegFormer", + "SegformerConfig", + "SegformerModel", + "adapt_first_conv_weight", + "load_checkpoint", + "mit_imagenet_url", + "segformer_builder", +] diff --git a/pyhazards/models/swin_blocks.py b/pyhazards/models/swin_blocks.py new file mode 100644 index 00000000..548bc2b3 --- /dev/null +++ b/pyhazards/models/swin_blocks.py @@ -0,0 +1,610 @@ +"""Swin Transformer building blocks shared by ``swin_unet``, ``asufm`` and ``swinlstm``. + +Attribution: + +- Window attention, the Swin block, patch embedding and patch merging are ported from + microsoft/Swin-Transformer ``models/swin_transformer.py`` at commit + ``f82860bfb5225915aca09c3227159ee9e1df874d`` (MIT License, Copyright (c) 2021 Microsoft). +- ``DropPath`` and ``trunc_normal_`` follow ``timm.models.layers`` from timm 0.4.12 (Apache-2.0, + Copyright 2019 Ross Wightman; ``trunc_normal_`` is itself taken from PyTorch, BSD-3-Clause), + the version Swin-Transformer pins, so initialisation and stochastic depth draw the same random + numbers as the reference implementations. (``torch.nn.init.trunc_normal_`` switched to + rejection sampling in recent PyTorch releases and no longer reproduces them.) +- ``FocalModulation`` is ported from microsoft/FocalNet ``classification/focalnet.py`` at commit + ``e8514bdcfe1eb6e7e110403e9f2972c67dfed1c3`` (MIT License, Copyright (c) Microsoft Corporation). +- The decoder pieces (``PatchExpand``, ``FinalPatchExpand_X4``, ``BasicLayer_up``) are written for + PyHazards from the description in the Swin-Unet paper (Cao et al., ECCV Workshops 2022, + arXiv:2105.05537, Sec. 3.4-3.5): a linear layer doubles (or, for the last layer, multiplies by + 16) the channel dimension and the result is rearranged into a 2x (4x) larger token grid. The + official Swin-Unet repository has no license, so none of its code is copied; module and + attribute names follow it so that its state dicts load with ``strict=True``. + +All blocks operate on token sequences ``(batch, height * width, channels)`` whose spatial size is +fixed at construction (``input_resolution``), as in the references. +""" + +from __future__ import annotations + +import math +from typing import List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torch.utils.checkpoint as torch_checkpoint + + +def to_2tuple(value: Union[int, Sequence[int]]) -> Tuple[int, int]: + if isinstance(value, (tuple, list)): + return int(value[0]), int(value[1]) + return int(value), int(value) + + +def trunc_normal_(tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0) -> torch.Tensor: + """Truncated normal fill by inverse-CDF sampling (timm 0.4.12 / PyTorch 1.x algorithm).""" + + def norm_cdf(value: float) -> float: + return (1.0 + math.erf(value / math.sqrt(2.0))) / 2.0 + + with torch.no_grad(): + low, high = norm_cdf((a - mean) / std), norm_cdf((b - mean) / std) + tensor.uniform_(2 * low - 1, 2 * high - 1) + tensor.erfinv_() + tensor.mul_(std * math.sqrt(2.0)) + tensor.add_(mean) + tensor.clamp_(min=a, max=b) + return tensor + + +def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor: + """Per-sample stochastic depth with the random draw of timm 0.4.12.""" + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) + random_tensor.floor_() + return x.div(keep_prob) * random_tensor + + +class DropPath(nn.Module): + def __init__(self, drop_prob: float = 0.0): + super().__init__() + self.drop_prob = drop_prob + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return drop_path(x, self.drop_prob, self.training) + + +def stochastic_depth_rates(drop_path_rate: float, depths: Sequence[int]) -> List[float]: + """Linearly increasing drop-path rates over all encoder blocks (Swin's decay rule).""" + return [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + + +class Mlp(nn.Module): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer=nn.GELU, + drop: float = 0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.drop(self.act(self.fc1(x))) + return self.drop(self.fc2(x)) + + +def window_partition(x: torch.Tensor, window_size: int) -> torch.Tensor: + """``(B, H, W, C)`` -> ``(B * num_windows, window_size, window_size, C)``.""" + b, h, w, c = x.shape + x = x.view(b, h // window_size, window_size, w // window_size, window_size, c) + return x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, c) + + +def window_reverse(windows: torch.Tensor, window_size: int, h: int, w: int) -> torch.Tensor: + """Inverse of :func:`window_partition`.""" + b = int(windows.shape[0] / (h * w / window_size / window_size)) + x = windows.view(b, h // window_size, w // window_size, window_size, window_size, -1) + return x.permute(0, 1, 3, 2, 4, 5).contiguous().view(b, h, w, -1) + + +class WindowAttention(nn.Module): + """Window multi-head self-attention with a learned relative position bias (W-MSA / SW-MSA).""" + + def __init__( + self, + dim: int, + window_size: Tuple[int, int], + num_heads: int, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ): + super().__init__() + self.dim = dim + self.window_size = window_size + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads) + ) + coords = torch.stack( + torch.meshgrid([torch.arange(window_size[0]), torch.arange(window_size[1])], indexing="ij") + ) + coords_flatten = torch.flatten(coords, 1) + relative_coords = (coords_flatten[:, :, None] - coords_flatten[:, None, :]).permute(1, 2, 0).contiguous() + relative_coords[:, :, 0] += window_size[0] - 1 + relative_coords[:, :, 1] += window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + self.register_buffer("relative_position_index", relative_coords.sum(-1)) + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + # Initialised after the projections, as in the reference (keeps seeded init identical). + trunc_normal_(self.relative_position_bias_table, std=0.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: + b_, n, c = x.shape + qkv = self.qkv(x).reshape(b_, n, 3, self.num_heads, c // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + attn = (q * self.scale) @ k.transpose(-2, -1) + + area = self.window_size[0] * self.window_size[1] + bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(area, area, -1) + attn = attn + bias.permute(2, 0, 1).contiguous().unsqueeze(0) + if mask is not None: + n_windows = mask.shape[0] + attn = attn.view(b_ // n_windows, n_windows, self.num_heads, n, n) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, n, n) + attn = self.attn_drop(self.softmax(attn)) + + x = (attn @ v).transpose(1, 2).reshape(b_, n, c) + return self.proj_drop(self.proj(x)) + + +class FocalModulation(nn.Module): + """Focal modulation (Yang et al., NeurIPS 2022) on ``(B, H, W, C)`` features.""" + + def __init__( + self, + dim: int, + focal_window: int, + focal_level: int, + focal_factor: int = 2, + bias: bool = True, + proj_drop: float = 0.0, + use_postln_in_modulation: bool = False, + normalize_modulator: bool = False, + ): + super().__init__() + self.dim = dim + self.focal_window = focal_window + self.focal_level = focal_level + self.focal_factor = focal_factor + self.use_postln_in_modulation = use_postln_in_modulation + self.normalize_modulator = normalize_modulator + + self.f = nn.Linear(dim, 2 * dim + (focal_level + 1), bias=bias) + self.h = nn.Conv2d(dim, dim, kernel_size=1, stride=1, bias=bias) + self.act = nn.GELU() + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.focal_layers = nn.ModuleList() + self.kernel_sizes = [] + for k in range(focal_level): + kernel_size = focal_factor * k + focal_window + self.focal_layers.append( + nn.Sequential( + nn.Conv2d(dim, dim, kernel_size=kernel_size, stride=1, groups=dim, padding=kernel_size // 2, bias=False), + nn.GELU(), + ) + ) + self.kernel_sizes.append(kernel_size) + if use_postln_in_modulation: + self.ln = nn.LayerNorm(dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + c = x.shape[-1] + x = self.f(x).permute(0, 3, 1, 2).contiguous() + q, ctx, gates = torch.split(x, (c, c, self.focal_level + 1), 1) + + ctx_all = 0 + for level in range(self.focal_level): + ctx = self.focal_layers[level](ctx) + ctx_all = ctx_all + ctx * gates[:, level : level + 1] + ctx_global = self.act(ctx.mean(2, keepdim=True).mean(3, keepdim=True)) + ctx_all = ctx_all + ctx_global * gates[:, self.focal_level :] + if self.normalize_modulator: + ctx_all = ctx_all / (self.focal_level + 1) + + x_out = (q * self.h(ctx_all)).permute(0, 2, 3, 1).contiguous() + if self.use_postln_in_modulation: + x_out = self.ln(x_out) + return self.proj_drop(self.proj(x_out)) + + +class SwinTransformerBlock(nn.Module): + """Swin block: (shifted) window attention and an MLP, each with a pre-norm residual. + + ``modulation`` optionally inserts a focal-modulation module between ``norm1`` and the + attention (ASUFM). It is registered whenever given; ``use_modulation`` decides whether the + forward pass applies it (ASUFM builds it in its decoder blocks but never uses it there). + """ + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + num_heads: int, + window_size: int = 7, + shift_size: int = 0, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + drop_path: float = 0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + modulation: Optional[nn.Module] = None, + use_modulation: bool = False, + ): + super().__init__() + self.dim = dim + self.input_resolution = tuple(input_resolution) + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # A window covering the whole map is neither partitioned nor shifted. + self.shift_size = 0 + self.window_size = min(self.input_resolution) + if not 0 <= self.shift_size < self.window_size: + raise ValueError(f"shift_size must be in [0, window_size), got {self.shift_size}") + self.use_modulation = bool(use_modulation and modulation is not None) + + self.norm1 = norm_layer(dim) + if modulation is not None: + self.modulation = modulation + self.attn = WindowAttention( + dim, + window_size=to_2tuple(self.window_size), + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, drop=drop) + self.register_buffer("attn_mask", self._shifted_window_mask() if self.shift_size > 0 else None) + + def _shifted_window_mask(self) -> torch.Tensor: + """-100 between tokens that come from different regions after the cyclic shift.""" + h, w = self.input_resolution + regions = torch.zeros((1, h, w, 1)) + bounds = (slice(0, -self.window_size), slice(-self.window_size, -self.shift_size), slice(-self.shift_size, None)) + label = 0 + for rows in bounds: + for cols in bounds: + regions[:, rows, cols, :] = label + label += 1 + labels = window_partition(regions, self.window_size).view(-1, self.window_size * self.window_size) + mask = labels.unsqueeze(1) - labels.unsqueeze(2) + return mask.masked_fill(mask != 0, float(-100.0)).masked_fill(mask == 0, float(0.0)) + + def _window_attention(self, x: torch.Tensor) -> torch.Tensor: + """(Shifted) window attention on normalised ``(B, H, W, C)`` features; returns ``(B, H * W, C)``.""" + b, h, w, c = x.shape + if self.shift_size > 0: + x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + windows = window_partition(x, self.window_size).view(-1, self.window_size * self.window_size, c) + windows = self.attn(windows, mask=self.attn_mask).view(-1, self.window_size, self.window_size, c) + x = window_reverse(windows, self.window_size, h, w) + if self.shift_size > 0: + x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + return x.view(b, h * w, c) + + def _check_tokens(self, x: torch.Tensor) -> None: + h, w = self.input_resolution + if x.ndim != 3 or x.shape[1] != h * w: + raise ValueError( + f"Swin block expected tokens of shape (batch, {h * w}, channels) for resolution {(h, w)}, " + f"got {tuple(x.shape)}." + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + self._check_tokens(x) + h, w = self.input_resolution + b, _, c = x.shape + + shortcut = x + x = self.norm1(x).view(b, h, w, c) + if self.use_modulation: + # ASUFM applies norm1 a second time to the modulated features. + x = self.norm1(self.modulation(x)) + x = shortcut + self.drop_path(self._window_attention(x)) + return x + self.drop_path(self.mlp(self.norm2(x))) + + +class PatchEmbed(nn.Module): + """Non-overlapping ``patch_size`` convolution from an image to a token sequence.""" + + def __init__(self, img_size=224, patch_size=4, in_chans: int = 3, embed_dim: int = 96, norm_layer=None): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + self.img_size = img_size + self.patch_size = patch_size + self.patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]] + self.num_patches = self.patches_resolution[0] * self.patches_resolution[1] + self.in_chans = in_chans + self.embed_dim = embed_dim + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + self.norm = norm_layer(embed_dim) if norm_layer is not None else None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x).flatten(2).transpose(1, 2) + return self.norm(x) if self.norm is not None else x + + +class PatchMerging(nn.Module): + """Concatenate each 2x2 neighbourhood (4C channels), normalise, and project to 2C.""" + + def __init__(self, input_resolution: Tuple[int, int], dim: int, norm_layer=nn.LayerNorm): + super().__init__() + self.input_resolution = tuple(input_resolution) + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h, w = self.input_resolution + b, _, c = x.shape + x = x.view(b, h, w, c) + x = torch.cat([x[:, 0::2, 0::2], x[:, 1::2, 0::2], x[:, 0::2, 1::2], x[:, 1::2, 1::2]], -1) + return self.reduction(self.norm(x.view(b, -1, 4 * c))) + + +def _tokens_to_finer_grid(x: torch.Tensor, h: int, w: int, scale: int) -> torch.Tensor: + """Split each token's channels into a ``scale x scale`` block of tokens (row-major). + + ``(B, h * w, scale * scale * c)`` -> ``(B, h * scale * w * scale, c)``; channel index + ``(i * scale + j) * c + k`` of token ``(r, s)`` becomes channel ``k`` of token + ``(r * scale + i, s * scale + j)``. + """ + b, length, channels = x.shape + if length != h * w: + raise ValueError(f"expected {h * w} tokens for resolution {(h, w)}, got {length}.") + c = channels // (scale * scale) + x = x.view(b, h, w, scale, scale, c).permute(0, 1, 3, 2, 4, 5) + return x.reshape(b, h * scale * w * scale, c) + + +class PatchExpand(nn.Module): + """Swin-Unet patch expanding: 2x more tokens with half the channels.""" + + def __init__(self, input_resolution: Tuple[int, int], dim: int, dim_scale: int = 2, norm_layer=nn.LayerNorm): + super().__init__() + self.input_resolution = tuple(input_resolution) + self.dim = dim + self.expand = nn.Linear(dim, 2 * dim, bias=False) if dim_scale == 2 else nn.Identity() + self.norm = norm_layer(dim // dim_scale) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h, w = self.input_resolution + return self.norm(_tokens_to_finer_grid(self.expand(x), h, w, 2)) + + +class FinalPatchExpand_X4(nn.Module): + """Last Swin-Unet expanding layer: 4x more tokens per side, ``dim`` channels each.""" + + def __init__(self, input_resolution: Tuple[int, int], dim: int, dim_scale: int = 4, norm_layer=nn.LayerNorm): + super().__init__() + self.input_resolution = tuple(input_resolution) + self.dim = dim + self.dim_scale = dim_scale + self.expand = nn.Linear(dim, 16 * dim, bias=False) + self.output_dim = dim + self.norm = norm_layer(self.output_dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h, w = self.input_resolution + return self.norm(_tokens_to_finer_grid(self.expand(x), h, w, self.dim_scale)) + + +def _run_blocks(blocks: nn.ModuleList, x: torch.Tensor, use_checkpoint: bool) -> torch.Tensor: + for block in blocks: + if use_checkpoint: + x = torch_checkpoint.checkpoint(block, x, use_reentrant=False) + else: + x = block(x) + return x + + +def _make_blocks( + dim: int, + input_resolution: Tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + mlp_ratio: float, + qkv_bias: bool, + qk_scale: Optional[float], + drop: float, + attn_drop: float, + drop_path: Union[float, Sequence[float]], + norm_layer, + focal_modulation: Optional[str], +) -> nn.ModuleList: + blocks = [] + for i in range(depth): + modulation = None + if focal_modulation is not None: + # Built before the block's attention, matching the reference creation order. + modulation = FocalModulation(dim, focal_window=3, focal_level=1, proj_drop=drop) + blocks.append( + SwinTransformerBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + shift_size=0 if i % 2 == 0 else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, (list, tuple)) else drop_path, + norm_layer=norm_layer, + modulation=modulation, + use_modulation=focal_modulation == "applied", + ) + ) + return nn.ModuleList(blocks) + + +class BasicLayer(nn.Module): + """One encoder stage: ``depth`` Swin blocks (alternating shift) and optional patch merging. + + ``focal_modulation`` is None (plain Swin), ``"applied"`` or ``"unused"`` (see + :class:`SwinTransformerBlock`). + """ + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + drop_path: Union[float, Sequence[float]] = 0.0, + norm_layer=nn.LayerNorm, + downsample: bool = False, + use_checkpoint: bool = False, + focal_modulation: Optional[str] = None, + ): + super().__init__() + self.dim = dim + self.input_resolution = tuple(input_resolution) + self.depth = depth + self.use_checkpoint = use_checkpoint + self.blocks = _make_blocks( + dim, input_resolution, depth, num_heads, window_size, mlp_ratio, qkv_bias, qk_scale, + drop, attn_drop, drop_path, norm_layer, focal_modulation, + ) + self.downsample = PatchMerging(input_resolution, dim=dim, norm_layer=norm_layer) if downsample else None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = _run_blocks(self.blocks, x, self.use_checkpoint) + return self.downsample(x) if self.downsample is not None else x + + +class BasicLayer_up(nn.Module): + """One decoder stage: ``depth`` Swin blocks and optional patch expanding.""" + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + drop_path: Union[float, Sequence[float]] = 0.0, + norm_layer=nn.LayerNorm, + upsample: bool = False, + use_checkpoint: bool = False, + focal_modulation: Optional[str] = None, + ): + super().__init__() + self.dim = dim + self.input_resolution = tuple(input_resolution) + self.depth = depth + self.use_checkpoint = use_checkpoint + self.blocks = _make_blocks( + dim, input_resolution, depth, num_heads, window_size, mlp_ratio, qkv_bias, qk_scale, + drop, attn_drop, drop_path, norm_layer, focal_modulation, + ) + self.upsample = PatchExpand(input_resolution, dim=dim, dim_scale=2, norm_layer=norm_layer) if upsample else None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = _run_blocks(self.blocks, x, self.use_checkpoint) + return self.upsample(x) if self.upsample is not None else x + + +def init_swin_weights(module: nn.Module) -> None: + """Truncated-normal(0.02) linear weights, zero biases, unit LayerNorms (``model.apply``).""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + elif isinstance(module, nn.LayerNorm): + nn.init.constant_(module.bias, 0) + nn.init.constant_(module.weight, 1.0) + + +def check_swin_geometry(img_size: int, patch_size: int, window_size: int, num_layers: int) -> None: + """Raise ``ValueError`` unless every stage's token grid splits into whole windows.""" + if img_size % patch_size: + raise ValueError(f"img_size {img_size} must be divisible by patch_size {patch_size}.") + resolution = img_size // patch_size + for stage in range(num_layers): + side = resolution // (2 ** stage) + if stage < num_layers - 1 and side % 2: + raise ValueError( + f"img_size {img_size}: stage {stage} has an odd token grid ({side}) and cannot be merged." + ) + window = min(window_size, side) + if side % window: + raise ValueError( + f"img_size {img_size}: stage {stage} token grid ({side}) is not divisible by window_size {window}." + ) + + +__all__ = [ + "BasicLayer", + "BasicLayer_up", + "DropPath", + "FinalPatchExpand_X4", + "FocalModulation", + "Mlp", + "PatchEmbed", + "PatchExpand", + "PatchMerging", + "SwinTransformerBlock", + "WindowAttention", + "check_swin_geometry", + "drop_path", + "init_swin_weights", + "stochastic_depth_rates", + "to_2tuple", + "trunc_normal_", + "window_partition", + "window_reverse", +] diff --git a/pyhazards/models/swin_unet.py b/pyhazards/models/swin_unet.py new file mode 100644 index 00000000..ad4b9217 --- /dev/null +++ b/pyhazards/models/swin_unet.py @@ -0,0 +1,293 @@ +"""Swin-Unet: a U-shaped pure Swin Transformer for dense prediction. + +Architecture paper: Cao et al., "Swin-Unet: Unet-like Pure Transformer for Medical Image +Segmentation", ECCV Workshops 2022 (arXiv:2105.05537). Wildfire usage: Lahrichi, Bova, Johnson +and Malof, "Improved Wildfire Spread Prediction with Time-Series Data and the WSTS+ Benchmark", +WACV 2026 (arXiv:2502.12003), which trains "SwinUnet-Tiny" on WildfireSpreadTS. + +The official code (github.com/HuCaoFighting/Swin-Unet) has no license, so this module is written +from the paper and from the MIT-licensed microsoft/Swin-Transformer blocks in +:mod:`pyhazards.models.swin_blocks`; the official code is only used as a test oracle +(tests/oracle/test_swin_oracle.py). Module and parameter names match the official +``SwinTransformerSys``, so its state dicts load with ``strict=True``, and modules are created in +the same order, so the same seed gives the same initial weights. + +Behaviour of the official code that is kept: + +- the decoder mirrors the encoder depths (``depths[2], depths[1], depths[0]`` after a plain + patch-expanding layer); the official ``depths_decoder`` argument and the yaml's + ``DECODER_DEPTHS`` are never used, so they are not exposed here; +- decoder blocks reuse the stochastic-depth rates of the mirrored encoder stage; +- :meth:`SwinUnet.load_swin_pretrained` reproduces the official ``load_from``: Swin-T ImageNet + weights initialise the encoder *and* (stage ``i`` copied to ``layers_up.{3-i}``) the decoder, + and any tensor whose shape differs (e.g. the patch embedding when ``in_chans != 3``) keeps its + random initialisation. +""" + +from __future__ import annotations + +import copy +from pathlib import Path +from typing import Mapping, Optional, Sequence, Union + +import torch +import torch.nn as nn + +from .swin_blocks import ( + BasicLayer, + BasicLayer_up, + FinalPatchExpand_X4, + PatchEmbed, + PatchExpand, + check_swin_geometry, + init_swin_weights, + stochastic_depth_rates, + trunc_normal_, +) + +# Swin-T ImageNet-1k checkpoint from microsoft/Swin-Transformer (MIT), the Swin-Unet initialisation. +SWIN_TINY_IMAGENET_URL = ( + "https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth" +) +SWIN_TINY_IMAGENET_SHA256 = "9f71c168d837d1b99dd1dc29e14990a7a9e8bdc5f673d46b04fe36fe15590ad3" + + +def _swin_tiny_imagenet_path() -> Path: + path = Path(torch.hub.get_dir()) / "checkpoints" / Path(SWIN_TINY_IMAGENET_URL).name + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + torch.hub.download_url_to_file( + SWIN_TINY_IMAGENET_URL, str(path), hash_prefix=SWIN_TINY_IMAGENET_SHA256, progress=False + ) + return path + + +class SwinUnet(nn.Module): + """Swin-Unet (``SwinTransformerSys`` with ``final_upsample="expand_first"``). + + Input ``(batch, in_chans, img_size, img_size)``, or ``(batch, time, channels, img_size, + img_size)`` flattened time-major to ``time * channels`` input channels (data-level fusion as + in WSTS+). Returns logits ``(batch, num_classes, img_size, img_size)``. + """ + + def __init__( + self, + img_size: int = 224, + patch_size: int = 4, + in_chans: int = 3, + num_classes: int = 1, + embed_dim: int = 96, + depths: Sequence[int] = (2, 2, 2, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + window_size: int = 7, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + ape: bool = False, + patch_norm: bool = True, + use_checkpoint: bool = False, + ): + super().__init__() + depths, num_heads = list(depths), list(num_heads) + if len(depths) != len(num_heads): + raise ValueError(f"depths and num_heads need the same length, got {depths} and {num_heads}.") + if in_chans <= 0 or num_classes <= 0: + raise ValueError(f"in_chans and num_classes must be positive, got {in_chans} and {num_classes}.") + check_swin_geometry(img_size, patch_size, window_size, len(depths)) + norm_layer = nn.LayerNorm + + self.img_size = int(img_size) + self.in_chans = int(in_chans) + self.num_classes = num_classes + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.ape = ape + self.patch_norm = patch_norm + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + self.num_features_up = int(embed_dim * 2) + self.mlp_ratio = mlp_ratio + self.final_upsample = "expand_first" + + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, + norm_layer=norm_layer if patch_norm else None, + ) + num_patches = self.patch_embed.num_patches + resolution = self.patch_embed.patches_resolution + self.patches_resolution = resolution + if ape: + self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim)) + trunc_normal_(self.absolute_pos_embed, std=0.02) + self.pos_drop = nn.Dropout(p=drop_rate) + + dpr = stochastic_depth_rates(drop_path_rate, depths) + stage_kwargs = dict( + window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint, + ) + + self.layers = nn.ModuleList() + for i in range(self.num_layers): + self.layers.append( + BasicLayer( + dim=int(embed_dim * 2 ** i), + input_resolution=(resolution[0] // 2 ** i, resolution[1] // 2 ** i), + depth=depths[i], + num_heads=num_heads[i], + drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])], + downsample=i < self.num_layers - 1, + **stage_kwargs, + ) + ) + + # Decoder: step i works at encoder stage j = num_layers - 1 - i. The skip-fusion linear + # is created before its stage (reference order); layers_up is registered first. + self.layers_up = nn.ModuleList() + self.concat_back_dim = nn.ModuleList() + for i in range(self.num_layers): + j = self.num_layers - 1 - i + dim = int(embed_dim * 2 ** j) + stage_resolution = (resolution[0] // 2 ** j, resolution[1] // 2 ** j) + concat_linear = nn.Linear(2 * dim, dim) if i > 0 else nn.Identity() + if i == 0: + layer_up = PatchExpand(stage_resolution, dim=dim, dim_scale=2, norm_layer=norm_layer) + else: + layer_up = BasicLayer_up( + dim=dim, + input_resolution=stage_resolution, + depth=depths[j], + num_heads=num_heads[j], + drop_path=dpr[sum(depths[:j]) : sum(depths[: j + 1])], + upsample=i < self.num_layers - 1, + **stage_kwargs, + ) + self.layers_up.append(layer_up) + self.concat_back_dim.append(concat_linear) + + self.norm = norm_layer(self.num_features) + self.norm_up = norm_layer(embed_dim) + self.up = FinalPatchExpand_X4(input_resolution=(img_size // patch_size, img_size // patch_size), dim_scale=4, dim=embed_dim) + self.output = nn.Conv2d(in_channels=embed_dim, out_channels=num_classes, kernel_size=1, bias=False) + self.apply(init_swin_weights) + + def forward_features(self, x: torch.Tensor): + x = self.patch_embed(x) + if self.ape: + x = x + self.absolute_pos_embed + x = self.pos_drop(x) + skips = [] + for layer in self.layers: + skips.append(x) + x = layer(x) + return self.norm(x), skips + + def forward_up_features(self, x: torch.Tensor, skips) -> torch.Tensor: + for i, layer_up in enumerate(self.layers_up): + if i > 0: + x = self.concat_back_dim[i](torch.cat([x, skips[self.num_layers - 1 - i]], -1)) + x = layer_up(x) + return self.norm_up(x) + + def up_x4(self, x: torch.Tensor) -> torch.Tensor: + h, w = self.patches_resolution + b = x.shape[0] + x = self.up(x).view(b, 4 * h, 4 * w, -1).permute(0, 3, 1, 2) + return self.output(x) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 5: + x = x.flatten(start_dim=1, end_dim=2) + if x.ndim != 4: + raise ValueError( + "SwinUnet expects input shape (batch, channels, height, width) or " + f"(batch, time, channels, height, width), got {tuple(x.shape)}." + ) + if x.size(1) == 1 and self.in_chans == 3: + x = x.repeat(1, 3, 1, 1) # official SwinUnet wrapper: grey-scale input to RGB + if x.size(1) != self.in_chans: + raise ValueError(f"SwinUnet expected {self.in_chans} input channels, got shape {tuple(x.shape)}.") + if tuple(x.shape[-2:]) != (self.img_size, self.img_size): + raise ValueError( + f"SwinUnet expects height and width {self.img_size} (pad smaller inputs; WSTS+ zero-pads " + f"128 to 224), got shape {tuple(x.shape)}." + ) + x, skips = self.forward_features(x) + return self.up_x4(self.forward_up_features(x, skips)) + + def load_swin_pretrained(self, checkpoint: Union[str, Path, Mapping[str, torch.Tensor]]): + """Initialise encoder and decoder from a Swin Transformer classification checkpoint. + + ``checkpoint`` is ``"imagenet"`` (Swin-T ImageNet-1k, downloaded and sha256-checked), a + path to a microsoft/Swin-Transformer checkpoint, or its loaded dict (``{"model": state}`` + or the state itself). Mirrors the official ``SwinUnet.load_from``; returns the + ``load_state_dict`` result. + """ + if isinstance(checkpoint, str) and checkpoint == "imagenet": + checkpoint = _swin_tiny_imagenet_path() + if isinstance(checkpoint, (str, Path)): + checkpoint = torch.load(str(checkpoint), map_location="cpu", weights_only=True) + state = checkpoint["model"] if "model" in checkpoint else checkpoint + + full = copy.deepcopy(dict(state)) + last = self.num_layers - 1 + for key, value in state.items(): + if "layers." in key: + full["layers_up." + str(last - int(key[7:8])) + key[8:]] = value + own = self.state_dict() + for key in list(full): + if key in own and full[key].shape != own[key].shape: + del full[key] + return self.load_state_dict(full, strict=False) + + +def swin_unet_builder( + task: str, + in_channels: int, + out_channels: int = 1, + history: int = 1, + img_size: int = 224, + patch_size: int = 4, + embed_dim: int = 96, + depths: Sequence[int] = (2, 2, 2, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + window_size: int = 7, + mlp_ratio: float = 4.0, + drop_rate: float = 0.0, + drop_path_rate: float = 0.2, + use_checkpoint: bool = False, + pretrained: Optional[str] = None, + **kwargs, +) -> nn.Module: + """Swin-Unet-Tiny with the official configuration (``swin_tiny_patch4_window7_224_lite.yaml``). + + ``history > 1`` multiplies the input channels (multi-day input is flattened, as in WSTS+). + ``pretrained`` is None, ``"imagenet"`` or a path to a Swin checkpoint. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"swin_unet supports task='segmentation', got {task!r}.") + if history <= 0: + raise ValueError(f"history must be positive, got {history}") + model = SwinUnet( + img_size=img_size, + patch_size=patch_size, + in_chans=in_channels * history, + num_classes=out_channels, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop_rate=drop_rate, + drop_path_rate=drop_path_rate, + use_checkpoint=use_checkpoint, + ) + if pretrained is not None: + model.load_swin_pretrained(pretrained) + return model + + +__all__ = ["SWIN_TINY_IMAGENET_SHA256", "SWIN_TINY_IMAGENET_URL", "SwinUnet", "swin_unet_builder"] diff --git a/pyhazards/models/swin_unetr.py b/pyhazards/models/swin_unetr.py new file mode 100644 index 00000000..2077f5c5 --- /dev/null +++ b/pyhazards/models/swin_unetr.py @@ -0,0 +1,1007 @@ +"""SwinUNETR as implemented by MONAI, with TS-SatFire's spatio-temporal (SwinUNETR-3D) modifications. + +Port of ``monai.networks.nets.SwinUNETR`` from MONAI 1.3.2 (``monai/networks/nets/swin_unetr.py``, +``monai/networks/blocks/patchembedding.py`` ``PatchEmbed`` and the UNETR blocks in +:mod:`pyhazards.models.monai_blocks`; Apache License 2.0, Copyright (c) MONAI Consortium). +TS-SatFire's copy (``spatial_models/swinunetr/``, itself an adaptation of MONAI's file) is +reproduced through the options described below. The TS-SatFire repository has no license, so its +code is not copied: its changes are re-implemented on top of the MONAI port from their behaviour +and checked against it as a test oracle. The Swin-V2 attention follows the algorithm of +microsoft/Swin-Transformer ``models/swin_transformer_v2.py`` (``WindowAttention``; MIT License, +Copyright (c) Microsoft Corporation), extended to 3D windows as in TS-SatFire. Changes made for +PyHazards: plain PyTorch (no MONAI or einops dependency), invalid configurations and input shapes +raise ``ValueError`` up front, and :class:`TemporalSwinUNETR` adds the TS-SatFire input layout and +temporal read-out. Module names, creation order and defaults follow MONAI (or TS-SatFire, for its +options), so their state dicts load with ``strict=True`` and the same seed gives the same initial +weights. + +SwinUNETR is Hatamizadeh et al., "Swin UNETR: Swin Transformers for Semantic Segmentation of +Brain Tumors in MRI Images" (BrainLes 2021, LNCS 12962, arXiv:2201.01266): a four-stage Swin +Transformer encoder (shifted-window attention, patch merging) whose five feature levels feed a +convolutional U-Net decoder of residual blocks. The authors' official code +(Project-MONAI/research-contributions) uses MONAI's implementation. + +TS-SatFire (Zhao, Gerard & Ban, Scientific Data 12:1817, 2025) uses it in two ways: +"SwinUNETR-2D" is stock MONAI ``SwinUNETR(img_size=(256, 256), spatial_dims=2, feature_size=48, +norm_name="batch")`` (25,151,996 parameters with 8 input channels, Table 3: 25.2M); +"SwinUNETR-3D" uses the repository's copy, which differs from MONAI 1.3.2 in that + +- ``patch_size`` and ``window_size`` are arguments -- ``(1, 2, 2)`` and ``(T, 4, 4)`` over + (time, height, width), so patches never span several days and every attention window covers + the whole time series (MONAI hard-codes 2 and 7); +- patch merging (``downsample="ts_satfire"`` here) concatenates neighbours only along the + dimensions whose size is even and down-samples only those; the decision is made at + construction from ``img_size`` (before patch embedding), and the decoder up-samples by the same + per-stage factors. With T = 6 the time axis is therefore halved once, by the first merging + (6 -> 3), and kept at 3 afterwards; with T = 4 it is halved twice; with T = 2 once. Its + eight-way concatenation order also differs from MONAI's ``"merging"`` (which repeats two of the + eight slices) and ``"mergingv2"``; +- ``attn_version`` selects MONAI's window attention (``"v1"``, used by the prediction script) or + Swin-V2 cosine attention with a continuous relative-position MLP (``"v2"``); +- the output block is wrapped in ``nn.Sequential`` (keys ``out.0.*``; ``wrap_out=True``), and + MONAI's ``feature_size % 12`` check is dropped. +""" + +from __future__ import annotations + +import itertools +from typing import Callable, List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as torch_checkpoint + +from .monai_blocks import ( + DropPath, + MLPBlock, + NormSpec, + TemporalReadout, + UnetOutBlock, + UnetrBasicBlock, + UnetrUpBlock, + as_tuple, + check_norm_name, + trunc_normal_, +) + +IntOrSeq = Union[int, Sequence[int]] + +_CONV = {2: nn.Conv2d, 3: nn.Conv3d} +DOWNSAMPLE_MODES = ("merging", "mergingv2", "ts_satfire") +ATTENTION_VERSIONS = ("v1", "v2") + +# TS-SatFire SwinUNETR-3D (run_spatial_temp_model_pred.py): window (T, 4, 4), patch (1, 2, 2). +TS_SATFIRE_SWIN3D_PATCH = (1, 2, 2) +TS_SATFIRE_SWIN3D_WINDOW_HW = (4, 4) + + +def _channels_last(x: torch.Tensor) -> torch.Tensor: + return x.permute(0, *range(2, x.ndim), 1) + + +def _channels_first(x: torch.Tensor) -> torch.Tensor: + return x.permute(0, x.ndim - 1, *range(1, x.ndim - 1)) + + +def window_partition(x: torch.Tensor, window_size: Sequence[int]) -> torch.Tensor: + """Split ``(b, [d,] h, w, c)`` into ``(num_windows * b, window_volume, c)`` (MONAI).""" + x_shape = x.size() + if len(x_shape) == 5: + b, d, h, w, c = x_shape + x = x.view( + b, + d // window_size[0], + window_size[0], + h // window_size[1], + window_size[1], + w // window_size[2], + window_size[2], + c, + ) + windows = x.permute(0, 1, 3, 5, 2, 4, 6, 7).contiguous().view(-1, window_size[0] * window_size[1] * window_size[2], c) + else: + b, h, w, c = x.shape + x = x.view(b, h // window_size[0], window_size[0], w // window_size[1], window_size[1], c) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size[0] * window_size[1], c) + return windows + + +def window_reverse(windows: torch.Tensor, window_size: Sequence[int], dims: Sequence[int]) -> torch.Tensor: + """Inverse of :func:`window_partition` (MONAI).""" + if len(dims) == 4: + b, d, h, w = dims + x = windows.view( + b, + d // window_size[0], + h // window_size[1], + w // window_size[2], + window_size[0], + window_size[1], + window_size[2], + -1, + ) + x = x.permute(0, 1, 4, 2, 5, 3, 6, 7).contiguous().view(b, d, h, w, -1) + else: + b, h, w = dims + x = windows.view(b, h // window_size[0], w // window_size[1], window_size[0], window_size[1], -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(b, h, w, -1) + return x + + +def get_window_size(x_size, window_size, shift_size=None): + """Shrink the window (and drop the shift) along dimensions not larger than the window (MONAI).""" + use_window_size = list(window_size) + use_shift_size = list(shift_size) if shift_size is not None else None + for i in range(len(x_size)): + if x_size[i] <= window_size[i]: + use_window_size[i] = x_size[i] + if use_shift_size is not None: + use_shift_size[i] = 0 + if use_shift_size is None: + return tuple(use_window_size) + return tuple(use_window_size), tuple(use_shift_size) + + +def compute_mask(dims: Sequence[int], window_size, shift_size, device) -> torch.Tensor: + """Attention mask for shifted windows (MONAI).""" + cnt = 0 + if len(dims) == 3: + d, h, w = dims + img_mask = torch.zeros((1, d, h, w, 1), device=device) + for ds in slice(-window_size[0]), slice(-window_size[0], -shift_size[0]), slice(-shift_size[0], None): + for hs in slice(-window_size[1]), slice(-window_size[1], -shift_size[1]), slice(-shift_size[1], None): + for ws in slice(-window_size[2]), slice(-window_size[2], -shift_size[2]), slice(-shift_size[2], None): + img_mask[:, ds, hs, ws, :] = cnt + cnt += 1 + else: + h, w = dims + img_mask = torch.zeros((1, h, w, 1), device=device) + for hs in slice(-window_size[0]), slice(-window_size[0], -shift_size[0]), slice(-shift_size[0], None): + for ws in slice(-window_size[1]), slice(-window_size[1], -shift_size[1]), slice(-shift_size[1], None): + img_mask[:, hs, ws, :] = cnt + cnt += 1 + mask_windows = window_partition(img_mask, window_size).squeeze(-1) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + return attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + +def _relative_position_index(window_size: Sequence[int]) -> torch.Tensor: + coords = torch.stack(torch.meshgrid(*[torch.arange(w) for w in window_size], indexing="ij")) + coords_flatten = torch.flatten(coords, 1) + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + for i, w in enumerate(window_size): + relative_coords[:, :, i] += w - 1 + if len(window_size) == 3: + relative_coords[:, :, 0] *= (2 * window_size[1] - 1) * (2 * window_size[2] - 1) + relative_coords[:, :, 1] *= 2 * window_size[2] - 1 + else: + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + return relative_coords.sum(-1) + + +def _apply_mask_and_softmax(attn: torch.Tensor, mask: Optional[torch.Tensor], num_heads: int, softmax: nn.Module): + if mask is not None: + b, n = attn.shape[0], attn.shape[-1] + nw = mask.shape[0] + attn = attn.view(b // nw, nw, num_heads, n, n) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, num_heads, n, n) + return softmax(attn) + + +class WindowAttention(nn.Module): + """Window attention with a learned relative-position bias table (MONAI; TS-SatFire ``"v1"``).""" + + def __init__( + self, + dim: int, + num_heads: int, + window_size: Sequence[int], + qkv_bias: bool = False, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ): + super().__init__() + self.dim = dim + self.window_size = window_size + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + table_size = int(np.prod([2 * w - 1 for w in window_size])) + self.relative_position_bias_table = nn.Parameter(torch.zeros(table_size, num_heads)) + self.register_buffer("relative_position_index", _relative_position_index(window_size)) + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + trunc_normal_(self.relative_position_bias_table, std=0.02) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor: + b, n, c = x.shape + qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, c // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + q = q * self.scale + attn = q @ k.transpose(-2, -1) + # MONAI indexes the full-window table with [:n, :n] also when the window was shrunk. + relative_position_bias = self.relative_position_bias_table[ + self.relative_position_index.clone()[:n, :n].reshape(-1) + ].reshape(n, n, -1) + attn = attn + relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) + attn = _apply_mask_and_softmax(attn, mask, self.num_heads, self.softmax) + attn = self.attn_drop(attn).to(v.dtype) + x = (attn @ v).transpose(1, 2).reshape(b, n, c) + return self.proj_drop(self.proj(x)) + + +class WindowAttentionV2(nn.Module): + """Swin-V2 window attention: scaled cosine attention and a log-spaced continuous position bias. + + TS-SatFire's ``WindowAttentionV2`` (``attn_version="v2"``), after Liu et al., "Swin Transformer + V2" (CVPR 2022): ``cos(q, k) * exp(min(logit_scale, log 100)) + 16 * sigmoid(cpb_mlp(coords))``. + """ + + def __init__( + self, + dim: int, + num_heads: int, + window_size: Sequence[int], + qkv_bias: bool = False, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ): + super().__init__() + if any(w < 2 for w in window_size): + # The reference divides the relative coordinates by (window - 1): NaN for a window of 1. + raise ValueError(f"attn_version='v2' needs window sizes >= 2, got {tuple(window_size)}") + self.dim = dim + self.window_size = window_size + self.num_heads = num_heads + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True) + self.cpb_mlp = nn.Sequential( + nn.Linear(len(window_size), 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False) + ) + axes = [torch.arange(-(w - 1), w, dtype=torch.float32) for w in window_size] + table = torch.stack(torch.meshgrid(*axes, indexing="ij")) + table = table.permute(*range(1, len(window_size) + 1), 0).contiguous().unsqueeze(0) + for i, w in enumerate(window_size): + # TS-SatFire indexes [:, :, :, i] -- the coordinate axis in 2D, but in 3D the i-th entry + # of the width axis (all three coordinates there are divided by window[i] - 1). Kept. + table[:, :, :, i] /= w - 1 + table *= 8 # normalise to [-8, 8] + table = torch.sign(table) * torch.log2(torch.abs(table) + 1.0) / np.log2(8) + self.register_buffer("relative_coords_table", table) + self.register_buffer("relative_position_index", _relative_position_index(window_size)) + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor: + b, n, c = x.shape + qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, c // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1) + max_scale = torch.log(torch.tensor(1.0 / 0.01, device=x.device)) + attn = attn * torch.clamp(self.logit_scale, max=max_scale).exp() + table = self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads) + relative_position_bias = table[self.relative_position_index.clone()[:n, :n].reshape(-1)].reshape(n, n, -1) + relative_position_bias = 16 * torch.sigmoid(relative_position_bias.permute(2, 0, 1).contiguous()) + attn = attn + relative_position_bias.unsqueeze(0) + attn = _apply_mask_and_softmax(attn, mask, self.num_heads, self.softmax) + attn = self.attn_drop(attn).to(v.dtype) + x = (attn @ v).transpose(1, 2).reshape(b, n, c) + return self.proj_drop(self.proj(x)) + + +class SwinTransformerBlock(nn.Module): + """(Shifted-)window attention and MLP with pre-norm residuals (MONAI).""" + + def __init__( + self, + dim: int, + num_heads: int, + window_size: Sequence[int], + shift_size: Sequence[int], + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + drop_path: float = 0.0, + use_checkpoint: bool = False, + attn_version: str = "v1", + ): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + self.use_checkpoint = use_checkpoint + self.norm1 = nn.LayerNorm(dim) + attention = WindowAttention if attn_version == "v1" else WindowAttentionV2 + self.attn = attention( + dim, window_size=self.window_size, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = nn.LayerNorm(dim) + self.mlp = MLPBlock(hidden_size=dim, mlp_dim=int(dim * mlp_ratio), dropout_rate=drop, dropout_mode="swin") + + def forward_part1(self, x: torch.Tensor, mask_matrix: Optional[torch.Tensor]) -> torch.Tensor: + x_shape = x.size() + x = self.norm1(x) + if len(x_shape) == 5: + b, d, h, w, c = x.shape + window_size, shift_size = get_window_size((d, h, w), self.window_size, self.shift_size) + pad_d1 = (window_size[0] - d % window_size[0]) % window_size[0] + pad_b = (window_size[1] - h % window_size[1]) % window_size[1] + pad_r = (window_size[2] - w % window_size[2]) % window_size[2] + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b, 0, pad_d1)) + _, dp, hp, wp, _ = x.shape + dims = [b, dp, hp, wp] + else: + b, h, w, c = x.shape + window_size, shift_size = get_window_size((h, w), self.window_size, self.shift_size) + pad_d1 = 0 + pad_b = (window_size[0] - h % window_size[0]) % window_size[0] + pad_r = (window_size[1] - w % window_size[1]) % window_size[1] + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b)) + _, hp, wp, _ = x.shape + dims = [b, hp, wp] + roll_dims = tuple(range(1, len(x_shape) - 1)) + if any(i > 0 for i in shift_size): + shifted_x = torch.roll(x, shifts=tuple(-s for s in shift_size), dims=roll_dims) + attn_mask = mask_matrix + else: + shifted_x = x + attn_mask = None + attn_windows = self.attn(window_partition(shifted_x, window_size), mask=attn_mask) + attn_windows = attn_windows.view(-1, *(window_size + (c,))) + shifted_x = window_reverse(attn_windows, window_size, dims) + if any(i > 0 for i in shift_size): + x = torch.roll(shifted_x, shifts=tuple(shift_size), dims=roll_dims) + else: + x = shifted_x + if len(x_shape) == 5: + if pad_d1 > 0 or pad_r > 0 or pad_b > 0: + x = x[:, :d, :h, :w, :].contiguous() + elif pad_r > 0 or pad_b > 0: + x = x[:, :h, :w, :].contiguous() + return x + + def forward_part2(self, x: torch.Tensor) -> torch.Tensor: + return self.drop_path(self.mlp(self.norm2(x))) + + def forward(self, x: torch.Tensor, mask_matrix: Optional[torch.Tensor]) -> torch.Tensor: + shortcut = x + if self.use_checkpoint: + x = torch_checkpoint.checkpoint(self.forward_part1, x, mask_matrix, use_reentrant=False) + else: + x = self.forward_part1(x, mask_matrix) + x = shortcut + self.drop_path(x) + if self.use_checkpoint: + x = x + torch_checkpoint.checkpoint(self.forward_part2, x, use_reentrant=False) + else: + x = x + self.forward_part2(x) + return x + + +class PatchMergingV2(nn.Module): + """Concatenate each 2x2(x2) neighbourhood, ``LayerNorm``, linear to ``2 * dim`` (MONAI ``"mergingv2"``).""" + + def __init__(self, dim: int, spatial_dims: int = 3): + super().__init__() + self.dim = dim + if spatial_dims == 3: + self.reduction = nn.Linear(8 * dim, 2 * dim, bias=False) + self.norm = nn.LayerNorm(8 * dim) + else: + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = nn.LayerNorm(4 * dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 5: + _, d, h, w, _ = x.shape + if (h % 2 == 1) or (w % 2 == 1) or (d % 2 == 1): + x = F.pad(x, (0, 0, 0, w % 2, 0, h % 2, 0, d % 2)) + x = torch.cat([x[:, i::2, j::2, k::2, :] for i, j, k in itertools.product(range(2), range(2), range(2))], -1) + else: + _, h, w, _ = x.shape + if (h % 2 == 1) or (w % 2 == 1): + x = F.pad(x, (0, 0, 0, w % 2, 0, h % 2)) + x = torch.cat([x[:, j::2, i::2, :] for i, j in itertools.product(range(2), range(2))], -1) + return self.reduction(self.norm(x)) + + +class PatchMerging(PatchMergingV2): + """MONAI's ``"merging"`` mode, "the PatchMerging module previously defined in v0.9.0". + + In 3D its eight slices are ``(0,0,0) (1,0,0) (0,1,0) (0,0,1) (1,0,1) (0,1,0) (0,0,1) (1,1,1)``: + ``(0,1,0)`` and ``(0,0,1)`` appear twice and ``(1,1,0)``, ``(0,1,1)`` never (kept for + compatibility with MONAI's pretrained weights). 2D inputs use :class:`PatchMergingV2`. + """ + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 4: + return super().forward(x) + _, d, h, w, _ = x.shape + if (h % 2 == 1) or (w % 2 == 1) or (d % 2 == 1): + x = F.pad(x, (0, 0, 0, w % 2, 0, h % 2, 0, d % 2)) + x0 = x[:, 0::2, 0::2, 0::2, :] + x1 = x[:, 1::2, 0::2, 0::2, :] + x2 = x[:, 0::2, 1::2, 0::2, :] + x3 = x[:, 0::2, 0::2, 1::2, :] + x4 = x[:, 1::2, 0::2, 1::2, :] + x5 = x[:, 0::2, 1::2, 0::2, :] + x6 = x[:, 0::2, 0::2, 1::2, :] + x7 = x[:, 1::2, 1::2, 1::2, :] + x = torch.cat([x0, x1, x2, x3, x4, x5, x6, x7], -1) + return self.reduction(self.norm(x)) + + +class AdaptivePatchMerging(nn.Module): + """TS-SatFire's 3D patch merging: merge only the dimensions in ``merge`` (``downsample="ts_satfire"``). + + ``merge`` is fixed at construction (TS-SatFire derives it from the stage resolution computed + from ``img_size``). The channels of the 2^k merged neighbours are concatenated in TS-SatFire's + order, normalised and projected to ``2 * dim``; without any merged dimension only the norm and + the projection are applied. + """ + + def __init__(self, dim: int, merge: Sequence[bool]): + super().__init__() + self.dim = dim + self.merge = tuple(bool(m) for m in merge) + dims_tmp = dim * 2 ** sum(self.merge) + self.resample_scale = [2 if m else 1 for m in self.merge] + self.norm = nn.LayerNorm(dims_tmp) + self.output_dims = 2 * dim + self.reduction = nn.Linear(dims_tmp, self.output_dims, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # x: (B, D, H, W, C) + merged = [axis + 1 for axis, m in enumerate(self.merge) if m] + if len(merged) == 3: + offsets = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1), (1, 1, 1)] + elif len(merged) == 2: + offsets = [(0, 0), (1, 0), (0, 1), (1, 1)] + elif len(merged) == 1: + offsets = [(0,), (1,)] + else: + offsets = [] + if offsets: + parts = [] + for offset in offsets: + index: List[slice] = [slice(None)] * x.ndim + for axis, start in zip(merged, offset): + index[axis] = slice(start, None, 2) + parts.append(x[tuple(index)]) + x = torch.cat(parts, dim=-1) + return self.reduction(self.norm(x)) + + +class BasicLayer(nn.Module): + """One Swin stage: ``depth`` blocks alternating unshifted / half-window-shifted, then merging (MONAI).""" + + def __init__( + self, + dim: int, + depth: int, + num_heads: int, + window_size: Sequence[int], + drop_path: List[float], + mlp_ratio: float, + qkv_bias: bool, + drop: float, + attn_drop: float, + downsample: Callable[[], nn.Module], + use_checkpoint: bool = False, + attn_version: str = "v1", + ): + super().__init__() + self.window_size = window_size + self.shift_size = tuple(i // 2 for i in window_size) + self.no_shift = tuple(0 for _ in window_size) + self.depth = depth + self.use_checkpoint = use_checkpoint + self.blocks = nn.ModuleList( + [ + SwinTransformerBlock( + dim=dim, + num_heads=num_heads, + window_size=self.window_size, + shift_size=self.no_shift if (i % 2 == 0) else self.shift_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i], + use_checkpoint=use_checkpoint, + attn_version=attn_version, + ) + for i in range(depth) + ] + ) + self.downsample = downsample() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b = x.shape[0] + spatial = tuple(x.shape[2:]) + window_size, shift_size = get_window_size(spatial, self.window_size, self.shift_size) + x = _channels_last(x) + padded = [int(np.ceil(s / w)) * w for s, w in zip(spatial, window_size)] + attn_mask = compute_mask(padded, window_size, shift_size, x.device) + for blk in self.blocks: + x = blk(x, attn_mask) + x = x.view(b, *spatial, -1) + x = self.downsample(x) + return _channels_first(x) + + +class PatchEmbed(nn.Module): + """Strided-convolution patch embedding, zero-padding inputs to a multiple of the patch (MONAI).""" + + def __init__(self, patch_size: Sequence[int], in_chans: int, embed_dim: int, spatial_dims: int = 3): + super().__init__() + self.patch_size = tuple(patch_size) + self.embed_dim = embed_dim + self.proj = _CONV[spatial_dims](in_channels=in_chans, out_channels=embed_dim, kernel_size=patch_size, stride=patch_size) + self.norm = None # MONAI's SwinTransformer uses patch_norm=False + + def forward(self, x: torch.Tensor) -> torch.Tensor: + pads: List[int] = [] + for size, patch in zip(reversed(x.shape[2:]), reversed(self.patch_size)): + pads += [0, (patch - size % patch) % patch] + if any(pads): + x = F.pad(x, pads) + return self.proj(x) + + +class SwinTransformer(nn.Module): + """Four-stage Swin encoder returning the (optionally layer-normalised) features of every level. + + ``stage_scales`` holds each stage's down-sampling factor per dimension (2 everywhere for MONAI's + merging; TS-SatFire's plan for ``downsample="ts_satfire"``); ``resamples`` lists them deepest + first, as TS-SatFire's ``SwinTransformer.resamples``. + """ + + def __init__( + self, + in_chans: int, + embed_dim: int, + window_size: Sequence[int], + patch_size: Sequence[int], + depths: Sequence[int], + num_heads: Sequence[int], + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.0, + use_checkpoint: bool = False, + spatial_dims: int = 3, + downsample: str = "merging", + use_v2: bool = False, + img_size: Optional[Sequence[int]] = None, + attn_version: str = "v1", + ): + super().__init__() + if downsample not in DOWNSAMPLE_MODES: + raise ValueError(f"downsample must be one of {DOWNSAMPLE_MODES}, got {downsample!r}") + if downsample == "ts_satfire" and img_size is None: + raise ValueError("downsample='ts_satfire' needs img_size: its merging plan is fixed at construction.") + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.patch_norm = False + self.window_size = tuple(window_size) + self.patch_size = tuple(patch_size) + self.patch_embed = PatchEmbed(self.patch_size, in_chans, embed_dim, spatial_dims=spatial_dims) + self.pos_drop = nn.Dropout(p=drop_rate) + # torch.linspace(...).item() as in the references, on the CPU so meta-device builds work too. + dpr = torch.linspace(0, drop_path_rate, sum(depths), device="cpu").tolist() + self.use_v2 = use_v2 + self.layers1 = nn.ModuleList() + self.layers2 = nn.ModuleList() + self.layers3 = nn.ModuleList() + self.layers4 = nn.ModuleList() + if self.use_v2: + self.layers1c = nn.ModuleList() + self.layers2c = nn.ModuleList() + self.layers3c = nn.ModuleList() + self.layers4c = nn.ModuleList() + self.stage_scales: List[Tuple[int, ...]] = [] + resolution = list(img_size) if img_size is not None else None + for i_layer in range(self.num_layers): + dim = int(embed_dim * 2**i_layer) + if downsample == "ts_satfire": + # TS-SatFire decides from the stage resolution derived from img_size (not divided by the patch). + merge = [r % 2 == 0 for r in resolution] + scale = tuple(2 if m else 1 for m in merge) + resolution = [r // s for r, s in zip(resolution, scale)] + + def factory(dim=dim, merge=merge) -> nn.Module: + return AdaptivePatchMerging(dim, merge) + + else: + scale = (2,) * spatial_dims + merging = PatchMerging if downsample == "merging" else PatchMergingV2 + + def factory(dim=dim, merging=merging) -> nn.Module: + return merging(dim=dim, spatial_dims=spatial_dims) + + self.stage_scales.append(scale) + layer = BasicLayer( + dim=dim, + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=self.window_size, + drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + drop=drop_rate, + attn_drop=attn_drop_rate, + downsample=factory, + use_checkpoint=use_checkpoint, + attn_version=attn_version, + ) + getattr(self, f"layers{i_layer + 1}").append(layer) + if self.use_v2: + layerc = UnetrBasicBlock( + spatial_dims=spatial_dims, + in_channels=dim, + out_channels=dim, + kernel_size=3, + stride=1, + norm_name="instance", + res_block=True, + ) + getattr(self, f"layers{i_layer + 1}c").append(layerc) + self.resamples = [list(s) for s in reversed(self.stage_scales)] + self.num_features = int(embed_dim * 2 ** (self.num_layers - 1)) + + @staticmethod + def proj_out(x: torch.Tensor, normalize: bool = False) -> torch.Tensor: + if normalize: + x = _channels_first(F.layer_norm(_channels_last(x), [x.shape[1]])) + return x + + def forward(self, x: torch.Tensor, normalize: bool = True) -> List[torch.Tensor]: + x0 = self.pos_drop(self.patch_embed(x)) + outs = [self.proj_out(x0, normalize)] + for i in range(1, 5): + if self.use_v2: + x0 = getattr(self, f"layers{i}c")[0](x0.contiguous()) + x0 = getattr(self, f"layers{i}")[0](x0.contiguous()) + outs.append(self.proj_out(x0, normalize)) + return outs + + +class SwinUNETR(nn.Module): + """MONAI ``SwinUNETR`` (1.3.2) in plain PyTorch, with TS-SatFire's options. + + Args: + img_size: spatial input size. Optional for MONAI's merging modes (only checked, as in + MONAI); required for ``downsample="ts_satfire"``, whose merging plan depends on it. + in_channels: input channels. + out_channels: output channels (logits, no activation). + depths: Swin blocks per stage (four stages). + num_heads: attention heads per stage. + feature_size: width of the first stage; doubled at every stage. + norm_name: decoder normalisation, ``"instance"`` (MONAI) or ``"batch"`` (TS-SatFire). + drop_rate, attn_drop_rate, dropout_path_rate: dropout, attention dropout, stochastic depth. + normalize: layer-normalise the encoder features passed to the decoder. + use_checkpoint: gradient checkpointing in the Swin blocks. + spatial_dims: 2 or 3 (``"ts_satfire"`` merging: 3 only). + downsample: ``"merging"`` (MONAI default, v0.9.0 slice order), ``"mergingv2"`` or + ``"ts_satfire"`` (merge only even-sized dimensions). + use_v2: MONAI's SwinUNETR-v2 residual convolution block before every stage. + patch_size: patch size (MONAI: 2; TS-SatFire: ``(1, 2, 2)``). + window_size: attention window (MONAI: 7; TS-SatFire: ``(T, 4, 4)``). + attn_version: ``"v1"`` (MONAI window attention) or ``"v2"`` (Swin-V2 cosine attention). + wrap_out: wrap the output block in ``nn.Sequential`` (TS-SatFire's parameter names). + + Input ``(batch, in_channels, *spatial)``; output ``(batch, out_channels, *spatial)``. + """ + + def __init__( + self, + img_size: Optional[IntOrSeq], + in_channels: int, + out_channels: int, + depths: Sequence[int] = (2, 2, 2, 2), + num_heads: Sequence[int] = (3, 6, 12, 24), + feature_size: int = 24, + norm_name: NormSpec = "instance", + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + dropout_path_rate: float = 0.0, + normalize: bool = True, + use_checkpoint: bool = False, + spatial_dims: int = 3, + downsample: str = "merging", + use_v2: bool = False, + patch_size: IntOrSeq = 2, + window_size: IntOrSeq = 7, + attn_version: str = "v1", + wrap_out: bool = False, + ): + super().__init__() + if spatial_dims not in (2, 3): + raise ValueError("spatial dimension should be 2 or 3.") + if downsample not in DOWNSAMPLE_MODES: + raise ValueError(f"downsample must be one of {DOWNSAMPLE_MODES}, got {downsample!r}") + if attn_version not in ATTENTION_VERSIONS: + raise ValueError( + f"attn_version must be one of {ATTENTION_VERSIONS}, got {attn_version!r} (TS-SatFire's " + "autoregressive 'ar' attention is not part of its prediction model and is not ported)" + ) + if in_channels <= 0 or out_channels <= 0 or feature_size <= 0: + raise ValueError("in_channels, out_channels and feature_size must be positive.") + for name, rate in (("dropout", drop_rate), ("attention dropout", attn_drop_rate), ("drop path", dropout_path_rate)): + if not 0 <= rate <= 1: + raise ValueError(f"{name} rate should be between 0 and 1.") + depths, num_heads = tuple(depths), tuple(num_heads) + if len(depths) != 4 or len(num_heads) != 4 or min(depths) < 1: + raise ValueError(f"depths and num_heads need four entries (depths >= 1), got {depths} and {num_heads}") + if any((feature_size * 2**i) % h for i, h in enumerate(num_heads)): + raise ValueError(f"Every stage width feature_size * 2**i must be divisible by num_heads[i], got {feature_size} and {num_heads}") + if downsample != "ts_satfire" and feature_size % 12 != 0: + raise ValueError("feature_size should be divisible by 12.") # MONAI's check (dropped by TS-SatFire) + check_norm_name(norm_name) + patch = as_tuple(patch_size, spatial_dims, "patch_size") + window = as_tuple(window_size, spatial_dims, "window_size") + if min(patch) < 1 or min(window) < 1: + raise ValueError(f"patch_size and window_size must be positive, got {patch} and {window}") + size = as_tuple(img_size, spatial_dims, "img_size") if img_size is not None else None + if downsample == "ts_satfire": + if spatial_dims != 3: + raise ValueError("downsample='ts_satfire' supports spatial_dims=3 only, as in TS-SatFire.") + if size is None: + raise ValueError("downsample='ts_satfire' needs img_size: its merging plan is fixed at construction.") + for m, p in zip(size, patch): # TS-SatFire's check + if any(m % p ** (i + 1) for i in range(5)): + raise ValueError("input image size (img_size) should be divisible by stage-wise image resolution.") + elif size is not None: + self._check_monai_size(size, patch) + + self.img_size = size + self.in_channels = in_channels + self.spatial_dims = spatial_dims + self.downsample = downsample + self.patch_size = patch + self.window_size = window + self.normalize = normalize + + self.swinViT = SwinTransformer( + in_chans=in_channels, + embed_dim=feature_size, + window_size=window, + patch_size=patch, + depths=depths, + num_heads=num_heads, + mlp_ratio=4.0, + qkv_bias=True, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=dropout_path_rate, + use_checkpoint=use_checkpoint, + spatial_dims=spatial_dims, + downsample=downsample, + use_v2=use_v2, + img_size=size, + attn_version=attn_version, + ) + resamples = self.swinViT.resamples + + def basic(in_mult: int) -> UnetrBasicBlock: + return UnetrBasicBlock( + spatial_dims=spatial_dims, + in_channels=in_mult * feature_size, + out_channels=in_mult * feature_size, + kernel_size=3, + stride=1, + norm_name=norm_name, + res_block=True, + ) + + self.encoder1 = UnetrBasicBlock( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=feature_size, + kernel_size=3, + stride=1, + norm_name=norm_name, + res_block=True, + ) + self.encoder2 = basic(1) + self.encoder3 = basic(2) + self.encoder4 = basic(4) + self.encoder10 = basic(16) + decoders = ( + ("decoder5", 16, 8, resamples[0]), + ("decoder4", 8, 4, resamples[1]), + ("decoder3", 4, 2, resamples[2]), + ("decoder2", 2, 1, resamples[3]), + ("decoder1", 1, 1, patch), + ) + for name, in_mult, out_mult, up in decoders: + setattr( + self, + name, + UnetrUpBlock( + spatial_dims=spatial_dims, + in_channels=in_mult * feature_size, + out_channels=out_mult * feature_size, + kernel_size=3, + upsample_kernel_size=tuple(up), + norm_name=norm_name, + res_block=True, + ), + ) + out = UnetOutBlock(spatial_dims=spatial_dims, in_channels=feature_size, out_channels=out_channels) + self.out = nn.Sequential(out) if wrap_out else out + + @staticmethod + def _check_monai_size(spatial: Sequence[int], patch: Sequence[int]) -> None: + # MONAI: divisible by patch_size**5 (= 2 * 2**4 with its fixed patch 2). + multiple = tuple(p * 2**4 for p in patch) + if any(s % m for s, m in zip(spatial, multiple)): + raise ValueError(f"spatial dimensions {tuple(spatial)} of input image must be divisible by {multiple}.") + + def _check_input(self, x: torch.Tensor, layout: str) -> None: + if x.ndim != self.spatial_dims + 2: + raise ValueError(f"{type(self).__name__} expects input shape {layout}, got {tuple(x.shape)}.") + if x.size(1) != self.in_channels: + raise ValueError(f"{type(self).__name__} expected {self.in_channels} input channels, got shape {tuple(x.shape)}.") + spatial = tuple(x.shape[2:]) + if self.downsample != "ts_satfire": + self._check_monai_size(spatial, self.patch_size) + return + if any(s % p for s, p in zip(spatial, self.patch_size)): + raise ValueError(f"Spatial shape {spatial} must be divisible by patch_size {self.patch_size}.") + sizes = [s // p for s, p in zip(spatial, self.patch_size)] + for stage, scale in enumerate(self.swinViT.stage_scales): + if any(f == 2 and n % 2 for n, f in zip(sizes, scale)): + raise ValueError( + f"Spatial shape {spatial} does not fit the merging plan {self.swinViT.stage_scales} fixed by " + f"img_size={self.img_size}: stage {stage + 1} would merge an odd-sized dimension." + ) + sizes = [n // f for n, f in zip(sizes, scale)] + + def _forward_network(self, x_in: torch.Tensor) -> torch.Tensor: + hidden_states_out = self.swinViT(x_in, self.normalize) + enc0 = self.encoder1(x_in) + enc1 = self.encoder2(hidden_states_out[0]) + enc2 = self.encoder3(hidden_states_out[1]) + enc3 = self.encoder4(hidden_states_out[2]) + dec4 = self.encoder10(hidden_states_out[4]) + dec3 = self.decoder5(dec4, hidden_states_out[3]) + dec2 = self.decoder4(dec3, enc3) + dec1 = self.decoder3(dec2, enc2) + dec0 = self.decoder2(dec1, enc1) + out = self.decoder1(dec0, enc0) + return self.out(out) + + def forward(self, x_in: torch.Tensor) -> torch.Tensor: + spatial = ", ".join(["D", "H", "W"][-self.spatial_dims :]) + self._check_input(x_in, f"(batch, channels, {spatial})") + return self._forward_network(x_in) + + +class TemporalSwinUNETR(TemporalReadout, SwinUNETR): + """3D :class:`SwinUNETR` over ``(time, H, W)`` for raster time series (TS-SatFire's SwinUNETR-3D). + + Takes ``(batch, time, channels, H, W)``, runs the network on ``(batch, channels, time, H, W)`` + and, with ``time_reduction="mean"``, averages the logits over time to + ``(batch, out_channels, H, W)``. Parameter names are those of :class:`SwinUNETR`. + """ + + def __init__(self, *args, time_reduction: str = "mean", **kwargs): + super().__init__(*args, **kwargs) + if self.spatial_dims != 3: + raise ValueError(f"TemporalSwinUNETR needs spatial_dims=3, got {self.spatial_dims}") + self._set_time_reduction(time_reduction) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self._to_network_layout(x, type(self).__name__) + self._check_input(x, "(batch, time, channels, height, width)") + return self._read_out(self._forward_network(x)) + + +def swin_unetr_builder( + task: str, + in_channels: int, + out_channels: int = 2, + spatial_dims: int = 3, + img_size: Optional[IntOrSeq] = None, + history: int = 6, + image_size: int = 256, + feature_size: Optional[int] = None, + num_heads: Optional[Union[int, Sequence[int]]] = None, + depths: Sequence[int] = (2, 2, 2, 2), + norm_name: NormSpec = "batch", + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + dropout_path_rate: float = 0.0, + normalize: bool = True, + use_checkpoint: bool = False, + patch_size: Optional[IntOrSeq] = None, + window_size: Optional[IntOrSeq] = None, + attn_version: str = "v1", + downsample: Optional[str] = None, + use_v2: bool = False, + time_reduction: str = "mean", + **kwargs, +) -> nn.Module: + """Build MONAI's SwinUNETR; the defaults are TS-SatFire's SwinUNETR models. + + ``spatial_dims=3`` returns TS-SatFire's SwinUNETR-3D as a :class:`TemporalSwinUNETR` (input + ``(B, T, C, H, W)``): ``img_size = (history, image_size, image_size)``, patch ``(1, 2, 2)``, + window ``(history, 4, 4)``, TS-SatFire's merging and output naming, feature size 36 and + 3 heads per stage. ``spatial_dims=2`` returns TS-SatFire's SwinUNETR-2D, stock MONAI + (patch 2, window 7, MONAI merging, feature size 48, heads (3, 6, 12, 24)), input + ``(B, C, H, W)``. ``num_heads`` may be one int for every stage, as in TS-SatFire's scripts. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"swin_unetr supports task='segmentation', got {task!r}.") + if spatial_dims not in (2, 3): + raise ValueError(f"swin_unetr supports spatial_dims 2 or 3, got {spatial_dims}.") + ts_3d = spatial_dims == 3 + if num_heads is None: + num_heads = 3 if ts_3d else (3, 6, 12, 24) + heads = (int(num_heads),) * 4 if isinstance(num_heads, int) else tuple(num_heads) + if img_size is None: + img_size = (history, image_size, image_size) if ts_3d else (image_size, image_size) + common = dict( + img_size=img_size, + in_channels=in_channels, + out_channels=out_channels, + depths=depths, + num_heads=heads, + feature_size=(36 if ts_3d else 48) if feature_size is None else feature_size, + norm_name=norm_name, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + dropout_path_rate=dropout_path_rate, + normalize=normalize, + use_checkpoint=use_checkpoint, + spatial_dims=spatial_dims, + use_v2=use_v2, + attn_version=attn_version, + ) + if ts_3d: + img = as_tuple(img_size, 3, "img_size") + return TemporalSwinUNETR( + downsample="ts_satfire" if downsample is None else downsample, + patch_size=TS_SATFIRE_SWIN3D_PATCH if patch_size is None else patch_size, + window_size=(img[0], *TS_SATFIRE_SWIN3D_WINDOW_HW) if window_size is None else window_size, + wrap_out=downsample in (None, "ts_satfire"), + time_reduction=time_reduction, + **common, + ) + return SwinUNETR( + downsample="merging" if downsample is None else downsample, + patch_size=2 if patch_size is None else patch_size, + window_size=7 if window_size is None else window_size, + **common, + ) + + +__all__ = [ + "AdaptivePatchMerging", + "BasicLayer", + "PatchEmbed", + "PatchMerging", + "PatchMergingV2", + "SwinTransformer", + "SwinTransformerBlock", + "SwinUNETR", + "TemporalSwinUNETR", + "WindowAttention", + "WindowAttentionV2", + "swin_unetr_builder", +] diff --git a/pyhazards/models/swinlstm.py b/pyhazards/models/swinlstm.py new file mode 100644 index 00000000..1cff0c3e --- /dev/null +++ b/pyhazards/models/swinlstm.py @@ -0,0 +1,704 @@ +"""SwinLSTM: a recurrent cell built from Swin Transformer blocks (Tang et al., ICCV 2023). + +Attribution: ported from SongTang-x/SwinLSTM at commit +``4425bcfefbebfac85c9fc6c6659361b8154d5ca3`` (MIT License, Copyright (c) 2023 Song Tang): +``SwinLSTM_D.py`` (SwinLSTM-D, the deep model with patch merging/expanding), ``SwinLSTM_B.py`` +(SwinLSTM-B, one or more cells at a single resolution) and the warm-up/prediction rollout of +``functions.py`` (``model_forward_multi_layer`` / ``model_forward_single_layer``). Window attention, +patch embedding, patch merging and patch expanding are the shared blocks of ``swin_blocks`` +(microsoft/Swin-Transformer, MIT; timm 0.4.12 ``trunc_normal_`` and ``DropPath``), which the +reference also uses. + +Module and attribute names follow the reference (``Downsample``/``Upsample`` for SwinLSTM-D, ``ST`` +for SwinLSTM-B), so the official state dicts, including the released Moving-MNIST SwinLSTM-D +weights, load with ``strict=True``, and modules are created in the reference order so that the same +``torch.manual_seed`` gives identical initial weights. +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn + +from .swin_blocks import ( + PatchEmbed, + PatchExpand, + PatchMerging, + SwinTransformerBlock, + stochastic_depth_rates, + to_2tuple, +) + +ImageSize = Union[int, Tuple[int, int]] +CellState = Tuple[torch.Tensor, torch.Tensor] + + +class SwinLSTMBlock(SwinTransformerBlock): + """Swin block that can fuse a second token sequence before attention. + + With ``hx`` given, ``norm1(x)`` and ``norm1(hx)`` are concatenated and projected back to + ``dim`` channels by ``red`` (the "LP" of the paper); the residual branch still starts from ``x``. + """ + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + num_heads: int, + window_size: int = 2, + shift_size: int = 0, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + drop_path: float = 0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ): + super().__init__( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + shift_size=shift_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path, + act_layer=act_layer, + norm_layer=norm_layer, + ) + # Created after the MLP, as in the reference (keeps seeded initialisation identical). + self.red = nn.Linear(2 * dim, dim) + + def forward(self, x: torch.Tensor, hx: Optional[torch.Tensor] = None) -> torch.Tensor: + self._check_tokens(x) + h, w = self.input_resolution + b, _, c = x.shape + + shortcut = x + x = self.norm1(x) + if hx is not None: + x = self.red(torch.cat((x, self.norm1(hx)), -1)) + x = shortcut + self.drop_path(self._window_attention(x.view(b, h, w, c))) + return x + self.drop_path(self.mlp(self.norm2(x))) + + +class SwinTransformerBlocks(nn.Module): + """The Swin blocks of one SwinLSTM cell (``SwinTransformer`` in ``SwinLSTM_D.py``). + + Block 0 fuses the input ``xt`` with the hidden state, odd blocks see only the previous block's + output, and even blocks after the first fuse the previous output with ``xt`` again. + ``drop_path`` gives one stochastic-depth rate per block. + """ + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + depth: int, + num_heads: int, + window_size: int, + drop_path: Sequence[float], + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + norm_layer=nn.LayerNorm, + ): + super().__init__() + if len(drop_path) != depth: + raise ValueError(f"expected {depth} drop-path rates, got {len(drop_path)}") + self.layers = nn.ModuleList( + SwinLSTMBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + shift_size=0 if i % 2 == 0 else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i], + norm_layer=norm_layer, + ) + for i in range(depth) + ) + + def forward(self, xt: torch.Tensor, hx: torch.Tensor) -> torch.Tensor: + x = xt + for index, layer in enumerate(self.layers): + if index == 0: + x = layer(xt, hx) + elif index % 2 == 0: + x = layer(x, xt) + else: + x = layer(x, None) + return x + + +class SwinLSTMCell(nn.Module): + """SwinLSTM cell (paper Eq. 5): ``F = STB(LP(x, h))``, ``c' = sigmoid(F) * (c + tanh(F))``, + ``h' = sigmoid(F) * tanh(c')``. Zero states are used when ``hidden_states`` is None.""" + + def __init__( + self, + dim: int, + input_resolution: Tuple[int, int], + num_heads: int, + window_size: int, + depth: int, + drop_path: Sequence[float], + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop: float = 0.0, + attn_drop: float = 0.0, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.Swin = SwinTransformerBlocks( + dim=dim, + input_resolution=input_resolution, + depth=depth, + num_heads=num_heads, + window_size=window_size, + drop_path=drop_path, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + norm_layer=norm_layer, + ) + + def forward( + self, xt: torch.Tensor, hidden_states: Optional[CellState] = None + ) -> Tuple[torch.Tensor, CellState]: + if hidden_states is None: + hx = xt.new_zeros(xt.shape) + cx = xt.new_zeros(xt.shape) + else: + hx, cx = hidden_states + ft = self.Swin(xt, hx) + gate = torch.sigmoid(ft) + cell = torch.tanh(ft) + cy = gate * (cx + cell) + hy = gate * torch.tanh(cy) + return hy, (hy, cy) + + +class PatchInflated(nn.Module): + """Reconstruction layer: tokens -> image through a 3x3 ``ConvTranspose2d`` with stride 2. + + The convolution is registered as ``Conv`` (SwinLSTM-D) or ``ConvT`` (SwinLSTM-B), as in the + reference files. + """ + + def __init__( + self, + in_chans: int, + embed_dim: int, + input_resolution: Tuple[int, int], + stride: int = 2, + padding: int = 1, + output_padding: int = 1, + conv_name: str = "Conv", + ): + super().__init__() + self.input_resolution = tuple(input_resolution) + self.conv_name = conv_name + self.add_module( + conv_name, + nn.ConvTranspose2d( + in_channels=embed_dim, + out_channels=in_chans, + kernel_size=(3, 3), + stride=to_2tuple(stride), + padding=to_2tuple(padding), + output_padding=to_2tuple(output_padding), + ), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h, w = self.input_resolution + b, length, c = x.shape + if length != h * w: + raise ValueError(f"PatchInflated expected {h * w} tokens, got input of shape {tuple(x.shape)}.") + x = x.view(b, h, w, c).permute(0, 3, 1, 2) + return getattr(self, self.conv_name)(x) + + +class DownSample(nn.Module): + """SwinLSTM-D encoder: patch embedding, then per level a SwinLSTM cell and patch merging.""" + + def __init__( + self, + img_size: ImageSize, + patch_size: int, + in_chans: int, + embed_dim: int, + depths_downsample: Sequence[int], + num_heads: Sequence[int], + window_size: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.num_layers = len(depths_downsample) + self.embed_dim = embed_dim + self.mlp_ratio = mlp_ratio + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=nn.LayerNorm + ) + patches_resolution = self.patch_embed.patches_resolution + dpr = stochastic_depth_rates(drop_path_rate, depths_downsample) + + self.layers = nn.ModuleList() + self.downsample = nn.ModuleList() + for i_layer in range(self.num_layers): + resolution = (patches_resolution[0] // (2 ** i_layer), patches_resolution[1] // (2 ** i_layer)) + dim = int(embed_dim * 2 ** i_layer) + # Patch merging is created before the cell, as in the reference. + downsample = PatchMerging(input_resolution=resolution, dim=dim) + layer = SwinLSTMCell( + dim=dim, + input_resolution=resolution, + depth=depths_downsample[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[sum(depths_downsample[:i_layer]) : sum(depths_downsample[: i_layer + 1])], + norm_layer=norm_layer, + ) + self.layers.append(layer) + self.downsample.append(downsample) + + def forward( + self, x: torch.Tensor, y: Sequence[Optional[CellState]] + ) -> Tuple[List[CellState], torch.Tensor]: + x = self.patch_embed(x) + hidden_states_down = [] + for index, layer in enumerate(self.layers): + x, hidden_state = layer(x, y[index]) + x = self.downsample[index](x) + hidden_states_down.append(hidden_state) + return hidden_states_down, x + + +class UpSample(nn.Module): + """SwinLSTM-D decoder: per level a SwinLSTM cell and patch expanding, then reconstruction. + + The reference indexes ``depths_upsample`` and ``num_heads`` from the deepest level upwards and + reverses the stochastic-depth rates inside each cell (``flag=0``); both are reproduced here. + ``patch_embed`` is never used in the forward pass but is part of the official state dict. + """ + + def __init__( + self, + img_size: ImageSize, + patch_size: int, + in_chans: int, + embed_dim: int, + depths_upsample: Sequence[int], + num_heads: Sequence[int], + window_size: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + norm_layer=nn.LayerNorm, + out_chans: Optional[int] = None, + ): + super().__init__() + self.img_size = img_size + self.num_layers = len(depths_upsample) + self.embed_dim = embed_dim + self.mlp_ratio = mlp_ratio + # Unused by the reference forward pass; kept so official checkpoints load strictly. + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=nn.LayerNorm + ) + patches_resolution = self.patch_embed.patches_resolution + self.Unembed = PatchInflated( + in_chans=in_chans if out_chans is None else out_chans, + embed_dim=embed_dim, + input_resolution=patches_resolution, + ) + dpr = stochastic_depth_rates(drop_path_rate, depths_upsample) + + self.layers = nn.ModuleList() + self.upsample = nn.ModuleList() + for i_layer in range(self.num_layers): + level = self.num_layers - 1 - i_layer + scale = 2 ** (self.num_layers - i_layer) + resolution = (patches_resolution[0] // scale, patches_resolution[1] // scale) + dim = int(embed_dim * scale) + upsample = PatchExpand(input_resolution=resolution, dim=dim) + rates = dpr[sum(depths_upsample[:level]) : sum(depths_upsample[: level + 1])] + layer = SwinLSTMCell( + dim=dim, + input_resolution=resolution, + depth=depths_upsample[level], + num_heads=num_heads[level], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=list(reversed(rates)), + norm_layer=norm_layer, + ) + self.layers.append(layer) + self.upsample.append(upsample) + + def forward( + self, x: torch.Tensor, y: Sequence[Optional[CellState]], apply_sigmoid: bool = True + ) -> Tuple[List[CellState], torch.Tensor]: + hidden_states_up = [] + for index, layer in enumerate(self.layers): + x, hidden_state = layer(x, y[index]) + x = self.upsample[index](x) + hidden_states_up.append(hidden_state) + x = self.Unembed(x) + return hidden_states_up, torch.sigmoid(x) if apply_sigmoid else x + + +class STconvert(nn.Module): + """SwinLSTM-B body: patch embedding, SwinLSTM cells at one resolution, reconstruction.""" + + def __init__( + self, + img_size: ImageSize, + patch_size: int, + in_chans: int, + embed_dim: int, + depths: Sequence[int], + num_heads: Sequence[int], + window_size: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + norm_layer=nn.LayerNorm, + out_chans: Optional[int] = None, + ): + super().__init__() + self.num_layers = len(depths) + self.embed_dim = embed_dim + self.mlp_ratio = mlp_ratio + self.patch_embed = PatchEmbed( + img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, norm_layer=nn.LayerNorm + ) + patches_resolution = self.patch_embed.patches_resolution + self.PatchInflated = PatchInflated( + in_chans=in_chans if out_chans is None else out_chans, + embed_dim=embed_dim, + input_resolution=patches_resolution, + conv_name="ConvT", + ) + # SwinLSTM-B uses the same stochastic-depth rate in every block (no linear decay). + self.layers = nn.ModuleList( + SwinLSTMCell( + dim=embed_dim, + input_resolution=(patches_resolution[0], patches_resolution[1]), + depth=depths[i_layer], + num_heads=num_heads[i_layer], + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=[drop_path_rate] * depths[i_layer], + norm_layer=norm_layer, + ) + for i_layer in range(self.num_layers) + ) + + def forward( + self, x: torch.Tensor, h: Sequence[Optional[CellState]], apply_sigmoid: bool = True + ) -> Tuple[List[CellState], torch.Tensor]: + x = self.patch_embed(x) + hidden_states = [] + for index, layer in enumerate(self.layers): + x, hidden_state = layer(x, h[index]) + hidden_states.append(hidden_state) + x = self.PatchInflated(x) + return hidden_states, torch.sigmoid(x) if apply_sigmoid else x + + +def _check_geometry(img_size: Tuple[int, int], patch_size: int, window_size: int, levels: int) -> None: + """Raise ``ValueError`` unless every token grid the model visits splits into whole windows.""" + if patch_size != 2: + raise ValueError( + f"patch_size must be 2, got {patch_size}: the reference reconstruction layer (a stride-2 " + "transposed convolution) only restores the input size for 2x2 patches." + ) + if window_size <= 0: + raise ValueError(f"window_size must be positive, got {window_size}") + if img_size[0] % patch_size or img_size[1] % patch_size: + raise ValueError(f"img_size {img_size} must be divisible by patch_size {patch_size}.") + tokens = (img_size[0] // patch_size, img_size[1] // patch_size) + if tokens[0] % (2 ** levels) or tokens[1] % (2 ** levels): + raise ValueError(f"img_size {img_size}: the {tokens} token grid cannot be halved {levels} times.") + for level in range(levels + 1): + scale = 2 ** level + grid = (tokens[0] // scale, tokens[1] // scale) + window = min(window_size, *grid) # a window never exceeds the grid (Swin rule) + if grid[0] % window or grid[1] % window: + raise ValueError(f"img_size {img_size}: the {grid} token grid is not divisible by window size {window}.") + + +class SwinLSTM(nn.Module): + """SwinLSTM frame forecaster (``variant="d"``: SwinLSTM-D, ``variant="b"``: SwinLSTM-B). + + ``forward`` takes ``(batch, T_in, in_chans, H, W)`` frames and returns the next + ``num_output_frames`` frames ``(batch, T_out, out_chans, H, W)`` in ``[0, 1]`` (sigmoid output), + using the reference rollout: a warm-up phase feeds the first ``T_in - 1`` frames, then the last + input frame starts an autoregressive prediction phase in which each predicted frame is the next + input. ``include_warmup=True`` also returns the ``T_in - 1`` warm-up predictions (frames 2 to + ``T_in``), i.e. the ``T_in - 1 + T_out`` frames the reference loss compares with + ``cat(inputs[:, 1:], targets)``. ``step`` is the reference single-step ``forward``. + """ + + def __init__( + self, + img_size: ImageSize = 64, + patch_size: int = 2, + in_chans: int = 1, + embed_dim: int = 128, + depths_downsample: Sequence[int] = (2, 6), + depths_upsample: Sequence[int] = (6, 2), + num_heads: Sequence[int] = (4, 8), + window_size: int = 4, + variant: str = "d", + depths: Sequence[int] = (12,), + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + qk_scale: Optional[float] = None, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + out_chans: Optional[int] = None, + num_output_frames: int = 10, + ): + super().__init__() + variant = str(variant).lower() + if variant not in {"b", "d"}: + raise ValueError(f"variant must be 'b' (SwinLSTM-B) or 'd' (SwinLSTM-D), got {variant!r}") + if in_chans <= 0: + raise ValueError(f"in_chans must be positive, got {in_chans}") + if out_chans is not None and out_chans <= 0: + raise ValueError(f"out_chans must be positive, got {out_chans}") + if num_output_frames <= 0: + raise ValueError(f"num_output_frames must be positive, got {num_output_frames}") + size = to_2tuple(img_size) + self.variant = variant + self.img_size = size + self.in_chans = int(in_chans) + self.out_chans = self.in_chans if out_chans is None else int(out_chans) + self.num_output_frames = int(num_output_frames) + common = dict( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + window_size=window_size, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rate, + ) + + if variant == "d": + depths_downsample = [int(d) for d in depths_downsample] + depths_upsample = [int(d) for d in depths_upsample] + if not depths_downsample or len(depths_upsample) != len(depths_downsample): + raise ValueError("depths_downsample and depths_upsample must be non-empty and of equal length.") + if len(num_heads) < len(depths_downsample): + raise ValueError("num_heads needs one entry per SwinLSTM-D level.") + _check_geometry(size, patch_size, window_size, levels=len(depths_downsample)) + self.num_layers = len(depths_downsample) + self.Downsample = DownSample(depths_downsample=depths_downsample, num_heads=num_heads, **common) + self.Upsample = UpSample( + depths_upsample=depths_upsample, num_heads=num_heads, out_chans=self.out_chans, **common + ) + else: + depths = [int(d) for d in depths] + if not depths or len(num_heads) < len(depths): + raise ValueError("depths must be non-empty and num_heads needs one entry per SwinLSTM-B cell.") + _check_geometry(size, patch_size, window_size, levels=0) + self.num_layers = len(depths) + self.ST = STconvert(depths=depths, num_heads=num_heads, out_chans=self.out_chans, **common) + + def _step(self, frame: torch.Tensor, states: Optional[tuple], apply_sigmoid: bool = True): + empty = [None] * self.num_layers + if self.variant == "d": + states_down, states_up = states if states is not None else (empty, empty) + states_down, x = self.Downsample(frame, states_down) + states_up, output = self.Upsample(x, states_up, apply_sigmoid=apply_sigmoid) + return output, (states_down, states_up) + (cell_states,) = states if states is not None else (empty,) + cell_states, output = self.ST(frame, cell_states, apply_sigmoid=apply_sigmoid) + return output, (cell_states,) + + def step(self, frame: torch.Tensor, *states): + """One reference time step on a ``(batch, in_chans, H, W)`` frame. + + SwinLSTM-D: ``step(frame, states_down, states_up) -> (output, states_down, states_up)``; + SwinLSTM-B: ``step(frame, states) -> (output, states)``. States may be lists of ``None`` + (or omitted) for zero initial states, as in the reference. + """ + if frame.ndim != 4 or frame.shape[1] != self.in_chans or tuple(frame.shape[-2:]) != self.img_size: + raise ValueError( + f"SwinLSTM.step expects a frame of shape (batch, {self.in_chans}, {self.img_size[0]}, " + f"{self.img_size[1]}), got {tuple(frame.shape)}." + ) + expected = 2 if self.variant == "d" else 1 + if states and len(states) != expected: + raise ValueError(f"SwinLSTM-{self.variant.upper()} step takes {expected} state arguments, got {len(states)}.") + output, new_states = self._step(frame, tuple(states) if states else None) + return (output,) + tuple(new_states) + + def _check_input(self, x: torch.Tensor) -> None: + if x.ndim != 5: + raise ValueError( + "SwinLSTM expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + if x.shape[1] < 1: + raise ValueError("SwinLSTM needs at least one input frame.") + if x.shape[2] != self.in_chans or tuple(x.shape[-2:]) != self.img_size: + raise ValueError( + f"SwinLSTM expects frames of shape ({self.in_chans}, {self.img_size[0]}, {self.img_size[1]}), " + f"got input of shape {tuple(x.shape)}." + ) + + def forward( + self, x: torch.Tensor, num_output_frames: Optional[int] = None, include_warmup: bool = False + ) -> torch.Tensor: + self._check_input(x) + n_out = self.num_output_frames if num_output_frames is None else int(num_output_frames) + if n_out <= 0: + raise ValueError(f"num_output_frames must be positive, got {n_out}") + if n_out > 1 and self.out_chans != self.in_chans: + raise ValueError( + "multi-frame rollout feeds each prediction back as the next input, so it needs " + f"out_chans == in_chans (got {self.out_chans} and {self.in_chans})." + ) + steps = x.shape[1] + states = None + outputs = [] + for t in range(steps - 1): + output, states = self._step(x[:, t], states) + outputs.append(output) + last_input = x[:, -1] + for _ in range(n_out): + output, states = self._step(last_input, states) + outputs.append(output) + last_input = output + frames = torch.stack(outputs, dim=1) + return frames if include_warmup else frames[:, steps - 1 :] + + +class SwinLSTMSegmenter(SwinLSTM): + """PyHazards adaptation for next-step fire masks: ``(batch, T, C, H, W)`` -> ``(batch, out_chans, H, W)``. + + The frames are fed through the reference rollout with one prediction step (warm-up on + ``x[:, :-1]``, prediction from ``x[:, -1]``); the reconstruction layer has ``out_chans`` + channels and its output is returned before the final sigmoid, as logits. Parameter names are + those of :class:`SwinLSTM` (no prefix). + """ + + def __init__(self, out_chans: int = 1, **kwargs): + kwargs.pop("num_output_frames", None) + super().__init__(out_chans=out_chans, num_output_frames=1, **kwargs) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override] + self._check_input(x) + states = None + for t in range(x.shape[1]): + logits, states = self._step(x[:, t], states, apply_sigmoid=False) + return logits + + +def swinlstm_builder( + task: str, + in_channels: int = 1, + out_channels: Optional[int] = None, + img_size: ImageSize = 64, + variant: str = "d", + patch_size: int = 2, + embed_dim: int = 128, + depths_downsample: Sequence[int] = (2, 6), + depths_upsample: Sequence[int] = (6, 2), + depths: Sequence[int] = (12,), + num_heads: Sequence[int] = (4, 8), + window_size: int = 4, + drop_rate: float = 0.0, + attn_drop_rate: float = 0.0, + drop_path_rate: float = 0.1, + num_output_frames: int = 10, + **kwargs, +) -> nn.Module: + """Build SwinLSTM. Defaults are the official Moving-MNIST SwinLSTM-D configuration. + + ``task="forecasting"``: :class:`SwinLSTM` (frames to frames). ``task="segmentation"``: + :class:`SwinLSTMSegmenter`, one output frame of ``out_channels`` (default 1) logits. + """ + _ = kwargs + task = task.lower() + config = dict( + img_size=img_size, + patch_size=patch_size, + in_chans=in_channels, + embed_dim=embed_dim, + depths_downsample=depths_downsample, + depths_upsample=depths_upsample, + num_heads=num_heads, + window_size=window_size, + variant=variant, + depths=depths, + drop_rate=drop_rate, + attn_drop_rate=attn_drop_rate, + drop_path_rate=drop_path_rate, + ) + if task == "forecasting": + return SwinLSTM(out_chans=out_channels, num_output_frames=num_output_frames, **config) + if task == "segmentation": + return SwinLSTMSegmenter(out_chans=1 if out_channels is None else out_channels, **config) + raise ValueError(f"swinlstm supports task='forecasting' or 'segmentation', got {task!r}.") + + +__all__ = [ + "SwinLSTM", + "SwinLSTMBlock", + "SwinLSTMCell", + "SwinLSTMSegmenter", + "swinlstm_builder", +] diff --git a/pyhazards/models/tcif_fusion.py b/pyhazards/models/tcif_fusion.py index a9d03a48..b4c16f41 100644 --- a/pyhazards/models/tcif_fusion.py +++ b/pyhazards/models/tcif_fusion.py @@ -1,68 +1,435 @@ +"""TCIF-fusion: model-knowledge-guided 24-hour tropical cyclone intensity forecasting. + +Paper: C. Wang, X. Li and G. Zheng, "Tropical cyclone intensity forecasting using model knowledge +guided deep learning model", Environmental Research Letters 19, 024006 (2024), +doi:10.1088/1748-9326/ad1bde (open access, CC BY 4.0). + +The official repository (github.com/wangchong96/TCIF-fusion) holds two Keras 2 / TensorFlow 1.x +notebooks and no LICENSE file, so this module is written from the paper (Section 2.3, Figure 1) and the +layer list of the notebook's ``TCIF_fusion()`` graph; the notebook is used only as a test oracle +(tests/oracle/test_tcif_fusion_oracle.py rebuilds its graph in Keras 3) and is never copied. + +TCIF-fusion forecasts the maximum sustained wind (2-minute, m/s) 24 hours ahead from five inputs, all +in the channels-last layout of the official notebook (the paper's "x-y-t-z" arrangement): + +* ``u``, ``v``, ``w``: ERA5 wind components ``(batch, 25, 25, 5, 4)`` - 25 x 25 one-degree grid around + the storm, 5 six-hourly times, 4 pressure levels (200, 500, 850, 1000 hPa) as channels; +* ``sst``: ERA5 sea surface temperature ``(batch, 25, 25, 5, 1)``; +* ``all``: the four ERA5 fields concatenated and reshaped to ``(batch, 25, 25, 65)`` (Figure 1, "ALL"; + built from ``u``, ``v``, ``w``, ``sst`` with :func:`era5_all` when not given); +* ``his``: 30 historical storm features (Figure 1: historical wind speed and pressure) ``(batch, 30)``; +* ``ir``: GridSat-B1 11 um infrared images ``(batch, 224, 224, 5)``. + +Network (``ReLU`` everywhere except the linear output): each ERA5 field has a 3-D CNN branch of three +blocks (three 3 x 3 x 5 convolutions with 128 / 256 / 512 filters and a 2 x 2 x 2 max pooling with +stride (2, 2, 1), Keras "same" padding); a fusion branch adds the four branches' outputs after every +block and runs blocks 2 and 3 on the sums; the ALL input runs through three 2-D blocks (three 3 x 3 +convolutions, 3 x 3 max pooling with stride 2). The flattened maps of the four field branches, the +fusion branch and the ALL branch (212,992 values) go through Dense(256) and Dense(15); the history +through Dense(32) and Dense(64); the IR images through a VGG-19 (filters 64-128-256-512-512, Dense +1024-1024-15). The 94 concatenated features pass two residual blocks of three dense layers (256, 128) +and a linear output. 299,588,223 parameters with the 65-channel ALL input. + +Model knowledge (MK, Section 2.4): a first TCIF-fusion model is trained; Grad-CAM heatmaps of its +inputs are computed; the inputs are multiplied element-wise by the absolute heatmaps and a second +TCIF-fusion is trained on them. :func:`model_knowledge_heatmaps` and :func:`apply_model_knowledge` +implement this step (see their docstrings for the parts the paper leaves open). + +The ALL input of the notebook's graph has 85 channels; the paper's Figure 1 shows 25 x 25 x 65, which is +exactly U, V, W (3 x 5 times x 4 levels) and SST (5 times), and the notebook's model-knowledge example +allocates 65 channels. ``all_channels=65`` (default) follows the paper; ``all_channels=85`` rebuilds the +notebook graph (299,611,263 parameters, the number printed in the notebook). +""" + from __future__ import annotations +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple + +import numpy as np import torch import torch.nn as nn +import torch.nn.functional as F + +#: Training settings of the notebook (paper Section 2.3): MAE loss, Adam 1e-4, batch 512, 100 epochs, +#: ReduceLROnPlateau(factor 0.5, patience 10, min_lr 1e-6) on the validation loss, best checkpoint kept. +TCIF_TRAINING = { + "loss": "mae", + "learning_rate": 1e-4, + "batch_size": 512, + "epochs": 100, + "reduce_lr_on_plateau": {"factor": 0.5, "patience": 10, "min_lr": 1e-6}, +} +ERA5_FIELDS = ("u", "v", "w", "sst") +INPUT_NAMES = ("u", "v", "w", "sst", "all", "his", "ir") + + +def _same_pads(sizes: Sequence[int], kernel: Sequence[int], stride: Sequence[int]) -> List[int]: + """F.pad arguments (last dimension first) for TensorFlow "same" padding.""" + pads: List[int] = [] + for size, k, s in reversed(list(zip(sizes, kernel, stride))): + out = -(-int(size) // int(s)) + total = max((out - 1) * int(s) + int(k) - int(size), 0) + pads += [total // 2, total - total // 2] + return pads + + +def _same_max_pool(x: torch.Tensor, kernel: Sequence[int], stride: Sequence[int]) -> torch.Tensor: + """Max pooling with TensorFlow "same" padding (padded cells never win).""" + pads = _same_pads(x.shape[2:], kernel, stride) + if any(pads): + x = F.pad(x, pads, value=float("-inf")) + pool = F.max_pool3d if len(kernel) == 3 else F.max_pool2d + return pool(x, tuple(kernel), tuple(stride)) + + +def _keras_init(module: nn.Module) -> nn.Module: + """Keras defaults: glorot-uniform kernels, zero biases.""" + nn.init.xavier_uniform_(module.weight) + nn.init.zeros_(module.bias) + return module + + +def _conv3d(c_in: int, c_out: int) -> nn.Conv3d: + return _keras_init(nn.Conv3d(c_in, c_out, kernel_size=(3, 3, 5), padding=(1, 1, 2))) + + +def _conv2d(c_in: int, c_out: int) -> nn.Conv2d: + return _keras_init(nn.Conv2d(c_in, c_out, kernel_size=3, padding=1)) + + +def _dense(n_in: int, n_out: int) -> nn.Linear: + return _keras_init(nn.Linear(n_in, n_out)) + + +class _Block3d(nn.Module): + """Three Conv3D(3 x 3 x 5, "same", ReLU) and MaxPooling3D(2 x 2 x 2, stride (2, 2, 1), "same").""" + + def __init__(self, c_in: int, c_out: int): + super().__init__() + self.conv1 = _conv3d(c_in, c_out) + self.conv2 = _conv3d(c_out, c_out) + self.conv3 = _conv3d(c_out, c_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = F.relu(self.conv3(F.relu(self.conv2(F.relu(self.conv1(x)))))) + return _same_max_pool(x, (2, 2, 2), (2, 2, 1)) + + +class _Block2d(nn.Module): + """Three Conv2D(3 x 3, "same", ReLU) and MaxPooling2D(3 x 3, stride 2, "same").""" + + def __init__(self, c_in: int, c_out: int): + super().__init__() + self.conv1 = _conv2d(c_in, c_out) + self.conv2 = _conv2d(c_out, c_out) + self.conv3 = _conv2d(c_out, c_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = F.relu(self.conv3(F.relu(self.conv2(F.relu(self.conv1(x)))))) + return _same_max_pool(x, (3, 3), (2, 2)) + + +_VGG_LAYOUT = (2, 2, 4, 4, 4) # convolutions per stage + + +class _VGG19(nn.Module): + """VGG-19 on the IR images: 16 Conv2D(3 x 3, ReLU) in five stages with 2 x 2 max pooling, then + Dense(fc) - Dense(fc) - Dense(classes), all with ReLU (the notebook's ``VGG192d``).""" + + def __init__(self, in_channels: int, image_size: int, filters: Sequence[int], fc_dim: int, classes: int): + super().__init__() + self.names: List[str] = [] + width = in_channels + for stage, (count, out) in enumerate(zip(_VGG_LAYOUT, filters), start=1): + for index in range(1, count + 1): + name = f"conv{stage}_{index}" + self.add_module(name, _conv2d(width, out)) + self.names.append(name) + width = out + size = image_size + for _ in _VGG_LAYOUT: + size = -(-size // 2) + self.flat_dim = size * size * width + self.fc1 = _dense(self.flat_dim, fc_dim) + self.fc2 = _dense(fc_dim, fc_dim) + self.prediction = _dense(fc_dim, classes) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + for stage, count in enumerate(_VGG_LAYOUT, start=1): + for index in range(1, count + 1): + x = F.relu(getattr(self, f"conv{stage}_{index}")(x)) + x = _same_max_pool(x, (2, 2), (2, 2)) + x = x.permute(0, 2, 3, 1).flatten(1) # Keras Flatten order (channels last) + return F.relu(self.prediction(F.relu(self.fc2(F.relu(self.fc1(x)))))) + + +def era5_all(u: torch.Tensor, v: torch.Tensor, w: torch.Tensor, sst: torch.Tensor) -> torch.Tensor: + """The ALL input: U, V, W ``(batch, X, Y, T, Z)`` and SST ``(batch, X, Y, T, 1)`` flattened over + (time, level) - time-major - and concatenated, ``(batch, X, Y, 3 T Z + T)`` (65 channels by default).""" + parts = [field.reshape(*field.shape[:3], -1) for field in (u, v, w, sst)] + return torch.cat(parts, dim=-1) class TCIFFusion(nn.Module): - """Knowledge-guided fusion baseline for tropical cyclone forecasting.""" + """TCIF-fusion intensity regressor; see the module docstring for the inputs. + + ``forward(inputs)`` takes a mapping with ``u``, ``v``, ``w``, ``sst``, ``his``, ``ir`` and optionally + ``all`` (built from the ERA5 fields when missing; required when ``all_channels`` is not + ``3 T Z + T``), or the seven tensors positionally in the notebook's input order + ``(u, v, w, sst, all, his, ir)``. Returns ``(batch, 1)``: the 24-hour intensity in the training + target's unit (m/s in the paper). + """ def __init__( self, - input_dim: int = 8, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, + grid_size: int = 25, + time_steps: int = 5, + levels: int = 4, + all_channels: Optional[int] = 65, + his_dim: int = 30, + ir_size: int = 224, + ir_channels: int = 5, + widths: Sequence[int] = (128, 256, 512), + vgg_filters: Sequence[int] = (64, 128, 256, 512, 512), + vgg_fc: int = 1024, + branch_dim: int = 15, + fusion_dim: int = 256, + head_dims: Sequence[int] = (256, 128), ): super().__init__() - self.horizon = int(horizon) - self.output_dim = int(output_dim) - left_dim = max(1, input_dim // 2) - right_dim = input_dim - left_dim - self.left_dim = left_dim - self.left_encoder = nn.GRU(left_dim, hidden_dim, batch_first=True) - self.right_encoder = nn.GRU(max(1, right_dim), hidden_dim, batch_first=True) - self.fusion = nn.Sequential( - nn.Linear(2 * hidden_dim, hidden_dim), - nn.ReLU(), - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), - ) + widths = tuple(int(c) for c in widths) + if len(widths) != 3 or len(tuple(vgg_filters)) != 5 or len(tuple(head_dims)) != 2: + raise ValueError("TCIF-fusion has three ERA5 blocks, five VGG stages and two residual blocks") + self.grid_size, self.time_steps, self.levels = int(grid_size), int(time_steps), int(levels) + self.derived_all_channels = 3 * self.time_steps * self.levels + self.time_steps + self.all_channels = self.derived_all_channels if all_channels is None else int(all_channels) + self.his_dim, self.ir_size, self.ir_channels = int(his_dim), int(ir_size), int(ir_channels) - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("TCIFFusion expects inputs shaped (batch, history, features).") - left = x[:, :, : self.left_dim] - right = x[:, :, self.left_dim :] - if right.size(-1) == 0: - right = x[:, :, :1] - _, left_hidden = self.left_encoder(left) - _, right_hidden = self.right_encoder(right) - fused = torch.cat([left_hidden[-1], right_hidden[-1]], dim=-1) - preds = self.fusion(fused) - return preds.view(x.size(0), self.horizon, self.output_dim) + # Creation order of the notebook graph: 3-D blocks, ALL blocks, ERA5 dense, history, VGG, head. + self.u_block1 = _Block3d(self.levels, widths[0]) + self.v_block1 = _Block3d(self.levels, widths[0]) + self.w_block1 = _Block3d(self.levels, widths[0]) + self.sst_block1 = _Block3d(1, widths[0]) + for stage in (2, 3): + c_in, c_out = widths[stage - 2], widths[stage - 1] + for name in ("u", "v", "w", "sst", "fusion"): + self.add_module(f"{name}_block{stage}", _Block3d(c_in, c_out)) + self.all_block1 = _Block2d(self.all_channels, widths[0]) + self.all_block2 = _Block2d(widths[0], widths[1]) + self.all_block3 = _Block2d(widths[1], widths[2]) + + side = self.grid_size + for _ in range(3): + side = -(-side // 2) + self.era5_flat_dim = 5 * side * side * self.time_steps * widths[2] + side * side * widths[2] + self.era5_dense1 = _dense(self.era5_flat_dim, fusion_dim) + self.era5_dense2 = _dense(fusion_dim, branch_dim) + self.his_dense1 = _dense(self.his_dim, 32) + self.his_dense2 = _dense(32, 64) + self.ir = _VGG19(self.ir_channels, self.ir_size, tuple(vgg_filters), int(vgg_fc), branch_dim) + head_in = branch_dim + 64 + branch_dim + self.res1_dense1 = _dense(head_in, head_dims[0]) + self.res1_dense2 = _dense(head_dims[0], head_dims[0]) + self.res1_dense3 = _dense(head_dims[0], head_dims[0]) + self.res2_dense1 = _dense(head_dims[0], head_dims[1]) + self.res2_dense2 = _dense(head_dims[1], head_dims[1]) + self.res2_dense3 = _dense(head_dims[1], head_dims[1]) + self.output = _dense(head_dims[1], 1) + + # -- inputs -------------------------------------------------------------------------------------- + def _gather(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]) -> Dict[str, torch.Tensor]: + if len(args) == 1 and isinstance(args[0], Mapping): + values = dict(args[0]) + else: + values = dict(zip(INPUT_NAMES, args)) + values.update({k: v for k, v in kwargs.items() if v is not None}) + missing = [name for name in INPUT_NAMES if name != "all" and values.get(name) is None] + if missing: + raise ValueError(f"TCIF-fusion needs inputs {list(INPUT_NAMES)}; missing {missing}") + g, t, z = self.grid_size, self.time_steps, self.levels + expected = { + "u": (g, g, t, z), + "v": (g, g, t, z), + "w": (g, g, t, z), + "sst": (g, g, t, 1), + "all": (g, g, self.all_channels), + "his": (self.his_dim,), + "ir": (self.ir_size, self.ir_size, self.ir_channels), + } + batch = None + for name in (*ERA5_FIELDS, "his", "ir", "all"): + if name == "all" and values.get("all") is None: + if self.all_channels != self.derived_all_channels: + raise ValueError(f"all_channels={self.all_channels} differs from U, V, W, SST ({self.derived_all_channels}); pass inputs['all']") + values["all"] = era5_all(values["u"], values["v"], values["w"], values["sst"]) + tensor = values[name] + if tensor.ndim != len(expected[name]) + 1 or tuple(tensor.shape[1:]) != expected[name]: + raise ValueError(f"TCIF-fusion input {name!r} must be shaped (batch, {', '.join(map(str, expected[name]))}), got {tuple(tensor.shape)}") + if batch is None: + batch = tensor.size(0) + elif tensor.size(0) != batch: + raise ValueError(f"TCIF-fusion inputs have different batch sizes ({name!r} shape {tuple(tensor.shape)})") + return values + + # -- network ------------------------------------------------------------------------------------- + @staticmethod + def _flat3d(x: torch.Tensor) -> torch.Tensor: + return x.permute(0, 2, 3, 4, 1).flatten(1) # Keras Flatten of (X, Y, T, C) + + def forward(self, *args: Any, **kwargs: Any) -> torch.Tensor: + x = self._gather(args, kwargs) + # channels-last (B, X, Y, T, Z) -> (B, Z, X, Y, T) + fields = {name: x[name].permute(0, 4, 1, 2, 3) for name in ERA5_FIELDS} + u, v, w, t = self.u_block1(fields["u"]), self.v_block1(fields["v"]), self.w_block1(fields["w"]), self.sst_block1(fields["sst"]) + fused = u + v + w + t + for stage in (2, 3): + u = getattr(self, f"u_block{stage}")(u) + v = getattr(self, f"v_block{stage}")(v) + w = getattr(self, f"w_block{stage}")(w) + t = getattr(self, f"sst_block{stage}")(t) + c = getattr(self, f"fusion_block{stage}")(fused) + fused = u + v + w + t + c + h = self.all_block3(self.all_block2(self.all_block1(x["all"].permute(0, 3, 1, 2)))) + flat = torch.cat([self._flat3d(u), self._flat3d(v), self._flat3d(w), self._flat3d(t), self._flat3d(fused), h.permute(0, 2, 3, 1).flatten(1)], dim=1) + era5 = F.relu(self.era5_dense2(F.relu(self.era5_dense1(flat)))) + his = F.relu(self.his_dense2(F.relu(self.his_dense1(x["his"])))) + ir = self.ir(x["ir"].permute(0, 3, 1, 2)) + joined = torch.cat([era5, his, ir], dim=1) + first = F.relu(self.res1_dense1(joined)) + joined = F.relu(self.res1_dense3(F.relu(self.res1_dense2(first)))) + first + first = F.relu(self.res2_dense1(joined)) + joined = F.relu(self.res2_dense3(F.relu(self.res2_dense2(first)))) + first + return self.output(joined) + + # -- Keras weights ------------------------------------------------------------------------------- + def keras_layer_names(self) -> Dict[str, str]: + """Keras layer name (the notebook's Keras 2 numbering, as in its printed summary) -> module name.""" + conv3d = [f"{field}_block{stage}.conv{i}" for stage in (1, 2, 3) for field in (("u", "v", "w", "sst") if stage == 1 else ("u", "v", "w", "sst", "fusion")) for i in (1, 2, 3)] + conv2d = [f"all_block{stage}.conv{i}" for stage in (1, 2, 3) for i in (1, 2, 3)] + [f"ir.{name}" for name in self.ir.names] + dense = ["era5_dense1", "era5_dense2", "his_dense1", "his_dense2", "ir.fc1", "ir.fc2", "ir.prediction", "res1_dense1", "res1_dense2", "res1_dense3", "res2_dense1", "res2_dense2", "res2_dense3", "output"] + names = {} + for prefix, modules in (("conv3d", conv3d), ("conv2d", conv2d), ("dense", dense)): + for index, module in enumerate(modules, start=1): + names[f"{prefix}_{index}"] = module + return names + + +def load_keras_weights(model: TCIFFusion, weights: Mapping[str, Sequence[np.ndarray]]) -> TCIFFusion: + """Copy Keras weights ``{layer name: [kernel, bias]}`` (names as in :meth:`TCIFFusion.keras_layer_names`).""" + names = model.keras_layer_names() + missing = sorted(set(names) - set(weights)) + if missing: + raise ValueError(f"missing Keras layers {missing[:5]}{' ...' if len(missing) > 5 else ''}") + modules = dict(model.named_modules()) + with torch.no_grad(): + for keras_name, module_name in names.items(): + kernel, bias = (np.asarray(a) for a in weights[keras_name]) + layer = modules[module_name] + kernel_t = torch.as_tensor(kernel, dtype=layer.weight.dtype) + if kernel_t.ndim == 5: + kernel_t = kernel_t.permute(4, 3, 0, 1, 2) + elif kernel_t.ndim == 4: + kernel_t = kernel_t.permute(3, 2, 0, 1) + else: + kernel_t = kernel_t.T + if kernel_t.shape != layer.weight.shape or tuple(bias.shape) != tuple(layer.bias.shape): + raise ValueError(f"{keras_name} -> {module_name}: kernel {tuple(kernel.shape)} does not fit weight {tuple(layer.weight.shape)}") + layer.weight.copy_(kernel_t) + layer.bias.copy_(torch.as_tensor(bias, dtype=layer.bias.dtype)) + return model + + +# --------------------------------------------------------------------------------------------------- +# Model knowledge (Section 2.4) + +MK_INPUTS = ("u", "v", "w", "sst", "ir") + + +def model_knowledge_heatmaps(model: nn.Module, inputs: Mapping[str, torch.Tensor], names: Iterable[str] = MK_INPUTS) -> Dict[str, torch.Tensor]: + """Grad-CAM heatmaps of the inputs of a trained TCIF-fusion model (the "model knowledge"). + + For every sample and input ``A`` (channels last), the gradient of the forecast with respect to + ``A`` is averaged over the two horizontal axes to give one weight per remaining position and + channel, and the heatmap is the channel mean of ``A`` times these weights: ``(batch, X, Y, T)`` for + the ERA5 fields, ``(batch, H, W)`` for IR. This follows the Grad-CAM recipe the official notebook + starts (gradient of the output w.r.t. an input, pooled over the batch and the horizontal axes); the + notebook stops before forming the heatmap, and the paper gives no normalisation, so none is applied. + """ + names = tuple(names) + leaves = {key: value.detach().clone().requires_grad_(key in names) for key, value in inputs.items()} + was_training = model.training + model.eval() + try: + output = model(leaves) + grads = torch.autograd.grad(output.sum(), [leaves[name] for name in names]) + finally: + model.train(was_training) + heatmaps = {} + for name, grad in zip(names, grads): + weights = grad.mean(dim=(1, 2), keepdim=True) + heatmaps[name] = (leaves[name].detach() * weights).mean(dim=-1) + return heatmaps + + +def apply_model_knowledge(inputs: Mapping[str, torch.Tensor], heatmaps: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + """MK-guided inputs: every input with a heatmap multiplied element-wise by the heatmap's absolute value. + + ALL is rebuilt from the guided ERA5 fields (it is their concatenation, Figure 1) when the inputs + carry the 65-channel layout; HIS is unchanged. + """ + guided = dict(inputs) + for name, heatmap in heatmaps.items(): + guided[name] = inputs[name] * heatmap.abs().unsqueeze(-1) + if any(name in heatmaps for name in ERA5_FIELDS) and all(name in guided for name in ERA5_FIELDS): + derived = era5_all(*(guided[name] for name in ERA5_FIELDS)) + if inputs.get("all") is None or inputs["all"].shape == derived.shape: + guided["all"] = derived + return guided def tcif_fusion_builder( task: str, - input_dim: int = 8, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, - **kwargs, + all_channels: Optional[int] = 65, + grid_size: int = 25, + time_steps: int = 5, + levels: int = 4, + his_dim: int = 30, + ir_size: int = 224, + ir_channels: int = 5, + widths: Sequence[int] = (128, 256, 512), + vgg_filters: Sequence[int] = (64, 128, 256, 512, 512), + vgg_fc: int = 1024, + **kwargs: Any, ) -> nn.Module: + """TCIF-fusion; the defaults are the paper's model (``all_channels=85`` gives the notebook graph). + + The size arguments only exist to build small copies for smoke tests; checked are the defaults. + """ _ = kwargs if task.lower() != "regression": - raise ValueError("TCIFFusion only supports regression for track/intensity forecasting.") + raise ValueError("tcif_fusion is a regression model (24-hour intensity); use task='regression'.") return TCIFFusion( - input_dim=input_dim, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - dropout=dropout, + grid_size=grid_size, + time_steps=time_steps, + levels=levels, + all_channels=all_channels, + his_dim=his_dim, + ir_size=ir_size, + ir_channels=ir_channels, + widths=widths, + vgg_filters=vgg_filters, + vgg_fc=vgg_fc, ) -__all__ = ["TCIFFusion", "tcif_fusion_builder"] +__all__ = [ + "INPUT_NAMES", + "MK_INPUTS", + "TCIF_TRAINING", + "TCIFFusion", + "apply_model_knowledge", + "era5_all", + "load_keras_weights", + "model_knowledge_heatmaps", + "tcif_fusion_builder", +] diff --git a/pyhazards/models/tcn.py b/pyhazards/models/tcn.py new file mode 100644 index 00000000..4b664bb2 --- /dev/null +++ b/pyhazards/models/tcn.py @@ -0,0 +1,268 @@ +"""Temporal Convolutional Network (Bai, Kolter & Koltun, 2018). + +Port of ``TemporalConvNet``, ``TemporalBlock`` and ``Chomp1d`` from the official repository +locuslab/TCN (``TCN/tcn.py`` at 2f8c2b8, MIT License, Copyright (c) 2018 CMU Locus Lab), plus the +linear task heads of its examples (``TCN/adding_problem/model.py``, ``TCN/mnist_pixel/model.py``, +``TCN/copy_memory/model.py``, ``TCN/poly_music/model.py``). + +Each residual block is two causal dilated convolutions (left padding ``(k - 1) * d`` followed by a +chomp of the same length), each with weight normalisation, ReLU and dropout, plus a 1x1 +convolution on the residual path when the width changes. Level ``i`` uses dilation ``2 ** i``. + +Two choices differ from the official file without changing its numbers: + +* Weight normalisation uses ``torch.nn.utils.parametrizations.weight_norm`` instead of the + deprecated hook-based ``torch.nn.utils.weight_norm``. Both compute ``g * v / ||v||`` with + ``torch._weight_norm`` and initialise ``g = ||w||``, ``v = w`` from the same convolution weight. + The parameters are stored as ``.parametrizations.weight.original0`` (g) and ``.original1`` + (v) instead of ``.weight_g`` / ``.weight_v``. Official state dicts load with + ``strict=True`` regardless, because PyTorch's parametrisation renames ``weight_g`` / ``weight_v`` + while loading; :func:`to_official_state_dict` converts in the other direction. +* :class:`TCN` takes PyHazards' ``(batch, time, features)`` layout and transposes it to the + ``(batch, channels, length)`` layout of the official code; :class:`TemporalConvNet` keeps the + official layout. + +As in the official code, ``init_weights`` draws ``N(0, 0.01)`` into the *computed* weights of the +two weight-normalised convolutions. Those values are discarded, because weight norm recomputes +the weight from ``g`` and ``v`` on every forward pass, so the effective initialisation of these +convolutions is PyTorch's default one; only the 1x1 residual convolution (and the adding-problem +style linear head) really receives ``N(0, 0.01)``. The draws are kept so that a given seed +produces the same parameters as the official code. +""" + +from __future__ import annotations + +from typing import Dict, Mapping, Optional, Sequence + +import torch +import torch.nn as nn +from torch.nn.utils.parametrizations import weight_norm + +_PARAMETRIZED_G = "parametrizations.weight.original0" +_PARAMETRIZED_V = "parametrizations.weight.original1" + + +class Chomp1d(nn.Module): + """Drop the last ``chomp_size`` steps, which turns symmetric padding into causal padding.""" + + def __init__(self, chomp_size: int): + super().__init__() + self.chomp_size = chomp_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x[:, :, : -self.chomp_size].contiguous() + + +class TemporalBlock(nn.Module): + """Residual block of two weight-normalised causal dilated convolutions.""" + + def __init__( + self, + n_inputs: int, + n_outputs: int, + kernel_size: int, + stride: int, + dilation: int, + padding: int, + dropout: float = 0.2, + ): + super().__init__() + if padding <= 0: + raise ValueError( + "TemporalBlock needs padding = (kernel_size - 1) * dilation > 0, i.e. kernel_size >= 2; " + f"got padding={padding}." + ) + self.conv1 = weight_norm( + nn.Conv1d(n_inputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation) + ) + self.chomp1 = Chomp1d(padding) + self.relu1 = nn.ReLU() + self.dropout1 = nn.Dropout(dropout) + + self.conv2 = weight_norm( + nn.Conv1d(n_outputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation) + ) + self.chomp2 = Chomp1d(padding) + self.relu2 = nn.ReLU() + self.dropout2 = nn.Dropout(dropout) + + # The official code registers the layers twice (as attributes and inside ``net``), so its + # state dicts contain both ``conv1.*`` and ``net.0.*`` keys; keep the same structure. + self.net = nn.Sequential( + self.conv1, self.chomp1, self.relu1, self.dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2 + ) + self.downsample = nn.Conv1d(n_inputs, n_outputs, 1) if n_inputs != n_outputs else None + self.relu = nn.ReLU() + self.init_weights() + + def init_weights(self) -> None: + # Official initialisation. For conv1/conv2 the draws land in the computed weight, which + # weight norm discards (see the module docstring); they are kept for seed compatibility. + self.conv1.weight.data.normal_(0, 0.01) + self.conv2.weight.data.normal_(0, 0.01) + if self.downsample is not None: + self.downsample.weight.data.normal_(0, 0.01) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + out = self.net(x) + res = x if self.downsample is None else self.downsample(x) + return self.relu(out + res) + + +class TemporalConvNet(nn.Module): + """Stack of :class:`TemporalBlock` with dilations ``1, 2, 4, ...`` (official layout). + + Input ``(batch, num_inputs, length)``; output ``(batch, num_channels[-1], length)``. The output + at step ``t`` depends only on inputs ``<= t``; the receptive field is + ``1 + 2 * (kernel_size - 1) * (2 ** levels - 1)`` steps. + """ + + def __init__(self, num_inputs: int, num_channels: Sequence[int], kernel_size: int = 2, dropout: float = 0.2): + super().__init__() + if num_inputs <= 0: + raise ValueError(f"num_inputs must be positive, got {num_inputs}") + if len(num_channels) == 0 or any(int(c) <= 0 for c in num_channels): + raise ValueError(f"num_channels must be a non-empty list of positive widths, got {num_channels!r}") + if kernel_size < 2: + raise ValueError(f"kernel_size must be >= 2 for the causal chomp, got {kernel_size}") + layers = [] + num_levels = len(num_channels) + for i in range(num_levels): + dilation_size = 2**i + in_channels = num_inputs if i == 0 else num_channels[i - 1] + out_channels = num_channels[i] + layers += [ + TemporalBlock( + in_channels, + out_channels, + kernel_size, + stride=1, + dilation=dilation_size, + padding=(kernel_size - 1) * dilation_size, + dropout=dropout, + ) + ] + self.network = nn.Sequential(*layers) + self.num_inputs = int(num_inputs) + self.kernel_size = int(kernel_size) + self.num_levels = num_levels + + @property + def receptive_field(self) -> int: + return 1 + 2 * (self.kernel_size - 1) * (2**self.num_levels - 1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 3 or x.size(1) != self.num_inputs: + raise ValueError( + f"TemporalConvNet expects input shape (batch, {self.num_inputs}, length), got {tuple(x.shape)}." + ) + return self.network(x) + + +class TCN(nn.Module): + """:class:`TemporalConvNet` with the linear heads of the official examples. + + Args: + input_size: features per time step. + output_size: outputs (classes or regression targets). + num_channels: width of each level. + kernel_size: temporal kernel size. + dropout: dropout inside the temporal blocks. + readout: ``"last"`` applies the head to the last time step (adding problem, sequential + MNIST) and returns ``(batch, output_size)``; ``"sequence"`` applies it to every step + (copy memory, polyphonic music) and returns ``(batch, time, output_size)``. + head_init: ``"normal"`` draws the head weight from ``N(0, 0.01)`` (adding problem, copy + memory); ``"default"`` keeps PyTorch's initialisation (sequential MNIST, music). + + Input ``(batch, time, input_size)``. Outputs are raw scores: the official sequential-MNIST + head's ``log_softmax`` and the music head's ``sigmoid`` belong in the loss. + """ + + def __init__( + self, + input_size: int, + output_size: int, + num_channels: Sequence[int], + kernel_size: int = 2, + dropout: float = 0.2, + readout: str = "last", + head_init: str = "normal", + ): + super().__init__() + if output_size <= 0: + raise ValueError(f"output_size must be positive, got {output_size}") + if readout not in {"last", "sequence"}: + raise ValueError(f"readout must be 'last' or 'sequence', got {readout!r}") + if head_init not in {"normal", "default"}: + raise ValueError(f"head_init must be 'normal' or 'default', got {head_init!r}") + self.tcn = TemporalConvNet(input_size, num_channels, kernel_size=kernel_size, dropout=dropout) + self.linear = nn.Linear(num_channels[-1], output_size) + self.input_size = int(input_size) + self.readout = readout + if head_init == "normal": + self.linear.weight.data.normal_(0, 0.01) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 3 or x.size(-1) != self.input_size: + raise ValueError( + f"TCN expects input shape (batch, time, {self.input_size}), got {tuple(x.shape)}." + ) + y = self.tcn(x.transpose(1, 2)) + if self.readout == "last": + return self.linear(y[:, :, -1]) + return self.linear(y.transpose(1, 2)) + + +def to_official_state_dict(state_dict: Mapping[str, torch.Tensor]) -> Dict[str, torch.Tensor]: + """Rename weight-norm parameters to the official ``weight_g`` / ``weight_v`` keys. + + The result loads with ``strict=True`` into the locuslab/TCN modules. The reverse direction + needs no conversion: PyHazards modules accept official state dicts directly. + """ + converted: Dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + if key.endswith(_PARAMETRIZED_G): + key = key[: -len(_PARAMETRIZED_G)] + "weight_g" + elif key.endswith(_PARAMETRIZED_V): + key = key[: -len(_PARAMETRIZED_V)] + "weight_v" + converted[key] = value + return converted + + +def tcn_builder( + task: str, + input_dim: int = 2, + out_dim: int = 1, + hidden_dim: int = 30, + num_levels: int = 8, + num_channels: Optional[Sequence[int]] = None, + kernel_size: int = 7, + dropout: float = 0.0, + readout: str = "last", + head_init: str = "normal", + **kwargs, +) -> nn.Module: + """Build a :class:`TCN`; the defaults are the official adding-problem model. + + ``num_channels`` overrides ``hidden_dim`` / ``num_levels`` (``[hidden_dim] * num_levels``, as + in the official scripts). + """ + _ = kwargs + if task.lower() not in {"classification", "regression"}: + raise ValueError(f"tcn supports task='classification' or 'regression', got {task!r}.") + if num_channels is None: + if num_levels <= 0 or hidden_dim <= 0: + raise ValueError("hidden_dim and num_levels must be positive.") + num_channels = [hidden_dim] * num_levels + return TCN( + input_size=input_dim, + output_size=out_dim, + num_channels=list(num_channels), + kernel_size=kernel_size, + dropout=dropout, + readout=readout, + head_init=head_init, + ) + + +__all__ = ["Chomp1d", "TemporalBlock", "TemporalConvNet", "TCN", "to_official_state_dict", "tcn_builder"] diff --git a/pyhazards/models/trajgru.py b/pyhazards/models/trajgru.py new file mode 100644 index 00000000..a050b695 --- /dev/null +++ b/pyhazards/models/trajgru.py @@ -0,0 +1,622 @@ +"""TrajGRU encoder-forecaster for precipitation nowcasting (Shi et al., NeurIPS 2017). + +Attribution: ported to PyTorch from the official MXNet code, sxjscience/HKO-7 at commit +``57b987bd893bd6910996494c247359ace371d333`` (MIT License, Copyright (c) 2017-2027 Xingjian Shi +and others): ``nowcasting/operators/traj_rnn.py`` (TrajGRU cell), ``nowcasting/operators/conv_rnn.py`` +(the ConvGRU cell of the paper's baselines), ``nowcasting/operators/base_rnn.py`` (stacked RNN +blocks), ``nowcasting/encoder_forecaster.py`` and ``nowcasting/prediction_base_factory.py`` +(encoder-forecaster wiring and input coordinates) and ``nowcasting/ops.py`` (activations, +down/up-sampling modules). + +Module names are chosen so that a parameter's PyTorch key with ``.`` replaced by ``_`` is its MXNet +name (``ebrnn1.0.i2h.weight`` <-> ``ebrnn1_0_i2h_weight``); :func:`load_hko7_params` loads the +official ``encoder_net-*.params`` / ``forecaster_net-*.params`` arrays. +""" + +from __future__ import annotations + +import math +from typing import Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +Pair = Tuple[int, int] +IntOrPair = Union[int, Sequence[int]] + +LEAKY_SLOPE = 0.2 # nowcasting/ops.py: LeakyReLU(slope=0.2) for act_type="leaky" +FLOW_CHANNELS = 32 # hidden channels of the TrajGRU flow generator (traj_rnn.py) +FLOW_KERNEL = 5 + + +def _pair(value: IntOrPair) -> Pair: + if isinstance(value, (list, tuple)): + if len(value) != 2: + raise ValueError(f"expected an int or a pair, got {value!r}") + return int(value[0]), int(value[1]) + return int(value), int(value) + + +def activation(x: torch.Tensor, act_type: str) -> torch.Tensor: + """``nowcasting.ops.activation``: leaky (slope 0.2), identity, or an ``mx.sym.Activation`` type.""" + if act_type == "leaky": + return F.leaky_relu(x, LEAKY_SLOPE) + if act_type == "identity": + return x + if act_type == "tanh": + return torch.tanh(x) + if act_type == "relu": + return F.relu(x) + if act_type == "sigmoid": + return torch.sigmoid(x) + raise ValueError(f"unsupported act_type {act_type!r}") + + +def _check_act(act_type: str) -> str: + if act_type not in {"leaky", "identity", "tanh", "relu", "sigmoid"}: + raise ValueError(f"unsupported act_type {act_type!r}") + return act_type + + +def warp(data: torch.Tensor, flows: torch.Tensor) -> torch.Tensor: + """Warp ``data`` (B, C, H, W) by each of the L flow fields in ``flows`` (B, 2L, H, W). + + As in ``traj_rnn.flow_conv``: ``GridGenerator(data=-flow, transform_type="warp")`` followed by + ``BilinearSampler``, i.e. output pixel ``(y, x)`` bilinearly samples ``data`` at + ``(y - flow_y, x - flow_x)`` (channel 0 of each flow is x, channel 1 is y), with zeros outside + the map. Returns the L warped maps concatenated along channels: (B, L * C, H, W). + """ + if data.ndim != 4 or flows.ndim != 4 or flows.shape[1] % 2: + raise ValueError( + f"warp expects data (B, C, H, W) and flows (B, 2L, H, W), got {tuple(data.shape)} and {tuple(flows.shape)}" + ) + b, c, h, w = data.shape + links = flows.shape[1] // 2 + flows = flows.view(b, links, 2, h, w) + xs = torch.arange(w, dtype=data.dtype, device=data.device).view(1, 1, 1, w) + ys = torch.arange(h, dtype=data.dtype, device=data.device).view(1, 1, h, 1) + # MXNet normalises to [-1, 1] with the corner-aligned convention: (pos) / ((size - 1) / 2) - 1. + grid_x = (xs - flows[:, :, 0]) / ((w - 1) / 2.0) - 1.0 + grid_y = (ys - flows[:, :, 1]) / ((h - 1) / 2.0) - 1.0 + grid = torch.stack((grid_x, grid_y), dim=-1).view(b * links, h, w, 2) + repeated = data.unsqueeze(1).expand(b, links, c, h, w).reshape(b * links, c, h, w) + warped = F.grid_sample(repeated, grid, mode="bilinear", padding_mode="zeros", align_corners=True) + return warped.view(b, links * c, h, w) + + +class TrajGRUCell(nn.Module): + """TrajGRU cell (paper Eq. 4; ``traj_rnn.TrajGRU``). + + A small network ``f_out(act(i2f_conv1(x) + h2f_conv1(h)))`` predicts L flow fields; the + previous state is warped along each and mixed by the 1x1 ``h2h`` convolution. Gates: + ``r = sigmoid(i2h_r + h2h_r)``, ``u = sigmoid(i2h_u + h2h_u)``, + ``h' = act(i2h_h + r * h2h_h)``, ``h_t = u * h_{t-1} + (1 - u) * h'``. A cell built with + ``input_channels=None`` takes no input (the top forecaster block) and has no ``i2h`` or + ``i2f_conv1``. + """ + + def __init__( + self, + input_channels: Optional[int], + num_filter: int, + L: int = 5, + i2h_kernel: IntOrPair = 3, + i2h_pad: IntOrPair = 1, + act_type: str = "leaky", + init_grid: bool = True, + ): + super().__init__() + if num_filter <= 0 or L <= 0: + raise ValueError(f"num_filter and L must be positive, got {num_filter} and {L}") + self.input_channels = input_channels + self.num_filter = int(num_filter) + self.L = int(L) + self.act_type = _check_act(act_type) + self.init_grid = bool(init_grid) + pad = FLOW_KERNEL // 2 + if input_channels is not None: + self.i2h = nn.Conv2d(input_channels, 3 * num_filter, _pair(i2h_kernel), padding=_pair(i2h_pad)) + self.i2f_conv1 = nn.Conv2d(input_channels, FLOW_CHANNELS, FLOW_KERNEL, padding=pad) + self.h2f_conv1 = nn.Conv2d(num_filter, FLOW_CHANNELS, FLOW_KERNEL, padding=pad) + self.f_out = nn.Conv2d(FLOW_CHANNELS, 2 * L, FLOW_KERNEL, padding=pad) + self.h2h = nn.Conv2d(L * num_filter, 3 * num_filter, 1) + + def flows(self, inputs: Optional[torch.Tensor], state: torch.Tensor) -> torch.Tensor: + """The L flow fields ``(B, 2L, H, W)`` (x then y offset per link).""" + f = self.h2f_conv1(state) + if inputs is not None: + f = self.i2f_conv1(inputs) + f + return self.f_out(activation(f, self.act_type)) + + def forward(self, inputs: Optional[torch.Tensor], state: Optional[torch.Tensor] = None) -> torch.Tensor: + if (inputs is None) != (self.input_channels is None): + raise ValueError("this TrajGRU cell was built " + ("without" if self.input_channels is None else "with") + " an input") + i2h = self.i2h(inputs) if inputs is not None else None + if state is None: + if i2h is None: + raise ValueError("a TrajGRU cell without input needs an explicit state") + state = i2h.new_zeros(i2h.shape[0], self.num_filter, i2h.shape[2], i2h.shape[3]) + h2h = self.h2h(warp(state, self.flows(inputs, state))) + h2h_r, h2h_u, h2h_h = torch.chunk(h2h, 3, dim=1) + if i2h is not None: + i2h_r, i2h_u, i2h_h = torch.chunk(i2h, 3, dim=1) + reset = torch.sigmoid(i2h_r + h2h_r) + update = torch.sigmoid(i2h_u + h2h_u) + new_mem = activation(i2h_h + reset * h2h_h, self.act_type) + else: + reset = torch.sigmoid(h2h_r) + update = torch.sigmoid(h2h_u) + new_mem = activation(reset * h2h_h, self.act_type) + return update * state + (1 - update) * new_mem + + +class EFConvGRUCell(nn.Module): + """The ConvGRU cell of the HKO-7 baselines (``conv_rnn.ConvGRU``). + + Unlike Ballas et al. (``pyhazards.models.convgru``), the reset gate multiplies the state-to-state + convolution (``h' = act(i2h_h + r * h2h_h)``), input and state convolutions have separate biases, + and ``h_t = u * h_{t-1} + (1 - u) * h'``. + """ + + def __init__( + self, + input_channels: Optional[int], + num_filter: int, + h2h_kernel: IntOrPair = 3, + h2h_dilate: IntOrPair = 1, + i2h_kernel: IntOrPair = 3, + i2h_pad: IntOrPair = 1, + act_type: str = "leaky", + ): + super().__init__() + kernel, dilate = _pair(h2h_kernel), _pair(h2h_dilate) + if kernel[0] % 2 == 0 or kernel[1] % 2 == 0: + raise ValueError(f"h2h_kernel must be odd, got {kernel}") + self.input_channels = input_channels + self.num_filter = int(num_filter) + self.act_type = _check_act(act_type) + if input_channels is not None: + self.i2h = nn.Conv2d(input_channels, 3 * num_filter, _pair(i2h_kernel), padding=_pair(i2h_pad)) + padding = (dilate[0] * (kernel[0] - 1) // 2, dilate[1] * (kernel[1] - 1) // 2) + self.h2h = nn.Conv2d(num_filter, 3 * num_filter, kernel, padding=padding, dilation=dilate) + + def forward(self, inputs: Optional[torch.Tensor], state: Optional[torch.Tensor] = None) -> torch.Tensor: + if (inputs is None) != (self.input_channels is None): + raise ValueError("this ConvGRU cell was built " + ("without" if self.input_channels is None else "with") + " an input") + i2h = self.i2h(inputs) if inputs is not None else None + if state is None: + if i2h is None: + raise ValueError("a ConvGRU cell without input needs an explicit state") + state = i2h.new_zeros(i2h.shape[0], self.num_filter, i2h.shape[2], i2h.shape[3]) + h2h_r, h2h_u, h2h_h = torch.chunk(self.h2h(state), 3, dim=1) + if i2h is not None: + i2h_r, i2h_u, i2h_h = torch.chunk(i2h, 3, dim=1) + reset = torch.sigmoid(i2h_r + h2h_r) + update = torch.sigmoid(i2h_u + h2h_u) + new_mem = activation(i2h_h + reset * h2h_h, self.act_type) + else: + reset = torch.sigmoid(h2h_r) + update = torch.sigmoid(h2h_u) + new_mem = activation(reset * h2h_h, self.act_type) + return update * state + (1 - update) * new_mem + + +class _ConvAct(nn.Module): + """``conv2d_act``: convolution with bias, then the CNN activation (``edown*_conv``).""" + + def __init__(self, in_channels: int, out_channels: int, kernel: int, stride: int, pad: int, act_type: str): + super().__init__() + self.act_type = act_type + self.conv = nn.Conv2d(in_channels, out_channels, kernel, stride=stride, padding=pad) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return activation(self.conv(x), self.act_type) + + +class _DeconvAct(nn.Module): + """``deconv2d_act``: transposed convolution *without* bias, then the CNN activation (``fup*_deconv``).""" + + def __init__(self, in_channels: int, out_channels: int, kernel: int, stride: int, pad: int, act_type: str): + super().__init__() + self.act_type = act_type + self.deconv = nn.ConvTranspose2d(in_channels, out_channels, kernel, stride=stride, padding=pad, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return activation(self.deconv(x), self.act_type) + + +def _conv_out(size: int, kernel: int, stride: int, pad: int) -> int: + return (size + 2 * pad - kernel) // stride + 1 + + +def _deconv_out(size: int, kernel: int, stride: int, pad: int) -> int: + return (size - 1) * stride - 2 * pad + kernel + + +# The architecture fields of the official configurations (HKO-7 experiments/*/configurations). +TRAJGRU_CONFIGS: Dict[str, Dict[str, object]] = { + # experiments/hko/configurations/trajgru_55_55_33_1_64_1_192_1_192_13_13_9_b4.yml (480x480 radar maps) + "hko7": dict( + num_filter=(64, 192, 192), + L=(13, 13, 9), + h2h_kernel=((5, 5), (5, 5), (3, 3)), + h2h_dilate=((1, 1), (1, 1), (1, 1)), + i2h_kernel=((3, 3), (3, 3), (3, 3)), + i2h_pad=((1, 1), (1, 1), (1, 1)), + stack_num=(1, 1, 1), + first_conv=(8, 7, 5, 1), + last_deconv=(8, 7, 5, 1), + downsample=((5, 3, 1), (3, 2, 1)), + upsample=((5, 3, 1), (4, 2, 1)), + num_output_frames=20, + ), + # experiments/movingmnist/configurations/trajgru_1_64_1_96_1_96_L13.yml (64x64 MovingMNIST++) + "movingmnist": dict( + num_filter=(64, 96, 96), + L=(13, 13, 13), + h2h_kernel=((5, 5), (5, 5), (5, 5)), + h2h_dilate=((1, 1), (1, 1), (1, 1)), + i2h_kernel=((3, 3), (3, 3), (3, 3)), + i2h_pad=((1, 1), (1, 1), (1, 1)), + stack_num=(1, 1, 1), + first_conv=(16, 3, 1, 1), + last_deconv=(16, 3, 1, 1), + downsample=((3, 2, 1), (3, 2, 1)), + upsample=((4, 2, 1), (4, 2, 1)), + num_output_frames=10, + ), +} + + +def _per_block(value, n: int, name: str) -> list: + """Broadcast a scalar (or string) setting to the ``n`` RNN blocks, or check one entry per block.""" + if isinstance(value, (str, int)): + return [value] * n + value = list(value) + if len(value) != n: + raise ValueError(f"{name} needs {n} entries (one per RNN block), got {len(value)}") + return value + + +class TrajGRU(nn.Module): + """HKO-7 encoder-forecaster with TrajGRU (or ConvGRU) blocks, frames to frames. + + Input ``(batch, T_in, in_channels, H, W)``; output ``(batch, T_out, out_channels, H, W)``. + Each input frame is concatenated with x/y coordinates in [-1, 1] and a channel of ones + (``_pre_encode_frame``), embedded by ``econv1`` and encoded by RNN blocks ``ebrnn1..n`` joined by + strided convolutions ``edown*``. The forecaster blocks ``fbrnn n..1`` start from the encoder's + final states (stack order reversed); the top block runs without input, lower blocks take the + up-sampled outputs (``fup*``) of the block above. The bottom block's outputs go through + ``fdeconv1``, ``conv_final`` and the 1x1 ``out`` convolution (no output activation). + """ + + def __init__( + self, + in_channels: int = 1, + out_channels: int = 1, + num_filter: Sequence[int] = (64, 192, 192), + layer_type: Union[str, Sequence[str]] = "TrajGRU", + L: Union[int, Sequence[int]] = (13, 13, 9), + h2h_kernel=((5, 5), (5, 5), (3, 3)), + h2h_dilate=((1, 1), (1, 1), (1, 1)), + i2h_kernel=((3, 3), (3, 3), (3, 3)), + i2h_pad=((1, 1), (1, 1), (1, 1)), + stack_num: Union[int, Sequence[int]] = (1, 1, 1), + first_conv: Sequence[int] = (8, 7, 5, 1), + last_deconv: Sequence[int] = (8, 7, 5, 1), + downsample: Sequence[Sequence[int]] = ((5, 3, 1), (3, 2, 1)), + upsample: Sequence[Sequence[int]] = ((5, 3, 1), (4, 2, 1)), + rnn_act_type: str = "leaky", + cnn_act_type: str = "leaky", + residual_connection: bool = True, + init_grid: bool = True, + num_output_frames: int = 20, + ): + super().__init__() + n = len(num_filter) + if n < 1: + raise ValueError("num_filter needs at least one RNN block") + if in_channels <= 0 or out_channels <= 0: + raise ValueError(f"in_channels and out_channels must be positive, got {in_channels} and {out_channels}") + if num_output_frames <= 0: + raise ValueError(f"num_output_frames must be positive, got {num_output_frames}") + if len(first_conv) != 4 or len(last_deconv) != 4: + raise ValueError("first_conv and last_deconv are (num_filter, kernel, stride, pad)") + if len(downsample) != n - 1 or len(upsample) != n - 1: + raise ValueError(f"downsample and upsample need {n - 1} (kernel, stride, pad) entries") + layer_types = _per_block(layer_type, n, "layer_type") + for kind in layer_types: + if kind not in {"TrajGRU", "ConvGRU"}: + raise ValueError(f"layer_type must be 'TrajGRU' or 'ConvGRU', got {kind!r}") + links = _per_block(L, n, "L") + h2h_kernels = _per_block(h2h_kernel, n, "h2h_kernel") + h2h_dilates = _per_block(h2h_dilate, n, "h2h_dilate") + i2h_kernels = _per_block(i2h_kernel, n, "i2h_kernel") + i2h_pads = _per_block(i2h_pad, n, "i2h_pad") + stacks = [int(s) for s in _per_block(stack_num, n, "stack_num")] + if min(stacks) < 1: + raise ValueError(f"stack_num entries must be positive, got {stacks}") + for kernel, pad in zip(i2h_kernels, i2h_pads): + kernel, pad = _pair(kernel), _pair(pad) + if kernel[0] != 2 * pad[0] + 1 or kernel[1] != 2 * pad[1] + 1: + # The encoder-forecaster wiring assumes the state has the size of the block input. + raise ValueError(f"i2h_kernel {kernel} with i2h_pad {pad} does not preserve the feature-map size") + self.in_channels = int(in_channels) + self.out_channels = int(out_channels) + self.num_filter = [int(f) for f in num_filter] + self.layer_type = layer_types + self.num_blocks = n + self.first_conv = tuple(int(v) for v in first_conv) + self.last_deconv = tuple(int(v) for v in last_deconv) + self.downsample = [tuple(int(v) for v in d) for d in downsample] + self.upsample = [tuple(int(v) for v in u) for u in upsample] + self.rnn_act_type = _check_act(rnn_act_type) + self.cnn_act_type = _check_act(cnn_act_type) + self.residual_connection = bool(residual_connection) + self.num_output_frames = int(num_output_frames) + + def make_cell(i: int, input_channels: Optional[int]) -> nn.Module: + if layer_types[i] == "TrajGRU": + return TrajGRUCell( + input_channels, self.num_filter[i], L=int(links[i]), i2h_kernel=i2h_kernels[i], + i2h_pad=i2h_pads[i], act_type=rnn_act_type, init_grid=init_grid, + ) + return EFConvGRUCell( + input_channels, self.num_filter[i], h2h_kernel=h2h_kernels[i], h2h_dilate=h2h_dilates[i], + i2h_kernel=i2h_kernels[i], i2h_pad=i2h_pads[i], act_type=rnn_act_type, + ) + + def make_block(i: int, input_channels: Optional[int]) -> nn.ModuleList: + # Stacked cells after the first take the previous cell's output (num_filter[i] channels). + return nn.ModuleList( + make_cell(i, input_channels if j == 0 else self.num_filter[i]) for j in range(stacks[i]) + ) + + # Encoder: 3 coordinate channels (x, y, ones) are appended to every frame. + c, k, s, p = self.first_conv + self.econv1 = nn.Conv2d(self.in_channels + 3, c, k, stride=s, padding=p) + for i in range(n): + setattr(self, f"ebrnn{i + 1}", make_block(i, c if i == 0 else self.num_filter[i])) + if i < n - 1: + k, s, p = self.downsample[i] + setattr(self, f"edown{i + 1}", _ConvAct(self.num_filter[i], self.num_filter[i + 1], k, s, p, cnn_act_type)) + # Forecaster: the top block has no input; block i < n - 1 takes fup{i + 1}'s output. + for i in reversed(range(n)): + setattr(self, f"fbrnn{i + 1}", make_block(i, None if i == n - 1 else self.num_filter[i + 1])) + if i > 0: + k, s, p = self.upsample[i - 1] + setattr(self, f"fup{i}", _DeconvAct(self.num_filter[i], self.num_filter[i], k, s, p, cnn_act_type)) + c, k, s, p = self.last_deconv + self.fdeconv1 = nn.ConvTranspose2d(self.num_filter[0], c, k, stride=s, padding=p, bias=False) + self.conv_final = nn.Conv2d(c, c, 3, padding=1) + self.out = nn.Conv2d(c, self.out_channels, 1) + self.reset_parameters() + + def reset_parameters(self, slope: float = 0.2) -> None: + """Reference initialisation: ``mx.init.MSRAPrelu(slope=0.2)`` for every weight (Gaussian, + ``std = sqrt(2 / (1 + slope**2) / fan_avg)``), zero biases, and (``init_grid``) zeros for + the flow output layer ``f_out`` so that every link starts as the identity warp.""" + magnitude = 2.0 / (1.0 + slope ** 2) + for module in self.modules(): + if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)): + weight = module.weight + receptive = weight[0][0].numel() + fan_avg = (weight.shape[0] + weight.shape[1]) * receptive / 2.0 + with torch.no_grad(): + weight.normal_(0.0, math.sqrt(magnitude / fan_avg)) + if module.bias is not None: + module.bias.zero_() + for module in self.modules(): + if isinstance(module, TrajGRUCell) and module.init_grid: + with torch.no_grad(): + module.f_out.weight.zero_() + module.f_out.bias.zero_() + + def _sizes(self, size: int) -> List[int]: + _, k, s, p = self.first_conv + sizes = [_conv_out(size, k, s, p)] + for k, s, p in self.downsample: + sizes.append(_conv_out(sizes[-1], k, s, p)) + return sizes + + def check_input_size(self, height: int, width: int) -> None: + """Raise ``ValueError`` unless the decoder restores every encoder feature map and the input size.""" + for size in (height, width): + sizes = self._sizes(size) + if min(sizes) < 1: + raise ValueError(f"input size {size} is too small for this configuration") + for i in range(1, self.num_blocks): + k, s, p = self.upsample[i - 1] + if _deconv_out(sizes[i], k, s, p) != sizes[i - 1]: + raise ValueError( + f"input size {(height, width)}: up-sampling block {i + 1} gives " + f"{_deconv_out(sizes[i], k, s, p)} pixels, block {i} expects {sizes[i - 1]} " + f"(encoder feature sizes {sizes})." + ) + _, k, s, p = self.last_deconv + if _deconv_out(sizes[0], k, s, p) != size: + raise ValueError( + f"input size {(height, width)}: the output layer gives {_deconv_out(sizes[0], k, s, p)} pixels." + ) + + def _coordinates(self, n: int, height: int, width: int, like: torch.Tensor) -> torch.Tensor: + x = torch.arange(width, dtype=like.dtype, device=like.device) / float(width - 1) * 2.0 - 1.0 + y = torch.arange(height, dtype=like.dtype, device=like.device) / float(height - 1) * 2.0 - 1.0 + grid = torch.stack( + (x.view(1, width).expand(height, width), y.view(height, 1).expand(height, width), like.new_ones(height, width)) + ) + return grid.unsqueeze(0).expand(n, 3, height, width) + + def _unroll( + self, + block: nn.ModuleList, + inputs: Optional[List[torch.Tensor]], + length: int, + begin_states: Optional[Sequence[torch.Tensor]], + ) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + """``BaseStackRNN.unroll``: returns the last cell's outputs and every cell's final state.""" + finals: List[torch.Tensor] = [] + outputs: List[torch.Tensor] = [] + for j, cell in enumerate(block): + state = begin_states[j] if begin_states is not None else None + outputs = [] + for t in range(length): + state = cell(inputs[t] if inputs is not None else None, state) + outputs.append(state) + if self.residual_connection and j > 0: + outputs = [o + x for o, x in zip(outputs, inputs)] + inputs = outputs + finals.append(state) + return outputs, finals + + def encode( + self, x: torch.Tensor, initial_states: Optional[Sequence[Sequence[torch.Tensor]]] = None + ) -> List[List[torch.Tensor]]: + """Final states of every encoder block (one tensor per stacked cell).""" + self._check_input(x) + b, t, c, h, w = x.shape + frames = x.transpose(0, 1).reshape(t * b, c, h, w) + frames = torch.cat((frames, self._coordinates(t * b, h, w, x)), dim=1) + seq = list(activation(self.econv1(frames), self.cnn_act_type).split(b, dim=0)) + states: List[List[torch.Tensor]] = [] + for i in range(self.num_blocks): + begin = initial_states[i] if initial_states is not None else None + outputs, finals = self._unroll(getattr(self, f"ebrnn{i + 1}"), seq, t, begin) + states.append(finals) + if i < self.num_blocks - 1: + seq = list(getattr(self, f"edown{i + 1}")(torch.cat(outputs, dim=0)).split(b, dim=0)) + return states + + def forecast(self, states: Sequence[Sequence[torch.Tensor]], num_output_frames: int) -> torch.Tensor: + """Run the forecaster from encoder states; returns ``(batch, T_out, out_channels, H, W)``.""" + inputs: Optional[List[torch.Tensor]] = None + outputs: List[torch.Tensor] = [] + b = states[0][0].shape[0] + for i in reversed(range(self.num_blocks)): + outputs, _ = self._unroll(getattr(self, f"fbrnn{i + 1}"), inputs, num_output_frames, list(states[i])[::-1]) + if i > 0: + inputs = list(getattr(self, f"fup{i}")(torch.cat(outputs, dim=0)).split(b, dim=0)) + y = activation(self.fdeconv1(torch.cat(outputs, dim=0)), self.cnn_act_type) + y = self.out(activation(self.conv_final(y), self.cnn_act_type)) + return y.view(num_output_frames, b, *y.shape[1:]).transpose(0, 1) + + def _check_input(self, x: torch.Tensor) -> None: + if x.ndim != 5: + raise ValueError( + f"TrajGRU expects input shape (batch, time, channels, height, width), got {tuple(x.shape)}." + ) + if x.shape[2] != self.in_channels: + raise ValueError(f"TrajGRU expected {self.in_channels} input channels, got input of shape {tuple(x.shape)}.") + if x.shape[1] < 1: + raise ValueError("TrajGRU needs at least one input frame.") + self.check_input_size(x.shape[3], x.shape[4]) + + def forward( + self, + x: torch.Tensor, + num_output_frames: Optional[int] = None, + initial_states: Optional[Sequence[Sequence[torch.Tensor]]] = None, + return_states: bool = False, + ): + """Forecast ``num_output_frames`` frames (default: the configuration's ``OUT_LEN``). + + ``initial_states`` (per block, per stacked cell) replaces the zero initial encoder state; + ``return_states=True`` also returns the final encoder states, which the official training + loop carries over between batches (see the model card). + """ + n_out = self.num_output_frames if num_output_frames is None else int(num_output_frames) + if n_out <= 0: + raise ValueError(f"num_output_frames must be positive, got {n_out}") + states = self.encode(x, initial_states) + prediction = self.forecast(states, n_out) + return (prediction, states) if return_states else prediction + + +class TrajGRUSegmenter(TrajGRU): + """PyHazards adaptation for next-step fire masks: ``(batch, T, C, H, W)`` -> ``(batch, out_channels, H, W)``. + + The encoder-forecaster predicts a single frame; its (linear) output is returned as logits. + Parameter names are those of :class:`TrajGRU` (no prefix). + """ + + def __init__(self, **kwargs): + kwargs.pop("num_output_frames", None) + super().__init__(num_output_frames=1, **kwargs) + + def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore[override] + return self.forecast(self.encode(x), 1)[:, 0] + + +def load_hko7_params(model: TrajGRU, params: Mapping[str, object], strict: bool = True) -> None: + """Load official HKO-7 parameters (``{"arg:": array}`` or ``{"": array}``, as read by + ``mx.nd.load`` from ``encoder_net-*.params`` and ``forecaster_net-*.params``) into ``model``.""" + arrays = {} + for name, value in params.items(): + name = name.split(":", 1)[1] if ":" in name else name + array = value.asnumpy() if hasattr(value, "asnumpy") else value + arrays[name] = torch.as_tensor(array) + state = {} + for key, tensor in model.state_dict().items(): + name = key.replace(".", "_") + if name not in arrays: + if strict: + raise KeyError(f"parameter {name!r} (for {key!r}) is missing from the HKO-7 checkpoint") + continue + value = arrays.pop(name) + if tuple(value.shape) != tuple(tensor.shape): + raise ValueError(f"{name}: checkpoint shape {tuple(value.shape)} != model shape {tuple(tensor.shape)}") + state[key] = value.to(tensor.dtype) + if strict and arrays: + raise KeyError(f"unexpected HKO-7 parameters: {sorted(arrays)}") + model.load_state_dict(state, strict=strict) + + +def trajgru_builder( + task: str, + config: str = "hko7", + in_channels: int = 1, + out_channels: int = 1, + layer_type: Union[str, Sequence[str]] = "TrajGRU", + num_output_frames: Optional[int] = None, + **kwargs, +) -> nn.Module: + """Build the HKO-7 TrajGRU encoder-forecaster. + + ``config``: ``"hko7"`` (HKO-7 benchmark model, 480x480 input, 5 -> 20 frames) or + ``"movingmnist"`` (TrajGRU-L13 of the MovingMNIST++ experiments, 64x64, 10 -> 10). Any + architecture field (``num_filter``, ``L``, ``h2h_kernel``, ``h2h_dilate``, ``i2h_kernel``, + ``i2h_pad``, ``stack_num``, ``first_conv``, ``last_deconv``, ``downsample``, ``upsample``, + activations) can be overridden; ``layer_type="ConvGRU"`` gives the paper's ConvGRU baseline. + ``task="forecasting"``: :class:`TrajGRU`; ``task="segmentation"``: :class:`TrajGRUSegmenter`. + """ + task = task.lower() + if config not in TRAJGRU_CONFIGS: + raise ValueError(f"config must be one of {sorted(TRAJGRU_CONFIGS)}, got {config!r}") + allowed = { + "num_filter", "L", "h2h_kernel", "h2h_dilate", "i2h_kernel", "i2h_pad", "stack_num", "first_conv", + "last_deconv", "downsample", "upsample", "rnn_act_type", "cnn_act_type", "residual_connection", "init_grid", + } + settings = dict(TRAJGRU_CONFIGS[config]) + settings.update({key: value for key, value in kwargs.items() if key in allowed}) + frames = settings.pop("num_output_frames") + if num_output_frames is not None: + frames = num_output_frames + common = dict(in_channels=in_channels, out_channels=out_channels, layer_type=layer_type, **settings) + if task == "forecasting": + return TrajGRU(num_output_frames=frames, **common) + if task == "segmentation": + return TrajGRUSegmenter(**common) + raise ValueError(f"trajgru supports task='forecasting' or 'segmentation', got {task!r}.") + + +__all__ = [ + "EFConvGRUCell", + "TRAJGRU_CONFIGS", + "TrajGRU", + "TrajGRUCell", + "TrajGRUSegmenter", + "load_hko7_params", + "trajgru_builder", + "warp", +] diff --git a/pyhazards/models/tropicalcyclone_mlp.py b/pyhazards/models/tropicalcyclone_mlp.py index 5e76c5ab..c0789a5a 100644 --- a/pyhazards/models/tropicalcyclone_mlp.py +++ b/pyhazards/models/tropicalcyclone_mlp.py @@ -1,64 +1,189 @@ +"""24-hour tropical cyclone intensity-change MLP of Xu et al. (2021). + +Paper: W. Xu, K. Balaguru, A. August, N. Lalo, N. Hodas, M. DeMaria and D. Judi, "Deep Learning +Experiments for Tropical Cyclone Intensity Forecasts", Weather and Forecasting 36(4), 1453-1470 +(2021), doi:10.1175/WAF-D-20-0104.1. + +Port of ``models.mlp`` and of the predictor list ``utils.hand_features`` from the official +repository wenweixu/tropicalcyclone_MLP (``models.py`` / ``utils.py`` at +73800596fc824c6d3f150fc41af0bdb7b9c3a7dc), BSD 2-Clause License, Copyright (c) 2021, Wenwei Xu. +The BSD notice is reproduced in ``LICENSE_NOTICE`` below as the license requires. + +The official network is a Keras model: 121 SHIPS predictors -> Dense(2048, sigmoid) -> +Dense(2048, relu) -> Dense(1, linear), trained with the MAE loss to predict the 24-hour change of +the maximum sustained wind (``dvs24``, knots). Keras ``Dense`` computes ``x @ kernel + bias`` with +glorot-uniform kernels and zero biases; :class:`TropicalCycloneMLP` uses ``nn.Linear`` (whose +weight is the transposed kernel) with the same initialisation distribution, and +:func:`load_keras_weights` copies the weights of a Keras model (``model.get_weights()``) into it. +""" + from __future__ import annotations +from typing import Sequence, Union + +import numpy as np import torch import torch.nn as nn +LICENSE_NOTICE = """\ +BSD 2-Clause License + +Copyright (c) 2021, Wenwei Xu +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +# The 121 predictors of the 24-hour model, in the official column order (utils.hand_features): +# initial intensity vs0, 18 GOES/PSLV, 21 MTPW and 20 IR00 predictors, 0-24 h time averages of +# the SHIPS environmental predictors (``*_t24``) and the 12-hour intensity change DELV-12. +SHIPS_PREDICTORS = ( + "vs0", "PSLV_v2", "PSLV_v3", "PSLV_v4", "PSLV_v5", "PSLV_v6", "PSLV_v7", + "PSLV_v8", "PSLV_v9", "PSLV_v10", "PSLV_v11", "PSLV_v12", "PSLV_v13", + "PSLV_v14", "PSLV_v15", "PSLV_v16", "PSLV_v17", "PSLV_v18", "PSLV_v19", + "MTPW_v2", "MTPW_v3", "MTPW_v4", "MTPW_v5", "MTPW_v6", "MTPW_v7", + "MTPW_v8", "MTPW_v9", "MTPW_v10", "MTPW_v11", "MTPW_v12", "MTPW_v13", + "MTPW_v14", "MTPW_v15", "MTPW_v16", "MTPW_v17", "MTPW_v18", "MTPW_v19", + "MTPW_v20", "MTPW_v21", "MTPW_v22", "IR00_v2", "IR00_v3", "IR00_v4", + "IR00_v5", "IR00_v6", "IR00_v7", "IR00_v8", "IR00_v9", "IR00_v10", + "IR00_v11", "IR00_v12", "IR00_v13", "IR00_v14", "IR00_v15", "IR00_v16", + "IR00_v17", "IR00_v18", "IR00_v19", "IR00_v20", "IR00_v21", "CSST_t24", + "CD20_t24", "CD26_t24", "COHC_t24", "DTL_t24", "RSST_t24", "U200_t24", + "U20C_t24", "V20C_t24", "E000_t24", "EPOS_t24", "ENEG_t24", "EPSS_t24", + "ENSS_t24", "RHLO_t24", "RHMD_t24", "RHHI_t24", "Z850_t24", "D200_t24", + "REFC_t24", "PEFC_t24", "T000_t24", "R000_t24", "Z000_t24", "TLAT_t24", + "TLON_t24", "TWAC_t24", "TWXC_t24", "G150_t24", "G200_t24", "G250_t24", + "V000_t24", "V850_t24", "V500_t24", "V300_t24", "TGRD_t24", "TADV_t24", + "PENC_t24", "SHDC_t24", "SDDC_t24", "SHGC_t24", "DIVC_t24", "T150_t24", + "T200_t24", "T250_t24", "SHRD_t24", "SHTD_t24", "SHRS_t24", "SHTS_t24", + "SHRG_t24", "PENV_t24", "VMPI_t24", "VVAV_t24", "VMFX_t24", "VVAC_t24", + "HE07_t24", "HE05_t24", "O500_t24", "O700_t24", "CFLX_t24", "DELV-12", +) + +_ACTIVATIONS = { + "sigmoid": nn.Sigmoid, + "relu": nn.ReLU, + "tanh": nn.Tanh, + "linear": nn.Identity, +} + + +def _layer_name(index: int) -> str: + # Keras names consecutive Dense layers dense, dense_1, dense_2, ... + return "dense" if index == 0 else f"dense_{index}" + class TropicalCycloneMLP(nn.Module): - """Compact MLP baseline for storm track and intensity forecasting.""" + """Fully connected regressor of the 24-hour intensity change from SHIPS predictors. + + Input ``(batch, input_dim)`` standardised predictors (default: the 121 of + :data:`SHIPS_PREDICTORS`, in that order); output ``(batch, 1)``, the predicted 24-hour change + of the maximum sustained wind in the target's units (knots in the paper). + """ def __init__( self, - input_dim: int = 8, - history: int = 6, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, + input_dim: int = len(SHIPS_PREDICTORS), + hidden_dims: Sequence[int] = (2048, 2048), + activations: Union[str, Sequence[str]] = ("sigmoid", "relu"), ): super().__init__() - self.history = int(history) - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.net = nn.Sequential( - nn.Linear(self.history * input_dim, hidden_dim), - nn.ReLU(), - nn.Dropout(dropout) if dropout > 0 else nn.Identity(), - nn.Linear(hidden_dim, hidden_dim), - nn.ReLU(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), - ) + hidden_dims = [int(width) for width in hidden_dims] + if isinstance(activations, str): + activations = [activations] * len(hidden_dims) + activations = [name.lower() for name in activations] + if len(activations) != len(hidden_dims): + raise ValueError("activations needs one entry per hidden layer") + unknown = sorted(set(activations) - set(_ACTIVATIONS)) + if unknown: + raise ValueError(f"unknown activation(s) {unknown}; choose from {sorted(_ACTIVATIONS)}") + if int(input_dim) < 1 or any(width < 1 for width in hidden_dims): + raise ValueError("input_dim and hidden_dims must be positive") + self.input_dim = int(input_dim) + self.hidden_dims = tuple(hidden_dims) + self.activation_names = tuple(activations) + + widths = [self.input_dim, *hidden_dims, 1] + self.layer_names = [] + for index, (width_in, width_out) in enumerate(zip(widths[:-1], widths[1:])): + linear = nn.Linear(width_in, width_out) + # Keras Dense defaults: glorot_uniform kernel, zero bias. + nn.init.xavier_uniform_(linear.weight) + nn.init.zeros_(linear.bias) + name = _layer_name(index) + self.add_module(name, linear) + self.layer_names.append(name) + self.activations = nn.ModuleList([_ACTIVATIONS[name]() for name in activations]) def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("TropicalCycloneMLP expects inputs shaped (batch, history, features).") - if x.size(1) != self.history: - raise ValueError(f"TropicalCycloneMLP expected history={self.history}, got {x.size(1)}.") - preds = self.net(x.reshape(x.size(0), -1)) - return preds.view(x.size(0), self.horizon, self.output_dim) + if x.ndim != 2 or x.size(1) != self.input_dim: + raise ValueError( + f"TropicalCycloneMLP expects predictors shaped (batch, {self.input_dim}), got {tuple(x.shape)}" + ) + hidden = x + for name, activation in zip(self.layer_names[:-1], self.activations): + hidden = activation(getattr(self, name)(hidden)) + return getattr(self, self.layer_names[-1])(hidden) + + +def load_keras_weights(model: TropicalCycloneMLP, weights: Sequence[np.ndarray]) -> TropicalCycloneMLP: + """Copy Keras ``Model.get_weights()`` (kernel, bias per Dense layer) into ``model`` in place.""" + weights = list(weights) + if len(weights) != 2 * len(model.layer_names): + raise ValueError( + f"expected {2 * len(model.layer_names)} arrays (kernel and bias per Dense layer), got {len(weights)}" + ) + with torch.no_grad(): + for index, name in enumerate(model.layer_names): + linear = getattr(model, name) + kernel = torch.as_tensor(np.asarray(weights[2 * index]), dtype=linear.weight.dtype) + bias = torch.as_tensor(np.asarray(weights[2 * index + 1]), dtype=linear.bias.dtype) + if kernel.shape != linear.weight.T.shape or bias.shape != linear.bias.shape: + raise ValueError( + f"{name}: Keras kernel {tuple(kernel.shape)} / bias {tuple(bias.shape)} do not match " + f"in_features={linear.in_features}, out_features={linear.out_features}" + ) + linear.weight.copy_(kernel.T) + linear.bias.copy_(bias) + return model def tropicalcyclone_mlp_builder( task: str, - input_dim: int = 8, - history: int = 6, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - dropout: float = 0.1, + input_dim: int = len(SHIPS_PREDICTORS), + hidden_dims: Sequence[int] = (2048, 2048), + activations: Union[str, Sequence[str]] = ("sigmoid", "relu"), **kwargs, ) -> nn.Module: _ = kwargs if task.lower() != "regression": - raise ValueError("TropicalCycloneMLP only supports regression for track/intensity forecasting.") - return TropicalCycloneMLP( - input_dim=input_dim, - history=history, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - dropout=dropout, - ) - - -__all__ = ["TropicalCycloneMLP", "tropicalcyclone_mlp_builder"] + raise ValueError("tropicalcyclone_mlp is a regression model (24-hour intensity change); use task='regression'.") + return TropicalCycloneMLP(input_dim=input_dim, hidden_dims=hidden_dims, activations=activations) + + +__all__ = [ + "LICENSE_NOTICE", + "SHIPS_PREDICTORS", + "TropicalCycloneMLP", + "load_keras_weights", + "tropicalcyclone_mlp_builder", +] diff --git a/pyhazards/models/tropicyclonenet.py b/pyhazards/models/tropicyclonenet.py index 69b3220f..9aae35fc 100644 --- a/pyhazards/models/tropicyclonenet.py +++ b/pyhazards/models/tropicyclonenet.py @@ -1,70 +1,787 @@ +"""TropiCycloneNet (TCN_M): multimodal GAN for global tropical cyclone track and intensity forecasts. + +Paper: C. Huang, P. Mu, J. Zhang, S. Chan, S. Zhang, H. Yan, S. Chen and C. Bai, "Benchmark dataset +and deep learning method for global tropical cyclone forecasting", Nature Communications 16, 5923 +(2025), doi:10.1038/s41467-025-61087-4. + +Port of the generator and discriminator of the official code release "TropiCycloneNet Model: A +Multimodal Tropical Cyclone Prediction Model Guided by Environmental Information" (Zenodo +doi:10.5281/zenodo.15024028, ``TropiCycloneNet.zip``, git commit b4e7101 of 2025-03-14), licensed +CC BY 4.0 by Cheng Huang et al.: ``TCNM/models_prior_unet.py`` (``make_mlp``, ``Encoder``, +``Decoder``, ``TrajectoryGenerator``, ``TrajectoryDiscriminator``), ``TCNM/Unet3D_merge_tiny.py`` +(``Conv3d``, ``Down``, ``Up``, ``OutConv``, ``Unet3D``) and ``TCNM/env_net_transformer_gphsplit.py`` +(``Env_net``). These files are identical (up to line endings) to github.com/xiaochengfuhuo/TropiCycloneNet +at de9cf0e9. Changes made here: device-agnostic tensors instead of ``.cuda()``, input validation, +the generator-index loop fix described below, and the :meth:`TropiCycloneNet.forecast` adapter. +Module and parameter names are unchanged, so the released checkpoint +(``checkpoint_with_model_16000.pt``, CC BY 4.0) loads with ``strict=True``, and modules are created +in the official order, so the same seed gives the same initial weights. + +The generator (4,767,195 parameters in the released configuration) observes 8 six-hourly steps of +the best track (``obs_traj``: longitude, latitude, central pressure, maximum wind, normalised as in +:data:`TCND_NORMALIZATION`; ``obs_traj_rel``: their 6-hourly differences, 0 at the first step), +500 hPa geopotential height crops resized to 64 x 64 (``image_obs``, ``(batch, 1, 8, 64, 64)``) and +the TCND environment features (``env_data``, nine one-hot or scalar features per step). A 3D U-Net +extrapolates the GPH sequence, LSTM encoders summarise the track with the GPH embeddings, and the +Env-T-Net transformer (``env_net_chooser``) summarises the environment. Six LSTM decoders +(generators) each roll out 4 steps (6, 12, 18, 24 h) of relative displacements; a generator-chooser +MLP gives categorical logits over the six decoders, and every sample draws a decoder index from +them plus a 16-d Gaussian noise vector. Outputs are relative (6-hourly) normalised displacements; +:meth:`TropiCycloneNet.forecast` turns them into absolute positions (degrees), central pressure +(hPa) and maximum sustained wind (m/s). + +Official behaviour that is kept: unused modules (``env_net``, ``time_embedding`` layers, +``traj_score``/``inte_score`` placeholders) exist and are counted; the decoders ignore the absolute +position they track; the mixing MLP ends with a ReLU; ``Up`` pads the decoder features with the +time difference on the width axis and the height difference on the time axis (all differences +are 0 for the released 8-step, 64 x 64 configuration). +""" + from __future__ import annotations +import collections +import hashlib +from pathlib import Path +from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union + import torch import torch.nn as nn +import torch.nn.functional as F +from torch.distributions.categorical import Categorical + +# Data1d normalisation of the TropiCycloneNet Dataset (TCND) and of the official evaluation +# (TCNM/losses.py ``toNE``): physical = normalised * scale + offset. +TCND_NORMALIZATION: Dict[str, Tuple[float, float]] = { + "lon": (5.0, 180.0), # degrees east + "lat": (5.0, 0.0), # degrees north + "pres": (50.0, 960.0), # hPa + "wind": (25.0, 40.0), # m/s, 2-minute mean maximum sustained wind +} +TRACK_VARIABLES = ("lon", "lat", "pres", "wind") + +# TCND Env-Data features (key, width) in the order Env_net concatenates them. +ENV_FEATURES: Tuple[Tuple[str, int], ...] = ( + ("wind", 1), + ("intensity_class", 6), + ("move_velocity", 1), + ("month", 12), + ("location_long", 36), + ("location_lat", 12), + ("history_direction12", 8), + ("history_direction24", 8), + ("history_inte_change24", 4), +) + +# Released checkpoint (Zenodo record 15024028, CC BY 4.0). +CHECKPOINT_URL = "https://zenodo.org/records/15024028/files/checkpoint_with_model_16000.pt" +CHECKPOINT_SHA256 = "68575d1d10fcd2d44eba2d54d0625410f5108cd3bf5d7b3e15df7491ba9f6215" +# Generator / discriminator arguments of that checkpoint (its ``args``). +RELEASED_CONFIG: Dict[str, Any] = { + "obs_len": 8, + "pred_len": 4, + "embedding_dim": 32, + "encoder_h_dim": 64, + "decoder_h_dim": 64, + "mlp_dim": 128, + "num_layers": 1, + "noise_dim": (16,), + "noise_type": "gaussian", + "noise_mix_type": "ped", + "pooling_type": None, + "pool_every_timestep": False, + "dropout": 0.0, + "bottleneck_dim": 16, + "batch_norm": False, +} + + +def make_mlp(dim_list: Sequence[int], activation: str = "relu", batch_norm: bool = True, dropout: float = 0) -> nn.Sequential: + layers = [] + for dim_in, dim_out in zip(dim_list[:-1], dim_list[1:]): + layers.append(nn.Linear(dim_in, dim_out)) + if batch_norm: + layers.append(nn.BatchNorm1d(dim_out)) + if activation == "relu": + layers.append(nn.ReLU()) + elif activation == "leakyrelu": + layers.append(nn.LeakyReLU()) + if dropout > 0: + layers.append(nn.Dropout(p=dropout)) + return nn.Sequential(*layers) + + +def get_noise(shape: Sequence[int], noise_type: str, device=None, dtype=None) -> torch.Tensor: + # Drawn on the CPU generator and then moved, as the official ``torch.randn(...).cuda()`` does, + # so a seed gives the official noise on any device. + if noise_type == "gaussian": + noise = torch.randn(*shape) + elif noise_type == "uniform": + noise = torch.rand(*shape).sub_(0.5).mul_(2.0) + else: + raise ValueError('Unrecognized noise type "%s"' % noise_type) + return noise.to(device=device, dtype=dtype) + + +# --------------------------------------------------------------------------------------------- +# 3D U-Net over the GPH sequence (TCNM/Unet3D_merge_tiny.py) +# --------------------------------------------------------------------------------------------- + + +class Conv3d(nn.Module): + """Two 3D conv - BN - ReLU layers plus a bias-free 1x1x1 residual convolution.""" + + def __init__(self, in_channel: int, out_channel: int, kernel_size, stride, padding): + super().__init__() + self.conv1 = nn.Sequential( + nn.Conv3d(in_channel, out_channel, kernel_size=kernel_size, stride=stride, padding=padding, bias=True), + nn.BatchNorm3d(out_channel), + nn.ReLU(inplace=True), + ) + self.conv2 = nn.Sequential( + nn.Conv3d(out_channel, out_channel, kernel_size=kernel_size, stride=stride, padding=padding, bias=True), + nn.BatchNorm3d(out_channel), + nn.ReLU(True), + ) + self.residual = nn.Conv3d(in_channel, out_channel, kernel_size=1, stride=1, padding=0, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv2(self.conv1(x)) + self.residual(x) + + +class Down(nn.Module): + def __init__(self, in_channel: int, out_channel: int, kernel_size, stride): + super().__init__() + self.maxpool_conv = nn.Sequential( + nn.MaxPool3d(kernel_size=kernel_size, stride=stride), + Conv3d(in_channel, out_channel, kernel_size=3, stride=1, padding=1), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.maxpool_conv(x) + + +class Up(nn.Module): + def __init__(self, x1_in: int, x2_in: int, out_channel: int, kernel_size, stride, padding): + super().__init__() + self.up = nn.Sequential( + nn.ConvTranspose3d(x1_in, x1_in, kernel_size=kernel_size, stride=stride, padding=padding, bias=True), + nn.ReLU(), + ) + self.conv = Conv3d(x1_in + x2_in, out_channel, kernel_size=3, stride=1, padding=1) + + def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor: + x1 = self.up(x1) + diff_t = x2.size(2) - x1.size(2) + diff_y = x2.size(3) - x1.size(3) + diff_x = x2.size(4) - x1.size(4) + # Official padding order: the time difference pads the last (width) axis and the height + # difference pads the time axis. All differences are 0 in the released configuration. + x1 = F.pad( + x1, + [diff_t // 2, diff_t - diff_t // 2, diff_x // 2, diff_x - diff_x // 2, diff_y // 2, diff_y - diff_y // 2], + ) + return self.conv(torch.cat([x2, x1], dim=1)) + + +class OutConv(nn.Module): + """Upsamples the four decoder levels to full resolution, stacks them in time and convolves.""" + + def __init__(self, in_channel_list: Sequence[int], out_channel: int, kernel_size, stride, padding): + super().__init__() + levels = len(in_channel_list) - 1 + up_list = [] + for index, channel in enumerate(in_channel_list[:-1]): + factor = 2 ** (levels - index) + up_list.append( + nn.Sequential( + nn.ConvTranspose3d( + channel, channel, kernel_size=[1, factor, factor], stride=[1, factor, factor], padding=padding, bias=True + ), + nn.ReLU(), + nn.Conv3d(channel, in_channel_list[-1], kernel_size=3, stride=1, padding=1, bias=True), + nn.BatchNorm3d(in_channel_list[-1]), + nn.ReLU(inplace=True), + ) + ) + self.up_list = nn.ModuleList(up_list) + self.conv = nn.Sequential( + nn.Conv3d(in_channel_list[-1], out_channel, kernel_size=kernel_size, stride=stride, padding=padding), + nn.BatchNorm3d(out_channel), + nn.ReLU(), + nn.Conv3d(out_channel, out_channel, kernel_size=1, stride=1, padding=0), + ) + + def forward(self, x: Sequence[torch.Tensor]) -> torch.Tensor: + x6, x7, x8, x9 = tuple(x) + x6 = self.up_list[0](x6) + x7 = self.up_list[1](x7) + x8 = self.up_list[2](x8) + return self.conv(torch.cat([x6, x7, x8, x9], dim=2)) + + +class Unet3D(nn.Module): + """3D U-Net mapping 8 observed GPH frames ``(batch, 1, 8, 64, 64)`` to 11 frames (steps 2-12).""" + + def __init__(self, in_channel: int, out_channel: int): + super().__init__() + self.inc = Conv3d(in_channel, 16, kernel_size=3, stride=1, padding=1) + self.down1 = Down(16, 32, kernel_size=[1, 2, 2], stride=[1, 2, 2]) + self.down2 = Down(32, 64, kernel_size=[1, 2, 2], stride=[1, 2, 2]) + self.down3 = Down(64, 128, kernel_size=[2, 2, 2], stride=[2, 2, 2]) + self.down4 = Down(128, 128, kernel_size=[2, 2, 2], stride=[2, 2, 2]) + self.up1 = Up(128, 128, 64, kernel_size=[2, 2, 2], stride=[2, 2, 2], padding=0) + self.up2 = Up(64, 64, 32, kernel_size=[2, 2, 2], stride=[2, 2, 2], padding=0) + self.up3 = Up(32, 32, 16, kernel_size=[1, 2, 2], stride=[1, 2, 2], padding=0) + self.up4 = Up(16, 16, 16, kernel_size=[1, 2, 2], stride=[1, 2, 2], padding=0) + self.outc = OutConv([64, 32, 16, 16], out_channel, kernel_size=[18, 1, 1], stride=[1, 1, 1], padding=0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x1 = self.inc(x) + x2 = self.down1(x1) + x3 = self.down2(x2) + x4 = self.down3(x3) + x5 = self.down4(x4) + x6 = self.up1(x5, x4) + x7 = self.up2(x6, x3) + x8 = self.up3(x7, x2) + x9 = self.up4(x8, x1) + return self.outc([x6, x7, x8, x9]) + + +# --------------------------------------------------------------------------------------------- +# Env-T-Net (TCNM/env_net_transformer_gphsplit.py) +# --------------------------------------------------------------------------------------------- + + +class Env_net(nn.Module): + """Embeds the TCND environment features and GPH maps per step and encodes them with a transformer. + + ``forward(env_data, gph)`` with ``env_data[key]`` ``(batch, obs_len, width)`` for the keys of + :data:`ENV_FEATURES` and ``gph`` ``(batch, 1, obs_len, 64, 64)``; returns the 64-d feature of + the last step and two placeholder zeros, as the official module does. + """ + + def __init__(self, obs_len: int = 8): + super().__init__() + embed_dim = 16 + self.data_embed = nn.ModuleDict() + for key, width in ENV_FEATURES: + self.data_embed[key] = nn.Linear(width, embed_dim) + self.GPH_embed = nn.Sequential( + nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=True), + nn.BatchNorm2d(1), + nn.LeakyReLU(inplace=True), + nn.AvgPool2d(8, 8), + ) + env_f_in = len(self.data_embed) * 16 + 8 * 8 + self.evn_extract = nn.Sequential( + nn.Linear(env_f_in, env_f_in // 2), + nn.ReLU(), + nn.Linear(env_f_in // 2, env_f_in // 2), + nn.ReLU(), + nn.Linear(env_f_in // 2, 64), + ) + encoder_layer = nn.TransformerEncoderLayer(d_model=64, nhead=4) + # enable_nested_tensor only matters with padding masks (never used); False avoids a warning. + self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=2, enable_nested_tensor=False) + + def forward(self, env_data: Mapping[str, torch.Tensor], gph: torch.Tensor): + gph = gph.permute(0, 2, 1, 3, 4) + batch, steps = gph.shape[:2] + embeds = [self.data_embed[key](env_data[key]) for key in self.data_embed] + gph_feature = torch.stack([self.GPH_embed(gph[:, step]).reshape(batch, -1) for step in range(steps)], dim=1) + embeds.append(gph_feature) + feature_in = self.evn_extract(torch.cat(embeds, dim=2)).permute(1, 0, 2) + output = self.encoder(feature_in) + return output[-1], 0, 0 -class TropiCycloneNet(nn.Module): - """GRU + attention baseline for all-basin tropical cyclone forecasting.""" +# --------------------------------------------------------------------------------------------- +# Trajectory encoder / decoders / generator / discriminator (TCNM/models_prior_unet.py) +# --------------------------------------------------------------------------------------------- + + +class Encoder(nn.Module): + """LSTM over embedded relative track steps plus image embeddings.""" + + def __init__(self, embedding_dim: int = 64, h_dim: int = 64, mlp_dim: int = 1024, num_layers: int = 1, dropout: float = 0.0): + super().__init__() + self.mlp_dim = 1024 + self.h_dim = h_dim + self.embedding_dim = embedding_dim + self.num_layers = num_layers + self.encoder = nn.LSTM(embedding_dim, h_dim, num_layers, dropout=dropout) + self.spatial_embedding = nn.Linear(4, embedding_dim) + self.time_embedding = nn.Linear(4, embedding_dim) # created but unused, as in the official code + + def init_hidden(self, batch: int, reference: torch.Tensor): + zeros = reference.new_zeros(self.num_layers, batch, self.h_dim) + return zeros, zeros.clone() + + def forward(self, obs_traj: torch.Tensor, img_embed_input: torch.Tensor) -> Dict[str, Any]: + batch = obs_traj.size(1) + embedding = self.spatial_embedding(obs_traj.reshape(-1, obs_traj.size(2))).view(-1, batch, self.embedding_dim) + embedding = embedding + img_embed_input + output, state = self.encoder(embedding, self.init_hidden(batch, embedding)) + return {"final_h": state, "output": output} + + +class Decoder(nn.Module): + """One generator: an LSTM rolling out ``seq_len`` relative steps from the mixed hidden state.""" + + def __init__( + self, + seq_len: int, + embedding_dim: int = 64, + h_dim: int = 128, + mlp_dim: int = 1024, + num_layers: int = 1, + pool_every_timestep: bool = True, + dropout: float = 0.0, + bottleneck_dim: int = 1024, + activation: str = "relu", + batch_norm: bool = True, + pooling_type: Optional[str] = "pool_net", + neighborhood_size: float = 2.0, + grid_size: int = 8, + embeddings_dim: int = 128, + h_dims: int = 128, + ): + super().__init__() + self.seq_len = seq_len + self.mlp_dim = mlp_dim + self.h_dim = h_dim + self.embedding_dim = embedding_dim + self.pool_every_timestep = pool_every_timestep + self.decoder = nn.LSTM(embedding_dim, h_dim, num_layers, dropout=dropout) + if pool_every_timestep: + # Created (and counted) but never applied, as in the official code. + self.mlp = make_mlp([h_dim + bottleneck_dim, mlp_dim, h_dim], activation=activation, batch_norm=batch_norm, dropout=dropout) + self.spatial_embedding = nn.Linear(4, embedding_dim) + self.time_embedding = nn.Linear(4, embedding_dim) # unused + self.hidden2pos = nn.Linear(h_dim, 4) + + def forward(self, obs_traj, obs_traj_rel, last_pos, last_pos_rel, state_tuple, seq_start_end, decoder_img, last_img): + batch = last_pos.size(0) + steps = [] + decoder_input = self.spatial_embedding(last_pos_rel).view(-1, batch, self.embedding_dim) + decoder_input = decoder_input + last_img.unsqueeze(0) + for step in range(self.seq_len): + output, state_tuple = self.decoder(decoder_input, state_tuple) + rel_pos = self.hidden2pos(output.view(-1, self.h_dim)) + # The official decoder also computes rel_pos + last_pos, which it never uses. + rel_pos = rel_pos.unsqueeze(0) + decoder_input = self.spatial_embedding(rel_pos).view(-1, batch, self.embedding_dim) + decoder_input = decoder_input + decoder_img[step].unsqueeze(0) + steps.append(rel_pos.view(batch, -1)) + return torch.stack(steps, dim=0), state_tuple[0] + + +def _env_from_mapping(batch: Mapping[str, Any]) -> Dict[str, torch.Tensor]: + env = batch.get("env_data") + if env is None: + env = {key: batch[key] for key, _ in ENV_FEATURES if key in batch} + return dict(env) + + +class TrajectoryGenerator(nn.Module): + """TCN_M generator (``TrajectoryGenerator`` of the official code).""" def __init__( self, - input_dim: int = 8, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - num_layers: int = 2, - dropout: float = 0.1, + obs_len: int = 8, + pred_len: int = 4, + embedding_dim: int = 32, + encoder_h_dim: int = 64, + decoder_h_dim: int = 64, + mlp_dim: int = 128, + num_layers: int = 1, + noise_dim: Sequence[int] = (16,), + noise_type: str = "gaussian", + noise_mix_type: str = "ped", + pooling_type: Optional[str] = None, + pool_every_timestep: bool = False, + dropout: float = 0.0, + bottleneck_dim: int = 16, + activation: str = "relu", + batch_norm: bool = False, + neighborhood_size: float = 2.0, + grid_size: int = 8, + num_gs: int = 6, + num_sample: int = 6, + official_sample_loop: bool = False, ): super().__init__() - self.horizon = int(horizon) - self.output_dim = int(output_dim) - self.encoder = nn.GRU( - input_size=input_dim, - hidden_size=hidden_dim, - num_layers=num_layers, - batch_first=True, - dropout=dropout if num_layers > 1 else 0.0, - bidirectional=True, + if pooling_type and pooling_type.lower() == "none": + pooling_type = None + if pooling_type is not None: + raise ValueError( + "TropiCycloneNet has no social-pooling module (the official 'pool_net'/'spool' branches are empty); " + "use pooling_type=None" + ) + if int(obs_len) != 8 or int(pred_len) != 4: + raise ValueError("TropiCycloneNet's GPH U-Net is built for obs_len=8 and pred_len=4 (11 output frames)") + self.obs_len = int(obs_len) + self.pred_len = int(pred_len) + self.mlp_dim = mlp_dim + self.encoder_h_dim = encoder_h_dim + self.decoder_h_dim = decoder_h_dim + self.embedding_dim = embedding_dim + self.noise_dim = tuple(noise_dim) if noise_dim is not None else (0,) + self.num_layers = num_layers + self.noise_type = noise_type + self.noise_mix_type = noise_mix_type + self.pooling_type = pooling_type + self.noise_first_dim = 0 + self.pool_every_timestep = pool_every_timestep + self.bottleneck_dim = 1024 + self.num_gs = int(num_gs) + self.num_sample = int(num_sample) + # The official sampling loop visits generator indices 0..(number of distinct sampled + # indices - 1) instead of the distinct indices themselves; see ``forward``. + self.official_sample_loop = bool(official_sample_loop) + + self.Unet = Unet3D(1, 1) + self.img_embedding = nn.Linear(64 * 64, 32) + self.img_embedding_real = nn.Linear(64 * 64, 32) + self.env_net = Env_net() # created but unused in the official forward pass + self.env_net_chooser = Env_net() + self.feature2dech_env = nn.Linear(128, 64) + self.feature2dech = nn.Linear(128, 64) + self.encoder = Encoder(embedding_dim=embedding_dim, h_dim=encoder_h_dim, mlp_dim=mlp_dim, num_layers=num_layers, dropout=dropout) + self.encoder_env = Encoder( + embedding_dim=embedding_dim, h_dim=encoder_h_dim, mlp_dim=mlp_dim, num_layers=num_layers, dropout=dropout ) - self.attention = nn.Linear(2 * hidden_dim, 1) - self.head = nn.Sequential( - nn.Linear(2 * hidden_dim, hidden_dim), + self.gs = nn.ModuleList( + [ + Decoder( + pred_len, + embedding_dim=embedding_dim, + h_dim=decoder_h_dim, + mlp_dim=mlp_dim, + num_layers=num_layers, + pool_every_timestep=pool_every_timestep, + dropout=dropout, + bottleneck_dim=bottleneck_dim, + activation=activation, + batch_norm=batch_norm, + pooling_type=pooling_type, + grid_size=grid_size, + neighborhood_size=neighborhood_size, + embeddings_dim=embedding_dim, + h_dims=encoder_h_dim, + ) + for _ in range(self.num_gs) + ] + ) + self.net_chooser = nn.Sequential( + nn.Linear(encoder_h_dim, encoder_h_dim // 2), + nn.ReLU(), + nn.Linear(encoder_h_dim // 2, encoder_h_dim // 2), nn.ReLU(), - nn.Linear(hidden_dim, self.horizon * self.output_dim), + nn.Linear(encoder_h_dim // 2, self.num_gs), ) + if self.noise_dim[0] == 0: + self.noise_dim = None + else: + self.noise_first_dim = self.noise_dim[0] + if self.mlp_decoder_needed(): + self.mlp_decoder_context = make_mlp( + [encoder_h_dim, mlp_dim, decoder_h_dim - self.noise_first_dim], + activation=activation, + batch_norm=batch_norm, + dropout=dropout, + ) - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: - raise ValueError("TropiCycloneNet expects inputs shaped (batch, history, features).") - encoded, _ = self.encoder(x) - weights = torch.softmax(self.attention(encoded), dim=1) - pooled = torch.sum(weights * encoded, dim=1) - preds = self.head(pooled) - return preds.view(x.size(0), self.horizon, self.output_dim) + # -- official helpers ------------------------------------------------------------------- + + def mlp_decoder_needed(self) -> bool: + return bool(self.noise_dim or self.pooling_type or self.encoder_h_dim != self.decoder_h_dim) + + def add_noise(self, _input: torch.Tensor, seq_start_end: torch.Tensor, user_noise: Optional[torch.Tensor] = None) -> torch.Tensor: + if not self.noise_dim: + return _input + if self.noise_mix_type == "global": + noise_shape = (seq_start_end.size(0),) + self.noise_dim + else: + noise_shape = (_input.size(0),) + self.noise_dim + if user_noise is not None: + z_decoder = user_noise + else: + z_decoder = get_noise(noise_shape, self.noise_type, device=_input.device, dtype=_input.dtype) + if self.noise_mix_type == "global": + pieces = [] + for idx, (start, end) in enumerate(seq_start_end): + start, end = int(start), int(end) + pieces.append(torch.cat([_input[start:end], z_decoder[idx].view(1, -1).repeat(end - start, 1)], dim=1)) + return torch.cat(pieces, dim=0) + return torch.cat([_input, z_decoder], dim=1) + + def get_samples(self, enc_h: torch.Tensor, num_samples: int = 6): + """Chooser logits ``(batch, num_gs)`` and sampled generator indices ``(batch, num_samples)``.""" + net_chooser_out = self.net_chooser(enc_h).reshape(-1, self.num_gs) + sampled_gen_idxs = Categorical(logits=net_chooser_out).sample((num_samples,)).transpose(0, 1) + return net_chooser_out, sampled_gen_idxs.detach() + + def mix_noise(self, final_encoder_h, seq_start_end, batch: int, user_noise=None): + context = final_encoder_h.view(-1, self.encoder_h_dim) + noise_input = self.mlp_decoder_context(context) if self.mlp_decoder_needed() else context + decoder_h = self.add_noise(noise_input, seq_start_end, user_noise=user_noise) + decoder_h = decoder_h.view(-1, batch, self.encoder_h_dim) + decoder_c = decoder_h.new_zeros(self.num_layers, batch, self.decoder_h_dim) + return decoder_h, decoder_c + + # -- forward ------------------------------------------------------------------------------ + + def _check_inputs(self, obs_traj, obs_traj_rel, image_obs, env_data) -> None: + if obs_traj.ndim != 3 or obs_traj.size(0) != self.obs_len or obs_traj.size(2) != 4: + raise ValueError( + f"obs_traj must be shaped (obs_len={self.obs_len}, batch, 4 [lon, lat, pres, wind]), got {tuple(obs_traj.shape)}" + ) + if obs_traj_rel.shape != obs_traj.shape: + raise ValueError(f"obs_traj_rel must have the shape of obs_traj {tuple(obs_traj.shape)}, got {tuple(obs_traj_rel.shape)}") + batch = obs_traj.size(1) + if image_obs.ndim != 5 or tuple(image_obs.shape) != (batch, 1, self.obs_len, 64, 64): + raise ValueError(f"image_obs must be shaped (batch, 1, {self.obs_len}, 64, 64), got {tuple(image_obs.shape)}") + for key, width in ENV_FEATURES: + if key not in env_data: + raise ValueError(f"env_data is missing {key!r}; expected keys {[name for name, _ in ENV_FEATURES]}") + if tuple(env_data[key].shape) != (batch, self.obs_len, width): + raise ValueError(f"env_data[{key!r}] must be shaped (batch, {self.obs_len}, {width}), got {tuple(env_data[key].shape)}") + + def forward( + self, + obs_traj, + obs_traj_rel: Optional[torch.Tensor] = None, + seq_start_end: Optional[torch.Tensor] = None, + image_obs: Optional[torch.Tensor] = None, + env_data: Optional[Mapping[str, torch.Tensor]] = None, + num_samples: int = 1, + all_g_out: bool = False, + predrnn_img=None, + user_noise=None, + ): + """Official generator forward pass. + + Returns ``(pred_traj_fake_rel_nums, image_out, net_chooser_out, sampled_gen_idxs)``: + relative normalised steps ``(pred_len, K, batch, 4)`` with ``K = num_samples`` (or + ``num_gs`` with ``all_g_out=True``: every decoder once, sharing one noise draw), the + observed-plus-extrapolated GPH frames ``(batch, 1, obs_len + pred_len, 64, 64)``, the + chooser logits ``(batch, num_gs)`` and the sampled decoder indices ``(batch, num_samples)``. + ``obs_traj`` may also be a mapping with keys ``obs_traj``, ``obs_traj_rel``, ``image_obs``, + optional ``seq_start_end``, and ``env_data`` (or the nine env keys at top level). + """ + if isinstance(obs_traj, Mapping): + batch_dict = obs_traj + obs_traj = batch_dict["obs_traj"] + obs_traj_rel = batch_dict["obs_traj_rel"] + image_obs = batch_dict["image_obs"] + seq_start_end = batch_dict.get("seq_start_end", seq_start_end) + env_data = _env_from_mapping(batch_dict) + if obs_traj_rel is None or image_obs is None or env_data is None: + raise ValueError("TropiCycloneNet needs obs_traj, obs_traj_rel, image_obs and env_data") + self._check_inputs(obs_traj, obs_traj_rel, image_obs, env_data) + batch = obs_traj_rel.size(1) + obs_len = obs_traj_rel.size(0) + if seq_start_end is None: + starts = torch.arange(batch, device=obs_traj.device) + seq_start_end = torch.stack([starts, starts + 1], dim=1) + + # Chooser branch: track encoder on the observed GPH embeddings plus Env-T-Net. + encoder_img_real = self.img_embedding_real(image_obs.reshape(batch, self.obs_len, -1)).permute(1, 0, 2) + final_encoder_env_h = self.encoder_env(obs_traj_rel, encoder_img_real)["final_h"][0] + evn_feature_chooser, _, _ = self.env_net_chooser(env_data, image_obs) + dec_h_evn = self.feature2dech_env(torch.cat([final_encoder_env_h.reshape(batch, -1), evn_feature_chooser], dim=1)) + + # Generator branch: GPH U-Net extrapolation, track encoder, mixed decoder state. + unet_out = self.Unet(image_obs) + all_img = torch.cat([image_obs[:, :, 0].unsqueeze(2), unet_out], dim=2) + img_embed_input = self.img_embedding(all_img.reshape(batch, self.obs_len + self.pred_len, -1)).permute(1, 0, 2) + final_encoder_h = self.encoder(obs_traj_rel, img_embed_input[:obs_len])["final_h"][0] + dec_h = self.feature2dech(torch.cat([final_encoder_h.reshape(batch, -1), evn_feature_chooser], dim=1)).unsqueeze(0) + + last_pos = obs_traj[-1] + last_pos_rel = obs_traj_rel[-1] + decoder_img = img_embed_input[obs_len:] + last_img = img_embed_input[obs_len - 1] + if all_g_out: + preds_rel = [] + with torch.no_grad(): + state_tuple = self.mix_noise(dec_h, seq_start_end, batch, user_noise=user_noise) + for decoder in self.gs: + pred_rel, _ = decoder(obs_traj, obs_traj_rel, last_pos, last_pos_rel, state_tuple, seq_start_end, decoder_img, last_img) + preds_rel.append(pred_rel.reshape(self.pred_len, 1, batch, 4)) + pred_traj_fake_rel_nums = torch.cat(preds_rel, dim=1) + net_chooser_out, sampled_gen_idxs = self.get_samples(dec_h_evn, num_samples) + else: + with torch.no_grad(): + net_chooser_out, sampled_gen_idxs = self.get_samples(dec_h_evn, num_samples) + preds_rel = [] + for sample in range(num_samples): + prediction = obs_traj.new_ones(self.pred_len, batch, 4) + gen_index = sampled_gen_idxs[:, sample] + distinct = torch.unique(gen_index).tolist() + # Official loop: ``for g_i in range(len(distinct))`` matches indices 0..len-1, so + # storms whose sampled decoder index is >= the number of distinct indices in the + # batch keep the placeholder value 1 for every step. PyHazards visits the distinct + # indices themselves unless ``official_sample_loop`` is set. + visit = range(len(distinct)) if self.official_sample_loop else distinct + for g_i in visit: + mask = gen_index == g_i + count = int(mask.sum()) + if count < 1: + continue + state_tuple = self.mix_noise(dec_h[:, mask], seq_start_end[mask], count) + pred_rel, _ = self.gs[g_i]( + obs_traj[:, mask], + obs_traj_rel[:, mask], + last_pos[mask], + last_pos_rel[mask], + state_tuple, + seq_start_end[mask], + decoder_img[:, mask], + last_img[mask], + ) + prediction[:, mask] = pred_rel + preds_rel.append(prediction.reshape(self.pred_len, 1, batch, 4)) + pred_traj_fake_rel_nums = torch.cat(preds_rel, dim=1) + return pred_traj_fake_rel_nums, all_img, net_chooser_out, sampled_gen_idxs + + +class TrajectoryDiscriminator(nn.Module): + """TCN_M discriminator: track encoder over GPH embeddings plus a real/fake MLP (231,009 parameters).""" + + def __init__( + self, + obs_len: int = 8, + pred_len: int = 4, + embedding_dim: int = 32, + h_dim: int = 128, + mlp_dim: int = 128, + num_layers: int = 1, + activation: str = "relu", + batch_norm: bool = False, + dropout: float = 0.0, + d_type: str = "local", + ): + super().__init__() + if d_type != "local": + raise ValueError("only the official d_type='local' discriminator is implemented") + self.obs_len = obs_len + self.pred_len = pred_len + self.seq_len = obs_len + pred_len + self.mlp_dim = mlp_dim + self.h_dim = h_dim + self.d_type = d_type + self.img_embedding = nn.Linear(64 * 64, 32) + self.encoder = Encoder(embedding_dim=embedding_dim, h_dim=h_dim, mlp_dim=mlp_dim, num_layers=num_layers, dropout=dropout) + self.real_classifier = make_mlp([h_dim, mlp_dim, 1], activation=activation, batch_norm=batch_norm, dropout=dropout) + + def forward(self, traj: torch.Tensor, traj_rel: torch.Tensor, seq_start_end: torch.Tensor, img: torch.Tensor): + """Scores ``(batch, 1)`` (after the official final ReLU) and the encoder feature ``(batch, h_dim)``.""" + if img.ndim != 5 or traj_rel.ndim != 3 or img.size(2) != traj_rel.size(0) or img.size(0) != traj_rel.size(1): + raise ValueError( + f"expected traj_rel (seq_len, batch, 4) and img (batch, 1, seq_len, 64, 64), got {tuple(traj_rel.shape)} and {tuple(img.shape)}" + ) + batch, _, length = img.shape[:3] + img_embed = self.img_embedding(img.reshape(batch, length, -1)).permute(1, 0, 2) + final_h = self.encoder(traj_rel, img_embed)["final_h"][0] + classifier_input = final_h.squeeze() + return self.real_classifier(classifier_input), classifier_input + + +# --------------------------------------------------------------------------------------------- +# PyHazards entry point +# --------------------------------------------------------------------------------------------- + + +def denormalize_track(values: torch.Tensor) -> Dict[str, torch.Tensor]: + """Map TCND-normalised ``[..., 4]`` values (lon, lat, pres, wind) to physical units.""" + return {name: values[..., i] * TCND_NORMALIZATION[name][0] + TCND_NORMALIZATION[name][1] for i, name in enumerate(TRACK_VARIABLES)} + + +def normalize_track(lon, lat, pres, wind) -> torch.Tensor: + """Inverse of :func:`denormalize_track`; returns ``[..., 4]`` normalised values.""" + parts = [torch.as_tensor(v, dtype=torch.float32) for v in (lon, lat, pres, wind)] + return torch.stack( + [(part - TCND_NORMALIZATION[name][1]) / TCND_NORMALIZATION[name][0] for part, name in zip(parts, TRACK_VARIABLES)], dim=-1 + ) + + +class TropiCycloneNet(TrajectoryGenerator): + """The TCN_M generator with a :meth:`forecast` adapter for the PyHazards cyclone benchmark. + + The module is the official generator itself (no key prefix), so official generator state + dicts load with ``strict=True``; :func:`load_tropicyclonenet_checkpoint` loads the released + one. ``forward`` keeps the official signature and outputs. + """ + + def forecast(self, batch: Mapping[str, Any], num_samples: Optional[int] = None) -> Dict[str, torch.Tensor]: + """Sampled forecasts in physical units. + + Returns ``lat``, ``lon`` (degrees), ``pres`` (hPa) and ``wind`` (m/s), each + ``(batch, num_samples, pred_len)`` for lead times 6, 12, 18 and 24 h, plus the chooser + ``logits`` and the sampled ``generator_index``. Positions are the last observed position + plus the cumulative sum of the predicted steps, as in the official evaluation. + """ + num_samples = int(num_samples or self.num_sample) + rel, _, logits, indices = self.forward(batch, num_samples=num_samples) + obs_traj = batch["obs_traj"] + absolute = torch.cumsum(rel, dim=0) + obs_traj[-1].unsqueeze(0).unsqueeze(0) + physical = denormalize_track(absolute.permute(2, 1, 0, 3)) + return {**physical, "logits": logits, "generator_index": indices} + + +def load_tropicyclonenet_checkpoint( + path: Union[str, Path], model: Optional[nn.Module] = None, state: str = "g_state", verify_sha256: bool = True +) -> nn.Module: + """Load the released ``checkpoint_with_model_16000.pt`` into a generator (or ``model``). + + The checkpoint stores training history in ``collections.defaultdict`` objects, which + ``torch.load(weights_only=True)`` rejects, so it is unpickled with ``weights_only=False``; + by default this only happens after the file's sha256 matched the released file + (:data:`CHECKPOINT_SHA256`). ``state`` picks ``g_state`` (used by the official evaluation; + identical to ``g_best_state`` in the release) or ``d_state`` for a discriminator. + """ + path = Path(path) + if verify_sha256: + digest = hashlib.sha256(path.read_bytes()).hexdigest() + if digest != CHECKPOINT_SHA256: + raise ValueError( + f"{path} has sha256 {digest}, not the released checkpoint {CHECKPOINT_SHA256}; " + "pass verify_sha256=False only for a file you trust (it is unpickled)" + ) + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + if model is None: + model = TrajectoryDiscriminator() if state.startswith("d_") else TropiCycloneNet() + model.load_state_dict(checkpoint[state], strict=True) + return model def tropicyclonenet_builder( task: str, - input_dim: int = 8, - hidden_dim: int = 64, - horizon: int = 5, - output_dim: int = 3, - num_layers: int = 2, - dropout: float = 0.1, + official_sample_loop: bool = False, + num_sample: int = 6, **kwargs, ) -> nn.Module: - _ = kwargs - if task.lower() != "regression": - raise ValueError("TropiCycloneNet only supports regression for track/intensity forecasting.") - return TropiCycloneNet( - input_dim=input_dim, - hidden_dim=hidden_dim, - horizon=horizon, - output_dim=output_dim, - num_layers=num_layers, - dropout=dropout, - ) + if task.lower() not in {"regression", "forecasting"}: + raise ValueError("tropicyclonenet forecasts tracks and intensities; use task='regression' or 'forecasting'.") + config = {key: kwargs[key] for key in RELEASED_CONFIG if key in kwargs} + return TropiCycloneNet(**{**RELEASED_CONFIG, **config}, num_sample=num_sample, official_sample_loop=official_sample_loop) -__all__ = ["TropiCycloneNet", "tropicyclonenet_builder"] +__all__ = [ + "CHECKPOINT_SHA256", + "CHECKPOINT_URL", + "ENV_FEATURES", + "RELEASED_CONFIG", + "TCND_NORMALIZATION", + "TRACK_VARIABLES", + "TrajectoryDiscriminator", + "TrajectoryGenerator", + "TropiCycloneNet", + "denormalize_track", + "load_tropicyclonenet_checkpoint", + "normalize_track", + "tropicyclonenet_builder", +] diff --git a/pyhazards/models/ts_satfire.py b/pyhazards/models/ts_satfire.py new file mode 100644 index 00000000..59e9c5bf --- /dev/null +++ b/pyhazards/models/ts_satfire.py @@ -0,0 +1,139 @@ +"""The TS-SatFire next-day prediction baselines with the benchmark's own configurations. + +Zhao, Gerard & Ban, "TS-SatFire: A Multi-Task Satellite Image Time-Series Dataset for Wildfire +Detection and Prediction", Scientific Data 12:1817 (2025), doi:10.1038/s41597-025-06271-3, +arXiv:2412.11555; code https://github.com/zhaoyutim/TS-SatFire (no license; used only as a test +oracle). TS-SatFire is a dataset paper: its prediction-task baselines are four spatio-temporal +MONAI networks, built in ``run_spatial_temp_model_pred.py`` at commit ``da75732``. This builder +returns each of them as configured there (the architectures are the PyHazards ports +:mod:`~pyhazards.models.unet3d`, :mod:`~pyhazards.models.attention_unet`, +:mod:`~pyhazards.models.unetr` and :mod:`~pyhazards.models.swin_unetr`): + +- ``unet3d``: MONAI U-Net, 3D, channels (64, 128, 256, 512, 1024), stride (1, 2, 2) at every level + (31,712,970 parameters with 43 channels; Table 3: 31.7M); +- ``attention_unet3d``: MONAI Attention U-Net with the same channels and strides (94,555,506; + Table 3: 94.5M); +- ``unetr3d``: UNETR with img_size (T, 256, 256), patch (1, 16, 16), (1, 2, 2) up-sampling, a + (1, 3, 3) ``decoder3`` kernel, feature size 16, hidden 384, MLP 1536, batch norm (28,816,866 at + T = 6; see the card for the 34.8M of Table 3); +- ``swinunetr3d`` (default; the model behind the paper's Tables 4 and 5): SwinUNETR with patch + (1, 2, 2), window (T, 4, 4), TS-SatFire's patch merging, ``attn_version="v1"``, feature size 36, + ``num_heads`` heads in every stage (3 by default, not published), batch norm (33,191,942 at + T = 6; Table 3: 33.2M). + +The input is ``(batch, T, 43, 256, 256)``: 27 bands with the 17-class land cover one-hot encoded +in place (21 + 17 + 5 channels, ``FireDataset.preprocess``), T in {2, 4, 6} days. Every model runs +on ``(batch, 43, T, H, W)`` and, as in the prediction script (``outputs.mean(2)``), the two-class +logits are averaged over time to ``(batch, 2, H, W)``. +""" + +from __future__ import annotations + +from typing import Optional + +import torch.nn as nn + +from .attention_unet import TemporalAttentionUnet +from .swin_unetr import TemporalSwinUNETR +from .unet3d import TS_SATFIRE_3D_STRIDES, TS_SATFIRE_CHANNELS, TemporalUNet +from .unetr import ( + TS_SATFIRE_UNETR3D_DECODER3_KERNEL, + TS_SATFIRE_UNETR3D_PATCH, + TS_SATFIRE_UNETR3D_UP, + TemporalUNETR, +) + +TS_SATFIRE_BASELINES = ("unet3d", "attention_unet3d", "unetr3d", "swinunetr3d") +# 27 raw bands; land cover (index 21) one-hot encoded into 17 channels. +TS_SATFIRE_PRED_CHANNELS = 43 +# run_spatial_temp_model_pred.py: hidden/MLP sizes of the default and the "v0" UNETR. +TS_SATFIRE_UNETR_WIDTHS = {"default": (384, 1536), "v0": (768, 3072)} + + +def ts_satfire_builder( + task: str, + baseline: str = "swinunetr3d", + in_channels: int = TS_SATFIRE_PRED_CHANNELS, + history: int = 6, + image_size: int = 256, + out_channels: int = 2, + feature_size: Optional[int] = None, + num_heads: int = 3, + unetr_version: str = "default", + time_reduction: str = "mean", + **kwargs, +) -> nn.Module: + """Build one TS-SatFire prediction baseline. + + ``history`` is the number of input days T and ``image_size`` the tile size (256 in + TS-SatFire); UNETR and SwinUNETR are built for exactly ``(history, image_size, image_size)``. + Every baseline takes ``(batch, history, in_channels, image_size, image_size)`` and returns + ``(batch, out_channels, image_size, image_size)`` logits (``time_reduction="none"`` keeps the + time axis). ``feature_size`` overrides the UNETR (16) or SwinUNETR (36) feature size, + ``num_heads`` is SwinUNETR's heads per stage (the ``-nh`` argument of the script) and + ``unetr_version="v0"`` selects the script's alternative UNETR widths (768 / 3072). Each baseline + checks its input shape and raises ``ValueError`` for any other layout. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"ts_satfire supports task='segmentation', got {task!r}.") + if in_channels <= 0 or history <= 0 or image_size <= 0: + raise ValueError( + f"in_channels, history and image_size must be positive, got {in_channels}, {history} and {image_size}." + ) + img_size = (history, image_size, image_size) + if baseline in ("unet3d", "attention_unet3d"): + network = TemporalUNet if baseline == "unet3d" else TemporalAttentionUnet + return network( + spatial_dims=3, + in_channels=in_channels, + out_channels=out_channels, + channels=TS_SATFIRE_CHANNELS, + strides=TS_SATFIRE_3D_STRIDES, + stride_mode="shared", + time_reduction=time_reduction, + ) + if baseline == "unetr3d": + if unetr_version not in TS_SATFIRE_UNETR_WIDTHS: + raise ValueError(f"unetr_version must be one of {sorted(TS_SATFIRE_UNETR_WIDTHS)}, got {unetr_version!r}.") + hidden_size, mlp_dim = TS_SATFIRE_UNETR_WIDTHS[unetr_version] + return TemporalUNETR( + in_channels=in_channels, + out_channels=out_channels, + img_size=img_size, + spatial_dims=3, + norm_name="batch", + feature_size=16 if feature_size is None else feature_size, + patch_size=TS_SATFIRE_UNETR3D_PATCH, + kernel_size_up_down=TS_SATFIRE_UNETR3D_UP, + decoder3_kernel_size=TS_SATFIRE_UNETR3D_DECODER3_KERNEL, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + time_reduction=time_reduction, + ) + if baseline == "swinunetr3d": + return TemporalSwinUNETR( + img_size=img_size, + patch_size=(1, 2, 2), + window_size=(history, 4, 4), + in_channels=in_channels, + out_channels=out_channels, + depths=(2, 2, 2, 2), + num_heads=(num_heads,) * 4, + feature_size=36 if feature_size is None else feature_size, + norm_name="batch", + drop_rate=0.0, + attn_drop_rate=0.0, + dropout_path_rate=0.0, + attn_version="v1", + normalize=True, + use_checkpoint=False, + spatial_dims=3, + downsample="ts_satfire", + wrap_out=True, + time_reduction=time_reduction, + ) + raise ValueError(f"baseline must be one of {TS_SATFIRE_BASELINES}, got {baseline!r}.") + + +__all__ = ["TS_SATFIRE_BASELINES", "TS_SATFIRE_PRED_CHANNELS", "ts_satfire_builder"] diff --git a/pyhazards/models/unet.py b/pyhazards/models/unet.py new file mode 100644 index 00000000..200d850b --- /dev/null +++ b/pyhazards/models/unet.py @@ -0,0 +1,229 @@ +"""U-Net (Ronneberger, Fischer & Brox, MICCAI 2015), rebuilt from the paper. + +Ronneberger, Fischer & Brox, "U-Net: Convolutional Networks for Biomedical Image Segmentation", +MICCAI 2015, LNCS 9351, pp. 234-241, arXiv:1505.04597 (Fig. 1 and Sections 2-3). + +The authors released only a Caffe/MATLAB tarball without a license (``u-net-release-2015-10-02``), +so nothing is copied from it: the network is written from the paper. The released network +definition (``phseg_v5-train.prototxt``) and its trained weights are used only as a test-time +oracle (tests/oracle/test_unet_oracle.py), and they settle details the paper leaves open: + +* module names follow the Caffe layer names (``conv_d0a-b`` -> ``conv_d0a_b``, ...), so the + released weights map onto this module one to one. ``d0``-``d4`` are the five levels of the + contracting path, ``u3``-``u0`` the four levels of the expansive path, and the letters + ``a``-``d`` the successive feature maps within a level; +* the up-sampled map comes first in each concatenation, followed by the cropped skip feature; +* the crop is centred (the release's crop layer aligns the two maps by their receptive fields); +* the two dropout layers (p = 0.5, training only) follow the last ReLU of the 512- and + 1024-channel levels; the first is applied in place, so the skip connection of the 512-channel + level carries it too; +* initialisation: the release's weight filler draws from N(0, 2 / n) with n = weights per output + unit (``count / num`` of the Caffe blob), and biases start at zero. For the 2x2 up-convolutions + this is n = 4 * out_channels, which is what ``kaiming_normal_(mode="fan_in")`` computes for + ``ConvTranspose2d``. + +Architecture (paper Fig. 1): four 2x2 max-pool down-sampling steps and four 2x2 up-convolutions, +64-128-256-512-1024 channels, two unpadded 3x3 convolutions with ReLU per level, centre-cropped +skip connections, and a final 1x1 convolution. With the paper's valid convolutions the output is +smaller than the input (572 -> 388); ``unet_output_size`` and ``unet_input_size`` give the sizes. +``padding="same"`` zero-pads the 3x3 convolutions so the output keeps the input size, which suits +fixed-size wildfire tiles but is not the paper's network. +""" + +from __future__ import annotations + +import math +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +UNET_CHANNELS = (64, 128, 256, 512, 1024) +UNET_VARIANTS = ("paper", "phseg_v5") +_LEVELS = 4 # down-sampling steps in the paper's network + + +def _valid_size_index(size: int) -> int: + """Return ``k`` with ``size == 16 * k + 60`` (valid-padding tile sizes), or raise ``ValueError``.""" + k, remainder = divmod(int(size) - 60, 16) + if remainder == 0 and k >= 8: + return k + above = 16 * max(k + 1, 8) + 60 + nearest = f"{16 * k + 60} or {above}" if k >= 8 else str(above) + raise ValueError( + f"U-Net with valid convolutions needs height and width of the form 16 * k + 60 with k >= 8 " + f"(188, 204, ..., 572, ...) so that every 2x2 max-pooling sees an even size; got {size} " + f"(nearest valid: {nearest})." + ) + + +def unet_output_size(input_size: int, padding: str = "valid") -> int: + """Output height/width of the U-Net for an input height/width (572 -> 388 for valid padding).""" + if padding == "same": + if input_size <= 0 or input_size % (2**_LEVELS): + raise ValueError(f"U-Net with padding='same' needs sizes divisible by 16, got {input_size}.") + return int(input_size) + if padding != "valid": + raise ValueError(f"padding must be 'valid' or 'same', got {padding!r}") + return 16 * _valid_size_index(input_size) - 124 + + +def unet_input_size(output_size: int) -> int: + """Smallest valid-padding input size whose output covers ``output_size`` pixels. + + This is the tile size rule of the authors' overlap-tile script: the input is + ``16 * k + 60`` and the output ``16 * k - 124`` for the smallest ``k`` that is large enough. + """ + if output_size <= 0: + raise ValueError(f"output_size must be positive, got {output_size}") + k = max(8, math.ceil((int(output_size) + 124) / 16)) + return 16 * k + 60 + + +def _center_crop(skip: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor: + top = (skip.size(-2) - size[0]) // 2 + left = (skip.size(-1) - size[1]) // 2 + return skip[..., top : top + size[0], left : left + size[1]] + + +class UNet(nn.Module): + """Ronneberger et al.'s U-Net: ``(batch, in_channels, H, W)`` -> ``(batch, out_channels, H', W')`` logits. + + ``padding="valid"`` (the paper) gives ``H' = unet_output_size(H)``; ``padding="same"`` keeps + ``H' = H`` and needs ``H`` and ``W`` divisible by 16. ``upconv_relu`` and + ``last_upconv_channels`` reproduce the released Caffe network (``phseg_v5``), which applies a + ReLU after every up-convolution and gives its last up-convolution 128 output channels. + """ + + def __init__( + self, + in_channels: int = 1, + out_channels: int = 2, + channels: Sequence[int] = UNET_CHANNELS, + padding: str = "valid", + dropout: float = 0.5, + upconv_relu: bool = False, + last_upconv_channels: Optional[int] = None, + ): + super().__init__() + channels = tuple(int(c) for c in channels) + if len(channels) != _LEVELS + 1 or min(channels) <= 0: + raise ValueError(f"channels needs five positive widths (paper: {UNET_CHANNELS}), got {channels}") + if in_channels <= 0 or out_channels <= 0: + raise ValueError(f"in_channels and out_channels must be positive, got {in_channels}, {out_channels}") + if padding not in ("valid", "same"): + raise ValueError(f"padding must be 'valid' or 'same', got {padding!r}") + if not 0.0 <= dropout < 1.0: + raise ValueError(f"dropout must be in [0, 1), got {dropout}") + c0, c1, c2, c3, c4 = channels + u0 = c0 if last_upconv_channels is None else int(last_upconv_channels) + if u0 <= 0: + raise ValueError(f"last_upconv_channels must be positive, got {last_upconv_channels}") + self.in_channels = int(in_channels) + self.out_channels = int(out_channels) + self.channels = channels + self.padding = padding + self.upconv_relu = bool(upconv_relu) + pad = 1 if padding == "same" else 0 + + def conv(cin: int, cout: int) -> nn.Conv2d: + return nn.Conv2d(cin, cout, kernel_size=3, padding=pad) + + def upconv(cin: int, cout: int) -> nn.ConvTranspose2d: + return nn.ConvTranspose2d(cin, cout, kernel_size=2, stride=2) + + # Contracting path (layer order of the released network definition). + self.conv_d0a_b = conv(in_channels, c0) + self.conv_d0b_c = conv(c0, c0) + self.conv_d1a_b = conv(c0, c1) + self.conv_d1b_c = conv(c1, c1) + self.conv_d2a_b = conv(c1, c2) + self.conv_d2b_c = conv(c2, c2) + self.conv_d3a_b = conv(c2, c3) + self.conv_d3b_c = conv(c3, c3) + self.dropout_d3c = nn.Dropout(dropout) + self.conv_d4a_b = conv(c3, c4) + self.conv_d4b_c = conv(c4, c4) + self.dropout_d4c = nn.Dropout(dropout) + # Expansive path: up-convolution, concatenation [up-sampled, cropped skip], two 3x3 convolutions. + self.upconv_d4c_u3a = upconv(c4, c3) + self.conv_u3b_c = conv(c3 + c3, c3) + self.conv_u3c_d = conv(c3, c3) + self.upconv_u3d_u2a = upconv(c3, c2) + self.conv_u2b_c = conv(c2 + c2, c2) + self.conv_u2c_d = conv(c2, c2) + self.upconv_u2d_u1a = upconv(c2, c1) + self.conv_u1b_c = conv(c1 + c1, c1) + self.conv_u1c_d = conv(c1, c1) + self.upconv_u1d_u0a = upconv(c1, u0) + self.conv_u0b_c = conv(u0 + c0, c0) + self.conv_u0c_d = conv(c0, c0) + self.conv_u0d_score = nn.Conv2d(c0, out_channels, kernel_size=1) + + # Paper Section 3: Gaussian weights with standard deviation sqrt(2 / N), N = inputs per unit. + for module in self.modules(): + if isinstance(module, (nn.Conv2d, nn.ConvTranspose2d)): + nn.init.kaiming_normal_(module.weight, mode="fan_in", nonlinearity="relu") + nn.init.zeros_(module.bias) + + def output_size(self, input_size: int) -> int: + """Output height/width for an input height/width under this model's padding.""" + return unet_output_size(input_size, self.padding) + + def _up(self, upconv: nn.ConvTranspose2d, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: + x = upconv(x) + if self.upconv_relu: + x = F.relu(x) + return torch.cat([x, _center_crop(skip, x.shape[-2:])], dim=1) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 4: + raise ValueError(f"UNet expects input shape (batch, channels, height, width), got {tuple(x.shape)}.") + if x.size(1) != self.in_channels: + raise ValueError(f"UNet expected {self.in_channels} input channels, got {x.size(1)}.") + for size in x.shape[-2:]: + self.output_size(int(size)) # raises ValueError for sizes the network cannot take + + d0c = F.relu(self.conv_d0b_c(F.relu(self.conv_d0a_b(x)))) + d1c = F.relu(self.conv_d1b_c(F.relu(self.conv_d1a_b(F.max_pool2d(d0c, 2))))) + d2c = F.relu(self.conv_d2b_c(F.relu(self.conv_d2a_b(F.max_pool2d(d1c, 2))))) + d3c = self.dropout_d3c(F.relu(self.conv_d3b_c(F.relu(self.conv_d3a_b(F.max_pool2d(d2c, 2)))))) + d4c = self.dropout_d4c(F.relu(self.conv_d4b_c(F.relu(self.conv_d4a_b(F.max_pool2d(d3c, 2)))))) + + u3d = F.relu(self.conv_u3c_d(F.relu(self.conv_u3b_c(self._up(self.upconv_d4c_u3a, d4c, d3c))))) + u2d = F.relu(self.conv_u2c_d(F.relu(self.conv_u2b_c(self._up(self.upconv_u3d_u2a, u3d, d2c))))) + u1d = F.relu(self.conv_u1c_d(F.relu(self.conv_u1b_c(self._up(self.upconv_u2d_u1a, u2d, d1c))))) + u0d = F.relu(self.conv_u0c_d(F.relu(self.conv_u0b_c(self._up(self.upconv_u1d_u0a, u1d, d0c))))) + return self.conv_u0d_score(u0d) + + +def unet_builder( + task: str, + in_channels: int = 1, + out_channels: int = 2, + padding: str = "valid", + dropout: float = 0.5, + variant: str = "paper", + channels: Sequence[int] = UNET_CHANNELS, + **kwargs, +) -> nn.Module: + """Build the U-Net. ``variant="phseg_v5"`` gives the authors' released Caffe network.""" + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"unet supports task='segmentation', got {task!r}.") + if variant not in UNET_VARIANTS: + raise ValueError(f"variant must be one of {UNET_VARIANTS}, got {variant!r}") + release = variant == "phseg_v5" + return UNet( + in_channels=in_channels, + out_channels=out_channels, + channels=channels, + padding=padding, + dropout=dropout, + upconv_relu=release, + last_upconv_channels=tuple(channels)[1] if release else None, + ) + + +__all__ = ["UNET_CHANNELS", "UNET_VARIANTS", "UNet", "unet_builder", "unet_input_size", "unet_output_size"] diff --git a/pyhazards/models/unet3d.py b/pyhazards/models/unet3d.py new file mode 100644 index 00000000..e8c87c49 --- /dev/null +++ b/pyhazards/models/unet3d.py @@ -0,0 +1,399 @@ +"""MONAI's ``UNet``, with TS-SatFire's spatio-temporal (U-Net-3D) configuration. + +Port of ``monai.networks.nets.UNet`` from MONAI 1.3.2 (``monai/networks/nets/unet.py``, +``monai/networks/blocks/convolutions.py`` ``ResidualUnit`` and +``monai/networks/layers/simplelayers.py`` ``SkipConnection``; Apache License 2.0, Copyright (c) +MONAI Consortium). The convolution blocks are shared with :mod:`pyhazards.models.attention_unet`. +Changes made for PyHazards: plain PyTorch (no MONAI dependency), invalid configurations and input +shapes raise ``ValueError`` up front, activations and norms are given by name (``"prelu"``, +``"relu"``; ``"instance"``, ``"batch"``), a ``stride_mode="shared"`` option reproduces the +TS-SatFire modification below, and :class:`TemporalUNet` adds the TS-SatFire input layout and +temporal read-out. Module names, creation order and defaults follow MONAI, so MONAI state dicts +load with ``strict=True`` and the same seed gives the same initial weights. + +What MONAI's ``UNet`` is: MONAI documents it as the "enhanced" residual U-Net of Kerfoot et al., +"Left-Ventricle Quantification Using Residual U-Net" (STACOM 2018, LNCS 11395, +doi:10.1007/978-3-030-12029-0_40). Each level has one encoder unit that down-samples with a +strided convolution (no pooling) and one decoder unit that up-samples with a strided transposed +convolution applied to the concatenation of the skip feature and the up-sampled deeper feature; +with ``num_res_units > 0`` these units are residual units. With ``num_res_units=0`` -- the +setting TS-SatFire uses -- every unit is a single ``Conv -> InstanceNorm -> Dropout -> PReLU``, +so the network is a plain strided-convolution encoder-decoder with concatenation skips, one +convolution per level and side, and no residual connections. It is neither Ronneberger et al.'s +2D U-Net (two unpadded 3x3 convolutions per level, max pooling) nor Cicek et al.'s 3D U-Net +(two 3x3x3 convolutions with batch norm per level, max pooling). + +TS-SatFire (Zhao, Gerard & Ban, Scientific Data 12:1817, 2025) uses it in two ways: the 2D +"U-Net" baseline is stock MONAI ``UNet(spatial_dims=2, channels=(64, 128, 256, 512, 1024), +strides=(2, 2, 2, 2))``; "U-Net-3D" uses the repository's copy ``spatial_models/unet.py``, whose +only change is that the single ``strides`` argument -- ``(1, 2, 2)`` over (time, height, width) +-- is applied at every level instead of one entry per level, so time is never down-sampled. The +prediction script feeds ``(batch, channels, time, H, W)`` and averages the logits over time. +""" + +from __future__ import annotations + +from typing import Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn + +from .attention_unet import _CONV, Convolution, _as_tuple, _same_padding +from .monai_blocks import TemporalReadout + +IntOrSeq = Union[int, Sequence[int]] + +# TS-SatFire configuration (run_spatial_temp_model_pred.py, run_spatial_model.py). +TS_SATFIRE_CHANNELS = (64, 128, 256, 512, 1024) +TS_SATFIRE_3D_STRIDES = (1, 2, 2) + + +class SkipConnection(nn.Module): + """``cat([x, submodule(x)], dim=1)`` (``monai.networks.layers.SkipConnection``, mode ``"cat"``).""" + + def __init__(self, submodule: nn.Module, dim: int = 1): + super().__init__() + self.submodule = submodule + self.dim = dim + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return torch.cat([x, self.submodule(x)], dim=self.dim) + + +class ResidualUnit(nn.Module): + """``subunits`` convolution units plus an additive residual (``monai.networks.blocks.ResidualUnit``). + + The residual path is the identity, or a convolution when the unit changes the channel count + (1x1, no padding) or strides (same kernel and padding as the units). + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + strides: IntOrSeq = 1, + kernel_size: IntOrSeq = 3, + subunits: int = 2, + adn_ordering: str = "NDA", + act: Optional[str] = "prelu", + norm: Optional[str] = "instance", + dropout: Optional[float] = None, + bias: bool = True, + last_conv_only: bool = False, + padding: Optional[IntOrSeq] = None, + ): + super().__init__() + self.spatial_dims = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.conv = nn.Sequential() + self.residual: nn.Module = nn.Identity() + if not padding: + padding = _same_padding(kernel_size) + schannels = in_channels + sstrides: IntOrSeq = strides + subunits = max(1, subunits) + for su in range(subunits): + conv_only = last_conv_only and su == (subunits - 1) + unit = Convolution( + spatial_dims, + schannels, + out_channels, + strides=sstrides, + kernel_size=kernel_size, + adn_ordering=adn_ordering, + act=act, + norm=norm, + dropout=dropout, + bias=bias, + conv_only=conv_only, + padding=padding, + ) + self.conv.add_module(f"unit{su:d}", unit) + schannels = out_channels + sstrides = 1 + if np.prod(strides) != 1 or in_channels != out_channels: + rkernel_size, rpadding = kernel_size, padding + if np.prod(strides) == 1: # only the channel count changes: 1x1 kernel without padding + rkernel_size, rpadding = 1, 0 + self.residual = _CONV[spatial_dims](in_channels, out_channels, rkernel_size, strides, rpadding, bias=bias) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + res = self.residual(x) + return self.conv(x) + res + + +class UNet(nn.Module): + """MONAI ``UNet`` (1.3.2) in plain PyTorch. + + Args: + spatial_dims: 1, 2 or 3. + in_channels: input channels. + out_channels: output channels (logits, no activation). + channels: feature widths, top level first; at least two entries. + strides: with ``stride_mode="per_level"`` (MONAI), one stride per level + (``len(channels) - 1`` entries are used), each an int or one value per spatial + dimension. With ``stride_mode="shared"`` (TS-SatFire's copy), a single stride -- an int + or one value per spatial dimension -- used at every level. + kernel_size: convolution kernel size (odd). + up_kernel_size: transposed-convolution kernel size (odd). + num_res_units: residual units per encoder unit (0: plain convolutions, MONAI's default). + act: ``"prelu"`` (MONAI's default), ``"relu"`` or ``None``. + norm: ``"instance"`` (MONAI's default), ``"batch"`` or ``None``. + dropout: dropout rate in every unit. + bias: convolution bias. + adn_ordering: order of normalisation (N), dropout (D) and activation (A). + stride_mode: ``"per_level"`` or ``"shared"``. + + Input ``(batch, in_channels, *spatial)``; output ``(batch, out_channels, *spatial)``. Every + spatial size must be divisible by the product of that dimension's strides. + """ + + def __init__( + self, + spatial_dims: int, + in_channels: int, + out_channels: int, + channels: Sequence[int], + strides: Union[IntOrSeq, Sequence[IntOrSeq]], + kernel_size: IntOrSeq = 3, + up_kernel_size: IntOrSeq = 3, + num_res_units: int = 0, + act: Optional[str] = "prelu", + norm: Optional[str] = "instance", + dropout: float = 0.0, + bias: bool = True, + adn_ordering: str = "NDA", + stride_mode: str = "per_level", + ): + super().__init__() + if spatial_dims not in (1, 2, 3): + raise ValueError(f"spatial_dims must be 1, 2 or 3, got {spatial_dims}") + if in_channels <= 0 or out_channels <= 0: + raise ValueError("in_channels and out_channels must be positive.") + channels = tuple(int(c) for c in channels) + if len(channels) < 2: + raise ValueError(f"channels needs at least two entries, got {channels!r}") + n_levels = len(channels) - 1 + if stride_mode == "shared": + level_strides = [strides] * n_levels # TS-SatFire: the same stride at every level + elif stride_mode == "per_level": + if isinstance(strides, int): + raise ValueError("stride_mode='per_level' needs one stride per level; use stride_mode='shared'.") + level_strides = list(strides) + if len(level_strides) < n_levels: + raise ValueError( + f"strides needs {n_levels} entries (len(channels) - 1) with stride_mode='per_level', " + f"got {len(level_strides)}." + ) + level_strides = level_strides[:n_levels] # MONAI ignores (and warns about) extra entries + else: + raise ValueError(f"stride_mode must be 'per_level' or 'shared', got {stride_mode!r}") + self.level_strides = [_as_tuple(s, spatial_dims, "each stride") for s in level_strides] + for name, kernel in (("kernel_size", kernel_size), ("up_kernel_size", up_kernel_size)): + _as_tuple(kernel, spatial_dims, name) + _same_padding(kernel) + if num_res_units < 0: + raise ValueError(f"num_res_units must be >= 0, got {num_res_units}") + + self.dimensions = spatial_dims + self.in_channels = in_channels + self.out_channels = out_channels + self.channels = channels + self.strides = strides + self.stride_mode = stride_mode + self.kernel_size = kernel_size + self.up_kernel_size = up_kernel_size + self.num_res_units = num_res_units + self.act = act + self.norm = norm + self.dropout = dropout + self.bias = bias + self.adn_ordering = adn_ordering + + def _create_block( + inc: int, outc: int, channels: Sequence[int], strides: Sequence[IntOrSeq], is_top: bool + ) -> nn.Module: + # Built from the bottom up, as in MONAI, so a seed gives the same initial weights. + c = channels[0] + s = strides[0] + if len(channels) > 2: + subblock = _create_block(c, c, channels[1:], strides[1:], False) + upc = c * 2 + else: + subblock = self._get_bottom_layer(c, channels[1]) + upc = c + channels[1] + down = self._get_down_layer(inc, c, s, is_top) + up = self._get_up_layer(upc, outc, s, is_top) + return nn.Sequential(down, SkipConnection(subblock), up) + + self.model = _create_block(in_channels, out_channels, self.channels, level_strides, True) + + def _get_down_layer(self, in_channels: int, out_channels: int, strides: IntOrSeq, is_top: bool) -> nn.Module: + _ = is_top + if self.num_res_units > 0: + return ResidualUnit( + self.dimensions, + in_channels, + out_channels, + strides=strides, + kernel_size=self.kernel_size, + subunits=self.num_res_units, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + adn_ordering=self.adn_ordering, + ) + return Convolution( + self.dimensions, + in_channels, + out_channels, + strides=strides, + kernel_size=self.kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + adn_ordering=self.adn_ordering, + ) + + def _get_bottom_layer(self, in_channels: int, out_channels: int) -> nn.Module: + return self._get_down_layer(in_channels, out_channels, 1, False) + + def _get_up_layer(self, in_channels: int, out_channels: int, strides: IntOrSeq, is_top: bool) -> nn.Module: + conv: nn.Module = Convolution( + self.dimensions, + in_channels, + out_channels, + strides=strides, + kernel_size=self.up_kernel_size, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + conv_only=is_top and self.num_res_units == 0, + is_transposed=True, + adn_ordering=self.adn_ordering, + ) + if self.num_res_units > 0: + ru = ResidualUnit( + self.dimensions, + out_channels, + out_channels, + strides=1, + kernel_size=self.kernel_size, + subunits=1, + act=self.act, + norm=self.norm, + dropout=self.dropout, + bias=self.bias, + last_conv_only=is_top, + adn_ordering=self.adn_ordering, + ) + conv = nn.Sequential(conv, ru) + return conv + + def size_multiple(self) -> Tuple[int, ...]: + """Per-dimension factor that every input spatial size must be a multiple of.""" + factors = [1] * self.dimensions + for stride in self.level_strides: + factors = [f * s for f, s in zip(factors, stride)] + return tuple(factors) + + def _check_input(self, x: torch.Tensor, layout: str) -> None: + if x.ndim != self.dimensions + 2: + raise ValueError(f"{type(self).__name__} expects input shape {layout}, got {tuple(x.shape)}.") + if x.size(1) != self.in_channels: + raise ValueError( + f"{type(self).__name__} expected {self.in_channels} input channels, got shape {tuple(x.shape)}." + ) + multiple = self.size_multiple() + if any(size % m for size, m in zip(x.shape[2:], multiple)): + raise ValueError( + f"Spatial shape {tuple(x.shape[2:])} must be divisible by {multiple} " + "(the product of the strides in each dimension)." + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + spatial = ", ".join(["D", "H", "W"][-self.dimensions :]) + self._check_input(x, f"(batch, channels, {spatial})") + return self.model(x) + + +class TemporalUNet(TemporalReadout, UNet): + """3D :class:`UNet` over ``(time, H, W)`` for raster time series (TS-SatFire's U-Net-3D). + + Takes ``(batch, time, channels, H, W)``, runs the network on ``(batch, channels, time, H, W)`` + and, with ``time_reduction="mean"``, averages the logits over time to + ``(batch, out_channels, H, W)``. Parameter names are those of :class:`UNet`. + """ + + def __init__(self, *args, time_reduction: str = "mean", **kwargs): + super().__init__(*args, **kwargs) + if self.dimensions != 3: + raise ValueError(f"TemporalUNet needs spatial_dims=3, got {self.dimensions}") + self._set_time_reduction(time_reduction) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self._to_network_layout(x, type(self).__name__) + self._check_input(x, "(batch, time, channels, height, width)") + return self._read_out(self.model(x)) + + +def unet3d_builder( + task: str, + in_channels: int, + out_channels: int = 2, + spatial_dims: int = 3, + channels: Sequence[int] = TS_SATFIRE_CHANNELS, + strides: Optional[Union[IntOrSeq, Sequence[IntOrSeq]]] = None, + stride_mode: str = "per_level", + kernel_size: IntOrSeq = 3, + up_kernel_size: IntOrSeq = 3, + num_res_units: int = 0, + act: Optional[str] = "prelu", + norm: Optional[str] = "instance", + dropout: float = 0.0, + bias: bool = True, + adn_ordering: str = "NDA", + time_reduction: str = "mean", + **kwargs, +) -> nn.Module: + """Build MONAI's U-Net; the defaults are TS-SatFire's U-Net-3D prediction model. + + ``spatial_dims=3`` returns a :class:`TemporalUNet` (input ``(B, T, C, H, W)``); + ``spatial_dims=2`` returns a :class:`UNet` (input ``(B, C, H, W)``). Without ``strides``, + TS-SatFire's strides are used: ``(1, 2, 2)`` at every level in 3D, ``2`` at every level in 2D. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"unet3d supports task='segmentation', got {task!r}.") + if strides is None: + strides = TS_SATFIRE_3D_STRIDES if spatial_dims == 3 else 2 + stride_mode = "shared" + common = dict( + in_channels=in_channels, + out_channels=out_channels, + channels=channels, + strides=strides, + kernel_size=kernel_size, + up_kernel_size=up_kernel_size, + num_res_units=num_res_units, + act=act, + norm=norm, + dropout=dropout, + bias=bias, + adn_ordering=adn_ordering, + stride_mode=stride_mode, + ) + if spatial_dims == 3: + return TemporalUNet(spatial_dims=3, time_reduction=time_reduction, **common) + if spatial_dims == 2: + return UNet(spatial_dims=2, **common) + raise ValueError(f"unet3d supports spatial_dims 2 or 3, got {spatial_dims}.") + + +__all__ = ["ResidualUnit", "SkipConnection", "TemporalUNet", "UNet", "unet3d_builder"] diff --git a/pyhazards/models/unetr.py b/pyhazards/models/unetr.py new file mode 100644 index 00000000..4f69c72e --- /dev/null +++ b/pyhazards/models/unetr.py @@ -0,0 +1,559 @@ +"""UNETR as implemented by MONAI, with TS-SatFire's spatio-temporal (UNETR-3D) modifications. + +Port of ``monai.networks.nets.UNETR`` from MONAI 1.3.2 (``monai/networks/nets/unetr.py``, +``monai/networks/nets/vit.py``, ``monai/networks/blocks/{patchembedding,transformerblock, +selfattention}.py`` and the UNETR / DynUNet blocks in :mod:`pyhazards.models.monai_blocks`; +Apache License 2.0, Copyright (c) MONAI Consortium). Changes made for PyHazards: plain PyTorch +(no MONAI or einops dependency), invalid configurations and input shapes raise ``ValueError`` up +front, three options reproduce the TS-SatFire modifications below, and :class:`TemporalUNETR` +adds the TS-SatFire input layout and temporal read-out. Module names, creation order and defaults +follow MONAI, so MONAI state dicts load with ``strict=True`` and the same seed gives the same +initial weights. + +UNETR is Hatamizadeh et al., "UNETR: Transformers for 3D Medical Image Segmentation" (WACV 2022, +arXiv:2103.10504): a 12-layer ViT encoder on non-overlapping patches whose layer-3/6/9/12 tokens +are reshaped to feature maps and up-sampled by transposed convolutions into a convolutional +U-Net decoder. The authors' official code (Project-MONAI/research-contributions) is built on +MONAI's blocks. + +TS-SatFire (Zhao, Gerard & Ban, Scientific Data 12:1817, 2025) uses it in two ways: "UNETR-2D" +is stock MONAI ``UNETR(spatial_dims=2, img_size=(256, 256), feature_size=16, hidden_size=384, +mlp_dim=1536, norm_name="batch")`` (23,521,186 parameters with 8 input channels, Table 3: +23.52M); "UNETR-3D" uses the repository's copy ``spatial_models/unetr/unetr.py``, which + +- takes a ``patch_size`` argument -- ``(1, 16, 16)`` over (time, height, width), so patches never + span several days (MONAI hard-codes 16 in every dimension); +- up-samples with ``(1, 2, 2)`` transposed convolutions everywhere (``kernel_size_up_down`` in the + prediction script), so time is never up-sampled; and +- uses a ``(1, 3, 3)`` kernel in ``decoder3`` (``(3, 3, 3)`` everywhere else). +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +import torch.nn as nn + +from .monai_blocks import ( + MLPBlock, + NormSpec, + TemporalReadout, + UnetOutBlock, + UnetrBasicBlock, + UnetrPrUpBlock, + UnetrUpBlock, + as_tuple, + check_norm_name, + trunc_normal_, +) + +IntOrSeq = Union[int, Sequence[int]] + +_CONV = {1: nn.Conv1d, 2: nn.Conv2d, 3: nn.Conv3d} + +# TS-SatFire UNETR-3D (run_spatial_temp_model_pred.py and spatial_models/unetr/unetr.py). +TS_SATFIRE_UNETR3D_PATCH = (1, 16, 16) +TS_SATFIRE_UNETR3D_UP = (1, 2, 2) +TS_SATFIRE_UNETR3D_DECODER3_KERNEL = (1, 3, 3) + + +class PatchEmbeddingBlock(nn.Module): + """ViT patch embedding with a learnable position embedding (``monai.networks.blocks``). + + ``proj_type="conv"`` uses a strided convolution, ``"perceptron"`` a linear layer on flattened + ``(patch..., channel)`` vectors. The position embedding is initialised with a truncated normal + (std 0.02), linear layers with a truncated normal and zero bias. + """ + + def __init__( + self, + in_channels: int, + img_size: Sequence[int], + patch_size: Sequence[int], + hidden_size: int, + num_heads: int, + proj_type: str = "conv", + dropout_rate: float = 0.0, + spatial_dims: int = 3, + ): + super().__init__() + if not 0 <= dropout_rate <= 1: + raise ValueError(f"dropout_rate {dropout_rate} should be between 0 and 1.") + if hidden_size % num_heads != 0: + raise ValueError(f"hidden size {hidden_size} should be divisible by num_heads {num_heads}.") + if proj_type not in {"conv", "perceptron"}: + raise ValueError(f"proj_type must be 'conv' or 'perceptron', got {proj_type!r}") + self.proj_type = proj_type + self.spatial_dims = spatial_dims + self.patch_size = tuple(patch_size) + for m, p in zip(img_size, patch_size): + if m < p: + raise ValueError("patch_size should be smaller than img_size.") + if self.proj_type == "perceptron" and m % p != 0: + raise ValueError("patch_size should be divisible by img_size for perceptron.") + self.n_patches = int(np.prod([im_d // p_d for im_d, p_d in zip(img_size, patch_size)])) + self.patch_dim = int(in_channels * np.prod(patch_size)) + self.patch_embeddings: nn.Module + if self.proj_type == "conv": + self.patch_embeddings = _CONV[spatial_dims]( + in_channels=in_channels, out_channels=hidden_size, kernel_size=patch_size, stride=patch_size + ) + else: + # MONAI: nn.Sequential(Rearrange("b c (h p1) (w p2) (d p3) -> b (h w d) (p1 p2 p3 c)"), Linear). + self.patch_embeddings = nn.Sequential(_PatchFlatten(self.patch_size), nn.Linear(self.patch_dim, hidden_size)) + self.position_embeddings = nn.Parameter(torch.zeros(1, self.n_patches, hidden_size)) + self.dropout = nn.Dropout(dropout_rate) + trunc_normal_(self.position_embeddings, mean=0.0, std=0.02, a=-2.0, b=2.0) + self.apply(self._init_weights) + + @staticmethod + def _init_weights(m: nn.Module) -> None: + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, mean=0.0, std=0.02, a=-2.0, b=2.0) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embeddings(x) + if self.proj_type == "conv": + x = x.flatten(2).transpose(-1, -2) + return self.dropout(x + self.position_embeddings) + + +class _PatchFlatten(nn.Module): + """``b c (s1 p1) (s2 p2) ... -> b (s1 s2 ...) (p1 p2 ... c)`` (MONAI's einops ``Rearrange``).""" + + def __init__(self, patch_size: Tuple[int, ...]): + super().__init__() + self.patch_size = patch_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, c = x.shape[:2] + dims = len(self.patch_size) + grid = [s // p for s, p in zip(x.shape[2:], self.patch_size)] + shape: List[int] = [b, c] + for g, p in zip(grid, self.patch_size): + shape += [g, p] + x = x.reshape(shape) + order = [0] + [2 + 2 * i for i in range(dims)] + [3 + 2 * i for i in range(dims)] + [1] + return x.permute(order).reshape(b, int(np.prod(grid)), -1) + + +class SABlock(nn.Module): + """Multi-head self-attention (``monai.networks.blocks.SABlock``).""" + + def __init__( + self, + hidden_size: int, + num_heads: int, + dropout_rate: float = 0.0, + qkv_bias: bool = False, + save_attn: bool = False, + ): + super().__init__() + if not 0 <= dropout_rate <= 1: + raise ValueError("dropout_rate should be between 0 and 1.") + if hidden_size % num_heads != 0: + raise ValueError("hidden size should be divisible by num_heads.") + self.num_heads = num_heads + self.dim_head = hidden_size // num_heads + self.inner_dim = self.dim_head * num_heads + self.out_proj = nn.Linear(self.inner_dim, hidden_size) + self.qkv = nn.Linear(hidden_size, self.inner_dim * 3, bias=qkv_bias) + self.drop_output = nn.Dropout(dropout_rate) + self.drop_weights = nn.Dropout(dropout_rate) + self.scale = self.dim_head**-0.5 + self.save_attn = save_attn + self.att_mat = torch.Tensor() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + b, n = x.shape[:2] + # einops "b h (qkv l d) -> qkv b l h d" + q, k, v = self.qkv(x).reshape(b, n, 3, self.num_heads, self.dim_head).permute(2, 0, 3, 1, 4) + att_mat = (torch.einsum("blxd,blyd->blxy", q, k) * self.scale).softmax(dim=-1) + if self.save_attn: + self.att_mat = att_mat.detach() + att_mat = self.drop_weights(att_mat) + x = torch.einsum("bhxy,bhyd->bhxd", att_mat, v) + x = x.transpose(1, 2).reshape(b, n, self.inner_dim) # "b h l d -> b l (h d)" + return self.drop_output(self.out_proj(x)) + + +class TransformerBlock(nn.Module): + """Pre-norm transformer block (``monai.networks.blocks.TransformerBlock``).""" + + def __init__( + self, + hidden_size: int, + mlp_dim: int, + num_heads: int, + dropout_rate: float = 0.0, + qkv_bias: bool = False, + save_attn: bool = False, + ): + super().__init__() + if not 0 <= dropout_rate <= 1: + raise ValueError("dropout_rate should be between 0 and 1.") + if hidden_size % num_heads != 0: + raise ValueError("hidden_size should be divisible by num_heads.") + self.mlp = MLPBlock(hidden_size, mlp_dim, dropout_rate) + self.norm1 = nn.LayerNorm(hidden_size) + self.attn = SABlock(hidden_size, num_heads, dropout_rate, qkv_bias, save_attn) + self.norm2 = nn.LayerNorm(hidden_size) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.attn(self.norm1(x)) + return x + self.mlp(self.norm2(x)) + + +class ViT(nn.Module): + """MONAI ``ViT`` encoder without the classification head (UNETR never builds it). + + Returns the final normalised tokens and the list of every block's output. + """ + + def __init__( + self, + in_channels: int, + img_size: Sequence[int], + patch_size: Sequence[int], + hidden_size: int = 768, + mlp_dim: int = 3072, + num_layers: int = 12, + num_heads: int = 12, + proj_type: str = "conv", + dropout_rate: float = 0.0, + spatial_dims: int = 3, + qkv_bias: bool = False, + save_attn: bool = False, + ): + super().__init__() + if not 0 <= dropout_rate <= 1: + raise ValueError("dropout_rate should be between 0 and 1.") + if hidden_size % num_heads != 0: + raise ValueError("hidden_size should be divisible by num_heads.") + self.classification = False + self.patch_embedding = PatchEmbeddingBlock( + in_channels=in_channels, + img_size=img_size, + patch_size=patch_size, + hidden_size=hidden_size, + num_heads=num_heads, + proj_type=proj_type, + dropout_rate=dropout_rate, + spatial_dims=spatial_dims, + ) + self.blocks = nn.ModuleList( + [TransformerBlock(hidden_size, mlp_dim, num_heads, dropout_rate, qkv_bias, save_attn) for _ in range(num_layers)] + ) + self.norm = nn.LayerNorm(hidden_size) + + def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + x = self.patch_embedding(x) + hidden_states_out = [] + for blk in self.blocks: + x = blk(x) + hidden_states_out.append(x) + return self.norm(x), hidden_states_out + + +class UNETR(nn.Module): + """MONAI ``UNETR`` (1.3.2) in plain PyTorch, with TS-SatFire's options. + + Args: + in_channels: input channels. + out_channels: output channels (logits, no activation). + img_size: spatial input size (int or one value per dimension); fixed, because the + position embedding has one entry per patch. + feature_size: decoder width (MONAI default 16). + hidden_size: ViT width (MONAI default 768; TS-SatFire uses 384). + mlp_dim: ViT MLP width (MONAI default 3072; TS-SatFire uses 1536). + num_heads: ViT attention heads. + proj_type: ``"conv"`` or ``"perceptron"`` patch embedding. + norm_name: ``"instance"`` (MONAI default) or ``"batch"`` (TS-SatFire), or ``(name, kwargs)``. + conv_block: convolution blocks after the projection up-sampling (MONAI default True). + res_block: residual convolution blocks (MONAI default True). + dropout_rate: ViT dropout. + spatial_dims: 2 or 3. + qkv_bias: bias in the attention's qkv projection. + save_attn: keep each block's attention matrix in ``attn.att_mat``. + patch_size: ViT patch size (MONAI: 16 in every dimension; TS-SatFire: ``(1, 16, 16)``). + kernel_size_up_down: kernel and stride of every transposed convolution (MONAI: 2; + TS-SatFire: ``(1, 2, 2)``). Each patch-size entry must equal its fourth power, so that + the decoder returns to the input resolution. + decoder3_kernel_size: kernel of the ``decoder3`` convolution block (MONAI: 3; + TS-SatFire: ``(1, 3, 3)``). + + Input ``(batch, in_channels, *img_size)``; output ``(batch, out_channels, *img_size)``. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + img_size: IntOrSeq, + feature_size: int = 16, + hidden_size: int = 768, + mlp_dim: int = 3072, + num_heads: int = 12, + proj_type: str = "conv", + norm_name: NormSpec = "instance", + conv_block: bool = True, + res_block: bool = True, + dropout_rate: float = 0.0, + spatial_dims: int = 3, + qkv_bias: bool = False, + save_attn: bool = False, + patch_size: IntOrSeq = 16, + kernel_size_up_down: IntOrSeq = 2, + decoder3_kernel_size: IntOrSeq = 3, + ): + super().__init__() + if spatial_dims not in (2, 3): + raise ValueError(f"spatial_dims must be 2 or 3, got {spatial_dims}") + if in_channels <= 0 or out_channels <= 0 or feature_size <= 0: + raise ValueError("in_channels, out_channels and feature_size must be positive.") + if not 0 <= dropout_rate <= 1: + raise ValueError("dropout_rate should be between 0 and 1.") + if hidden_size % num_heads != 0: + raise ValueError("hidden_size should be divisible by num_heads.") + check_norm_name(norm_name) + img_size = as_tuple(img_size, spatial_dims, "img_size") + patch = as_tuple(patch_size, spatial_dims, "patch_size") + up = as_tuple(kernel_size_up_down, spatial_dims, "kernel_size_up_down") + decoder3_kernel = as_tuple(decoder3_kernel_size, spatial_dims, "decoder3_kernel_size") + if any(k % 2 == 0 for k in decoder3_kernel): + raise ValueError(f"decoder3_kernel_size must be odd, got {decoder3_kernel_size!r}") + if any(u < 1 for u in up) or any(p != u**4 for p, u in zip(patch, up)): + raise ValueError( + f"Each patch_size entry must be kernel_size_up_down**4 (four up-sampling steps back to the " + f"input resolution), got patch_size={patch} and kernel_size_up_down={up}." + ) + if any(m % p for m, p in zip(img_size, patch)): + raise ValueError(f"img_size {img_size} must be divisible by patch_size {patch}.") + + self.num_layers = 12 + self.img_size = img_size + self.in_channels = in_channels + self.spatial_dims = spatial_dims + self.patch_size = patch + self.kernel_size_up_down = up + self.feat_size = tuple(img_d // p_d for img_d, p_d in zip(img_size, self.patch_size)) + self.hidden_size = hidden_size + self.classification = False + self.vit = ViT( + in_channels=in_channels, + img_size=img_size, + patch_size=self.patch_size, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + num_layers=self.num_layers, + num_heads=num_heads, + proj_type=proj_type, + dropout_rate=dropout_rate, + spatial_dims=spatial_dims, + qkv_bias=qkv_bias, + save_attn=save_attn, + ) + self.encoder1 = UnetrBasicBlock( + spatial_dims=spatial_dims, + in_channels=in_channels, + out_channels=feature_size, + kernel_size=3, + stride=1, + norm_name=norm_name, + res_block=res_block, + ) + for name, out_mult, num_layer in (("encoder2", 2, 2), ("encoder3", 4, 1), ("encoder4", 8, 0)): + setattr( + self, + name, + UnetrPrUpBlock( + spatial_dims=spatial_dims, + in_channels=hidden_size, + out_channels=feature_size * out_mult, + num_layer=num_layer, + kernel_size=3, + stride=1, + upsample_kernel_size=up, + norm_name=norm_name, + conv_block=conv_block, + res_block=res_block, + ), + ) + decoders = ( + ("decoder5", hidden_size, feature_size * 8, 3), + ("decoder4", feature_size * 8, feature_size * 4, 3), + ("decoder3", feature_size * 4, feature_size * 2, decoder3_kernel), # TS-SatFire: (1, 3, 3) + ("decoder2", feature_size * 2, feature_size, 3), + ) + for name, in_ch, out_ch, kernel in decoders: + setattr( + self, + name, + UnetrUpBlock( + spatial_dims=spatial_dims, + in_channels=in_ch, + out_channels=out_ch, + kernel_size=kernel, + upsample_kernel_size=up, + norm_name=norm_name, + res_block=res_block, + ), + ) + self.out = UnetOutBlock(spatial_dims=spatial_dims, in_channels=feature_size, out_channels=out_channels) + self.proj_axes = (0, spatial_dims + 1) + tuple(d + 1 for d in range(spatial_dims)) + self.proj_view_shape = list(self.feat_size) + [self.hidden_size] + + def proj_feat(self, x: torch.Tensor) -> torch.Tensor: + x = x.view([x.size(0)] + self.proj_view_shape) + return x.permute(self.proj_axes).contiguous() + + def _check_input(self, x: torch.Tensor, layout: str) -> None: + if x.ndim != self.spatial_dims + 2: + raise ValueError(f"{type(self).__name__} expects input shape {layout}, got {tuple(x.shape)}.") + if x.size(1) != self.in_channels or tuple(x.shape[2:]) != self.img_size: + raise ValueError( + f"{type(self).__name__} was built for {self.in_channels} channels and spatial size " + f"{self.img_size} (img_size), got shape {tuple(x.shape)}." + ) + + def _forward_network(self, x_in: torch.Tensor) -> torch.Tensor: + x, hidden_states_out = self.vit(x_in) + enc1 = self.encoder1(x_in) + enc2 = self.encoder2(self.proj_feat(hidden_states_out[3])) + enc3 = self.encoder3(self.proj_feat(hidden_states_out[6])) + enc4 = self.encoder4(self.proj_feat(hidden_states_out[9])) + dec4 = self.proj_feat(x) + dec3 = self.decoder5(dec4, enc4) + dec2 = self.decoder4(dec3, enc3) + dec1 = self.decoder3(dec2, enc2) + out = self.decoder2(dec1, enc1) + return self.out(out) + + def forward(self, x_in: torch.Tensor) -> torch.Tensor: + spatial = ", ".join(["D", "H", "W"][-self.spatial_dims :]) + self._check_input(x_in, f"(batch, channels, {spatial})") + return self._forward_network(x_in) + + +class TemporalUNETR(TemporalReadout, UNETR): + """3D :class:`UNETR` over ``(time, H, W)`` for raster time series (TS-SatFire's UNETR-3D). + + Takes ``(batch, time, channels, H, W)`` with ``(time, H, W) == img_size``, runs the network on + ``(batch, channels, time, H, W)`` and, with ``time_reduction="mean"``, averages the logits over + time to ``(batch, out_channels, H, W)``. Parameter names are those of :class:`UNETR`. + """ + + def __init__(self, *args, time_reduction: str = "mean", **kwargs): + super().__init__(*args, **kwargs) + if self.spatial_dims != 3: + raise ValueError(f"TemporalUNETR needs spatial_dims=3, got {self.spatial_dims}") + self._set_time_reduction(time_reduction) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self._to_network_layout(x, type(self).__name__) + self._check_input(x, "(batch, time, channels, height, width)") + return self._read_out(self._forward_network(x)) + + +def unetr_builder( + task: str, + in_channels: int, + out_channels: int = 2, + spatial_dims: int = 3, + img_size: Optional[IntOrSeq] = None, + history: int = 6, + image_size: int = 256, + feature_size: int = 16, + hidden_size: int = 384, + mlp_dim: int = 1536, + num_heads: int = 12, + proj_type: str = "conv", + norm_name: NormSpec = "batch", + conv_block: bool = True, + res_block: bool = True, + dropout_rate: float = 0.0, + qkv_bias: bool = False, + patch_size: Optional[IntOrSeq] = None, + kernel_size_up_down: Optional[IntOrSeq] = None, + decoder3_kernel_size: Optional[IntOrSeq] = None, + time_reduction: str = "mean", + **kwargs, +) -> nn.Module: + """Build MONAI's UNETR; the defaults are TS-SatFire's UNETR models. + + ``spatial_dims=3`` returns a :class:`TemporalUNETR` (input ``(B, T, C, H, W)``) for + ``img_size = (history, image_size, image_size)`` with TS-SatFire's patch ``(1, 16, 16)``, + ``(1, 2, 2)`` up-sampling and ``(1, 3, 3)`` ``decoder3`` kernel. ``spatial_dims=2`` returns a + stock MONAI :class:`UNETR` (input ``(B, C, H, W)``, patch 16) as in TS-SatFire's UNETR-2D. The + widths default to the TS-SatFire prediction script (feature size 16, hidden 384, MLP 1536) + and batch norm; pass ``hidden_size=768, mlp_dim=3072, norm_name="instance"`` for MONAI's + defaults. + """ + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"unetr supports task='segmentation', got {task!r}.") + if spatial_dims == 3: + if img_size is None: + img_size = (history, image_size, image_size) + model = TemporalUNETR( + in_channels=in_channels, + out_channels=out_channels, + img_size=img_size, + feature_size=feature_size, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + num_heads=num_heads, + proj_type=proj_type, + norm_name=norm_name, + conv_block=conv_block, + res_block=res_block, + dropout_rate=dropout_rate, + spatial_dims=3, + qkv_bias=qkv_bias, + patch_size=TS_SATFIRE_UNETR3D_PATCH if patch_size is None else patch_size, + kernel_size_up_down=TS_SATFIRE_UNETR3D_UP if kernel_size_up_down is None else kernel_size_up_down, + decoder3_kernel_size=( + TS_SATFIRE_UNETR3D_DECODER3_KERNEL if decoder3_kernel_size is None else decoder3_kernel_size + ), + time_reduction=time_reduction, + ) + return model + if spatial_dims == 2: + return UNETR( + in_channels=in_channels, + out_channels=out_channels, + img_size=(image_size, image_size) if img_size is None else img_size, + feature_size=feature_size, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + num_heads=num_heads, + proj_type=proj_type, + norm_name=norm_name, + conv_block=conv_block, + res_block=res_block, + dropout_rate=dropout_rate, + spatial_dims=2, + qkv_bias=qkv_bias, + patch_size=16 if patch_size is None else patch_size, + kernel_size_up_down=2 if kernel_size_up_down is None else kernel_size_up_down, + decoder3_kernel_size=3 if decoder3_kernel_size is None else decoder3_kernel_size, + ) + raise ValueError(f"unetr supports spatial_dims 2 or 3, got {spatial_dims}.") + + +__all__ = [ + "PatchEmbeddingBlock", + "SABlock", + "TemporalUNETR", + "TransformerBlock", + "UNETR", + "ViT", + "unetr_builder", +] diff --git a/pyhazards/models/urbanfloodcast.py b/pyhazards/models/urbanfloodcast.py index cfeb2e9f..45c3a461 100644 --- a/pyhazards/models/urbanfloodcast.py +++ b/pyhazards/models/urbanfloodcast.py @@ -1,62 +1,278 @@ +"""UrbanFloodCast deep neural operator (DNO; Xu et al., Journal of Hydrology 661:133705, 2025). + +The DNO is a U-shaped Fourier neural operator in space and time (U-NO): a lifting MLP, three operator +blocks that change the space-time grid (to 3/4 of the spatial size, then twice the time steps, then back +to the input grid) with concatenated skip connections, and a projection MLP. It maps the current water +depth and unit discharges, the rainfall of every future step and the terrain of an urban area to depth +and discharges at all ``T`` (24) future 5-minute steps at once ("one-shot"). + +The official repository (https://github.com/HydroPML/UrbanFloodCast) has no licence, so this module is +written from the paper and from permissively licensed building blocks: + +- the operator blocks follow U-NO (Rahman, Ross and Azizzadenesheli, arXiv:2204.11127), ``integral_operators.py`` + of https://github.com/ashiq24/UNO @ 19462d82729ef64ef7b9e97056ddcaaf3044ad47 (BSD-2-Clause, + Copyright (c) 2022, Md Ashiqur Rahman): ``SpectralConv3d_Uno``, ``pointwise_op_3D``, ``OperatorBlock_3D``; +- the extra point-wise MLP branch of every block is the two-layer 1x1x1 convolution MLP of the Fourier + neural operator (https://github.com/neuraloperator/neuraloperator, MIT, Copyright (c) 2023 NeuralOperator + developers). + +As in the DNO, the point-wise branch of a block is a 1x1x1 convolution followed by trilinear +resampling (U-NO's current code also low-pass filters it), and each block adds the MLP branch. +Parameter names follow the official model so its state dicts load with ``strict=True``; the oracle test +(``tests/oracle/test_urbanfloodcast_oracle.py``) runs the official code (fetched at test time, never +vendored) and checks parameters, seeded initialisation and outputs. +""" + from __future__ import annotations +from typing import Any, Tuple + import torch import torch.nn as nn +import torch.nn.functional as F + +_MIN_SPATIAL = 27 # int(3 * D / 4) must reach the 20 spatial modes of conv0 / conv8. +_MIN_TIME = 14 # rfft over time must hold the 8 temporal modes. + + +class SpectralConv3d_Uno(nn.Module): + """3-D Fourier layer with a different output grid (U-NO). + + FFT over (x, y, t), multiply the lowest ``modes1 x modes2 x modes3`` frequencies (four corners of the + two signed spatial axes) by complex weights, and inverse-FFT onto the ``(dim1, dim2, dim3)`` grid; + ``norm="forward"`` makes the operator independent of the grid size. + """ + + def __init__(self, in_codim, out_codim, dim1, dim2, dim3, modes1=None, modes2=None, modes3=None): + super().__init__() + in_codim = int(in_codim) + out_codim = int(out_codim) + self.in_channels = in_codim + self.out_channels = out_codim + self.dim1 = dim1 + self.dim2 = dim2 + self.dim3 = dim3 + if modes1 is not None: + self.modes1 = modes1 + self.modes2 = modes2 + self.modes3 = modes3 + else: + self.modes1 = dim1 + self.modes2 = dim2 + self.modes3 = dim3 // 2 + 1 + self.scale = (1 / (2 * in_codim)) ** (1.0 / 2.0) + shape = (in_codim, out_codim, self.modes1, self.modes2, self.modes3) + self.weights1 = nn.Parameter(self.scale * torch.randn(*shape, dtype=torch.cfloat)) + self.weights2 = nn.Parameter(self.scale * torch.randn(*shape, dtype=torch.cfloat)) + self.weights3 = nn.Parameter(self.scale * torch.randn(*shape, dtype=torch.cfloat)) + self.weights4 = nn.Parameter(self.scale * torch.randn(*shape, dtype=torch.cfloat)) + + @staticmethod + def compl_mul3d(inputs: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + return torch.einsum("bixyz,ioxyz->boxyz", inputs, weights) + + def forward(self, x: torch.Tensor, dim1=None, dim2=None, dim3=None) -> torch.Tensor: + if dim1 is not None: + # As in U-NO, the last requested grid becomes the default of later calls. + self.dim1, self.dim2, self.dim3 = dim1, dim2, dim3 + batchsize = x.shape[0] + x_ft = torch.fft.rfftn(x, dim=[-3, -2, -1], norm="forward") + out_ft = torch.zeros( + batchsize, self.out_channels, self.dim1, self.dim2, self.dim3 // 2 + 1, dtype=torch.cfloat, device=x.device + ) + m1, m2, m3 = self.modes1, self.modes2, self.modes3 + out_ft[:, :, :m1, :m2, :m3] = self.compl_mul3d(x_ft[:, :, :m1, :m2, :m3], self.weights1) + out_ft[:, :, -m1:, :m2, :m3] = self.compl_mul3d(x_ft[:, :, -m1:, :m2, :m3], self.weights2) + out_ft[:, :, :m1, -m2:, :m3] = self.compl_mul3d(x_ft[:, :, :m1, -m2:, :m3], self.weights3) + out_ft[:, :, -m1:, -m2:, :m3] = self.compl_mul3d(x_ft[:, :, -m1:, -m2:, :m3], self.weights4) + return torch.fft.irfftn(out_ft, s=(self.dim1, self.dim2, self.dim3), norm="forward") + + +class MLP3d(nn.Module): + """Point-wise two-layer MLP (1x1x1 convolutions, GELU) resampled trilinearly to the output grid.""" + + def __init__(self, in_channels: int, out_channels: int, mid_channels: int): + super().__init__() + self.mlp1 = nn.Conv3d(in_channels, mid_channels, 1) + self.mlp2 = nn.Conv3d(mid_channels, out_channels, 1) + + def forward(self, x: torch.Tensor, dim1: int, dim2: int, dim3: int) -> torch.Tensor: + x = self.mlp2(F.gelu(self.mlp1(x))) + return F.interpolate(x, size=(dim1, dim2, dim3), mode="trilinear", align_corners=True) + + +class pointwise_op_3D(nn.Module): # noqa: N801 (reference class name) + """Point-wise linear map (1x1x1 convolution) resampled trilinearly to the output grid.""" + + def __init__(self, in_codim, out_codim, dim1, dim2, dim3): + super().__init__() + self.conv = nn.Conv3d(int(in_codim), int(out_codim), 1) + self.dim1 = int(dim1) + self.dim2 = int(dim2) + self.dim3 = int(dim3) + + def forward(self, x: torch.Tensor, dim1=None, dim2=None, dim3=None) -> torch.Tensor: + if dim1 is None: + dim1, dim2, dim3 = self.dim1, self.dim2, self.dim3 + return F.interpolate(self.conv(x), size=(dim1, dim2, dim3), mode="trilinear", align_corners=True) + + +class OperatorBlock_3D(nn.Module): # noqa: N801 (reference class name) + """``GELU(Norm(K(v) + MLP(v) + W(v)))`` on a new grid: spectral, MLP and point-wise branches.""" + + def __init__(self, in_codim, out_codim, dim1, dim2, dim3, modes1, modes2, modes3, Normalize=False, Non_Lin=True): # noqa: N803 + super().__init__() + self.conv = SpectralConv3d_Uno(in_codim, out_codim, dim1, dim2, dim3, modes1, modes2, modes3) + self.mlp = MLP3d(in_codim, out_codim, 2 * out_codim) + self.w = pointwise_op_3D(in_codim, out_codim, dim1, dim2, dim3) + self.normalize = Normalize + self.non_lin = Non_Lin + if Normalize: + self.normalize_layer = nn.InstanceNorm3d(int(out_codim), affine=True) + + def forward(self, x: torch.Tensor, dim1=None, dim2=None, dim3=None) -> torch.Tensor: + x_out = self.conv(x, dim1, dim2, dim3) + self.mlp(x, dim1, dim2, dim3) + self.w(x, dim1, dim2, dim3) + if self.normalize: + x_out = self.normalize_layer(x_out) + if self.non_lin: + x_out = F.gelu(x_out) + return x_out class UrbanFloodCast(nn.Module): - """U-Net style urban inundation baseline.""" + """The UrbanFloodCast deep neural operator (DNO-3, the official default). + + Input ``(batch, Sy, Sx, T, initial_step, num_channels)`` (or with the last two axes merged): for each + cell and each of the ``T`` output steps, the ``num_channels=5`` inputs of the UrbanFloodCast data + pipeline - current water depth, x and y unit discharge (repeated over the output steps), the + log-transformed rainfall of that step and the normalised terrain (see + :func:`pyhazards.datasets.flood.urbanfloodcast.prepare_urbanfloodcast_event`). A (y, x, t) grid in + [0, 1] is appended, the 8 channels are lifted by ``fc`` (8 -> 16) and ``fc0`` (16 -> ``width``), + passed through ``conv0`` (to 3/4 of the spatial grid), ``conv7`` (twice the time steps; concatenated with + resampled ``conv0`` output) and ``conv8`` (back to the input grid; concatenated with the lifted input), + and projected by ``fc1`` / ``fc2`` to 3 outputs. Output ``(batch, Sy, Sx, T, 3)``: water depth and the + two unit discharges at every step. + + Defaults are the official configuration (``DNO(num_channels=5, width=10, initial_step=1, pad=False, + factor=1)``, 4,470,437 parameters, complex weights counted once). The fixed Fourier modes need + ``Sy, Sx >= 27`` and ``T >= 14``. + """ def __init__( self, - in_channels: int = 3, - history: int = 4, - base_channels: int = 32, - out_channels: int = 1, + num_channels: int = 5, + width: int = 10, + initial_step: int = 1, + pad: int = 0, + factor: int = 1, + pad_both: bool = False, ): super().__init__() - self.history = int(history) - merged_channels = in_channels * history - self.encoder = nn.Sequential( - nn.Conv2d(merged_channels, base_channels, kernel_size=3, padding=1), - nn.ReLU(), - nn.Conv2d(base_channels, base_channels, kernel_size=3, padding=1), - nn.ReLU(), + if pad: + raise ValueError( + "UrbanFloodCast supports pad=0 only: the official time padding (--time_pad) changes the output " + "length and fails in its own training script." + ) + self.num_channels = int(num_channels) + self.initial_step = int(initial_step) + self.in_width = self.initial_step * self.num_channels + 3 + self.width = int(width) + self.padding = 0 + self.pad_both = bool(pad_both) + width = self.width + self.fc = nn.Linear(self.in_width, self.in_width * 2) + self.fc0 = nn.Linear(self.in_width * 2, width) + self.conv0 = OperatorBlock_3D(width, 1 * factor * width, 48, 48, 10, 20, 20, 8, Normalize=True) + self.conv7 = OperatorBlock_3D(1 * factor * width, 1 * factor * width, 48, 48, 20, 14, 14, 8, Normalize=True) + self.conv8 = OperatorBlock_3D(2 * factor * width, width, 64, 64, 20, 20, 20, 8) + self.fc1 = nn.Linear(2 * width, 4 * width) + self.fc2 = nn.Linear(4 * width, 3) + + @staticmethod + def get_grid(shape: Tuple[int, ...], device: Any = None) -> torch.Tensor: + batchsize, size_x, size_y, size_z = shape[0], shape[1], shape[2], shape[3] + gridx = torch.linspace(0, 1, size_x).reshape(1, size_x, 1, 1, 1).repeat([batchsize, 1, size_y, size_z, 1]) + gridy = torch.linspace(0, 1, size_y).reshape(1, 1, size_y, 1, 1).repeat([batchsize, size_x, 1, size_z, 1]) + gridz = torch.linspace(0, 1, size_z).reshape(1, 1, 1, size_z, 1).repeat([batchsize, size_x, size_y, 1, 1]) + grid = torch.cat((gridx, gridy, gridz), dim=-1) + return grid if device is None else grid.to(device) + + def _check_input(self, x: torch.Tensor) -> None: + expected = self.initial_step * self.num_channels + if x.ndim == 6: + features = x.shape[4] * x.shape[5] + elif x.ndim == 5: + features = x.shape[4] + else: + raise ValueError( + "UrbanFloodCast expects inputs of shape (batch, Sy, Sx, T, initial_step, num_channels) or " + f"(batch, Sy, Sx, T, initial_step * num_channels), got ndim={x.ndim} {tuple(x.shape)}." + ) + if features != expected: + raise ValueError( + f"UrbanFloodCast expects {self.initial_step} x {self.num_channels} input features per cell and step, " + f"got shape {tuple(x.shape)}." + ) + if min(x.shape[1], x.shape[2]) < _MIN_SPATIAL or x.shape[3] < _MIN_TIME: + raise ValueError( + f"UrbanFloodCast needs Sy, Sx >= {_MIN_SPATIAL} and T >= {_MIN_TIME} for its Fourier modes; got shape {tuple(x.shape)}." + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + self._check_input(x) + x = x.view(x.shape[0], x.shape[1], x.shape[2], x.shape[3], -1) + x = torch.cat((x, self.get_grid(x.shape, x.device)), dim=-1) + x_fc0 = F.gelu(self.fc0(F.gelu(self.fc(x.float())))) + x_fc0 = x_fc0.permute(0, 4, 1, 2, 3) + d1, d2, d3 = x_fc0.shape[-3], x_fc0.shape[-2], x_fc0.shape[-1] + x_c0 = self.conv0(x_fc0, int(3 * d1 / 4), int(3 * d2 / 4), d3) + x_c7 = self.conv7(x_c0, int(3 * d1 / 4), int(3 * d2 / 4), int(2.0 * d3)) + x_c7 = torch.cat( + [x_c7, F.interpolate(x_c0, size=tuple(x_c7.shape[2:]), mode="trilinear", align_corners=True)], dim=1 ) - self.decoder = nn.Sequential( - nn.Conv2d(base_channels, base_channels, kernel_size=3, padding=1), - nn.ReLU(), - nn.Conv2d(base_channels, out_channels, kernel_size=1), + x_c8 = self.conv8(x_c7, d1, d2, d3) + x_c8 = torch.cat( + [x_c8, F.interpolate(x_fc0, size=tuple(x_c8.shape[2:]), mode="trilinear", align_corners=True)], dim=1 ) + x_c8 = x_c8.permute(0, 2, 3, 4, 1) + return self.fc2(F.gelu(self.fc1(x_c8))) - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 5: - raise ValueError("UrbanFloodCast expects inputs shaped (batch, history, channels, height, width).") - if x.size(1) != self.history: - raise ValueError(f"UrbanFloodCast expected history={self.history}, got {x.size(1)}.") - bsz, history, channels, height, width = x.shape - merged = x.reshape(bsz, history * channels, height, width) - features = self.encoder(merged) - return self.decoder(features) + +DNO = UrbanFloodCast def urbanfloodcast_builder( task: str, - in_channels: int = 3, - history: int = 4, - base_channels: int = 32, - out_channels: int = 1, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() not in {"regression", "segmentation"}: - raise ValueError("UrbanFloodCast only supports regression or segmentation-style inundation outputs.") + num_channels: int = 5, + width: int = 10, + initial_step: int = 1, + pad: int = 0, + factor: int = 1, + pad_both: bool = False, + **kwargs: Any, +) -> UrbanFloodCast: + """UrbanFloodCast DNO at the official configuration by default.""" + if task.lower() != "regression": + raise ValueError(f"UrbanFloodCast only supports task='regression', got {task!r}.") + kwargs.pop("name", None) + if kwargs: + raise ValueError(f"Unknown UrbanFloodCast arguments: {sorted(kwargs)}.") return UrbanFloodCast( - in_channels=in_channels, - history=history, - base_channels=base_channels, - out_channels=out_channels, + num_channels=num_channels, + width=width, + initial_step=initial_step, + pad=pad, + factor=factor, + pad_both=pad_both, ) -__all__ = ["UrbanFloodCast", "urbanfloodcast_builder"] +__all__ = [ + "DNO", + "MLP3d", + "OperatorBlock_3D", + "SpectralConv3d_Uno", + "UrbanFloodCast", + "pointwise_op_3D", + "urbanfloodcast_builder", +] diff --git a/pyhazards/models/utae.py b/pyhazards/models/utae.py new file mode 100644 index 00000000..a2fd5db6 --- /dev/null +++ b/pyhazards/models/utae.py @@ -0,0 +1,477 @@ +"""U-TAE: U-Net with a Lightweight Temporal Attention Encoder (L-TAE). + +Port of Sainte Fare Garnot & Landrieu, "Panoptic Segmentation of Satellite Image Time Series +with Convolutional Temporal Attention Networks" (ICCV 2021), from the reference implementation +``VSainteuf/utae-paps`` (``src/backbones/utae.py``, ``ltae.py``, ``positional_encoding.py``; +MIT License, Copyright (c) 2021 Vivien Sainte Fare Garnot). WildfireSpreadTS (Gerard et al., +NeurIPS 2023 D&B) vendors the same code unchanged for its UTAE baseline. + +Parameter names match the reference modules, so official checkpoints (for example the PASTIS +weights on Zenodo) load with ``strict=True``. Behaviour that the reference code has and this +port keeps on purpose: + +- the output convolution block ends in BatchNorm + ReLU, so the returned scores are + non-negative; +- input frames that equal ``pad_value`` everywhere are treated as temporal padding. +""" + +from __future__ import annotations + +import copy +import math +from typing import List, Optional, Sequence + +import torch +import torch.nn as nn + + +class PositionalEncoder(nn.Module): + """Sinusoidal encoding of acquisition dates (e.g. day of year), repeated once per head.""" + + def __init__(self, d: int, T: int = 1000, repeat: Optional[int] = None, offset: int = 0): + super().__init__() + self.d = d + self.T = T + self.repeat = repeat + denom = torch.pow(T, 2 * (torch.arange(offset, offset + d).float() // 2) / d) + self.register_buffer("denom", denom, persistent=False) + + def forward(self, batch_positions: torch.Tensor) -> torch.Tensor: + table = batch_positions[:, :, None] / self.denom[None, None, :] + table[:, :, 0::2] = torch.sin(table[:, :, 0::2]) + table[:, :, 1::2] = torch.cos(table[:, :, 1::2]) + if self.repeat is not None: + table = torch.cat([table for _ in range(self.repeat)], dim=-1) + return table + + +class ScaledDotProductAttention(nn.Module): + def __init__(self, temperature: float, attn_dropout: float = 0.1): + super().__init__() + self.temperature = temperature + self.dropout = nn.Dropout(attn_dropout) + self.softmax = nn.Softmax(dim=2) + + def forward(self, q, k, v, pad_mask=None): + attn = torch.matmul(q.unsqueeze(1), k.transpose(1, 2)) / self.temperature + if pad_mask is not None: + attn = attn.masked_fill(pad_mask.unsqueeze(1), -1e3) + attn = self.dropout(self.softmax(attn)) + return torch.matmul(attn, v), attn + + +class MultiHeadAttention(nn.Module): + """L-TAE attention: one learned master query per head, keys from a linear layer.""" + + def __init__(self, n_head: int, d_k: int, d_in: int): + super().__init__() + self.n_head = n_head + self.d_k = d_k + self.d_in = d_in + self.Q = nn.Parameter(torch.zeros((n_head, d_k))) + nn.init.normal_(self.Q, mean=0, std=math.sqrt(2.0 / d_k)) + self.fc1_k = nn.Linear(d_in, n_head * d_k) + nn.init.normal_(self.fc1_k.weight, mean=0, std=math.sqrt(2.0 / d_k)) + self.attention = ScaledDotProductAttention(temperature=math.pow(d_k, 0.5)) + + def forward(self, v: torch.Tensor, pad_mask: Optional[torch.Tensor] = None): + d_k, n_head = self.d_k, self.n_head + sz_b, seq_len, _ = v.size() + q = torch.stack([self.Q for _ in range(sz_b)], dim=1).view(-1, d_k) + k = self.fc1_k(v).view(sz_b, seq_len, n_head, d_k) + k = k.permute(2, 0, 1, 3).contiguous().view(-1, seq_len, d_k) + if pad_mask is not None: + pad_mask = pad_mask.repeat((n_head, 1)) + v = torch.stack(v.split(v.shape[-1] // n_head, dim=-1)).view(n_head * sz_b, seq_len, -1) + output, attn = self.attention(q, k, v, pad_mask=pad_mask) + attn = attn.view(n_head, sz_b, 1, seq_len).squeeze(dim=2) + output = output.view(n_head, sz_b, 1, self.d_in // n_head).squeeze(dim=2) + return output, attn + + +class LTAE2d(nn.Module): + """Lightweight Temporal Attention Encoder applied independently at every pixel.""" + + def __init__( + self, + in_channels: int = 128, + n_head: int = 16, + d_k: int = 4, + mlp: Sequence[int] = (256, 128), + dropout: float = 0.2, + d_model: Optional[int] = 256, + T: int = 1000, + return_att: bool = False, + positional_encoding: bool = True, + ): + super().__init__() + self.in_channels = in_channels + mlp = list(copy.deepcopy(mlp)) + self.return_att = return_att + self.n_head = n_head + if d_model is not None: + self.d_model = d_model + self.inconv = nn.Conv1d(in_channels, d_model, 1) + else: + self.d_model = in_channels + self.inconv = None + if mlp[0] != self.d_model: + raise ValueError(f"mlp[0] must equal d_model ({self.d_model}), got {mlp[0]}") + self.positional_encoder = ( + PositionalEncoder(self.d_model // n_head, T=T, repeat=n_head) if positional_encoding else None + ) + self.attention_heads = MultiHeadAttention(n_head=n_head, d_k=d_k, d_in=self.d_model) + self.in_norm = nn.GroupNorm(num_groups=n_head, num_channels=self.in_channels) + self.out_norm = nn.GroupNorm(num_groups=n_head, num_channels=mlp[-1]) + layers: List[nn.Module] = [] + for i in range(len(mlp) - 1): + layers.extend([nn.Linear(mlp[i], mlp[i + 1]), nn.BatchNorm1d(mlp[i + 1]), nn.ReLU()]) + self.mlp = nn.Sequential(*layers) + self.dropout = nn.Dropout(dropout) + + def forward(self, x: torch.Tensor, batch_positions: Optional[torch.Tensor] = None, pad_mask: Optional[torch.Tensor] = None): + sz_b, seq_len, d, h, w = x.shape + if pad_mask is not None: + pad_mask = pad_mask.unsqueeze(-1).repeat((1, 1, h)).unsqueeze(-1).repeat((1, 1, 1, w)) + pad_mask = pad_mask.permute(0, 2, 3, 1).contiguous().view(sz_b * h * w, seq_len) + + out = x.permute(0, 3, 4, 1, 2).contiguous().view(sz_b * h * w, seq_len, d) + out = self.in_norm(out.permute(0, 2, 1)).permute(0, 2, 1) + if self.inconv is not None: + out = self.inconv(out.permute(0, 2, 1)).permute(0, 2, 1) + if self.positional_encoder is not None: + if batch_positions is None: + raise ValueError("LTAE2d with positional encoding needs batch_positions of shape (batch, time).") + bp = batch_positions.unsqueeze(-1).repeat((1, 1, h)).unsqueeze(-1).repeat((1, 1, 1, w)) + bp = bp.permute(0, 2, 3, 1).contiguous().view(sz_b * h * w, seq_len) + out = out + self.positional_encoder(bp) + + out, attn = self.attention_heads(out, pad_mask=pad_mask) + out = out.permute(1, 0, 2).contiguous().view(sz_b * h * w, -1) + out = self.dropout(self.mlp(out)) + out = self.out_norm(out) if self.out_norm is not None else out + out = out.view(sz_b, h, w, -1).permute(0, 3, 1, 2) + attn = attn.view(self.n_head, sz_b, h, w, seq_len).permute(0, 1, 4, 2, 3) + if self.return_att: + return out, attn + return out + + +class TemporallySharedBlock(nn.Module): + """Applies a 2D block to every frame of a ``(B, T, C, H, W)`` sequence, skipping padded frames.""" + + def __init__(self, pad_value: Optional[float] = None): + super().__init__() + self.pad_value = pad_value + + def smart_forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim == 4: + return self.forward(x) + b, t, c, h, w = x.shape + out = x.view(b * t, c, h, w) + if self.pad_value is not None: + pad_mask = (out == self.pad_value).all(dim=-1).all(dim=-1).all(dim=-1) + if pad_mask.any(): + # Padded frames bypass the block and are filled with pad_value. (The reference code + # also runs the block on an all-zero copy of the batch to read the output shape; with + # the default GroupNorm that extra pass changes nothing, so it is skipped here.) + if (~pad_mask).any(): + valid = self.forward(out[~pad_mask]) + temp = valid.new_full((b * t, *valid.shape[1:]), float(self.pad_value)) + temp[~pad_mask] = valid + else: + with torch.no_grad(): + out_shape = self.forward(out[:1]).shape[1:] + temp = out.new_full((b * t, *out_shape), float(self.pad_value)) + out = temp + else: + out = self.forward(out) + else: + out = self.forward(out) + _, c, h, w = out.shape + return out.view(b, t, c, h, w) + + +class ConvLayer(nn.Module): + def __init__( + self, + nkernels: Sequence[int], + norm: str = "batch", + k: int = 3, + s: int = 1, + p: int = 1, + n_groups: int = 4, + last_relu: bool = True, + padding_mode: str = "reflect", + ): + super().__init__() + if norm == "batch": + norm_layer = nn.BatchNorm2d + elif norm == "instance": + norm_layer = nn.InstanceNorm2d + elif norm == "group": + def norm_layer(num_feats: int) -> nn.Module: + return nn.GroupNorm(num_channels=num_feats, num_groups=n_groups) + else: + norm_layer = None + layers: List[nn.Module] = [] + for i in range(len(nkernels) - 1): + layers.append( + nn.Conv2d( + in_channels=nkernels[i], + out_channels=nkernels[i + 1], + kernel_size=k, + padding=p, + stride=s, + padding_mode=padding_mode, + ) + ) + if norm_layer is not None: + layers.append(norm_layer(nkernels[i + 1])) + if last_relu or i < len(nkernels) - 2: + layers.append(nn.ReLU()) + self.conv = nn.Sequential(*layers) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv(x) + + +class ConvBlock(TemporallySharedBlock): + def __init__(self, nkernels, pad_value=None, norm="batch", last_relu=True, padding_mode="reflect"): + super().__init__(pad_value=pad_value) + self.conv = ConvLayer(nkernels=nkernels, norm=norm, last_relu=last_relu, padding_mode=padding_mode) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.conv(x) + + +class DownConvBlock(TemporallySharedBlock): + def __init__(self, d_in, d_out, k, s, p, pad_value=None, norm="batch", padding_mode="reflect"): + super().__init__(pad_value=pad_value) + self.down = ConvLayer(nkernels=[d_in, d_in], norm=norm, k=k, s=s, p=p, padding_mode=padding_mode) + self.conv1 = ConvLayer(nkernels=[d_in, d_out], norm=norm, padding_mode=padding_mode) + self.conv2 = ConvLayer(nkernels=[d_out, d_out], norm=norm, padding_mode=padding_mode) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + out = self.down(x) + out = self.conv1(out) + return out + self.conv2(out) + + +class UpConvBlock(nn.Module): + def __init__(self, d_in, d_out, k, s, p, norm="batch", d_skip=None, padding_mode="reflect"): + super().__init__() + d = d_out if d_skip is None else d_skip + self.skip_conv = nn.Sequential(nn.Conv2d(in_channels=d, out_channels=d, kernel_size=1), nn.BatchNorm2d(d), nn.ReLU()) + self.up = nn.Sequential( + nn.ConvTranspose2d(in_channels=d_in, out_channels=d_out, kernel_size=k, stride=s, padding=p), + nn.BatchNorm2d(d_out), + nn.ReLU(), + ) + self.conv1 = ConvLayer(nkernels=[d_out + d, d_out], norm=norm, padding_mode=padding_mode) + self.conv2 = ConvLayer(nkernels=[d_out, d_out], norm=norm, padding_mode=padding_mode) + + def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor: + out = self.up(x) + out = torch.cat([out, self.skip_conv(skip)], dim=1) + out = self.conv1(out) + return out + self.conv2(out) + + +class TemporalAggregator(nn.Module): + """Collapses the time axis of skip connections using the L-TAE attention masks.""" + + def __init__(self, mode: str = "mean"): + super().__init__() + if mode not in {"att_group", "att_mean", "mean"}: + raise ValueError(f"agg_mode must be 'att_group', 'att_mean' or 'mean', got {mode!r}") + self.mode = mode + + def forward(self, x, pad_mask=None, attn_mask=None): + padded = pad_mask is not None and bool(pad_mask.any()) + if self.mode == "att_group": + n_heads, b, t, h, w = attn_mask.shape + attn = attn_mask.view(n_heads * b, t, h, w) + if x.shape[-2] > w: + attn = nn.functional.interpolate(attn, size=x.shape[-2:], mode="bilinear", align_corners=False) + else: + attn = nn.functional.avg_pool2d(attn, kernel_size=w // x.shape[-2]) + attn = attn.view(n_heads, b, t, *x.shape[-2:]) + if padded: + attn = attn * (~pad_mask).float()[None, :, :, None, None] + out = torch.stack(x.chunk(n_heads, dim=2)) + out = (attn[:, :, :, None, :, :] * out).sum(dim=2) + return torch.cat([group for group in out], dim=1) + if self.mode == "att_mean": + attn = attn_mask.mean(dim=0) + attn = nn.functional.interpolate(attn, size=x.shape[-2:], mode="bilinear", align_corners=False) + if padded: + attn = attn * (~pad_mask).float()[:, :, None, None] + return (x * attn[:, :, None, :, :]).sum(dim=1) + if padded: + out = x * (~pad_mask).float()[:, :, None, None, None] + return out.sum(dim=1) / (~pad_mask).sum(dim=1)[:, None, None, None] + return x.mean(dim=1) + + +class UTAE(nn.Module): + """U-TAE for satellite image time series segmentation. + + Input ``(batch, time, channels, height, width)`` plus ``batch_positions`` ``(batch, time)`` + holding the acquisition dates (day of year in WildfireSpreadTS and PASTIS). When + ``batch_positions`` is omitted, ``0..T-1`` is used. Height and width must be divisible by + ``str_conv_s ** (len(encoder_widths) - 1)``. + """ + + def __init__( + self, + input_dim: int, + encoder_widths: Sequence[int] = (64, 64, 64, 128), + decoder_widths: Optional[Sequence[int]] = (32, 32, 64, 128), + out_conv: Sequence[int] = (32, 20), + str_conv_k: int = 4, + str_conv_s: int = 2, + str_conv_p: int = 1, + agg_mode: str = "att_group", + encoder_norm: str = "group", + n_head: int = 16, + d_model: int = 256, + d_k: int = 4, + encoder: bool = False, + return_maps: bool = False, + pad_value: float = 0, + padding_mode: str = "reflect", + ): + super().__init__() + if input_dim <= 0: + raise ValueError(f"input_dim must be positive, got {input_dim}") + encoder_widths = list(encoder_widths) + decoder_widths = list(decoder_widths) if decoder_widths is not None else list(encoder_widths) + if len(encoder_widths) != len(decoder_widths) or encoder_widths[-1] != decoder_widths[-1]: + raise ValueError("decoder_widths must match encoder_widths in length and in the last entry.") + self.input_dim = int(input_dim) + self.n_stages = len(encoder_widths) + self.encoder_widths = encoder_widths + self.decoder_widths = decoder_widths + self.enc_dim = decoder_widths[0] + self.stack_dim = sum(decoder_widths) + self.pad_value = pad_value + self.encoder = encoder + self.return_maps = return_maps or encoder + self.downsample_factor = str_conv_s ** (self.n_stages - 1) + + self.in_conv = ConvBlock( + nkernels=[input_dim, encoder_widths[0], encoder_widths[0]], + pad_value=pad_value, + norm=encoder_norm, + padding_mode=padding_mode, + ) + self.down_blocks = nn.ModuleList( + DownConvBlock( + d_in=encoder_widths[i], + d_out=encoder_widths[i + 1], + k=str_conv_k, + s=str_conv_s, + p=str_conv_p, + pad_value=pad_value, + norm=encoder_norm, + padding_mode=padding_mode, + ) + for i in range(self.n_stages - 1) + ) + self.up_blocks = nn.ModuleList( + UpConvBlock( + d_in=decoder_widths[i], + d_out=decoder_widths[i - 1], + d_skip=encoder_widths[i - 1], + k=str_conv_k, + s=str_conv_s, + p=str_conv_p, + norm="batch", + padding_mode=padding_mode, + ) + for i in range(self.n_stages - 1, 0, -1) + ) + self.temporal_encoder = LTAE2d( + in_channels=encoder_widths[-1], + d_model=d_model, + n_head=n_head, + mlp=[d_model, encoder_widths[-1]], + return_att=True, + d_k=d_k, + ) + self.temporal_aggregator = TemporalAggregator(mode=agg_mode) + self.out_conv = ConvBlock(nkernels=[decoder_widths[0]] + list(out_conv), padding_mode=padding_mode) + + def forward(self, x: torch.Tensor, batch_positions: Optional[torch.Tensor] = None, return_att: bool = False): + if x.ndim != 5: + raise ValueError( + "UTAE expects input shape (batch, time, channels, height, width), " + f"got {tuple(x.shape)}." + ) + if x.size(2) != self.input_dim: + raise ValueError(f"UTAE expected {self.input_dim} channels, got {x.size(2)}.") + if x.size(-2) % self.downsample_factor or x.size(-1) % self.downsample_factor: + raise ValueError( + f"UTAE needs height and width divisible by {self.downsample_factor}, got {tuple(x.shape[-2:])}." + ) + if batch_positions is None: + batch_positions = torch.arange(x.size(1), device=x.device, dtype=x.dtype).expand(x.size(0), -1) + + pad_mask = (x == self.pad_value).all(dim=-1).all(dim=-1).all(dim=-1) + out = self.in_conv.smart_forward(x) + feature_maps = [out] + for i in range(self.n_stages - 1): + out = self.down_blocks[i].smart_forward(feature_maps[-1]) + feature_maps.append(out) + out, att = self.temporal_encoder(feature_maps[-1], batch_positions=batch_positions, pad_mask=pad_mask) + maps = [out] + for i in range(self.n_stages - 1): + skip = self.temporal_aggregator(feature_maps[-(i + 2)], pad_mask=pad_mask, attn_mask=att) + out = self.up_blocks[i](out, skip) + maps.append(out) + if self.encoder: + return out, maps + out = self.out_conv(out) + if return_att: + return out, att + if self.return_maps: + return out, maps + return out + + +def utae_builder( + task: str, + in_channels: int, + out_channels: int = 1, + encoder_widths: Sequence[int] = (64, 64, 64, 128), + decoder_widths: Sequence[int] = (32, 32, 64, 128), + out_conv_hidden: int = 32, + agg_mode: str = "att_group", + encoder_norm: str = "group", + n_head: int = 16, + d_model: int = 256, + d_k: int = 4, + pad_value: float = 0, + padding_mode: str = "reflect", + **kwargs, +) -> nn.Module: + _ = kwargs + if task.lower() != "segmentation": + raise ValueError(f"utae supports task='segmentation', got {task!r}.") + return UTAE( + input_dim=in_channels, + encoder_widths=encoder_widths, + decoder_widths=decoder_widths, + out_conv=[out_conv_hidden, out_channels], + agg_mode=agg_mode, + encoder_norm=encoder_norm, + n_head=n_head, + d_model=d_model, + d_k=d_k, + pad_value=pad_value, + padding_mode=padding_mode, + ) + + +__all__ = ["LTAE2d", "PositionalEncoder", "UTAE", "utae_builder"] diff --git a/pyhazards/models/wavecastnet.py b/pyhazards/models/wavecastnet.py index 18c738ef..392531f8 100644 --- a/pyhazards/models/wavecastnet.py +++ b/pyhazards/models/wavecastnet.py @@ -1,352 +1,671 @@ +"""WaveCastNet: ConvLEM sequence-to-sequence forecasting of earthquake ground-motion wavefields. + +Lyu, Nakata, Ren, Mahoney, Pitarka, Nakata & Erichson, "Rapid wavefield forecasting for earthquake early +warning via deep sequence to sequence learning", Nature Communications 16:10622 (2025), +doi:10.1038/s41467-025-65435-2 (arXiv 2405.20516). + +Port of the official PyTorch code, dwlyu/WaveCastNet at commit +``c859e04c85acd6657306f08bce8c6f9129ba1480`` (MIT License, Copyright (c) 2023 dwlyu): +``src/models_earthquake/ConvLEMCell.py`` (``ConvLEMCell``, ``ConvLEMCell_1``), ``EncoderDecoder.py`` +(``encoder_layer``, ``encoder1``, ``encoder_sparser``, ``decoder_layer``, ``decoder2_48``), +``AEConvLEM_dense.py``, ``AEConvLEM_sparse.py``, ``EncodingSparse.py`` (``Encoder1d``) and +``earthquake_train.py`` (``Huber`` loss, rolling validation forecast). + +Architecture (dense configuration, 10,093,242 parameters): every input frame ``(3, 344, 224)`` goes +through an embedding of three ``Conv2d(k4, s2, p1) -> BatchNorm2d -> LeakyReLU`` layers (3 -> 36 -> 72 -> +144 channels, latent grid 43 x 28); two stacked ConvLEM cells with reset gate (``ConvLEMCell_1``) encode +the sequence; two more ConvLEM cells, started from the encoder states, decode ``future_seq`` latent frames; +each latent frame is reconstructed by ``ConvTranspose2d(k4, s2, p1) -> LeakyReLU -> PixelShuffle(4)`` and +a 3x3 convolution. The sparse variant (``WaveCastNetSparse``, official ``AEConvLEM_sparse``) samples the +wavefield at station grid points, zeroes a random subset of the stations (masked-autoencoder training) +and embeds the station vector with two fully connected layers and two convolutions. + +Faithfulness notes: + +- Module and parameter names equal the official ones (``encoder.model.encoder_layer1.layer.0.weight``, + ``encoder_1_convlem.convx.weight``, ``W_z1``, ...) and modules are created in the official order with + the official initialisation (xavier on every tensor with two or more dimensions, including the per-pixel + peephole weights ``W_z*`` of shape ``(channels, H/8, W/8)``; zeros for biases), so the same seed gives + the same weights and ``best_lem_dense_.pt`` loads with ``strict=True``. +- The decoder's first input is uniform noise, ``torch.rand_like`` of the latent state, in training *and* + evaluation, so two forward passes on the same input differ. ``forward(..., generator=g)`` draws that + noise (and the sparse station mask) from ``g`` instead of the global generator, and + ``decoder_noise=`` supplies it explicitly; without either, the global generator is used in the official + order (station mask first, then decoder noise), so ``torch.manual_seed`` reproduces the official outputs. +- The sparse station mask is drawn in evaluation too (the official ``Encoder1d.forward`` always masks); + ``station_mask=`` (``True`` = station kept) replaces the random draw. +""" + from __future__ import annotations +from pathlib import Path +from typing import Dict, Optional, Sequence, Tuple, Union + +import numpy as np import torch import torch.nn as nn import torch.nn.init as init +from ..metrics.wavefield import wavefield_acc, wavefield_rfne, wavefield_rmse +from ._pretrained import cached_download + +WAVECASTNET_COMMIT = "c859e04c85acd6657306f08bce8c6f9129ba1480" +_RAW = f"https://raw.githubusercontent.com/dwlyu/WaveCastNet/{WAVECASTNET_COMMIT}/src/models_earthquake/" +_DRIVE = "https://drive.usercontent.google.com/download?id={file_id}&export=download&confirm=t" + +# Released checkpoints (README "Data Availability", Google Drive folder 10pe6Zc1NEzIunwJv80214dB9fmb-X8yw). +WAVECASTNET_WEIGHTS: Dict[str, Dict[str, str]] = { + "dense": { + "filename": "best_lem_dense_.pt", + "file_id": "1vFoo1eqO2WoZH0R6kkRZJ8XhNG3zF8nO", + "sha256": "cccadaa7ae02736eb1835c0dc2b04a6291cdd348c901128fb03c92f4c7647acc", + "license": "not stated (Google Drive release of the MIT-licensed dwlyu/WaveCastNet)", + }, +} + +# Station grid indices (row, column) on the 344 x 224 grid, shipped with the official code (MIT). +WAVECASTNET_STATIONS: Dict[str, Dict[str, str]] = { + "candidates": { + "filename": "filtered_coord.npy", + "sha256": "c6cb49cf61b4f4229bd8f8206538218889368d5bd3c96fbbb3350e7ec8e8bb1e", + }, + "shakealert": { + "filename": "shakealert_coords.npy", + "sha256": "b64f6b37cfe15755214e8c2e07ac2cb772d6b80f167cf14a41ec5d901ee6ccc4", + }, +} + +# README / load_pretrained_model.ipynb: mask_ratio = 1 - len(shakealert_coords) / len(filtered_coord). +DEFAULT_MASK_RATIO = 1.0 - 101.0 / 564.0 + +_ACTIVATIONS = {"tanh": torch.tanh, "relu": torch.relu} + + +def _pair(value: Union[int, Sequence[int]], name: str) -> Tuple[int, int]: + if isinstance(value, int): + return int(value), int(value) + values = tuple(int(item) for item in value) + if len(values) != 2: + raise ValueError(f"{name} must be an int or a pair, got {value!r}.") + return values + class ConvLEMCell(nn.Module): - """ - Convolutional Long Expressive Memory (ConvLEM) cell used by WaveCastNet. + """Convolutional Long Expressive Memory cell (official ``ConvLEMCell_1`` / ``ConvLEMCell``). + + ``reset_gate=True`` is ``ConvLEMCell_1`` (the cell of both WaveCastNet models: an extra gate scales the + convolved memory; xavier-uniform initialisation); ``reset_gate=False`` is ``ConvLEMCell`` + (xavier-normal initialisation). Peephole weights ``W_z*`` are per pixel, shaped + ``(out_channels, *frame_size)``, so the cell only runs on that grid. ``forward(x, h, c)`` takes + ``(batch, channels, *frame_size)`` tensors and returns the new ``(h, c)``. """ def __init__( self, in_channels: int, out_channels: int, - kernel_size: int = 3, + frame_size: Union[int, Sequence[int]], + kernel_size: Union[int, Sequence[int]] = 3, + padding: Optional[Union[int, Sequence[int]]] = None, dt: float = 1.0, activation: str = "tanh", - use_reset_gate: bool = False, + reset_gate: bool = True, ): super().__init__() + if activation not in _ACTIVATIONS: + raise ValueError(f"Unsupported activation {activation!r}; use 'tanh' or 'relu'.") + self.activation = _ACTIVATIONS[activation] + self.reset_gate = bool(reset_gate) + self.frame_size = _pair(frame_size, "frame_size") + kernel_size = _pair(kernel_size, "kernel_size") + padding = tuple(k // 2 for k in kernel_size) if padding is None else _pair(padding, "padding") + x_gates, h_gates = (5, 4) if self.reset_gate else (4, 3) + self.convx = nn.Conv2d(in_channels, x_gates * out_channels, kernel_size, padding=padding) + self.convy = nn.Conv2d(out_channels, h_gates * out_channels, kernel_size, padding=padding) + self.convz = nn.Conv2d(out_channels, out_channels, kernel_size, padding=padding) + self.dt = dt + self.W_z1 = nn.Parameter(torch.empty(out_channels, *self.frame_size)) + self.W_z2 = nn.Parameter(torch.empty(out_channels, *self.frame_size)) + if self.reset_gate: + self.W_z4 = nn.Parameter(torch.empty(out_channels, *self.frame_size)) + self.reset_parameters() - if activation == "tanh": - self.activation = torch.tanh - elif activation == "relu": - self.activation = torch.relu - else: - raise ValueError( - "Unsupported activation: {activation}. Use 'tanh' or 'relu'.".format( - activation=activation - ) - ) + def reset_parameters(self) -> None: + # Official order: the cell's own peephole tensors first, then convx, convy, convz. + xavier = init.xavier_uniform_ if self.reset_gate else init.xavier_normal_ + for param in self.parameters(): + if param.ndim > 1: + xavier(param) + else: + nn.init.constant_(param, 0) - self.dt = float(dt) - self.use_reset_gate = bool(use_reset_gate) - self.out_channels = int(out_channels) - - padding = (kernel_size - 1) // 2 - if self.use_reset_gate: - self.conv_x = nn.Conv2d( - in_channels, - 5 * out_channels, - kernel_size, - padding=padding, - ) - self.conv_h = nn.Conv2d( - out_channels, - 4 * out_channels, - kernel_size, - padding=padding, + def forward(self, x: torch.Tensor, h: torch.Tensor, c: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + if x.ndim != 4 or h.shape != c.shape or tuple(h.shape[-2:]) != self.frame_size or x.shape[-2:] != h.shape[-2:]: + raise ValueError( + f"ConvLEMCell expects x, h, c shaped (batch, channels, {self.frame_size[0]}, {self.frame_size[1]}); " + f"got shapes {tuple(x.shape)}, {tuple(h.shape)}, {tuple(c.shape)}." ) + transformed_inp = self.convx(x) + transformed_hid = self.convy(h) + if self.reset_gate: + i_dt1, i_dt2, g_dx2, i_z, i_y = torch.chunk(transformed_inp, chunks=5, dim=1) + h_dt1, h_dt2, h_y, g_dy2 = torch.chunk(transformed_hid, chunks=4, dim=1) else: - self.conv_x = nn.Conv2d( - in_channels, - 4 * out_channels, - kernel_size, - padding=padding, - ) - self.conv_h = nn.Conv2d( - out_channels, - 3 * out_channels, - kernel_size, - padding=padding, - ) + i_dt1, i_dt2, i_z, i_y = torch.chunk(transformed_inp, chunks=4, dim=1) + h_dt1, h_dt2, h_y = torch.chunk(transformed_hid, chunks=3, dim=1) + ms_dt = self.dt * torch.sigmoid(i_dt2 + h_dt2 + self.W_z2 * c) + c = (1.0 - ms_dt) * c + ms_dt * self.activation(i_y + h_y) + if self.reset_gate: + ms_dt_bar = self.dt * torch.sigmoid(i_dt1 + h_dt1 + self.W_z1 * c) + gate2 = self.dt * torch.sigmoid(g_dx2 + g_dy2 + self.W_z4 * c) + transformed_z = gate2 * self.convz(c) + else: + transformed_z = self.convz(c) + ms_dt_bar = self.dt * torch.sigmoid(i_dt1 + h_dt1 + self.W_z1 * c) + h = (1.0 - ms_dt_bar) * h + ms_dt_bar * self.activation(transformed_z + i_z) + return h, c - self.conv_c = nn.Conv2d(out_channels, out_channels, kernel_size, padding=padding) - self.W_c1 = nn.Parameter(torch.empty(out_channels, 1, 1)) - self.W_c2 = nn.Parameter(torch.empty(out_channels, 1, 1)) - if self.use_reset_gate: - self.W_c4 = nn.Parameter(torch.empty(out_channels, 1, 1)) - self.reset_parameters() +class _EncoderLayer(nn.Module): + """Official ``encoder_layer``: ``Conv2d(k4, s2, p1) -> BatchNorm2d -> LeakyReLU``.""" - def reset_parameters(self) -> None: - for name, param in self.named_parameters(): - if "W_c" in name: - nn.init.constant_(param, 0.0) - elif param.ndim > 1: - init.xavier_uniform_(param) - else: - nn.init.constant_(param, 0.0) + def __init__(self, in_dim: int, out_dim: int): + super().__init__() + self.layer = nn.Sequential( + nn.Conv2d(in_dim, out_dim, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=True), + nn.BatchNorm2d(out_dim), + nn.LeakyReLU(), + ) - def forward( - self, - x: torch.Tensor, - h: torch.Tensor, - c: torch.Tensor, - ) -> tuple[torch.Tensor, torch.Tensor]: - if x.ndim != 4 or h.ndim != 4 or c.ndim != 4: - raise ValueError("ConvLEMCell expects x, h, c shaped (B, C, H, W).") + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.layer(x) - conv_x_out = self.conv_x(x) - conv_h_out = self.conv_h(h) - if self.use_reset_gate: - i_dt1, i_dt2, g_dx2, i_c, i_h = torch.chunk(conv_x_out, chunks=5, dim=1) - h_dt1, h_dt2, h_h, g_dh2 = torch.chunk(conv_h_out, chunks=4, dim=1) +class DenseEmbedding(nn.Module): + """Official ``encoder1``: three encoder layers, ``C -> 12C -> 24C -> 48C`` channels, grid / 8.""" - ms_dt = self.dt * torch.sigmoid(i_dt2 + h_dt2 + self.W_c2 * c) - c = (1.0 - ms_dt) * c + ms_dt * self.activation(i_h + h_h) + def __init__(self, num_channels: int): + super().__init__() + self.model = nn.Sequential() + self.model.add_module("encoder_layer1", _EncoderLayer(num_channels, 12 * num_channels)) + self.model.add_module("encoder_layer2", _EncoderLayer(12 * num_channels, 24 * num_channels)) + self.model.add_module("encoder_layer3", _EncoderLayer(24 * num_channels, 48 * num_channels)) - gate2 = self.dt * torch.sigmoid(g_dx2 + g_dh2 + self.W_c4 * c) - conv_c_out = gate2 * self.conv_c(c) + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.model(x) - ms_dt_bar = self.dt * torch.sigmoid(i_dt1 + h_dt1 + self.W_c1 * c) - h = (1.0 - ms_dt_bar) * h + ms_dt_bar * self.activation(conv_c_out + i_c) - else: - i_dt1, i_dt2, i_c, i_h = torch.chunk(conv_x_out, chunks=4, dim=1) - h_dt1, h_dt2, h_h = torch.chunk(conv_h_out, chunks=3, dim=1) - ms_dt = self.dt * torch.sigmoid(i_dt2 + h_dt2 + self.W_c2 * c) - c = (1.0 - ms_dt) * c + ms_dt * self.activation(i_h + h_h) +class _SparseConvEncoder(nn.Module): + """Official ``encoder_sparser``: ``Conv2d(k3) -> BatchNorm2d -> LeakyReLU`` then one encoder layer.""" - conv_c_out = self.conv_c(c) - ms_dt_bar = self.dt * torch.sigmoid(i_dt1 + h_dt1 + self.W_c1 * c) - h = (1.0 - ms_dt_bar) * h + ms_dt_bar * self.activation(conv_c_out + i_c) + def __init__(self, num_channels: int): + super().__init__() + self.model = nn.Sequential( + nn.Conv2d(num_channels, 24 * num_channels, kernel_size=(3, 3), padding=(1, 1), bias=True), + nn.BatchNorm2d(24 * num_channels), + nn.LeakyReLU(), + ) + self.model.add_module("encoder_layer2", _EncoderLayer(24 * num_channels, 48 * num_channels)) - return h, c + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.model(x) -class WaveCastNet(nn.Module): - """ - Sequence-to-sequence wavefield forecasting model based on ConvLEM cells. +class SparseEmbedding(nn.Module): + """Official ``Encoder1d``: station sampling, masking, two dense layers and a convolutional encoder. - Input shape: (B, C, T_in, H, W) - Output shape: (B, C, T_out, H, W) + ``station_coords`` are ``(stations, 2)`` (row, column) grid indices. A frame ``(batch, C, H, W)`` is + sampled at the stations, the stations with ``keep == False`` are zeroed, ``FC1`` / ``FC2`` (each + ``Linear -> LeakyReLU -> BatchNorm1d(C)``) map the ``stations`` values of each channel to an + ``(H/4, W/4)`` grid, and the convolutional encoder brings it to ``(48C, H/8, W/8)``. At the official + 344 x 224 grid the hidden width is 1,204 and the ``FC2`` output 86 x 56 = 4,816. """ - def __init__( - self, - in_channels: int, - height: int, - width: int, - temporal_in: int, - temporal_out: int, - hidden_dim: int = 144, - num_layers: int = 2, - kernel_size: int = 3, - dt: float = 1.0, - activation: str = "tanh", - dropout: float = 0.1, - ): + def __init__(self, num_channels: int, station_coords: torch.Tensor, height: int, width: int): super().__init__() - - self.in_channels = int(in_channels) - self.height = int(height) - self.width = int(width) - self.temporal_in = int(temporal_in) - self.temporal_out = int(temporal_out) - self.hidden_dim = int(hidden_dim) - self.num_layers = int(num_layers) - - padding = (kernel_size - 1) // 2 - proj_dim = max(1, self.hidden_dim // 2) - - self.input_embed = nn.Sequential( - nn.Conv2d(self.in_channels, self.hidden_dim, kernel_size, padding=padding), - nn.BatchNorm2d(self.hidden_dim), - nn.ReLU(), - nn.Dropout2d(dropout), + coords = torch.as_tensor(np.asarray(station_coords)).round().long() + if coords.ndim != 2 or coords.shape[1] != 2 or len(coords) == 0: + raise ValueError(f"station_coords must be shaped (stations, 2), got shape {tuple(coords.shape)}.") + if (coords < 0).any() or (coords[:, 0] >= height).any() or (coords[:, 1] >= width).any(): + raise ValueError(f"station_coords must index the {height} x {width} grid.") + self.num_channels = int(num_channels) + self.coarse = (height // 4, width // 4) + coarse_size = self.coarse[0] * self.coarse[1] + hidden = coarse_size // 4 + self.FC1 = nn.Sequential(nn.Linear(len(coords), hidden), nn.LeakyReLU(), nn.BatchNorm1d(num_channels)) + self.FC2 = nn.Sequential(nn.Linear(hidden, coarse_size), nn.LeakyReLU(), nn.BatchNorm1d(num_channels)) + self.encoder = _SparseConvEncoder(num_channels) + self.register_buffer("station_coords", coords, persistent=False) + + @property + def num_stations(self) -> int: + return int(self.station_coords.shape[0]) + + def forward(self, x: torch.Tensor, keep: Optional[torch.Tensor] = None) -> torch.Tensor: + sampled = x[:, :, self.station_coords[:, 0], self.station_coords[:, 1]] # (batch, C, stations) + if keep is not None: + sampled = sampled.masked_fill(~keep.unsqueeze(1).expand_as(sampled), 0) + out = self.FC2(self.FC1(sampled)) + return self.encoder(out.reshape(x.shape[0], self.num_channels, *self.coarse)) + + +class _DecoderLayer(nn.Module): + """Official ``decoder_layer``: ``ConvTranspose2d(k4, s2, p1) -> LeakyReLU``.""" + + def __init__(self, in_dim: int, out_dim: int): + super().__init__() + self.layer = nn.Sequential( + nn.ConvTranspose2d(in_dim, out_dim, kernel_size=4, stride=2, padding=1, bias=True), + nn.LeakyReLU(), ) - self.encoder_layers = nn.ModuleList( - [ - ConvLEMCell( - in_channels=self.hidden_dim, - out_channels=self.hidden_dim, - kernel_size=kernel_size, - dt=dt, - activation=activation, - use_reset_gate=False, - ) - for _ in range(self.num_layers) - ] - ) - self.decoder_layers = nn.ModuleList( - [ - ConvLEMCell( - in_channels=self.hidden_dim, - out_channels=self.hidden_dim, - kernel_size=kernel_size, - dt=dt, - activation=activation, - use_reset_gate=False, - ) - for _ in range(self.num_layers) - ] - ) + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.layer(x) - self.output_proj = nn.Sequential( - nn.Conv2d(self.hidden_dim, proj_dim, kernel_size, padding=padding), - nn.ReLU(), - nn.Dropout2d(dropout), - nn.Conv2d(proj_dim, self.in_channels, kernel_size, padding=padding), - ) - self.dropout = nn.Dropout2d(dropout) - - def _init_states(self, x: torch.Tensor) -> tuple[list[torch.Tensor], list[torch.Tensor]]: - hidden = [ - x.new_zeros(x.size(0), self.hidden_dim, self.height, self.width) - for _ in range(self.num_layers) - ] - memory = [ - x.new_zeros(x.size(0), self.hidden_dim, self.height, self.width) - for _ in range(self.num_layers) - ] - return hidden, memory + +class Reconstruction(nn.Module): + """Official ``decoder2_48``: ``(48C, H/8, W/8) -> ConvTranspose2d -> PixelShuffle(4) -> (3C, H, W)``.""" + + def __init__(self, num_channels: int): + super().__init__() + self.model = nn.Sequential() + self.model.add_module("decoder_layer1", _DecoderLayer(48 * num_channels, 48 * num_channels)) + self.model.add_module("decoder_layer2", nn.PixelShuffle(4)) def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 5: - raise ValueError( - "WaveCastNet expects x shaped (B, C, T, H, W), got {shape}".format( - shape=tuple(x.shape) - ) - ) + return self.model(x) + - batch_size, channels, temporal_in, height, width = x.shape - if channels != self.in_channels: +class WaveCastNet(nn.Module): + """WaveCastNet with dense input (official ``AEConvLEM_dense``). + + ``forward(x, future_seq=None)``: ``x`` is ``(batch, channels, time, height, width)``; returns + ``(batch, channels, future_seq, height, width)``. ``future_seq`` defaults to the value given at + construction (30 steps, the official training horizon). ``height`` and ``width`` must be multiples of + 8 (latent grid ``(height / 8, width / 8)``, the shape of the per-pixel peepholes); the latent width is + fixed by the official code at ``48 * channels`` (144 for three components). + + Keyword-only hooks (see the module docstring): ``generator`` (a ``torch.Generator`` for the decoder + noise and the sparse station mask) and ``decoder_noise`` (the first decoder input itself, shaped like + the latent state ``(batch, 48 * channels, height / 8, width / 8)``). :meth:`rollout` repeats the + forecast on its own output, as the official validation does. + """ + + sampling = "dense" + + def __init__( + self, + num_channels: int = 3, + height: int = 344, + width: int = 224, + kernel_size: Union[int, Sequence[int]] = 3, + padding: Optional[Union[int, Sequence[int]]] = None, + dt: float = 1.0, + activation: str = "tanh", + future_seq: int = 30, + num_kernels: Optional[int] = None, + station_coords: Optional[torch.Tensor] = None, + mask_mode: bool = False, + mask_ratio: float = 0.0, + ): + super().__init__() + if int(num_channels) < 1: + raise ValueError(f"num_channels must be positive, got {num_channels}.") + if int(height) % 8 or int(width) % 8 or int(height) < 8 or int(width) < 8: raise ValueError( - "Expected in_channels={expected}, got {actual}".format( - expected=self.in_channels, - actual=channels, - ) + f"WaveCastNet needs height and width that are multiples of 8 (latent grid / 8), got {height} x {width}." ) - if temporal_in != self.temporal_in: + latent = 48 * int(num_channels) + if num_kernels is not None and int(num_kernels) != latent: raise ValueError( - "Expected temporal_in={expected}, got {actual}".format( - expected=self.temporal_in, - actual=temporal_in, - ) + f"The official embedding fixes the latent width at 48 * num_channels = {latent}; got num_kernels={num_kernels}." ) - if height != self.height or width != self.width: + if int(future_seq) < 1: + raise ValueError(f"future_seq must be at least 1, got {future_seq}.") + if not 0.0 <= float(mask_ratio) <= 1.0: + raise ValueError(f"mask_ratio must be in [0, 1], got {mask_ratio}.") + self.num_channels = int(num_channels) + self.height, self.width = int(height), int(width) + self.frame_size = (self.height // 8, self.width // 8) + self.out_channels = latent + self.future_seq = int(future_seq) + self.mask_mode = bool(mask_mode) + self.mask_ratio = float(mask_ratio) + kernel_size = _pair(kernel_size, "kernel_size") + padding = tuple(k // 2 for k in kernel_size) if padding is None else _pair(padding, "padding") + + # Creation order of the official __init__: embedding, reconstruction, four cells, conv1. + if self.sampling == "dense": + self.encoder = DenseEmbedding(self.num_channels) + else: + if station_coords is None: + raise ValueError("The sparse WaveCastNet needs station_coords shaped (stations, 2).") + self.encoder = SparseEmbedding(self.num_channels, station_coords, self.height, self.width) + self.decoder = Reconstruction(self.num_channels) + cell = dict( + in_channels=latent, + out_channels=latent, + frame_size=self.frame_size, + kernel_size=kernel_size, + padding=padding, + dt=dt, + activation=activation, + reset_gate=True, + ) + self.encoder_1_convlem = ConvLEMCell(**cell) + self.encoder_2_convlem = ConvLEMCell(**cell) + self.decoder_1_convlem = ConvLEMCell(**cell) + self.decoder_2_convlem = ConvLEMCell(**cell) + self.conv1 = nn.Conv2d(3 * self.num_channels, self.num_channels, kernel_size=kernel_size, padding=padding) + + def _check_input(self, x: torch.Tensor) -> None: + if x.ndim != 5 or x.shape[1] != self.num_channels or tuple(x.shape[-2:]) != (self.height, self.width): raise ValueError( - "Expected spatial size ({h}, {w}), got ({actual_h}, {actual_w})".format( - h=self.height, - w=self.width, - actual_h=height, - actual_w=width, - ) + f"WaveCastNet expects x shaped (batch, {self.num_channels}, time, {self.height}, {self.width}), " + f"got shape {tuple(x.shape)}." ) - encoder_h, encoder_c = self._init_states(x) - for t in range(self.temporal_in): - encoded = self.input_embed(x[:, :, t, :, :]) - for i, layer in enumerate(self.encoder_layers): - layer_input = encoded if i == 0 else encoder_h[i - 1] - encoder_h[i], encoder_c[i] = layer(layer_input, encoder_h[i], encoder_c[i]) + def _station_keep(self, batch: int, x: torch.Tensor, generator, station_mask) -> Optional[torch.Tensor]: + return None - decoder_h = [state.clone() for state in encoder_h] - decoder_c = [state.clone() for state in encoder_c] + def _decoder_start(self, h: torch.Tensor, generator, decoder_noise) -> torch.Tensor: + if decoder_noise is not None: + if tuple(decoder_noise.shape) != tuple(h.shape): + raise ValueError( + f"decoder_noise must have the latent shape {tuple(h.shape)}, got shape {tuple(decoder_noise.shape)}." + ) + return decoder_noise.to(device=h.device, dtype=h.dtype) + if generator is None: + return torch.rand_like(h) # official: uniform noise from the global generator + return torch.rand(h.shape, generator=generator, dtype=h.dtype, device=generator.device).to(h.device) + def forward( + self, + x: torch.Tensor, + future_seq: Optional[int] = None, + *, + generator: Optional[torch.Generator] = None, + decoder_noise: Optional[torch.Tensor] = None, + station_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + self._check_input(x) + steps = self.future_seq if future_seq is None else int(future_seq) + if steps < 1: + raise ValueError(f"future_seq must be at least 1, got {future_seq}.") + batch, _, seq_len = x.shape[:3] + state = (batch, self.out_channels, *self.frame_size) + h1, c1, h2, c2 = (x.new_zeros(state) for _ in range(4)) + keep = self._station_keep(batch, x, generator, station_mask) + for t in range(seq_len): + frame = x[:, :, t] + embedded = self.encoder(frame) if keep is None else self.encoder(frame, keep) + h1, c1 = self.encoder_1_convlem(embedded, h1, c1) + h2, c2 = self.encoder_2_convlem(h1, h2, c2) + h3, c3, h4, c4 = h1, c1, h2, c2 + decoder_input = self._decoder_start(h1, generator, decoder_noise) outputs = [] - for t in range(self.temporal_out): - decoder_input = encoder_h[-1] if t == 0 else decoder_h[-1] - for i, layer in enumerate(self.decoder_layers): - layer_input = decoder_input if i == 0 else decoder_h[i - 1] - decoder_h[i], decoder_c[i] = layer(layer_input, decoder_h[i], decoder_c[i]) - output_t = self.output_proj(self.dropout(decoder_h[-1])) - outputs.append(output_t) - - if len(outputs) != self.temporal_out: - raise RuntimeError( - "Decoder generated {actual} steps, expected {expected}".format( - actual=len(outputs), - expected=self.temporal_out, - ) - ) + for _ in range(steps): + h3, c3 = self.decoder_1_convlem(decoder_input, h3, c3) + h4, c4 = self.decoder_2_convlem(h3, h4, c4) + decoder_input = h4 + outputs.append(self.conv1(self.decoder(h4))) return torch.stack(outputs, dim=2) + def rollout( + self, + x: torch.Tensor, + steps: int, + *, + step: Optional[int] = None, + generator: Optional[torch.Generator] = None, + station_mask: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """Forecast ``steps`` frames by repeated calls of ``step`` frames (default ``future_seq``), each + taking the previous output as its input; the last call is shortened to fit. With 30-step inputs, + ``step=30`` and ``steps=195`` this is the official validation forecast (six calls of 30 frames and + one of 15, 101.4 s at 0.52 s per frame).""" + step = self.future_seq if step is None else int(step) + if int(steps) < 1 or step < 1: + raise ValueError(f"rollout needs steps >= 1 and step >= 1, got {steps} and {step}.") + outputs, remaining, current = [], int(steps), x + while remaining > 0: + count = min(step, remaining) + current = self(current, count, generator=generator, station_mask=station_mask) + outputs.append(current) + remaining -= count + return torch.cat(outputs, dim=2) + + +class WaveCastNetSparse(WaveCastNet): + """WaveCastNet with sparse station input (official ``AEConvLEM_sparse``). + + The input is still the dense wavefield ``(batch, channels, time, height, width)``: the embedding + reads it at ``station_coords`` (``(stations, 2)`` row / column indices; the official 564 candidate + stations are :func:`wavecastnet_station_coords` ``("candidates")``). With ``mask_mode`` (the + official configuration), one uniform draw per (sample, station) is taken per call and stations with a + draw below ``mask_ratio`` are zeroed at every time step, in evaluation too; ``station_mask`` + (``(stations,)`` or ``(batch, stations)`` booleans, ``True`` = kept) replaces that draw. + """ -def wavecastnet_builder( - task: str, - in_channels: int, - height: int, - width: int, - temporal_in: int, - temporal_out: int, - **kwargs, -) -> WaveCastNet: - if task.lower() != "regression": - raise ValueError("WaveCastNet only supports regression tasks.") + sampling = "sparse" - return WaveCastNet( - in_channels=in_channels, - height=height, - width=width, - temporal_in=temporal_in, - temporal_out=temporal_out, - hidden_dim=kwargs.get("hidden_dim", 144), - num_layers=kwargs.get("num_layers", 2), - kernel_size=kwargs.get("kernel_size", 3), - dt=kwargs.get("dt", 1.0), - activation=kwargs.get("activation", "tanh"), - dropout=kwargs.get("dropout", 0.1), - ) + def __init__( + self, + station_coords: torch.Tensor, + num_channels: int = 3, + height: int = 344, + width: int = 224, + kernel_size: Union[int, Sequence[int]] = 3, + padding: Optional[Union[int, Sequence[int]]] = None, + dt: float = 1.0, + activation: str = "tanh", + future_seq: int = 30, + num_kernels: Optional[int] = None, + mask_mode: bool = True, + mask_ratio: float = DEFAULT_MASK_RATIO, + ): + super().__init__( + num_channels=num_channels, + height=height, + width=width, + kernel_size=kernel_size, + padding=padding, + dt=dt, + activation=activation, + future_seq=future_seq, + num_kernels=num_kernels, + station_coords=station_coords, + mask_mode=mask_mode, + mask_ratio=mask_ratio, + ) + + def _station_keep(self, batch: int, x: torch.Tensor, generator, station_mask) -> Optional[torch.Tensor]: + stations = self.encoder.num_stations + if station_mask is not None: + keep = torch.as_tensor(station_mask, device=x.device).bool() + if keep.shape == (stations,): + keep = keep.unsqueeze(0).expand(batch, stations) + if keep.shape != (batch, stations): + raise ValueError( + f"station_mask must be shaped ({stations},) or ({batch}, {stations}), got shape {tuple(keep.shape)}." + ) + return keep + if not self.mask_mode: + return None + if generator is None: + draw = torch.rand(batch, stations).to(x.device) # official: torch.rand(batch, stations).to(device) + else: + draw = torch.rand((batch, stations), generator=generator, device=generator.device).to(x.device) + return draw >= self.mask_ratio + + +def wavecastnet_station_coords(name: str = "candidates") -> torch.Tensor: + """Official station grid indices ``(stations, 2)``: ``"candidates"`` (``filtered_coord.npy``, 564 + stations, the sparse model's input) or ``"shakealert"`` (``shakealert_coords.npy``, 101 ShakeAlert + stations). Downloaded from the pinned repository commit and checked by sha256.""" + if name not in WAVECASTNET_STATIONS: + raise ValueError(f"Unknown station set {name!r}; expected one of {sorted(WAVECASTNET_STATIONS)}.") + spec = WAVECASTNET_STATIONS[name] + path = cached_download("wavecastnet", spec["filename"], [_RAW + spec["filename"]], spec["sha256"]) + return torch.as_tensor(np.load(path)).round().long() + + +def load_wavecastnet_checkpoint(model: WaveCastNet, checkpoint: Union[str, Path]) -> WaveCastNet: + """Load an official state dict (``module.`` prefixes of DataParallel removed) with ``strict=True``.""" + state = torch.load(str(checkpoint), map_location="cpu", weights_only=True) + state = {key.replace("module.", "", 1) if key.startswith("module.") else key: value for key, value in state.items()} + model.load_state_dict(state, strict=True) + return model + + +def wavecastnet_checkpoint_path(name: str = "dense") -> Path: + if name not in WAVECASTNET_WEIGHTS: + raise ValueError(f"Unknown WaveCastNet weights {name!r}; expected one of {sorted(WAVECASTNET_WEIGHTS)}.") + spec = WAVECASTNET_WEIGHTS[name] + return cached_download("wavecastnet", spec["filename"], [_DRIVE.format(file_id=spec["file_id"])], spec["sha256"]) class WaveCastNetLoss(nn.Module): - """ - Huber loss used in the WaveCastNet paper. + """Training loss of WaveCastNet. + + ``variant="official"`` (default) is the ``Huber`` class of ``earthquake_train.py`` with its default + ``delta=0.2``: ``mean(where(|e| <= delta, 0.5 e^2 / delta + 0.5 delta, |e|))``, which equals the + standard Huber loss divided by ``delta`` plus ``delta / 2``. ``variant="paper"`` is equation (4) of + the paper, the standard Huber loss ``0.5 e^2`` / ``delta (|e| - delta / 2)``. """ - def __init__(self, delta: float = 1.0): + def __init__(self, delta: float = 0.2, variant: str = "official"): super().__init__() + if variant not in {"official", "paper"}: + raise ValueError(f"variant must be 'official' or 'paper', got {variant!r}.") + if delta <= 0: + raise ValueError(f"delta must be positive, got {delta}.") self.delta = float(delta) + self.variant = variant def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: - diff = pred - target - abs_diff = diff.abs() - quadratic = 0.5 * diff.square() - linear = self.delta * abs_diff - 0.5 * self.delta**2 - return torch.where(abs_diff <= self.delta, quadratic, linear).mean() + if pred.shape != target.shape: + raise ValueError(f"pred and target must have the same shape, got {tuple(pred.shape)} and {tuple(target.shape)}.") + error = pred - target + abs_error = torch.abs(error) + if self.variant == "official": + loss = torch.where(abs_error <= self.delta, 0.5 * error**2 / self.delta + 0.5 * self.delta, abs_error) + else: + loss = torch.where(abs_error <= self.delta, 0.5 * error**2, self.delta * (abs_error - 0.5 * self.delta)) + return torch.mean(loss) class WavefieldMetrics: - """ - ACC and RFNE metrics reported in the WaveCastNet paper. - """ + """ACC, RFNE and RMSE of the official validation (``Validation_pixel.py``): one value per + (sample, channel) over time and space, averaged. See :mod:`pyhazards.metrics.wavefield`.""" @staticmethod def accuracy(pred: torch.Tensor, target: torch.Tensor) -> float: - pred_flat = pred.reshape(pred.size(0), -1) - target_flat = target.reshape(target.size(0), -1) - numerator = (pred_flat * target_flat).sum(dim=1) - pred_norm = pred_flat.square().sum(dim=1).sqrt() - target_norm = target_flat.square().sum(dim=1).sqrt() - acc = numerator / (pred_norm * target_norm).clamp(min=1e-8) - return float(acc.mean().detach().cpu()) + return float(wavefield_acc(pred.detach(), target.detach()).mean()) @staticmethod def rfne(pred: torch.Tensor, target: torch.Tensor) -> float: - error_norm = (pred - target).reshape(pred.size(0), -1).square().sum(dim=1).sqrt() - target_norm = target.reshape(target.size(0), -1).square().sum(dim=1).sqrt() - rfne = error_norm / target_norm.clamp(min=1e-8) - return float(rfne.mean().detach().cpu()) + return float(wavefield_rfne(pred.detach(), target.detach()).mean()) + + @staticmethod + def rmse(pred: torch.Tensor, target: torch.Tensor) -> float: + return float(wavefield_rmse(pred.detach(), target.detach()).mean()) @staticmethod - def compute_all(pred: torch.Tensor, target: torch.Tensor) -> dict[str, float]: + def compute_all(pred: torch.Tensor, target: torch.Tensor) -> Dict[str, float]: return { "ACC": WavefieldMetrics.accuracy(pred, target), "RFNE": WavefieldMetrics.rfne(pred, target), + "RMSE": WavefieldMetrics.rmse(pred, target), } +_OLD_ARGUMENTS = {"temporal_in", "temporal_out", "hidden_dim", "num_layers", "dropout"} + + +def wavecastnet_builder( + task: str = "forecasting", + variant: str = "dense", + in_channels: int = 3, + height: int = 344, + width: int = 224, + future_seq: int = 30, + kernel_size: Union[int, Sequence[int]] = 3, + padding: Optional[Union[int, Sequence[int]]] = None, + dt: float = 1.0, + activation: str = "tanh", + num_kernels: Optional[int] = None, + station_coords: Optional[Union[str, torch.Tensor, np.ndarray]] = None, + mask_mode: bool = True, + mask_ratio: float = DEFAULT_MASK_RATIO, + pretrained: Optional[Union[bool, str, Path]] = None, + **kwargs, +) -> WaveCastNet: + """WaveCastNet for ``task="forecasting"`` (``"regression"`` is accepted as an older alias). + + ``variant="dense"`` (default, ``AEConvLEM_dense``) or ``"sparse"`` (``AEConvLEM_sparse``, with + ``station_coords``: a ``(stations, 2)`` index array or the name of an official station set, default + ``"candidates"``). ``pretrained``: ``True`` / ``"dense"`` loads the released ``best_lem_dense_.pt`` + (dense model at 344 x 224, three channels; downloaded from the authors' Google Drive and checked by + sha256; no licence is stated for it), a path loads any official state dict. + """ + kwargs.pop("name", None) + old = sorted(set(kwargs) & _OLD_ARGUMENTS) + if old: + raise TypeError( + f"WaveCastNet no longer takes {old}: the official model has two ConvLEM layers per side, latent width " + "48 * in_channels, no dropout, any input length, and the horizon is future_seq." + ) + if kwargs: + raise TypeError(f"Unexpected WaveCastNet arguments: {sorted(kwargs)}.") + if task.lower() not in {"forecasting", "regression"}: + raise ValueError(f"WaveCastNet supports task='forecasting', got {task!r}.") + common = dict( + num_channels=in_channels, + height=height, + width=width, + kernel_size=kernel_size, + padding=padding, + dt=dt, + activation=activation, + future_seq=future_seq, + num_kernels=num_kernels, + ) + if variant == "dense": + model: WaveCastNet = WaveCastNet(**common) + elif variant == "sparse": + coords = station_coords if station_coords is not None else "candidates" + if isinstance(coords, str): + coords = wavecastnet_station_coords(coords) + model = WaveCastNetSparse(station_coords=coords, mask_mode=mask_mode, mask_ratio=mask_ratio, **common) + else: + raise ValueError(f"WaveCastNet variant must be 'dense' or 'sparse', got {variant!r}.") + if pretrained: + name = "dense" if pretrained is True else str(pretrained) + if name in WAVECASTNET_WEIGHTS: + if variant != "dense" or (in_channels, height, width) != (3, 344, 224): + raise ValueError("The released dense checkpoint needs variant='dense', 3 channels and a 344 x 224 grid.") + path = wavecastnet_checkpoint_path(name) + else: + path = Path(name) + load_wavecastnet_checkpoint(model, path) + return model + + __all__ = [ "ConvLEMCell", + "DEFAULT_MASK_RATIO", + "DenseEmbedding", + "Reconstruction", + "SparseEmbedding", + "WAVECASTNET_STATIONS", + "WAVECASTNET_WEIGHTS", "WaveCastNet", "WaveCastNetLoss", + "WaveCastNetSparse", "WavefieldMetrics", + "load_wavecastnet_checkpoint", "wavecastnet_builder", + "wavecastnet_checkpoint_path", + "wavecastnet_station_coords", ] diff --git a/pyhazards/models/wildfire_aspp.py b/pyhazards/models/wildfire_aspp.py index cd3be885..3d88e984 100644 --- a/pyhazards/models/wildfire_aspp.py +++ b/pyhazards/models/wildfire_aspp.py @@ -7,18 +7,21 @@ class WildfireASPP(WildfireCNNASPP): - """ - Backward-compatible name for the CNN + ASPP wildfire model. - """ + """Public name of the CNN-ASPP wildfire spread model (Marjani et al., IEEE GRSL 2024).""" def wildfire_aspp_builder(task: str, **kwargs) -> nn.Module: + """Build CNN-ASPP; input shape ``(batch, channels, height, width)``, raises ValueError otherwise.""" return cnn_aspp_builder(task=task, **kwargs) class TverskyLoss(nn.Module): - """ - Tversky loss for binary segmentation. + """Tversky loss ``1 - TP / (TP + alpha * FP + beta * FN)`` for binary segmentation. + + ``alpha`` weights false positives and ``beta`` false negatives (Salehi et al., 2017). + Marjani et al. (2024) write the same index with the roles named the other way round and + train CNN-ASPP with 0.7 on false negatives and 0.3 on false positives, i.e. + ``TverskyLoss(alpha=0.3, beta=0.7)`` here. """ def __init__( @@ -35,22 +38,16 @@ def __init__( self.from_logits = bool(from_logits) def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: - if self.from_logits: - probs = torch.sigmoid(logits) - else: - probs = logits - - targets = targets.float() - - probs = probs.view(probs.size(0), -1) - targets = targets.view(targets.size(0), -1) + probs = torch.sigmoid(logits) if self.from_logits else logits + probs = probs.reshape(probs.size(0), -1) + targets = targets.float().reshape(targets.size(0), -1) tp = (probs * targets).sum(dim=1) fp = (probs * (1 - targets)).sum(dim=1) fn = ((1 - probs) * targets).sum(dim=1) - tversky = (tp + self.smooth) / ( - tp + self.alpha * fp + self.beta * fn + self.smooth - ) - loss = 1.0 - tversky - return loss.mean() + tversky = (tp + self.smooth) / (tp + self.alpha * fp + self.beta * fn + self.smooth) + return (1.0 - tversky).mean() + + +__all__ = ["TverskyLoss", "WildfireASPP", "wildfire_aspp_builder"] diff --git a/pyhazards/models/wildfire_forecasting.py b/pyhazards/models/wildfire_forecasting.py index 087de17d..fab54e6c 100644 --- a/pyhazards/models/wildfire_forecasting.py +++ b/pyhazards/models/wildfire_forecasting.py @@ -1,91 +1,204 @@ +"""LSTM and ConvLSTM next-day wildfire danger classifiers of Kondylatos et al. (2022). + +Kondylatos, Prapas, Ronco, Papoutsis, Camps-Valls, Piles, Fernandez-Torres & Carvalhais, +"Wildfire Danger Prediction and Understanding With Deep Learning", Geophysical Research Letters +49(17), e2022GL099368 (https://doi.org/10.1029/2022GL099368). + +Ported from Orion-AI-Lab/wildfire_forecasting, ``wildfire_forecasting/models/modules/fire_modules.py`` +(``SimpleLSTM``, ``SimpleConvLSTM``), MIT License, Copyright (c) 2022 iprapas. Commit +2b18bcf194284d56bd4e1774f7d5315db94cba34; the model code is unchanged since the v0.1-alpha release +that the paper cites (Zenodo 10.5281/zenodo.6524771). The recurrence of the repository's +``models/modules/convlstm.py`` (from ndrplz/ConvLSTM_pytorch) is provided by +:class:`pyhazards.models.convlstm.ConvLSTM`, which computes the same gates with the same parameter +names; tests/oracle checks the two against each other. + +Both models classify one 1 km grid cell as burned / not burned on day ``t`` from the ten previous +days. Each day has 25 features, concatenated as dynamic, static, land cover: 10 dynamic variables +(NDVI, day and night LST, ERA5-Land max 2 m dew point, max 2 m temperature, max surface pressure, +total precipitation, soil moisture index, max wind speed, min relative humidity), 5 static variables +(elevation, slope, distance to roads, distance to waterways, population density) repeated over time, +and the 10 Corine Land Cover class fractions. Within each group the reference dataset orders the +variables as listed in its ``variable_dict.json``. + +- ``SimpleLSTM`` reads the cell's ``(batch, 10, 25)`` time series: LayerNorm(25) -> LSTM(25, 64) -> + last step -> Linear 64-64-32-2 with ReLU and dropout 0.5 -> log-softmax (29,652 parameters). +- ``SimpleConvLSTM`` reads the ``(batch, 10, 25, 25, 25)`` block of 25 x 25 cells centred on the cell: + LayerNorm over the features of every pixel -> ConvLSTM(25, 32, 3x3) -> last hidden state -> + Conv2d 3x3 + ReLU + 2x2 max-pool -> Linear 4608-64-32-2 with dropout 0.5 -> log-softmax + (372,212 parameters). + +Both return **log-probabilities** over (no fire, fire), exactly as the reference does; the reference +trains them with ``nn.NLLLoss`` and takes ``exp(output)[:, 1]`` as the fire-danger probability. +Parameter names and initialisation order match the reference, so its state dicts load with +``strict=True`` and the same seed gives the same initial weights. +""" + from __future__ import annotations +from typing import Optional + import torch import torch.nn as nn +import torch.nn.functional as F + +from .convlstm import ConvLSTM +WILDFIRE_FORECASTING_VARIANTS = ("lstm", "convlstm") -class WildfireForecasting(nn.Module): - """Sequence forecaster for weekly wildfire size-group activity.""" +# Hidden sizes of the paper runs (configs/experiment/lstm_temporal_cls.yaml and +# clstm_spatiotemporal_cls.yaml, which the reference README names as the paper's hyperparameters). +PAPER_HIDDEN_SIZE = {"lstm": 64, "convlstm": 32} + + +def _check_common(input_dim: int, hidden_size: int, lstm_layers: int, dropout: float) -> None: + if input_dim <= 0: + raise ValueError(f"input_dim must be positive, got {input_dim}") + if hidden_size < 2: + raise ValueError(f"hidden_size must be at least 2, got {hidden_size}") + if lstm_layers <= 0: + raise ValueError(f"lstm_layers must be positive, got {lstm_layers}") + if not 0.0 <= dropout < 1.0: + raise ValueError(f"dropout must be in [0, 1), got {dropout}") + + +class SimpleLSTM(nn.Module): + """Per-cell LSTM danger classifier (``SimpleLSTM`` in the reference ``fire_modules.py``). + + Input ``(batch, time, input_dim)``; output ``(batch, 2)`` log-probabilities. + """ + + def __init__(self, input_dim: int = 25, hidden_size: int = 64, lstm_layers: int = 1, dropout: float = 0.5): + super().__init__() + _check_common(input_dim, hidden_size, lstm_layers, dropout) + self.input_dim = int(input_dim) + self.ln1 = nn.LayerNorm(input_dim) + self.lstm = nn.LSTM(input_dim, hidden_size, num_layers=lstm_layers, batch_first=True) + self.fc1 = nn.Linear(hidden_size, hidden_size) + self.drop1 = nn.Dropout(dropout) + self.relu = nn.ReLU() + self.fc2 = nn.Linear(hidden_size, hidden_size // 2) + self.drop2 = nn.Dropout(dropout) + self.fc3 = nn.Linear(hidden_size // 2, 2) + # The reference registers the same layers again inside ``fc_nn``; its state dict therefore + # holds each fully connected tensor under two keys (``fc1.*`` and ``fc_nn.0.*``, ...). + self.fc_nn = nn.Sequential(self.fc1, self.relu, self.drop1, self.fc2, self.relu, self.drop2, self.fc3) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 3: + raise ValueError( + "SimpleLSTM expects input shape (batch, time, features), e.g. (batch, 10, 25), " + f"got {tuple(x.shape)}." + ) + if x.size(-1) != self.input_dim: + raise ValueError(f"SimpleLSTM expected {self.input_dim} features per day, got shape {tuple(x.shape)}.") + x = self.ln1(x) + lstm_out, _ = self.lstm(x) + x = self.fc_nn(lstm_out[:, -1, :]) + return F.log_softmax(x, dim=1) + + +class SimpleConvLSTM(nn.Module): + """Patch ConvLSTM danger classifier (``SimpleConvLSTM`` in the reference ``fire_modules.py``). + + Input ``(batch, time, input_dim, patch_size, patch_size)``; output ``(batch, 2)`` log-probabilities. + The fully connected head is sized for ``patch_size x patch_size`` patches (25 in the paper). + """ def __init__( self, - input_dim: int = 7, - hidden_dim: int = 64, - output_dim: int = 5, - lookback: int = 12, - num_layers: int = 2, - dropout: float = 0.1, + input_dim: int = 25, + hidden_size: int = 32, + lstm_layers: int = 1, + dropout: float = 0.5, + patch_size: int = 25, ): super().__init__() - if input_dim <= 0: - raise ValueError(f"input_dim must be positive, got {input_dim}") - if hidden_dim <= 0: - raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") - if output_dim <= 0: - raise ValueError(f"output_dim must be positive, got {output_dim}") - if lookback <= 0: - raise ValueError(f"lookback must be positive, got {lookback}") - if num_layers <= 0: - raise ValueError(f"num_layers must be positive, got {num_layers}") - if not 0.0 <= dropout < 1.0: - raise ValueError(f"dropout must be in [0, 1), got {dropout}") - - self.lookback = int(lookback) - self.encoder = nn.GRU( - input_size=input_dim, - hidden_size=hidden_dim, - num_layers=num_layers, - batch_first=True, - dropout=dropout if num_layers > 1 else 0.0, - ) - self.attention = nn.Linear(hidden_dim, 1) - self.head = nn.Sequential( - nn.Linear(hidden_dim, hidden_dim), - nn.GELU(), - nn.Dropout(dropout), - nn.Linear(hidden_dim, output_dim), + _check_common(input_dim, hidden_size, lstm_layers, dropout) + if patch_size < 2: + raise ValueError(f"patch_size must be at least 2, got {patch_size}") + kernel_size = 3 + self.input_dim = int(input_dim) + self.patch_size = int(patch_size) + self.ln1 = nn.LayerNorm(input_dim) + # The reference uses its own ConvLSTM (from ndrplz/ConvLSTM_pytorch) with batch_first=True, + # bias=True, return_all_layers=False and dilation=1. pyhazards.models.convlstm.ConvLSTM has the + # same gates, zero initial state and parameter names (``cell_list.{i}.conv``). + self.convlstm = ConvLSTM(input_dim, hidden_size, kernel_size=(kernel_size, kernel_size), num_layers=lstm_layers) + self.conv1 = nn.Conv2d( + hidden_size, hidden_size, kernel_size=(kernel_size, kernel_size), stride=(1, 1), padding=(1, 1) ) + self.fc1 = nn.Linear((patch_size // 2) * (patch_size // 2) * hidden_size, 2 * hidden_size) + self.drop1 = nn.Dropout(dropout) + self.fc2 = nn.Linear(2 * hidden_size, hidden_size) + self.drop2 = nn.Dropout(dropout) + self.fc3 = nn.Linear(hidden_size, 2) def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 3: + if x.ndim != 5: raise ValueError( - "WildfireForecasting expects input shape (batch, lookback, features), " - f"got {tuple(x.shape)}." + "SimpleConvLSTM expects input shape (batch, time, features, height, width), " + f"e.g. (batch, 10, 25, 25, 25), got {tuple(x.shape)}." ) - if x.size(1) != self.lookback: + if x.size(2) != self.input_dim: raise ValueError( - f"WildfireForecasting expected lookback={self.lookback}, got sequence length {x.size(1)}." + f"SimpleConvLSTM expected {self.input_dim} features per day, got shape {tuple(x.shape)}." ) - encoded, _ = self.encoder(x) - weights = torch.softmax(self.attention(encoded), dim=1) - pooled = torch.sum(weights * encoded, dim=1) - return self.head(pooled) + pooled = self.patch_size // 2 + if (x.size(3) // 2, x.size(4) // 2) != (pooled, pooled): + raise ValueError( + f"SimpleConvLSTM's head is sized for {self.patch_size}x{self.patch_size} patches, " + f"got shape {tuple(x.shape)}." + ) + # LayerNorm over the features of every pixel: (b, t, c, h, w) -> (b, t, h, w, c) -> back. + x = self.ln1(x.permute(0, 1, 3, 4, 2)).permute(0, 1, 4, 2, 3) + _, last_states = self.convlstm(x) + x = last_states[-1][0] # hidden state of the last layer at the last step + x = F.max_pool2d(F.relu(self.conv1(x)), 2) + x = torch.flatten(x, 1) + x = F.relu(self.drop1(self.fc1(x))) + x = F.relu(self.drop2(self.fc2(x))) + x = self.fc3(x) + return F.log_softmax(x, dim=1) def wildfire_forecasting_builder( task: str, - input_dim: int = 7, - hidden_dim: int = 64, - output_dim: int = 5, - lookback: int = 12, - num_layers: int = 2, - dropout: float = 0.1, + variant: str = "lstm", + input_dim: int = 25, + hidden_size: Optional[int] = None, + lstm_layers: int = 1, + dropout: float = 0.5, + patch_size: int = 25, **kwargs, ) -> nn.Module: + """Build the Kondylatos et al. (2022) LSTM (``variant="lstm"``, default) or ConvLSTM. + + ``hidden_size`` defaults to the paper value of the chosen variant (64 for the LSTM, 32 for the + ConvLSTM). ``patch_size`` only applies to the ConvLSTM. Both models return ``(batch, 2)`` + log-probabilities. + """ _ = kwargs - if task.lower() not in {"forecasting", "regression"}: - raise ValueError( - "wildfire_forecasting supports task='forecasting' or 'regression', " - f"got {task!r}." - ) - return WildfireForecasting( + if task.lower() != "classification": + raise ValueError(f"wildfire_forecasting supports task='classification', got {task!r}.") + if variant not in WILDFIRE_FORECASTING_VARIANTS: + raise ValueError(f"variant must be one of {WILDFIRE_FORECASTING_VARIANTS}, got {variant!r}.") + if hidden_size is None: + hidden_size = PAPER_HIDDEN_SIZE[variant] + if variant == "lstm": + return SimpleLSTM(input_dim=input_dim, hidden_size=hidden_size, lstm_layers=lstm_layers, dropout=dropout) + return SimpleConvLSTM( input_dim=input_dim, - hidden_dim=hidden_dim, - output_dim=output_dim, - lookback=lookback, - num_layers=num_layers, + hidden_size=hidden_size, + lstm_layers=lstm_layers, dropout=dropout, + patch_size=patch_size, ) -__all__ = ["WildfireForecasting", "wildfire_forecasting_builder"] +__all__ = [ + "PAPER_HIDDEN_SIZE", + "SimpleConvLSTM", + "SimpleLSTM", + "WILDFIRE_FORECASTING_VARIANTS", + "wildfire_forecasting_builder", +] diff --git a/pyhazards/models/wildfirespreadts.py b/pyhazards/models/wildfirespreadts.py index 1de85416..85320987 100644 --- a/pyhazards/models/wildfirespreadts.py +++ b/pyhazards/models/wildfirespreadts.py @@ -1,79 +1,97 @@ -from __future__ import annotations +"""The WildfireSpreadTS benchmark baselines with the benchmark's own configurations. -import torch -import torch.nn as nn +Gerard, Zhao & Sullivan, "WildfireSpreadTS: A dataset of multi-modal time series for wildfire +spread prediction", NeurIPS 2023 Datasets & Benchmarks (https://github.com/SebastianGer/WildfireSpreadTS, +MIT). The benchmark trains four learned baselines on next-day active-fire segmentation; this +builder returns each of them exactly as configured in ``src/models``: +- ``logistic_regression``: ``Conv2d(C * T, 1, 3, padding=1)`` (361 parameters for 40 channels, 1 day); +- ``resnet18_unet``: ``smp.Unet("resnet18", encoder_weights=None)`` on the flattened time axis; +- ``convlstm``: one ConvLSTM layer, 64 hidden channels, 3x3 kernels, head on the last cell state + (240,449 parameters for 40 channels); +- ``utae``: U-TAE with encoder widths (64, 64, 64, 128), decoder widths (32, 32, 64, 128), + output convolutions (32, 1), 16 heads, d_model 256, d_k 4 (1,099,011 parameters for 40 channels). -class WildfireSpreadTS(nn.Module): - """Temporal convolution baseline for wildfire spread masks.""" +With all features, WildfireSpreadTS has 40 channels per day (23 raw features with the 17-class +land cover one-hot encoded) and uses 1 or 5 days of history. +""" - def __init__( - self, - history: int = 4, - in_channels: int = 6, - hidden_dim: int = 32, - out_channels: int = 1, - dropout: float = 0.1, - ): - super().__init__() - if history <= 0: - raise ValueError(f"history must be positive, got {history}") - if in_channels <= 0: - raise ValueError(f"in_channels must be positive, got {in_channels}") - if hidden_dim <= 0: - raise ValueError(f"hidden_dim must be positive, got {hidden_dim}") - if out_channels <= 0: - raise ValueError(f"out_channels must be positive, got {out_channels}") - if not 0.0 <= dropout < 1.0: - raise ValueError(f"dropout must be in [0, 1), got {dropout}") +from __future__ import annotations - self.history = int(history) - self.in_channels = int(in_channels) - self.encoder = nn.Sequential( - nn.Conv3d(in_channels, hidden_dim, kernel_size=(3, 3, 3), padding=1), - nn.GELU(), - nn.Dropout3d(dropout) if dropout > 0 else nn.Identity(), - nn.Conv3d(hidden_dim, hidden_dim, kernel_size=(3, 3, 3), padding=1), - nn.GELU(), - ) - self.head = nn.Conv2d(hidden_dim, out_channels, kernel_size=1) +from typing import Optional, Sequence + +import torch.nn as nn + +from .convlstm import ConvLSTMSegmenter +from .logistic_regression import PixelLogisticRegression +from .resnet_unet import ResNetUNet +from .utae import UTAE - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 5: - raise ValueError( - "WildfireSpreadTS expects input shape (batch, history, channels, height, width), " - f"got {tuple(x.shape)}." - ) - if x.size(1) != self.history: - raise ValueError(f"WildfireSpreadTS expected history={self.history}, got {x.size(1)}.") - if x.size(2) != self.in_channels: - raise ValueError(f"WildfireSpreadTS expected in_channels={self.in_channels}, got {x.size(2)}.") - encoded = self.encoder(x.permute(0, 2, 1, 3, 4)) - return self.head(torch.mean(encoded, dim=2)) +WILDFIRESPREADTS_BASELINES = ("logistic_regression", "resnet18_unet", "convlstm", "utae") +# Static per-day features of the 40-channel "All features" layout (topography and the 17 land-cover +# one-hot channels); FireSpreadDataset.get_static_and_dynamic_feature_ids in WildfireSpreadTS. +WILDFIRESPREADTS_STATIC_FEATURE_IDS = (12, 13, 14, *range(16, 33)) def wildfirespreadts_builder( task: str, - history: int = 4, - in_channels: int = 6, - hidden_dim: int = 32, - out_channels: int = 1, - dropout: float = 0.1, + baseline: str = "utae", + in_channels: int = 40, + history: int = 5, + remove_duplicate_features: Optional[bool] = None, + static_feature_ids: Sequence[int] = WILDFIRESPREADTS_STATIC_FEATURE_IDS, **kwargs, ) -> nn.Module: + """Build one WildfireSpreadTS baseline. + + ``in_channels`` is the number of features per day; ``history`` is the number of days, used + by the baselines that flatten time into channels (logistic regression and the U-Net). Every + baseline takes input shape ``(batch, history, in_channels, height, width)`` and returns + ``(batch, 1, height, width)`` logits; ``utae`` also accepts ``batch_positions`` (day of year). + + ``remove_duplicate_features`` (``resnet18_unet`` only; on by default for the 40-feature layout, + as in the benchmark's U-Net runs) keeps the static features listed in ``static_feature_ids`` + for the last day only, so a 5-day, 40-feature U-Net has 4 * 20 + 40 = 120 input channels + instead of 200. + """ _ = kwargs - if task.lower() not in {"segmentation", "regression"}: - raise ValueError( - "wildfirespreadts supports task='segmentation' or 'regression', " - f"got {task!r}." + if task.lower() != "segmentation": + raise ValueError(f"wildfirespreadts supports task='segmentation', got {task!r}.") + if in_channels <= 0 or history <= 0: + raise ValueError(f"in_channels and history must be positive, got {in_channels} and {history}.") + if baseline == "logistic_regression": + return PixelLogisticRegression(in_channels * history, out_channels=1, kernel_size=3) + if baseline == "resnet18_unet": + if remove_duplicate_features is None: + # On by default only for the benchmark's own 40-feature layout, where static_feature_ids apply. + remove_duplicate_features = in_channels == 40 + static = tuple(static_feature_ids) if remove_duplicate_features and history > 1 else None + if static is not None and (not static or max(static) >= in_channels): + raise ValueError(f"static_feature_ids must index the {in_channels} input channels, got {static}.") + channels = in_channels * history if static is None else (history - 1) * (in_channels - len(static)) + in_channels + return ResNetUNet( + channels, classes=1, encoder_name="resnet18", encoder_weights=None, static_feature_ids=static + ) + if baseline == "convlstm": + return ConvLSTMSegmenter(in_channels, num_classes=1, hidden_dim=64, kernel_size=3, num_layers=1) + if baseline == "utae": + return UTAE( + input_dim=in_channels, + encoder_widths=[64, 64, 64, 128], + decoder_widths=[32, 32, 64, 128], + out_conv=[32, 1], + str_conv_k=4, + str_conv_s=2, + str_conv_p=1, + agg_mode="att_group", + encoder_norm="group", + n_head=16, + d_model=256, + d_k=4, + pad_value=0, + padding_mode="reflect", ) - return WildfireSpreadTS( - history=history, - in_channels=in_channels, - hidden_dim=hidden_dim, - out_channels=out_channels, - dropout=dropout, - ) + raise ValueError(f"baseline must be one of {WILDFIRESPREADTS_BASELINES}, got {baseline!r}.") -__all__ = ["WildfireSpreadTS", "wildfirespreadts_builder"] +__all__ = ["WILDFIRESPREADTS_BASELINES", "wildfirespreadts_builder"] diff --git a/pyhazards/models/wrf_sfire.py b/pyhazards/models/wrf_sfire.py deleted file mode 100644 index be71a950..00000000 --- a/pyhazards/models/wrf_sfire.py +++ /dev/null @@ -1,66 +0,0 @@ -from __future__ import annotations - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class WRFSFireAdapter(nn.Module): - """Lightweight raster adapter inspired by WRF-SFIRE style spread diffusion.""" - - def __init__( - self, - in_channels: int = 12, - out_channels: int = 1, - diffusion_steps: int = 3, - ): - super().__init__() - if in_channels <= 0: - raise ValueError(f"in_channels must be positive, got {in_channels}") - if out_channels != 1: - raise ValueError(f"WRFSFireAdapter only supports out_channels=1, got {out_channels}") - if diffusion_steps <= 0: - raise ValueError(f"diffusion_steps must be positive, got {diffusion_steps}") - self.in_channels = int(in_channels) - self.diffusion_steps = int(diffusion_steps) - kernel = torch.tensor( - [[0.02, 0.08, 0.02], [0.08, 0.60, 0.08], [0.02, 0.08, 0.02]], - dtype=torch.float32, - ).view(1, 1, 3, 3) - self.register_buffer("transport_kernel", kernel) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - if x.ndim != 4: - raise ValueError( - "WRFSFireAdapter expects input shape (batch, channels, height, width), " - f"got {tuple(x.shape)}." - ) - if x.size(1) != self.in_channels: - raise ValueError(f"WRFSFireAdapter expected in_channels={self.in_channels}, got {x.size(1)}.") - fireline = torch.sigmoid(x[:, :1]) - terrain = torch.sigmoid(x[:, 1:2]) - moisture = torch.sigmoid(x[:, 2:3]) - for _ in range(self.diffusion_steps): - fireline = F.conv2d(fireline, self.transport_kernel, padding=1) - fireline = torch.clamp(fireline * (0.9 + 0.1 * terrain) * (1.0 - 0.15 * moisture), 0.0, 1.0) - return fireline - - -def wrf_sfire_builder( - task: str, - in_channels: int = 12, - out_channels: int = 1, - diffusion_steps: int = 3, - **kwargs, -) -> nn.Module: - _ = kwargs - if task.lower() not in {"segmentation", "regression"}: - raise ValueError(f"wrf_sfire supports task='segmentation' or 'regression', got {task!r}.") - return WRFSFireAdapter( - in_channels=in_channels, - out_channels=out_channels, - diffusion_steps=diffusion_steps, - ) - - -__all__ = ["WRFSFireAdapter", "wrf_sfire_builder"] diff --git a/pyhazards/prompted/__init__.py b/pyhazards/prompted/__init__.py new file mode 100644 index 00000000..663015f6 --- /dev/null +++ b/pyhazards/prompted/__init__.py @@ -0,0 +1,80 @@ +"""Prompted multimodal-LLM baselines for wildfire smoke, following SmokeBench. + +SmokeBench (Qi, Li & Barnes, "SmokeBench: Evaluating Multimodal Large Language Models for Wildfire +Smoke Detection", WACV 2026, arXiv:2512.11215) asks multimodal LLMs four questions about FIgLib camera +frames: whether there is smoke (classification), which of 3 x 4 tiles contain smoke (each tile asked +separately), which cells of a numbered 5 x 5 grid contain smoke, and for smoke bounding boxes +(detection). This package holds the paper's verbatim prompts (:mod:`.prompts`), the image partitions +(:mod:`.geometry`), answer parsing (:mod:`.parsers`), the metrics and smoke-area / contrast bins +(:mod:`.metrics`), backends for the evaluated models (:mod:`.backends`, optional dependencies) and a +resumable runner (:func:`evaluate_smokebench`). The images come from +:mod:`pyhazards.datasets.figlib_smokebench`. + +These are not ``nn.Module`` models and are not in the model registry; see the "Prompted VLM +Baselines" documentation page. +""" + +from __future__ import annotations + +from .backends import ( + GeminiBackend, + Idefics2Backend, + InternVL3Backend, + OpenAIBackend, + PromptedBackend, + Qwen25VLBackend, + available_backends, + build_backend, +) +from .geometry import PROTOCOLS, covered_cells, crop_tiles, draw_grid_overlay, tile_rects +from .metrics import accuracy, detection_iou, set_iou, weber_contrast +from .parsers import parse_classification, parse_detection, parse_grid, parse_tile +from .prompts import ( + CLASSIFICATION_PROMPT, + DETECTION_PROMPT, + GRID_LAYOUT, + GRID_PROMPT, + PROMPTS, + TASKS, + TEMPERATURE, + TILE_LAYOUT, + TILE_PROMPT, + get_prompt, +) +from .runner import evaluate_smokebench, summarize + +__all__ = [ + "CLASSIFICATION_PROMPT", + "DETECTION_PROMPT", + "GRID_LAYOUT", + "GRID_PROMPT", + "GeminiBackend", + "Idefics2Backend", + "InternVL3Backend", + "OpenAIBackend", + "PROMPTS", + "PROTOCOLS", + "PromptedBackend", + "Qwen25VLBackend", + "TASKS", + "TEMPERATURE", + "TILE_LAYOUT", + "TILE_PROMPT", + "accuracy", + "available_backends", + "build_backend", + "covered_cells", + "crop_tiles", + "detection_iou", + "draw_grid_overlay", + "evaluate_smokebench", + "get_prompt", + "parse_classification", + "parse_detection", + "parse_grid", + "parse_tile", + "set_iou", + "summarize", + "tile_rects", + "weber_contrast", +] diff --git a/pyhazards/prompted/__main__.py b/pyhazards/prompted/__main__.py new file mode 100644 index 00000000..e71ecac6 --- /dev/null +++ b/pyhazards/prompted/__main__.py @@ -0,0 +1,71 @@ +"""Command line: run one SmokeBench task with one backend. + +usage: python -m pyhazards.prompted --backend qwen2_5_vl_7b --task classification \\ + --root data/figlib --output runs/qwen7b_cls [--download] [--sequences A B ...] +""" + +from __future__ import annotations + +import argparse +import json +from typing import List, Optional + +from .backends import available_backends, build_backend +from .geometry import PROTOCOLS +from .prompts import TASKS +from .runner import evaluate_smokebench + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="python -m pyhazards.prompted", description=__doc__.splitlines()[0]) + parser.add_argument("--backend", required=True, choices=available_backends()) + parser.add_argument("--task", required=True, choices=TASKS) + parser.add_argument("--root", required=True, help="FIgLib SmokeBench directory (see figlib_smokebench)") + parser.add_argument("--output", required=True, help="directory for records.jsonl and report.json") + parser.add_argument("--protocol", default="paper", choices=PROTOCOLS) + parser.add_argument("--download", action="store_true", help="download missing boxes and frames first") + parser.add_argument("--sequences", nargs="*", default=None, help="restrict to these FIgLib sequences") + parser.add_argument("--negatives", type=int, default=1000, help="smoke-free frames to draw (classification)") + parser.add_argument("--negative-seed", type=int, default=0) + parser.add_argument("--model-id", default=None, help="override the preset's model id") + parser.add_argument("--greedy", action="store_true", help="greedy decoding instead of temperature 0.5") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--limit", type=int, default=None) + parser.add_argument("--no-resume", action="store_true") + args = parser.parse_args(argv) + + from ..datasets.figlib_smokebench import FIgLibSmokeBench # noqa: PLC0415 + + dataset = FIgLibSmokeBench( + args.root, + sequences=args.sequences, + negatives=args.negatives, + negative_seed=args.negative_seed, + download=args.download, + ) + kwargs = {} + if args.model_id: + kwargs["model_id"] = args.model_id + if args.greedy: + if args.backend in {"gemini_2_5_pro", "gpt_4o"}: + kwargs["temperature"] = 0.0 + else: + kwargs["do_sample"] = False + backend = build_backend(args.backend, **kwargs) + report = evaluate_smokebench( + backend, + dataset, + args.task, + protocol=args.protocol, + output_dir=args.output, + resume=not args.no_resume, + seed=args.seed, + limit=args.limit, + progress=True, + ) + print(json.dumps({"metrics": report["metrics"], "paper_reported": report["paper_reported"]}, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyhazards/prompted/backends/__init__.py b/pyhazards/prompted/backends/__init__.py new file mode 100644 index 00000000..f0ce5672 --- /dev/null +++ b/pyhazards/prompted/backends/__init__.py @@ -0,0 +1,91 @@ +"""Backends for prompted baselines. Optional packages are imported only when a backend is built.""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, List + +from .api import GeminiBackend, OpenAIBackend +from .base import PromptedBackend, check_image, encode_jpeg, to_pil +from .hf import Idefics2Backend, InternVL3Backend, Qwen25VLBackend, TransformersBackend + +# Hugging Face revisions of the open checkpoints, pinned on 2026-10-07 (SmokeBench did not pin any); +# pass revision=None to build_backend for the latest revision. +REVISIONS: Dict[str, str] = { + "Qwen/Qwen2.5-VL-7B-Instruct": "cc594898137f460bfe9f0759e9844b3ce807cfb5", + "Qwen/Qwen2.5-VL-32B-Instruct": "7cfb30d71a1f4f49a57592323337a4a4727301da", + "OpenGVLab/InternVL3-14B-hf": "e22931943e5336f85e06f4e2b38f3e5e6ee4de3b", + "HuggingFaceM4/idefics2-8b": "2c42686c57fe21cf0348c9ce1077d094b72e7698", +} + + +def _open(cls: Callable[..., PromptedBackend], model_id: str) -> Callable[..., PromptedBackend]: + def build(**kwargs: Any) -> PromptedBackend: + kwargs.setdefault("model_id", model_id) + if kwargs["model_id"] == model_id: + kwargs.setdefault("revision", REVISIONS[model_id]) + return cls(**kwargs) + + return build + + +def _api(cls: Callable[..., PromptedBackend], model_id: str) -> Callable[..., PromptedBackend]: + def build(**kwargs: Any) -> PromptedBackend: + kwargs.setdefault("model_id", model_id) + return cls(**kwargs) + + return build + + +# Named configurations of the models SmokeBench evaluated (one per card in pyhazards/prompted/cards). +MODEL_IDS: Dict[str, str] = { + "qwen2_5_vl_7b": "Qwen/Qwen2.5-VL-7B-Instruct", + "qwen2_5_vl_32b": "Qwen/Qwen2.5-VL-32B-Instruct", + "internvl3_14b": "OpenGVLab/InternVL3-14B-hf", + "idefics2_8b": "HuggingFaceM4/idefics2-8b", + "gemini_2_5_pro": "gemini-2.5-pro", + "gpt_4o": "gpt-4o", +} +_PRESETS: Dict[str, Callable[..., PromptedBackend]] = { + "qwen2_5_vl_7b": _open(Qwen25VLBackend, MODEL_IDS["qwen2_5_vl_7b"]), + "qwen2_5_vl_32b": _open(Qwen25VLBackend, MODEL_IDS["qwen2_5_vl_32b"]), + "internvl3_14b": _open(InternVL3Backend, MODEL_IDS["internvl3_14b"]), + "idefics2_8b": _open(Idefics2Backend, MODEL_IDS["idefics2_8b"]), + "gemini_2_5_pro": _api(GeminiBackend, MODEL_IDS["gemini_2_5_pro"]), + "gpt_4o": _api(OpenAIBackend, MODEL_IDS["gpt_4o"]), +} + + +def available_backends() -> List[str]: + return sorted(_PRESETS) + + +def build_backend(name: str, **kwargs: Any) -> PromptedBackend: + """Build a SmokeBench model by preset name (see :func:`available_backends`). + + Keyword arguments go to the backend class. The backend keeps the preset name (which links run + reports to the numbers SmokeBench reports) only while ``model_id`` is the preset's model. + """ + if name not in _PRESETS: + raise KeyError(f"unknown prompted backend {name!r}; known: {available_backends()}") + backend = _PRESETS[name](**kwargs) + if backend.model_id == MODEL_IDS[name]: + backend.name = name + return backend + + +__all__ = [ + "MODEL_IDS", + "REVISIONS", + "GeminiBackend", + "Idefics2Backend", + "InternVL3Backend", + "OpenAIBackend", + "PromptedBackend", + "Qwen25VLBackend", + "TransformersBackend", + "available_backends", + "build_backend", + "check_image", + "encode_jpeg", + "to_pil", +] diff --git a/pyhazards/prompted/backends/api.py b/pyhazards/prompted/backends/api.py new file mode 100644 index 00000000..14a4a734 --- /dev/null +++ b/pyhazards/prompted/backends/api.py @@ -0,0 +1,137 @@ +"""Closed SmokeBench models through their official Python clients (optional extras). + +SmokeBench ran GPT-4o and Gemini-2.5 Pro on the classification task only (Sec. 4.1), at temperature +0.5. The release contains no code for these runs, so the request layout is a PyHazards choice: the +image is sent as a JPEG (quality 95, OpenCV's ``imencode`` default that the authors' one GPT-4o script +uses) and the prompt as text. GPT-4o gets ``[text, image]`` with ``max_tokens=300`` as in that script +(``mllm_smoke_locate.py`` of github.com/SoraLink/MLLM @ 183cdca); Gemini gets ``[image, text]``, the +order Google's prompting guide recommends for single-image prompts, and no output cap (Gemini 2.5 Pro +spends output tokens on thinking). + +API keys are read from the environment only: ``OPENAI_API_KEY`` for OpenAI, ``GEMINI_API_KEY`` (or +``GOOGLE_API_KEY``) for Gemini. Each call records the model version the provider reports in +``last_served_model``; providers update the models behind an alias, so results drift over time. +""" + +from __future__ import annotations + +import base64 +import os +from typing import Any, Dict, Optional + +import numpy as np + +from ..prompts import TEMPERATURE +from .base import PromptedBackend, encode_jpeg, require + + +class GeminiBackend(PromptedBackend): + """Google Gemini (Gemini 2.5 report: Comanici et al., arXiv:2507.06261) via ``google-genai``.""" + + name = "gemini" + + def __init__( + self, + model_id: str = "gemini-2.5-pro", + *, + temperature: Optional[float] = TEMPERATURE, + jpeg_quality: int = 95, + max_output_tokens: Optional[int] = None, + client: Any = None, + ) -> None: + super().__init__() + self.model_id = model_id + self.temperature = temperature + self.jpeg_quality = int(jpeg_quality) + self.max_output_tokens = max_output_tokens + if client is None: + genai = require("google.genai", "prompted-gemini", "The Gemini backend") + api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") + if not api_key: + raise RuntimeError("The Gemini backend reads its API key from GEMINI_API_KEY (or GOOGLE_API_KEY); set it in the environment.") + client = genai.Client(api_key=api_key) + self.client = client + + def _config(self) -> Dict[str, Any]: + config: Dict[str, Any] = {} + if self.temperature is not None: + config["temperature"] = float(self.temperature) + if self.max_output_tokens is not None: + config["max_output_tokens"] = int(self.max_output_tokens) + return config + + def generate(self, image: np.ndarray, prompt: str) -> str: + image_part = {"inline_data": {"mime_type": "image/jpeg", "data": encode_jpeg(image, self.jpeg_quality)}} + response = self.client.models.generate_content( + model=self.model_id, + contents=[{"role": "user", "parts": [image_part, {"text": prompt}]}], + config=self._config(), + ) + self.last_served_model = getattr(response, "model_version", None) + return getattr(response, "text", None) or "" + + def describe(self) -> Dict[str, Any]: + info = super().describe() + info.update(generation=self._config(), jpeg_quality=self.jpeg_quality, content_order="image, text") + return info + + +class OpenAIBackend(PromptedBackend): + """OpenAI chat models such as GPT-4o (GPT-4o system card: Hurst et al., arXiv:2410.21276).""" + + name = "openai" + + def __init__( + self, + model_id: str = "gpt-4o", + *, + temperature: Optional[float] = TEMPERATURE, + max_tokens: Optional[int] = 300, + jpeg_quality: int = 95, + client: Any = None, + ) -> None: + super().__init__() + self.model_id = model_id + self.temperature = temperature + self.max_tokens = max_tokens + self.jpeg_quality = int(jpeg_quality) + if client is None: + openai = require("openai", "prompted-openai", "The OpenAI backend") + if not os.environ.get("OPENAI_API_KEY"): + raise RuntimeError("The OpenAI backend reads its API key from OPENAI_API_KEY; set it in the environment.") + client = openai.OpenAI() + self.client = client + + def _options(self) -> Dict[str, Any]: + options: Dict[str, Any] = {} + if self.temperature is not None: + options["temperature"] = float(self.temperature) + if self.max_tokens is not None: + options["max_tokens"] = int(self.max_tokens) + return options + + def generate(self, image: np.ndarray, prompt: str) -> str: + data = base64.b64encode(encode_jpeg(image, self.jpeg_quality)).decode("ascii") + response = self.client.chat.completions.create( + model=self.model_id, + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{data}"}}, + ], + } + ], + **self._options(), + ) + self.last_served_model = getattr(response, "model", None) + return response.choices[0].message.content or "" + + def describe(self) -> Dict[str, Any]: + info = super().describe() + info.update(generation=self._options(), jpeg_quality=self.jpeg_quality, content_order="text, image") + return info + + +__all__ = ["GeminiBackend", "OpenAIBackend"] diff --git a/pyhazards/prompted/backends/base.py b/pyhazards/prompted/backends/base.py new file mode 100644 index 00000000..68cd57cf --- /dev/null +++ b/pyhazards/prompted/backends/base.py @@ -0,0 +1,72 @@ +"""Backend interface for prompted multimodal-LLM baselines: (RGB image, text prompt) -> answer text.""" + +from __future__ import annotations + +import abc +import importlib +import io +from typing import Any, Dict, List, Optional, Sequence + +import numpy as np + + +def require(module: str, extra: str, purpose: str): + """Import an optional dependency or raise an ``ImportError`` naming the PyHazards extra.""" + try: + return importlib.import_module(module) + except ImportError as exc: + raise ImportError( + f"{purpose} needs the optional package '{module.split('.')[0]}'. " + f"Install it with `pip install pyhazards[{extra}]`." + ) from exc + + +def check_image(image: np.ndarray) -> np.ndarray: + array = np.asarray(image) + if array.ndim != 3 or array.shape[2] != 3 or array.dtype != np.uint8: + raise ValueError( + f"expected an RGB uint8 image array of shape (H, W, 3), got shape {array.shape} and dtype {array.dtype}" + ) + return array + + +def to_pil(image: np.ndarray): + """RGB uint8 array -> ``PIL.Image`` (needs Pillow).""" + pil_image = require("PIL.Image", "prompted", "Converting images for prompted backends") + return pil_image.fromarray(check_image(image)) + + +def encode_jpeg(image: np.ndarray, quality: int = 95) -> bytes: + """JPEG bytes of an RGB uint8 array (Pillow; quality 95 is also OpenCV's ``imencode`` default).""" + buffer = io.BytesIO() + to_pil(image).save(buffer, format="JPEG", quality=quality) + return buffer.getvalue() + + +class PromptedBackend(abc.ABC): + """A model answering one text prompt about one image. + + Subclasses implement :meth:`generate`. :meth:`generate_batch` (used for the 12 tiles of an image) + defaults to a loop. :attr:`last_served_model` is set by API backends to the model version the + provider reports for the latest call. + """ + + name: str = "backend" + model_id: str = "" + + def __init__(self) -> None: + self.last_served_model: Optional[str] = None + + @abc.abstractmethod + def generate(self, image: np.ndarray, prompt: str) -> str: + """Answer ``prompt`` about an RGB ``(H, W, 3)`` uint8 image.""" + + def generate_batch(self, images: Sequence[np.ndarray], prompt: str) -> List[str]: + return [self.generate(image, prompt) for image in images] + + def describe(self) -> Dict[str, Any]: + """Settings recorded in evaluation reports.""" + return {"backend": type(self).__name__, "name": self.name, "model_id": self.model_id} + + +__all__ = ["PromptedBackend", "check_image", "encode_jpeg", "require", "to_pil"] diff --git a/pyhazards/prompted/backends/hf.py b/pyhazards/prompted/backends/hf.py new file mode 100644 index 00000000..e7b3ee10 --- /dev/null +++ b/pyhazards/prompted/backends/hf.py @@ -0,0 +1,255 @@ +"""Open-weight SmokeBench models through Hugging Face transformers (optional extra ``prompted-hf``). + +SmokeBench evaluated Qwen2.5-VL-7B/32B-Instruct, InternVL3-14B and Idefics2-8B. The paper states only +the prompts and the decoding temperature (0.5); everything else here follows the authors' +``mllms.py`` (github.com/SoraLink/MLLM, commit 183cdca488e8c7afa5a254f86ac675cb98951c73, no licence; +nothing is copied, the settings are re-implemented and listed in the docs): + +* Qwen2.5-VL: the image is resized to 448 x 448 with ``PIL.Image.resize`` before the processor + (all four tasks), single-turn chat template with the image before the text, 128 new tokens, and a + Markdown ```json fence is stripped from the answer; +* InternVL3: the transformers-native checkpoint ``OpenGVLab/InternVL3-14B-hf`` through its chat + template (the image-text-to-text pipeline the authors used), float32 weights, 256 new tokens (the + pipeline default); +* Idefics2: ``do_image_splitting=False``, bfloat16. Single images (classification, grid, detection) + are sent as the raw text ``"\\n" + prompt`` without the chat template, 256 new tokens (the + pipeline call of the authors' ``predict``); the 12 tiles of the tile task go as one left-padded + batch through the chat template with 16 new tokens (their ``batch_predict``). + +Sampling: ``temperature=0.5`` with ``do_sample=True`` as the paper states. The released script never +sets a temperature, so its runs used each checkpoint's ``generation_config`` (greedy for Idefics2 and +InternVL3, temperature 1e-6 for Qwen2.5-VL); pass ``do_sample=False`` to decode greedily instead. +Other sampling parameters come from the checkpoint's ``generation_config``. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union + +import numpy as np + +from ..parsers import strip_json_fence +from ..prompts import TEMPERATURE +from .base import PromptedBackend, require, to_pil + +DTypeLike = Union[str, Any] + + +def _resolve_dtype(dtype: DTypeLike): + if isinstance(dtype, str) and dtype != "auto": + import torch # noqa: PLC0415 + + return getattr(torch, dtype) + return dtype + + +def _load(model_id: str, revision: Optional[str], dtype: DTypeLike, device_map: Any): + transformers = require("transformers", "prompted-hf", f"Loading {model_id}") + major_minor = tuple(int(part) for part in transformers.__version__.split(".")[:2]) + dtype_key = "dtype" if major_minor >= (4, 56) else "torch_dtype" + processor = transformers.AutoProcessor.from_pretrained(model_id, revision=revision) + model = transformers.AutoModelForImageTextToText.from_pretrained( + model_id, revision=revision, device_map=device_map, **{dtype_key: _resolve_dtype(dtype)} + ) + return model, processor + + +class TransformersBackend(PromptedBackend): + """Shared loading, generation settings and decoding of the transformers backends.""" + + default_model_id = "" + default_dtype: DTypeLike = "auto" + default_max_new_tokens = 256 + + def __init__( + self, + model_id: Optional[str] = None, + *, + revision: Optional[str] = None, + dtype: Optional[DTypeLike] = None, + device_map: Any = "auto", + max_new_tokens: Optional[int] = None, + temperature: Optional[float] = TEMPERATURE, + do_sample: bool = True, + model: Any = None, + processor: Any = None, + ) -> None: + super().__init__() + self.model_id = model_id or self.default_model_id + self.revision = revision + self.dtype = self.default_dtype if dtype is None else dtype + self.device_map = device_map + self.max_new_tokens = self.default_max_new_tokens if max_new_tokens is None else int(max_new_tokens) + self.temperature = temperature + self.do_sample = bool(do_sample) + if model is None or processor is None: + model, processor = _load(self.model_id, revision, self.dtype, device_map) + self.model = model + self.processor = processor + if hasattr(self.model, "eval"): + self.model.eval() + + def generation_kwargs(self, max_new_tokens: Optional[int] = None) -> Dict[str, Any]: + kwargs: Dict[str, Any] = {"max_new_tokens": max_new_tokens or self.max_new_tokens, "do_sample": self.do_sample} + if self.do_sample and self.temperature is not None: + kwargs["temperature"] = float(self.temperature) + return kwargs + + def _to_device(self, inputs): + dtype = getattr(self.model, "dtype", None) + device = getattr(self.model, "device", None) + if dtype is not None: + return inputs.to(device, dtype=dtype) + return inputs.to(device) + + def _generate(self, inputs, max_new_tokens: Optional[int] = None) -> List[str]: + import torch # noqa: PLC0415 + + inputs = self._to_device(inputs) + with torch.inference_mode(): + output = self.model.generate(**inputs, **self.generation_kwargs(max_new_tokens)) + new_tokens = output[:, inputs["input_ids"].shape[1]:] + return list( + self.processor.batch_decode(new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False) + ) + + def _left_padding(self) -> None: + tokenizer = getattr(self.processor, "tokenizer", None) + if tokenizer is not None: + if getattr(tokenizer, "pad_token", None) is None: + tokenizer.pad_token = tokenizer.eos_token + tokenizer.padding_side = "left" + + def describe(self) -> Dict[str, Any]: + info = super().describe() + config = getattr(self.model, "config", None) + info.update( + revision=self.revision or getattr(config, "_commit_hash", None), + dtype=str(self.dtype), + generation=self.generation_kwargs(), + ) + return info + + +class Qwen25VLBackend(TransformersBackend): + """Qwen2.5-VL-Instruct (Bai et al., arXiv:2502.13923) as run by SmokeBench.""" + + name = "qwen2_5_vl" + default_model_id = "Qwen/Qwen2.5-VL-7B-Instruct" + default_max_new_tokens = 128 + + def __init__( + self, + model_id: Optional[str] = None, + *, + image_size: Optional[Tuple[int, int]] = (448, 448), + strip_fence: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(model_id, **kwargs) + self.image_size = None if image_size is None else (int(image_size[0]), int(image_size[1])) + self.strip_fence = bool(strip_fence) + + def _prepare(self, image: np.ndarray): + pil = to_pil(image) + if self.image_size is not None: + pil = pil.resize(self.image_size) + return pil + + def generate(self, image: np.ndarray, prompt: str) -> str: + return self.generate_batch([image], prompt)[0] + + def generate_batch(self, images: Sequence[np.ndarray], prompt: str) -> List[str]: + pils = [self._prepare(image) for image in images] + texts = [ + self.processor.apply_chat_template( + [{"role": "user", "content": [{"type": "image", "image": pil}, {"type": "text", "text": prompt}]}], + tokenize=False, + add_generation_prompt=True, + ) + for pil in pils + ] + if len(pils) > 1: + self._left_padding() + inputs = self.processor(text=texts, images=pils, padding=True, return_tensors="pt") + answers = self._generate(inputs) + return [strip_json_fence(text) if self.strip_fence else text for text in answers] + + def describe(self) -> Dict[str, Any]: + info = super().describe() + info.update(image_size=self.image_size, strip_json_fence=self.strip_fence) + return info + + +class InternVL3Backend(TransformersBackend): + """InternVL3 (Zhu et al., arXiv:2504.10479) through its transformers-native ``-hf`` checkpoint.""" + + name = "internvl3" + default_model_id = "OpenGVLab/InternVL3-14B-hf" + default_dtype = "float32" + default_max_new_tokens = 256 + + def generate(self, image: np.ndarray, prompt: str) -> str: + return self.generate_batch([image], prompt)[0] + + def generate_batch(self, images: Sequence[np.ndarray], prompt: str) -> List[str]: + conversations = [ + [{"role": "user", "content": [{"type": "image", "image": to_pil(image)}, {"type": "text", "text": prompt}]}] + for image in images + ] + if len(conversations) > 1: + self._left_padding() + inputs = self.processor.apply_chat_template( + conversations, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + padding=True, + ) + return self._generate(inputs) + + +class Idefics2Backend(TransformersBackend): + """Idefics2 (Laurencon et al., NeurIPS 2024) as run by SmokeBench (no image splitting).""" + + name = "idefics2" + default_model_id = "HuggingFaceM4/idefics2-8b" + default_dtype = "bfloat16" + default_max_new_tokens = 256 + batch_max_new_tokens = 16 + + def __init__(self, model_id: Optional[str] = None, **kwargs: Any) -> None: + super().__init__(model_id, **kwargs) + image_processor = getattr(self.processor, "image_processor", None) + if image_processor is not None: + image_processor.do_image_splitting = False + + def generate(self, image: np.ndarray, prompt: str) -> str: + text = prompt if "" in prompt else "\n" + prompt + inputs = self.processor(text=[text], images=[[to_pil(image)]], return_tensors="pt") + return self._generate(inputs)[0].lstrip() + + def generate_batch(self, images: Sequence[np.ndarray], prompt: str) -> List[str]: + pils = [to_pil(image) for image in images] + texts = [ + self.processor.apply_chat_template( + [{"role": "user", "content": [{"type": "image", "image": pil}, {"type": "text", "text": prompt}]}], + add_generation_prompt=True, + tokenize=False, + ) + for pil in pils + ] + self._left_padding() + inputs = self.processor( + text=texts, images=[[pil] for pil in pils], return_tensors="pt", padding=True, truncation=True + ) + return [text.strip() for text in self._generate(inputs, max_new_tokens=self.batch_max_new_tokens)] + + def describe(self) -> Dict[str, Any]: + info = super().describe() + info.update(do_image_splitting=False, batch_generation=self.generation_kwargs(self.batch_max_new_tokens)) + return info + + +__all__ = ["Idefics2Backend", "InternVL3Backend", "Qwen25VLBackend", "TransformersBackend"] diff --git a/pyhazards/prompted/cards/gemini_2_5_pro.yaml b/pyhazards/prompted/cards/gemini_2_5_pro.yaml new file mode 100644 index 00000000..6b237efe --- /dev/null +++ b/pyhazards/prompted/cards/gemini_2_5_pro.yaml @@ -0,0 +1,25 @@ +name: gemini_2_5_pro +order: 5 +display_name: Gemini 2.5 Pro +model_id: gemini-2.5-pro +access: API +install_extra: prompted-gemini +license: Proprietary (Gemini API terms); no weights +paper: + title: "Gemini 2.5: Pushing the Frontier with Advanced Reasoning, Multimodality, Long Context, and Next Generation Agentic Capabilities (Gemini Team, arXiv:2507.06261, 2025)" + url: https://arxiv.org/abs/2507.06261 +model_url: https://ai.google.dev/gemini-api/docs/models +smokebench_tasks: [classification] +smokebench_reported: + classification: + tables: Tables 1-2 + area: {Very Small: 0.441, Small: 0.608, Medium: 0.713, Large: 0.773, Very Large: 0.882, Overall: 0.683} + contrast: {Very Low: 0.588, Low: 0.629, Medium: 0.717, High: 0.696, Very High: 0.786, Overall: 0.683} +settings: + - "Classification only (\"due to cost and resource constraints\", Sec. 4.1), temperature 0.5. SmokeBench released no code for its Gemini runs and does not report smoke-free accuracy for the closed models (Table 3 lists the open models only)." +deviations: + - "Request layout chosen by PyHazards: ``google-genai`` ``generate_content`` with the image as an inline JPEG (quality 95) followed by the prompt, temperature 0.5, no output-token cap (Gemini 2.5 Pro spends output tokens on thinking). The API key is read from ``GEMINI_API_KEY`` or ``GOOGLE_API_KEY``." +notes: + - "The provider-reported model version of every answer is stored in the run records (``served_model``); the model behind ``gemini-2.5-pro`` can change, so results drift over time." + - "Google's model page (checked 2026-10-07) limits 2.5-generation access to projects that used it before; new projects may need another model id (``build_backend(\"gemini_2_5_pro\", model_id=...)``), which is then no longer the SmokeBench model." + - "Images are sent to Google; FIgLib frames are public HPWREN data." diff --git a/pyhazards/prompted/cards/gpt_4o.yaml b/pyhazards/prompted/cards/gpt_4o.yaml new file mode 100644 index 00000000..f1587f49 --- /dev/null +++ b/pyhazards/prompted/cards/gpt_4o.yaml @@ -0,0 +1,24 @@ +name: gpt_4o +order: 6 +display_name: GPT-4o +model_id: gpt-4o +access: API +install_extra: prompted-openai +license: Proprietary (OpenAI API terms); no weights +paper: + title: GPT-4o System Card (OpenAI, arXiv:2410.21276, 2024) + url: https://arxiv.org/abs/2410.21276 +model_url: https://platform.openai.com/docs/models/gpt-4o +smokebench_tasks: [classification] +smokebench_reported: + classification: + tables: Tables 1-2 + area: {Very Small: 0.529, Small: 0.727, Medium: 0.770, Large: 0.831, Very Large: 0.931, Overall: 0.758} + contrast: {Very Low: 0.739, Low: 0.703, Medium: 0.774, High: 0.792, Very High: 0.781, Overall: 0.758} +settings: + - "Classification only (Sec. 4.1), temperature 0.5. The paper does not give the GPT-4o snapshot, and the release has no code for these runs and no smoke-free accuracy for the closed models." +deviations: + - "Request layout from the only GPT-4o call in the authors' repository (an early grid script): Chat Completions with ``[text, image]`` content, the image as a base64 JPEG data URL (quality 95, OpenCV's default there) and ``max_tokens=300``; temperature 0.5 as the paper states. The API key is read from ``OPENAI_API_KEY``." +notes: + - "The snapshot behind the ``gpt-4o`` alias is recorded per answer (``served_model``); pass a dated snapshot as ``model_id`` to pin it." + - "Images are sent to OpenAI; FIgLib frames are public HPWREN data." diff --git a/pyhazards/prompted/cards/idefics2_8b.yaml b/pyhazards/prompted/cards/idefics2_8b.yaml new file mode 100644 index 00000000..58ca5d30 --- /dev/null +++ b/pyhazards/prompted/cards/idefics2_8b.yaml @@ -0,0 +1,38 @@ +name: idefics2_8b +order: 1 +display_name: Idefics2-8B +model_id: HuggingFaceM4/idefics2-8b +access: open weights +install_extra: prompted-hf +license: Apache-2.0 +paper: + title: "What matters when building vision-language models? (Laurencon et al., NeurIPS 2024, arXiv:2405.02246)" + url: https://arxiv.org/abs/2405.02246 +model_url: https://huggingface.co/HuggingFaceM4/idefics2-8b +smokebench_tasks: [classification, tile, grid, detection] +smokebench_reported: + classification: + tables: Tables 1-3 + area: {Very Small: 0.482, Small: 0.596, Medium: 0.598, Large: 0.575, Very Large: 0.709, Overall: 0.592} + contrast: {Very Low: 0.607, Low: 0.589, Medium: 0.616, High: 0.558, Very High: 0.589, Overall: 0.592} + smoke_free: 0.498 + tile: + tables: Tables 4-5 + area: {Very Small: 0.348, Small: 0.505, Medium: 0.487, Large: 0.530, Very Large: 0.507, Overall: 0.475} + contrast: {Very Low: 0.416, Low: 0.440, Medium: 0.480, High: 0.477, Very High: 0.563, Overall: 0.475} + grid: + tables: Tables 6-7 + area: {Very Small: 0.029, Small: 0.025, Medium: 0.033, Large: 0.054, Very Large: 0.067, Overall: 0.042} + contrast: {Very Low: 0.036, Low: 0.042, Medium: 0.040, High: 0.048, Very High: 0.043, Overall: 0.042} + detection: + tables: Table 8 + overall: 0.000 +settings: + - "bfloat16 weights, ``do_image_splitting=False``." + - "Classification, grid and detection: the raw text ``\"\\n\" + prompt`` without the chat template through the ``image-text-to-text`` pipeline (256 new tokens, the checkpoint's greedy generation config)." + - "Tiles: the 12 tiles of an image as one left-padded batch through the chat template, greedy, 16 new tokens." +deviations: + - "Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the greedy decoding of the released script." +notes: + - "``build_backend`` loads Hugging Face revision ``2c42686c57fe21cf0348c9ce1077d094b72e7698`` (2026-10-07) unless ``revision=`` is given (the base checkpoint, not the instruction-tuned ``idefics2-8b-chatty``; the paper says only \"Idefics2\" and the script loads ``idefics2-8b``)." + - "SmokeBench notes that Idefics2 answers close to chance on smoke-free images (0.498), which inflates its accuracy on smoke images." diff --git a/pyhazards/prompted/cards/internvl3_14b.yaml b/pyhazards/prompted/cards/internvl3_14b.yaml new file mode 100644 index 00000000..ce0b8896 --- /dev/null +++ b/pyhazards/prompted/cards/internvl3_14b.yaml @@ -0,0 +1,35 @@ +name: internvl3_14b +order: 4 +display_name: InternVL3-14B +model_id: OpenGVLab/InternVL3-14B-hf +access: open weights +install_extra: prompted-hf +license: "MIT per the model card text; the Hugging Face metadata says 'other' and links the Qwen licence (Qwen2.5 component)" +paper: + title: "InternVL3: Exploring Advanced Training and Test-Time Recipes for Open-Source Multimodal Models (Zhu et al., arXiv:2504.10479, 2025)" + url: https://arxiv.org/abs/2504.10479 + repo_url: https://github.com/OpenGVLab/InternVL +model_url: https://huggingface.co/OpenGVLab/InternVL3-14B-hf +smokebench_tasks: [classification, grid, detection] +smokebench_reported: + classification: + tables: Tables 1-3 + area: {Very Small: 0.090, Small: 0.262, Medium: 0.376, Large: 0.432, Very Large: 0.636, Overall: 0.359} + contrast: {Very Low: 0.269, Low: 0.304, Medium: 0.368, High: 0.401, Very High: 0.453, Overall: 0.359} + smoke_free: 0.985 + grid: + tables: Tables 6-7 + area: {Very Small: 0.001, Small: 0.017, Medium: 0.057, Large: 0.095, Very Large: 0.114, Overall: 0.057} + contrast: {Very Low: 0.042, Low: 0.041, Medium: 0.055, High: 0.062, Very High: 0.084, Overall: 0.057} + detection: + tables: Table 8 + overall: 0.000 +settings: + - "The authors run the transformers-native checkpoint ``OpenGVLab/InternVL3-14B-hf`` through the ``image-text-to-text`` pipeline with float32 weights (``device_map=\"balanced\"``): chat template with the image before the text, the processor's dynamic 448-pixel tiling at native resolution, 256 new tokens (the pipeline default) and the checkpoint's greedy generation config." + - "The tile task was not run with InternVL3 (the paper's Tables 4-5 have no InternVL3 row; the script has no batch path for it)." +deviations: + - "Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the greedy decoding of the released script." + - "``device_map=\"auto\"`` by default (pass ``device_map=\"balanced\"`` to match the authors' sharding; it does not change outputs)." +notes: + - "``build_backend`` loads Hugging Face revision ``e22931943e5336f85e06f4e2b38f3e5e6ee4de3b`` (2026-10-07) unless ``revision=`` is given. About 30 GB in bfloat16; the authors' float32 load needs about 60 GB." + - "SmokeBench groups InternVL3 with the grounding-trained models; prompted with the SmokeBench detection prompt it still scores 0.000." diff --git a/pyhazards/prompted/cards/qwen2_5_vl_32b.yaml b/pyhazards/prompted/cards/qwen2_5_vl_32b.yaml new file mode 100644 index 00000000..f9eeda3c --- /dev/null +++ b/pyhazards/prompted/cards/qwen2_5_vl_32b.yaml @@ -0,0 +1,37 @@ +name: qwen2_5_vl_32b +order: 3 +display_name: Qwen2.5-VL-32B-Instruct +model_id: Qwen/Qwen2.5-VL-32B-Instruct +access: open weights +install_extra: prompted-hf +license: Apache-2.0 +paper: + title: Qwen2.5-VL Technical Report (Bai et al., arXiv:2502.13923, 2025) + url: https://arxiv.org/abs/2502.13923 + repo_url: https://github.com/QwenLM/Qwen2.5-VL +model_url: https://huggingface.co/Qwen/Qwen2.5-VL-32B-Instruct +smokebench_tasks: [classification, tile, grid, detection] +smokebench_reported: + classification: + tables: Tables 1-3 + area: {Very Small: 0.041, Small: 0.103, Medium: 0.222, Large: 0.284, Very Large: 0.569, Overall: 0.244} + contrast: {Very Low: 0.204, Low: 0.224, Medium: 0.251, High: 0.249, Very High: 0.291, Overall: 0.244} + smoke_free: 0.983 + tile: + tables: Tables 4-5 + area: {Very Small: 0.348, Small: 0.466, Medium: 0.422, Large: 0.456, Very Large: 0.483, Overall: 0.435} + contrast: {Very Low: 0.380, Low: 0.420, Medium: 0.450, High: 0.440, Very High: 0.485, Overall: 0.435} + grid: + tables: Tables 6-7 + area: {Very Small: 0.057, Small: 0.155, Medium: 0.242, Large: 0.226, Very Large: 0.239, Overall: 0.184} + contrast: {Very Low: 0.155, Low: 0.157, Medium: 0.189, High: 0.202, Very High: 0.215, Overall: 0.184} + detection: + tables: Table 8 + overall: 0.000 +settings: + - "Same code path as the 7B model (``QwenVL`` in the authors' script, switched to the 32B checkpoint): 448 x 448 input, chat template, 128 new tokens, ``json`` fence stripped, ``torch_dtype=\"auto\"``, ``device_map=\"auto\"``, checkpoint generation config (temperature 1e-6)." +deviations: + - "Samples at temperature 0.5 as the paper states; ``do_sample=False`` reproduces the effectively greedy decoding of the released script." + - "Detection boxes are scored in the pixel frame of the original image (as the authors do) although the model answers in its 448 x 448 input frame." +notes: + - "``build_backend`` loads Hugging Face revision ``7cfb30d71a1f4f49a57592323337a4a4727301da`` (2026-10-07) unless ``revision=`` is given. The weights are about 68 GB in bfloat16." diff --git a/pyhazards/prompted/cards/qwen2_5_vl_7b.yaml b/pyhazards/prompted/cards/qwen2_5_vl_7b.yaml new file mode 100644 index 00000000..4e1aa7bb --- /dev/null +++ b/pyhazards/prompted/cards/qwen2_5_vl_7b.yaml @@ -0,0 +1,42 @@ +name: qwen2_5_vl_7b +order: 2 +display_name: Qwen2.5-VL-7B-Instruct +model_id: Qwen/Qwen2.5-VL-7B-Instruct +access: open weights +install_extra: prompted-hf +license: Apache-2.0 +paper: + title: Qwen2.5-VL Technical Report (Bai et al., arXiv:2502.13923, 2025) + url: https://arxiv.org/abs/2502.13923 + repo_url: https://github.com/QwenLM/Qwen2.5-VL +model_url: https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct +smokebench_tasks: [classification, tile, grid, detection] +smokebench_reported: + classification: + tables: Tables 1-3 + area: {Very Small: 0.098, Small: 0.232, Medium: 0.423, Large: 0.463, Very Large: 0.686, Overall: 0.380} + contrast: {Very Low: 0.289, Low: 0.327, Medium: 0.395, High: 0.417, Very High: 0.473, Overall: 0.380} + smoke_free: 0.982 + tile: + tables: Tables 4-5 + area: {Very Small: 0.311, Small: 0.479, Medium: 0.485, Large: 0.485, Very Large: 0.520, Overall: 0.456} + contrast: {Very Low: 0.376, Low: 0.458, Medium: 0.482, High: 0.478, Very High: 0.485, Overall: 0.456} + grid: + tables: Tables 6-7 + area: {Very Small: 0.000, Small: 0.000, Medium: 0.000, Large: 0.000, Very Large: 0.000, Overall: 0.000} + contrast: {Very Low: 0.000, Low: 0.000, Medium: 0.000, High: 0.000, Very High: 0.000, Overall: 0.000} + detection: + tables: Table 8 + overall: 0.000 +settings: + - "Every image (whole frame, grid overlay or tile) is resized to 448 x 448 with ``PIL.Image.resize`` before the processor, as in the authors' ``QwenVL.predict``; the paper does not mention it. ``image_size=None`` keeps the native resolution." + - "Chat template with the image before the text; up to 128 new tokens; a Markdown ``json`` fence is stripped from the answer." + - "The authors' script loads the weights with ``torch_dtype=\"auto\"`` (bfloat16) and ``device_map=\"auto\"`` and never sets a temperature, so its runs used the checkpoint's generation config (``do_sample=True``, temperature 1e-6, repetition penalty 1.05: effectively greedy)." +deviations: + - "Samples at temperature 0.5 as the paper states (other sampling parameters from the checkpoint's generation config); ``do_sample=False`` reproduces the effectively greedy decoding of the released script." + - "The 12 tiles of an image are generated as one left-padded batch (the authors also batch them; their padding side is the processor default)." + - "Detection boxes are scored in the pixel frame of the original image, as in the authors' script, although the model answers in the frame of its 448 x 448 input, so a box placed correctly on that input generally misses the ground-truth box of the 2048 x 1536 or 3072 x 2048 frame (Table 8: 0.000)." +notes: + - "PyHazards run (2026-10-07; this revision, transformers 5.19, one RTX 6000 Ada, temperature 0.5, seed 0, ``protocol=\"paper\"``, 22 min): accuracy on the 5,046 smoke images 0.375 (paper 0.380); by smoke area 0.088 / 0.249 / 0.408 / 0.463 / 0.666 (paper 0.098 / 0.232 / 0.423 / 0.463 / 0.686); by contrast 0.294 / 0.329 / 0.392 / 0.412 / 0.446 (paper 0.289 / 0.327 / 0.395 / 0.417 / 0.473); 0.975 on 1,000 seeded smoke-free frames (paper 0.982 on its unreleased sample). On a stratified subset (120 smoke images per area bin + 200 smoke-free) greedy decoding gave 0.382 / 0.985 against 0.363 / 0.975 at temperature 0.5. In the full run every answer was exactly ``True`` or ``False``." + - "``build_backend`` loads Hugging Face revision ``cc594898137f460bfe9f0759e9844b3ce807cfb5`` (2026-10-07) unless ``revision=`` is given. The SmokeBench runs did not pin a revision." + - "Section 5.2 of the paper says Qwen2.5-VL-7B underperforms the 32B model on tiles, but Table 4 gives 0.456 (7B) against 0.435 (32B); the numbers above are the tables'." diff --git a/pyhazards/prompted/catalog.py b/pyhazards/prompted/catalog.py new file mode 100644 index 00000000..2b9ee85e --- /dev/null +++ b/pyhazards/prompted/catalog.py @@ -0,0 +1,373 @@ +"""Cards of the prompted baselines and the generated ``docs/source/pyhazards_prompted.rst`` page. + +Prompted multimodal LLMs are not ``nn.Module`` models with a builder, parameter counts or oracle-tested +weights, so they are not in the model catalog (``pyhazards/model_cards``). Each SmokeBench model has a +card in ``pyhazards/prompted/cards/.yaml`` with its citation, licence, the settings of the +authors' runs, the numbers SmokeBench reports and PyHazards' deviations; this module validates the +cards and renders them into one documentation page (``scripts/render_prompted_docs.py``). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Dict, List, Literal, Optional, Sequence + +import yaml +from pydantic import BaseModel, Field, model_validator + +from .metrics import AREA_BIN_LABELS, CONTRAST_BIN_LABELS +from .prompts import PROMPTS, TASKS + +REPO_ROOT = Path(__file__).resolve().parent.parent.parent +CARDS_DIR = Path(__file__).resolve().parent / "cards" +DOCS_PAGE_PATH = REPO_ROOT / "docs" / "source" / "pyhazards_prompted.rst" +GENERATED_MARKER = ".. This file is generated by scripts/render_prompted_docs.py. Do not edit by hand." + +SMOKEBENCH_TITLE = "SmokeBench: Evaluating Multimodal Large Language Models for Wildfire Smoke Detection" +SMOKEBENCH_URL = "https://arxiv.org/abs/2512.11215" +SMOKEBENCH_CODE_URL = "https://github.com/SoraLink/MLLM" +SMOKEBENCH_CODE_COMMIT = "183cdca488e8c7afa5a254f86ac675cb98951c73" + +_BIN_KEYS = {"area": list(AREA_BIN_LABELS) + ["Overall"], "contrast": list(CONTRAST_BIN_LABELS) + ["Overall"]} + + +class Citation(BaseModel): + title: str + url: str + repo_url: Optional[str] = None + + +class TaskNumbers(BaseModel): + """Numbers of one task as printed in the SmokeBench tables.""" + + area: Optional[Dict[str, float]] = None + contrast: Optional[Dict[str, float]] = None + smoke_free: Optional[float] = None + overall: Optional[float] = None + tables: str + + @model_validator(mode="after") + def check_bins(self) -> "TaskNumbers": + for kind in ("area", "contrast"): + values = getattr(self, kind) + if values is not None and list(values) != _BIN_KEYS[kind]: + raise ValueError(f"{kind} numbers must list {_BIN_KEYS[kind]} in order, got {list(values)}") + return self + + +class SmokeBenchNumbers(BaseModel): + classification: Optional[TaskNumbers] = None + tile: Optional[TaskNumbers] = None + grid: Optional[TaskNumbers] = None + detection: Optional[TaskNumbers] = None + + +class PromptedCard(BaseModel): + name: str + order: int + display_name: str + model_id: str + access: Literal["open weights", "API"] + install_extra: str + license: str + paper: Citation + model_url: str + smokebench_tasks: List[str] + smokebench_reported: SmokeBenchNumbers + settings: List[str] = Field(default_factory=list) + deviations: List[str] = Field(default_factory=list) + notes: List[str] = Field(default_factory=list) + + @model_validator(mode="after") + def check_tasks(self) -> "PromptedCard": + unknown = [task for task in self.smokebench_tasks if task not in TASKS] + if unknown: + raise ValueError(f"unknown SmokeBench tasks {unknown}") + for task in self.smokebench_tasks: + if getattr(self.smokebench_reported, task) is None: + raise ValueError(f"card {self.name} lists task {task} without reported numbers") + return self + + +def load_prompted_cards(cards_dir: Path = CARDS_DIR) -> List[PromptedCard]: + cards: List[PromptedCard] = [] + for path in sorted(cards_dir.glob("*.yaml")): + card = PromptedCard.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")) or {}) + if card.name != path.stem: + raise ValueError(f"card file name must match its name: {path.name} vs {card.name}") + cards.append(card) + return sorted(cards, key=lambda card: (card.order, card.name)) + + +def _fmt(value: Optional[float]) -> str: + return "--" if value is None else f"{value:.3f}" + + +def _table(title: str, header: Sequence[str], rows: Sequence[Sequence[str]]) -> List[str]: + lines = [f".. list-table:: {title}", " :header-rows: 1", ""] + for row in [list(header)] + [list(r) for r in rows]: + lines.append(f" * - {row[0]}") + lines.extend(f" - {cell}" for cell in row[1:]) + return lines + [""] + + +_TASK_TITLES = { + "classification": "Smoke classification", + "tile": "Tile-based localization", + "grid": "Grid-based localization", + "detection": "Smoke detection", +} + +_PROTOCOL_LINES = [ + "Protocol", + "--------", + "", + f"PyHazards implements the four tasks of `{SMOKEBENCH_TITLE} <{SMOKEBENCH_URL}>`_ (Qi, Li & Barnes,", + "WACV 2026) on the SmokeBench images, :doc:`FIgLib frames with the SmokeyNet smoke boxes `", + "(5,046 smoke images and 1,000 smoke-free images). A model sees one image (or one tile) and one", + "prompt and answers in text; decoding temperature 0.5. The prompts are the paper's, verbatim:", + "", +] + +_SCORING_LINES = [ + "Metrics and scoring", + "~~~~~~~~~~~~~~~~~~~", + "", + "- **Classification** -- accuracy, reported separately on the smoke images (paper Tables 1-2, per", + " smoke-area and Weber-contrast quintile) and on the smoke-free images (Table 3). An answer counts", + " as \"smoke\" iff it contains ``True``; every other answer, including unparseable ones, counts as", + " \"no smoke\" (the authors' script; the paper does not say).", + "- **Tile** -- the 3 x 4 tiles are classified independently with the classification prompt (a tile is", + " positive iff its answer contains ``True`` or ``true``); per-image IoU of the predicted and", + " ground-truth tile sets, averaged over smoke images (mIoU, Tables 4-5).", + "- **Grid** -- the image carries a numbered 5 x 5 grid; every integer in the answer is a predicted", + " cell (an answer without numbers predicts nothing, IoU 0); mIoU of the cell sets (Tables 6-7).", + "- **Detection** -- the first ``[[...]]`` span is read as JSON boxes; anything unparseable is the box", + " ``[0, 0, 0, 0]``. Per image, the largest IoU between a predicted and a ground-truth box (pixel", + " coordinates of the original frame), averaged over smoke images (Table 8).", + "- A tile or cell is ground-truth positive when it contains a pixel of a box (both box ends inclusive).", + "- Smoke area is the area of the (single) box; Weber contrast is ``|I_box - I_frame| / I_frame`` on the", + " OpenCV grey image with a 20-pixel frame around the box. Reports bin results at the quintiles of", + " the 5,046 boxes: area ``(42, 4356], (4356, 11232], (11232, 28565], (28565, 83157], (83157, 2232020]``", + " and contrast ``(0, 0.0246], (0.0246, 0.0549], (0.0549, 0.0878], (0.0878, 0.13], (0.13, 0.728]``", + " (Q1 = Very Small / Very Low ... Q5 = Very Large / Very High). PyHazards' area and contrast values", + " for the 5,046 SmokeBench images give exactly these quintiles (contrast to the 3 printed digits).", + "", + "The paper defines the tasks, prompts, temperature, partitions and metrics. Where it is silent", + "(answer parsing, cell geometry, contrast background, per-model input handling) PyHazards follows", + f"the authors' evaluation script (`SoraLink/MLLM <{SMOKEBENCH_CODE_URL}>`_ at ``{SMOKEBENCH_CODE_COMMIT[:7]}``;", + "no licence, so it is used only as a test oracle and nothing is copied). The oracle test", + "``tests/oracle/test_smokebench_oracle.py`` runs that script's own functions against PyHazards'.", + "", +] + +_DEVIATION_LINES = [ + "Differences from the paper and the authors' script", + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", + "", + "- **Prompts.** The released script words the prompts slightly differently from the paper: the", + " classification prompt ends \"Do MUST not return any other words\"; the grid and detection prompts say", + " \"If you cannot find any smoke return empty list []\"; the detection prompt asks for \"bounding box", + " in the format[[x1, y1, x2, y2], ...]\" and ends \"without other wordsDo not return dict!\" (string", + " pieces joined without spaces). PyHazards sends the paper's text.", + "- **Temperature.** The paper fixes it at 0.5; the released script never sets it, so the authors' runs", + " used each checkpoint's generation config (greedy for Idefics2 and InternVL3, temperature 1e-6 for", + " Qwen2.5-VL). PyHazards samples at 0.5; ``do_sample=False`` gives greedy decoding.", + "- **Tile crops.** The script crops ``image[i*hb:(i+1)*wb, j*wb:(j+1)*hb]`` (height and width blocks", + " swapped), so on the 3072 x 2048 frames (1,994 of 5,046) tiles overlap or leave gaps, while the", + " paper describes non-overlapping tiles. ``protocol=\"paper\"`` (default) crops the paper's tiles;", + " ``protocol=\"reference_code\"`` reproduces the script.", + "- **Edge cells.** The script maps a box reaching the last ``H % rows`` / ``W % cols`` pixels to a", + " non-existent row/column, i.e. to a wrong cell id (72 grid and 19 tile cases among the 5,046 boxes).", + " ``protocol=\"paper\"`` clamps to the last row/column; ``protocol=\"reference_code\"`` keeps the script's ids.", + "- **Malformed boxes.** The script scores boxes with fewer than four numbers 0 and crashes on other", + " malformed values; PyHazards scores every malformed prediction (and a zero-union NaN IoU) 0 and", + " counts them in the report.", + "- **Smoke-free images.** The authors' 1,000 smoke-free frames were drawn without a seed from all", + " FIgLib sequences and not released; PyHazards draws a seeded sample from the pre-ignition frames of", + " the 145 annotated sequences, so smoke-free accuracy is not the same sample as Table 3.", + "- **Closed models.** No code was released for GPT-4o and Gemini-2.5 Pro (classification only);", + " the request layout is documented on their cards below.", + "", +] + + +def render_prompted_page(cards: Sequence[PromptedCard]) -> str: + lines: List[str] = [ + GENERATED_MARKER, + "", + "Prompted VLM Baselines", + "======================", + "", + "Zero-shot multimodal large language models used as wildfire-smoke detectors by prompting them", + "with an image and a question. They are not trainable ``nn.Module`` models and are therefore not", + "part of the :doc:`model catalog `; ``pyhazards.prompted`` provides the", + "SmokeBench protocol (prompts, image partitions, answer parsing, metrics, a resumable runner) and", + "backends for the models SmokeBench evaluated: open-weight checkpoints through Hugging Face", + "``transformers`` and closed models through their official Python clients.", + "", + "Install the optional dependencies of the backend you use (nothing is added to the core install):", + "", + ".. code-block:: bash", + "", + " pip install \"pyhazards[prompted]\" # Pillow + OpenCV: data, grid overlay, metrics", + " pip install \"pyhazards[prompted-hf]\" # + transformers, accelerate, torchvision (Qwen2.5-VL, InternVL3, Idefics2)", + " pip install \"pyhazards[prompted-gemini]\" # + google-genai (reads GEMINI_API_KEY)", + " pip install \"pyhazards[prompted-openai]\" # + openai (reads OPENAI_API_KEY)", + "", + ] + lines.extend(_PROTOCOL_LINES) + for task in TASKS: + title = _TASK_TITLES[task] + if task == "tile": + lines.extend([f"**{title}** -- the classification prompt on each tile of a 3 x 4 grid.", ""]) + continue + suffix = " (on the image with the numbered 5 x 5 grid drawn on it)" if task == "grid" else "" + lines.extend([f"**{title}**{suffix}:", "", ".. code-block:: text", "", f" {PROMPTS[task]}", ""]) + lines.extend(_SCORING_LINES) + lines.extend(_DEVIATION_LINES) + lines.extend( + [ + "Usage", + "-----", + "", + ".. code-block:: python", + "", + " from pyhazards.datasets.figlib_smokebench import FIgLibSmokeBench, download_smokebench", + " from pyhazards.prompted import build_backend, evaluate_smokebench", + "", + " download_smokebench(\"data/figlib\") # SmokeyNet boxes + 145 FIgLib sequences (~11.4 GB)", + " data = FIgLibSmokeBench(\"data/figlib\") # 5,046 smoke + 1,000 sampled smoke-free frames", + " backend = build_backend(\"qwen2_5_vl_7b\") # temperature 0.5, 448 x 448 input as in SmokeBench", + " report = evaluate_smokebench(backend, data, \"classification\", output_dir=\"runs/qwen7b_cls\")", + " print(report[\"metrics\"][\"accuracy_smoke\"], report[\"paper_reported\"])", + "", + "or from the command line:", + "", + ".. code-block:: bash", + "", + " python -m pyhazards.prompted --backend qwen2_5_vl_7b --task classification \\", + " --root data/figlib --output runs/qwen7b_cls", + "", + "Any object with ``generate(image, prompt) -> str`` (a subclass of", + "``pyhazards.prompted.PromptedBackend``) can be evaluated the same way.", + "", + "Models", + "------", + "", + ] + ) + lines.extend( + _table( + "SmokeBench models available as backends", + ["Backend", "Model", "Access", "Licence", "Extra", "SmokeBench tasks"], + [ + [ + f"``{card.name}``", + f"`{card.display_name} <{card.model_url}>`__", + card.access, + card.license, + f"``{card.install_extra}``", + ", ".join(card.smokebench_tasks), + ] + for card in cards + ], + ) + ) + lines.extend( + [ + "Unified-IO 2 and Grounding DINO (detection only in SmokeBench) are not included: they are a", + "referring-expression model and an open-set detector driven without the SmokeBench prompts. Llama 4", + "is not part of SmokeBench and has no published wildfire-smoke protocol here, so it is not included.", + "", + ] + ) + for card in cards: + lines.extend(_render_card(card)) + lines.extend( + [ + "References", + "----------", + "", + f"- Qi, T., Li, W., Barnes, N. `{SMOKEBENCH_TITLE} <{SMOKEBENCH_URL}>`_. WACV 2026.", + "- Dewangan, A. et al. `FIgLib & SmokeyNet: Dataset and Deep Learning Model for Real-Time Wildland", + " Fire Smoke Detection `_. Remote Sensing 14(4):1007, 2022.", + "- HPWREN Fire Ignition images Library (FIgLib), https://www.hpwren.ucsd.edu/FIgLib/ (credit", + " https://www.hpwren.ucsd.edu/ in derivative work).", + "", + ] + ) + return "\n".join(lines).rstrip() + "\n" + + +def _render_card(card: PromptedCard) -> List[str]: + title = card.display_name + lines = [title, "~" * len(title), ""] + paper = f"`{card.paper.title} <{card.paper.url}>`_" + if card.paper.repo_url: + paper += f" (`code <{card.paper.repo_url}>`__)" + lines.extend( + [ + f"**Model paper:** {paper}.", + "", + f"**Backend:** ``build_backend(\"{card.name}\")`` -- ``{card.model_id}`` ({card.access}; licence: {card.license}).", + "", + ] + ) + reported = card.smokebench_reported + for task in TASKS: + numbers = getattr(reported, task) + if numbers is None: + continue + caption = f"SmokeBench {_TASK_TITLES[task].lower()} ({numbers.tables})" + rows: List[List[str]] = [] + if numbers.area is not None: + rows.append(["smoke area"] + [_fmt(numbers.area[key]) for key in _BIN_KEYS["area"]]) + if numbers.contrast is not None: + rows.append(["Weber contrast"] + [_fmt(numbers.contrast[key]) for key in _BIN_KEYS["contrast"]]) + if rows: + metric = "accuracy" if task == "classification" else "mIoU" + header = [f"{metric} by quintile", "Q1 (lowest)", "Q2", "Q3", "Q4", "Q5 (highest)", "Overall"] + lines.extend(_table(caption, header, rows)) + extra = [] + if numbers.smoke_free is not None: + extra.append(f"accuracy on smoke-free images {_fmt(numbers.smoke_free)}") + if numbers.overall is not None and not rows: + extra.append(f"mIoU {_fmt(numbers.overall)}") + if extra: + lines.extend([f"{caption}: " + "; ".join(extra) + ".", ""]) + for heading, items in (("Settings of the SmokeBench runs", card.settings), ("Deviations", card.deviations), ("Notes", card.notes)): + if items: + lines.extend([f"**{heading}:**", ""]) + lines.extend(f"- {item}" for item in items) + lines.append("") + return lines + + +def rendered_prompted_docs(cards: Optional[Sequence[PromptedCard]] = None) -> Dict[Path, str]: + cards = load_prompted_cards() if cards is None else cards + return {DOCS_PAGE_PATH: render_prompted_page(cards)} + + +def sync_prompted_docs(check: bool = False) -> List[Path]: + """Write the generated page (or, with ``check``, list the files that are out of date).""" + changed: List[Path] = [] + for path, text in rendered_prompted_docs().items(): + current = path.read_text(encoding="utf-8") if path.exists() else None + if current != text: + changed.append(path) + if not check: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return changed + + +__all__ = [ + "CARDS_DIR", + "DOCS_PAGE_PATH", + "PromptedCard", + "load_prompted_cards", + "render_prompted_page", + "rendered_prompted_docs", + "sync_prompted_docs", +] diff --git a/pyhazards/prompted/geometry.py b/pyhazards/prompted/geometry.py new file mode 100644 index 00000000..0e9353c2 --- /dev/null +++ b/pyhazards/prompted/geometry.py @@ -0,0 +1,169 @@ +"""Image partitions of SmokeBench: 3 x 4 tiles, the numbered 5 x 5 grid, and box-to-cell labels. + +SmokeBench (Qi, Li & Barnes, WACV 2026) defines the partitions in Sec. 3.2/4.3 and Figs. 2-5: +the tile task crops the image into a fixed 3 x 4 set of non-overlapping tiles; the grid task draws a +fixed 5 x 5 grid of numbered cells (left to right, top to bottom) on the whole image; a tile or cell +is ground-truth positive when it overlaps an annotated smoke box. + +What the paper leaves open is taken from the authors' evaluation script (github.com/SoraLink/MLLM, +commit 183cdca488e8c7afa5a254f86ac675cb98951c73, no licence; used only as a test oracle, nothing is +copied): cells are ``H // rows`` by ``W // cols`` pixels (remainder rows/columns at the bottom/right +belong to no tile), a box ``[x1, y1, x2, y2]`` covers the cells containing the pixel indices +``x1..x2`` and ``y1..y2`` (both ends inclusive), and the grid overlay is drawn with OpenCV: a white +1-pixel cell outline and the cell number in red ``FONT_HERSHEY_SIMPLEX`` (scale 1, thickness 2), +placed at ``(cx - text_width // 2, cy - text_height // 2)``. + +Two behaviours of that script contradict the paper and are reproduced only with +``protocol="reference_code"``: + +* tile crops use ``image[i*hb:(i+1)*wb, j*wb:(j+1)*hb]`` (the block height and width are swapped in + the end coordinates), so tiles overlap or leave gaps whenever ``H // 3 != W // 4`` -- e.g. on the + 3072 x 2048 FIgLib frames (1,994 of the 5,046 smoke images); on the 2048 x 1536, 2560 x 1920 and + 1600 x 1200 frames both protocols agree; +* a box reaching the last ``H % rows`` / ``W % cols`` pixels (e.g. ``x2 == W``) is mapped to row or + column index ``rows`` / ``cols``, i.e. to a wrong cell id (the first cell of the next row, or an id + above ``rows * cols``); this concerns 72 of the 5,046 smoke boxes for the grid and 19 for the tiles. + ``protocol="paper"`` clamps those indices to the last row/column. +""" + +from __future__ import annotations + +from typing import List, Sequence, Tuple + +import numpy as np + +from .prompts import GRID_LAYOUT, TILE_LAYOUT + +PROTOCOLS: Tuple[str, ...] = ("paper", "reference_code") + +Box = Sequence[float] +Rect = Tuple[int, int, int, int] + + +def _check_protocol(protocol: str) -> None: + if protocol not in PROTOCOLS: + raise ValueError(f"unknown protocol {protocol!r}; expected one of {PROTOCOLS}") + + +def _check_layout(height: int, width: int, layout: Tuple[int, int]) -> Tuple[int, int]: + rows, cols = (int(v) for v in layout) + if rows < 1 or cols < 1: + raise ValueError(f"layout must be (rows, cols) with positive entries, got {layout}") + if height < rows or width < cols: + raise ValueError( + f"image of shape (H={height}, W={width}) is too small for a {rows} x {cols} partition" + ) + return rows, cols + + +def _check_image(image: np.ndarray) -> np.ndarray: + array = np.asarray(image) + if array.ndim != 3 or array.shape[2] != 3: + raise ValueError(f"expected an RGB image array of shape (H, W, 3), got shape {array.shape}") + return array + + +def tile_rects(height: int, width: int, layout: Tuple[int, int] = TILE_LAYOUT, *, protocol: str = "paper") -> List[Rect]: + """Pixel slices ``(x1, y1, x2, y2)`` of the tiles, row-major (tile id = index + 1). + + The slice ``image[y1:y2, x1:x2]`` is the tile; with ``protocol="reference_code"`` the + coordinates may exceed the image and are clipped by the slicing, as in the authors' script. + """ + _check_protocol(protocol) + rows, cols = _check_layout(height, width, layout) + hb, wb = height // rows, width // cols + rects: List[Rect] = [] + for i in range(rows): + for j in range(cols): + if protocol == "paper": + rects.append((j * wb, i * hb, (j + 1) * wb, (i + 1) * hb)) + else: + rects.append((j * wb, i * hb, (j + 1) * hb, (i + 1) * wb)) + return rects + + +def crop_tiles(image: np.ndarray, layout: Tuple[int, int] = TILE_LAYOUT, *, protocol: str = "paper") -> List[np.ndarray]: + """Crop an ``(H, W, 3)`` image into its tiles (row-major, contiguous copies).""" + array = _check_image(image) + height, width = array.shape[:2] + return [ + np.ascontiguousarray(array[y1:y2, x1:x2]) + for x1, y1, x2, y2 in tile_rects(height, width, layout, protocol=protocol) + ] + + +def covered_cells( + boxes: Sequence[Box], + height: int, + width: int, + layout: Tuple[int, int], + *, + protocol: str = "paper", +) -> List[int]: + """1-based ids (row-major) of the cells that the boxes ``[x1, y1, x2, y2]`` overlap. + + Box coordinates are pixel indices, both ends inclusive (the FIgLib/SmokeyNet boxes are the + rounded extremes of the annotated polygon). Returns the sorted unique ids. + """ + _check_protocol(protocol) + rows, cols = _check_layout(height, width, layout) + cell_h, cell_w = height // rows, width // cols + ids = set() + for box in boxes: + if len(box) != 4: + raise ValueError(f"boxes must be [x1, y1, x2, y2], got {list(box)}") + x1, y1, x2, y2 = box + r0, r1 = int(y1 // cell_h), int(y2 // cell_h) + c0, c1 = int(x1 // cell_w), int(x2 // cell_w) + if protocol == "paper": + r0, r1 = min(max(r0, 0), rows - 1), min(max(r1, 0), rows - 1) + c0, c1 = min(max(c0, 0), cols - 1), min(max(c1, 0), cols - 1) + for i in range(r0, r1 + 1): + for j in range(c0, c1 + 1): + ids.add(i * cols + j + 1) + return sorted(ids) + + +def require_cv2(): + try: + import cv2 # noqa: PLC0415 + except ImportError as exc: # pragma: no cover - depends on the environment + raise ImportError( + "The SmokeBench grid overlay is drawn with OpenCV, as in the authors' script. " + "Install it with `pip install pyhazards[prompted]` (opencv-python-headless)." + ) from exc + return cv2 + + +def draw_grid_overlay(image: np.ndarray, layout: Tuple[int, int] = GRID_LAYOUT) -> np.ndarray: + """Return a copy of an RGB ``(H, W, 3)`` uint8 image with the numbered SmokeBench grid drawn on it.""" + array = _check_image(image) + if array.dtype != np.uint8: + raise ValueError(f"expected a uint8 image, got dtype {array.dtype}") + cv2 = require_cv2() + height, width = array.shape[:2] + rows, cols = _check_layout(height, width, layout) + cell_h, cell_w = height // rows, width // cols + canvas = np.ascontiguousarray(array[:, :, ::-1]) # draw in OpenCV's BGR order + font = cv2.FONT_HERSHEY_SIMPLEX + cell_id = 1 + for i in range(rows): + for j in range(cols): + left, top = j * cell_w, i * cell_h + cv2.rectangle(canvas, (left, top), (left + cell_w, top + cell_h), (255, 255, 255), 1) + label = str(cell_id) + (text_w, text_h), _ = cv2.getTextSize(label, font, 1, 2) + origin = (left + cell_w // 2 - text_w // 2, top + cell_h // 2 - text_h // 2) + cv2.putText(canvas, label, origin, font, 1, (0, 0, 255), 2) + cell_id += 1 + return np.ascontiguousarray(canvas[:, :, ::-1]) + + +__all__ = [ + "PROTOCOLS", + "covered_cells", + "crop_tiles", + "draw_grid_overlay", + "require_cv2", + "tile_rects", +] diff --git a/pyhazards/prompted/metrics.py b/pyhazards/prompted/metrics.py new file mode 100644 index 00000000..6af1b03c --- /dev/null +++ b/pyhazards/prompted/metrics.py @@ -0,0 +1,233 @@ +"""SmokeBench metrics: accuracy, mean IoU, and the smoke-area / Weber-contrast bins. + +Paper (Qi, Li & Barnes, WACV 2026, Sec. 4.2 and 4.4): + +* accuracy = mean of ``1[pred == label]`` with ``True -> 1`` and ``False -> 0``. Table 1 reports it + on the smoke images only (per area bin and overall), Table 3 on the 1,000 smoke-free images; +* mIoU = mean over images of ``|P n G| / |P u G|``. For the tile and grid tasks ``P`` and ``G`` are + sets of tile / cell ids (:func:`set_iou`). For detection the authors' script scores an image by the + largest pairwise IoU between a predicted and a ground-truth box (:func:`detection_iou`); +* smoke area = pixel area of the ground-truth box, binned at the quintiles of the 5,046 FIgLib + boxes: ``(42, 4356], (4356, 11232], (11232, 28565], (28565, 83157], (83157, 2232020]``. These edges + are exactly the quintiles of the SmokeyNet boxes (checked in tests/oracle/test_smokebench_oracle.py); +* Weber contrast ``|I_smoke - I_background| / I_background``, binned at its quintiles over the same + boxes. The paper prints them to 3 significant digits, ``(0, 0.0246], (0.0246, 0.0549], + (0.0549, 0.0878], (0.0878, 0.13], (0.13, 0.728]``; :data:`CONTRAST_BIN_EDGES` holds the full-precision + quintiles that PyHazards computes on the 5,046 SmokeBench images, which round to exactly those + values (so the contrast definition below is the authors'). + +The paper does not define the background region or how the area of several boxes is combined; both +follow the authors' ``summary_evaluation.py`` (commit 183cdca, test oracle only): the area is that of +the first box, and the background is a 20-pixel frame around each box in the OpenCV grey image +(pixels equal to 0 are ignored), averaged over boxes. + +:func:`box_iou` is a port of ``torchvision.ops.box_iou`` for ``(N, 4)`` xyxy boxes (torchvision, +BSD-3-Clause, Copyright (c) Soumith Chintala 2016, torchvision/ops/boxes.py); torchvision is not a +PyHazards dependency. +""" + +from __future__ import annotations + +import math +from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple + +import numpy as np +import torch + +AREA_BIN_EDGES: Tuple[float, ...] = (42, 4356, 11232, 28565, 83157, 2232020) +AREA_BIN_LABELS: Tuple[str, ...] = ("Very Small", "Small", "Medium", "Large", "Very Large") +# Quintiles of weber_contrast over the 5,046 SmokeBench smoke images (FIgLib JPEGs decoded with +# Pillow 12.3 / libjpeg-turbo); the paper prints them as 0.0246, 0.0549, 0.0878, 0.13 and 0.728. +CONTRAST_BIN_EDGES: Tuple[float, ...] = ( + 0.0, + 0.02461763919669502, + 0.054876825799815156, + 0.08778381526434637, + 0.1297575902787221, + 0.7280443703122176, +) +CONTRAST_BIN_EDGES_PRINTED: Tuple[float, ...] = (0.0, 0.0246, 0.0549, 0.0878, 0.13, 0.728) +CONTRAST_BIN_LABELS: Tuple[str, ...] = ("Very Low", "Low", "Medium", "High", "Very High") +CONTRAST_PAD = 20 + + +def accuracy(predictions: Sequence[bool], labels: Sequence[bool]) -> float: + if len(predictions) != len(labels): + raise ValueError(f"{len(predictions)} predictions for {len(labels)} labels") + if not labels: + raise ValueError("accuracy of an empty set is undefined") + return float(np.mean([bool(p) == bool(y) for p, y in zip(predictions, labels)])) + + +def set_iou(predicted: Iterable[int], target: Iterable[int]) -> float: + """``|P n G| / |P u G|`` for sets of tile or cell ids (raises when both are empty).""" + pred, true = set(predicted), set(target) + union = pred | true + if not union: + raise ValueError("IoU of two empty sets is undefined") + return len(pred & true) / len(union) + + +def _upcast(t: torch.Tensor) -> torch.Tensor: + if t.is_floating_point(): + return t if t.dtype in (torch.float32, torch.float64) else t.float() + return t if t.dtype in (torch.int32, torch.int64) else t.int() + + +def _box_area(boxes: torch.Tensor) -> torch.Tensor: + boxes = _upcast(boxes) + return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) + + +def box_iou(boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor: + """Pairwise IoU ``(N, M)`` of xyxy boxes ``(N, 4)`` and ``(M, 4)`` (torchvision semantics).""" + for name, boxes in (("boxes1", boxes1), ("boxes2", boxes2)): + if boxes.ndim != 2 or boxes.shape[-1] != 4: + raise ValueError(f"{name} must have shape (N, 4), got {tuple(boxes.shape)}") + area1 = _box_area(boxes1) + area2 = _box_area(boxes2) + lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) + rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) + wh = _upcast(rb - lt).clamp(min=0) + inter = wh[:, :, 0] * wh[:, :, 1] + union = area1[:, None] + area2 - inter + return inter / union + + +def detection_iou(predicted_boxes: Sequence, target_boxes: Sequence) -> Tuple[float, Optional[str]]: + """Per-image detection score: the largest pairwise IoU (``np.max(box_iou(P, G))``). + + ``predicted_boxes`` are the raw JSON values from :func:`~pyhazards.prompted.parsers.parse_detection`. + Returns ``(score, problem)``; ``problem`` is ``None`` for well-formed ``(N, 4)`` numeric boxes. + Boxes that are not ``(N, 4)`` numbers score 0 (the authors' script scores fewer than four + coordinates 0 and crashes on other malformed values); a NaN IoU (zero union) also scores 0. + """ + target = torch.tensor([np.asarray(box).tolist() for box in target_boxes]) + try: + pred = torch.tensor(predicted_boxes) + except (TypeError, ValueError, RuntimeError, OverflowError): + return 0.0, "non_numeric" + if pred.ndim != 2 or pred.shape[-1] != 4: + return 0.0, "malformed" + score = float(np.max(box_iou(pred, target).tolist())) + if math.isnan(score): + return 0.0, "nan" + return score, None + + +def mean(values: Sequence[float]) -> float: + if not values: + raise ValueError("mean of an empty set is undefined") + return float(np.mean(values)) + + +def box_area(box: Sequence[float]) -> float: + """``(x2 - x1) * (y2 - y1)`` of one box.""" + x1, y1, x2, y2 = box + return (x2 - x1) * (y2 - y1) + + +def smoke_area(boxes: Sequence[Sequence[float]]) -> float: + """SmokeBench smoke area: the area of the first ground-truth box.""" + if not boxes: + raise ValueError("a smoke image needs at least one box") + return box_area(boxes[0]) + + +def opencv_gray(image: np.ndarray) -> np.ndarray: + """Grey level of an RGB uint8 image exactly as ``cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)``. + + OpenCV uses 15-bit fixed point: ``(9798 R + 19235 G + 3735 B + 2**14) >> 15`` (checked against + OpenCV 4.10 on all 2**24 colours in the oracle test). + """ + array = np.asarray(image) + if array.ndim != 3 or array.shape[2] != 3 or array.dtype != np.uint8: + raise ValueError(f"expected an RGB uint8 image of shape (H, W, 3), got {array.shape} {array.dtype}") + rgb = array.astype(np.int32) # at most 255 * 2**15 + 2**14, well inside int32 + gray = (rgb[..., 0] * 9798 + rgb[..., 1] * 19235 + rgb[..., 2] * 3735 + (1 << 14)) >> 15 + return gray.astype(np.uint8) + + +def weber_contrast(image: np.ndarray, boxes: Sequence[Sequence[int]], pad: int = CONTRAST_PAD) -> float: + """Mean over boxes of ``|mean(box) - mean(frame)| / mean(frame)`` on the OpenCV grey image. + + The frame is the box grown by ``pad`` pixels (clipped to the image) minus the box; grey value 0 + pixels are excluded from it. Boxes with an empty frame or a zero frame mean are skipped; 0 if + none is left. Box coordinates are integer pixel indices. + """ + array = np.asarray(image) + if array.ndim != 3 or array.shape[2] != 3: + raise ValueError(f"expected an RGB image of shape (H, W, 3), got {array.shape}") + height, width = array.shape[:2] + ratios: List[float] = [] + for x1, y1, x2, y2 in (tuple(int(v) for v in box) for box in boxes): + bx1, by1 = max(0, x1 - pad), max(0, y1 - pad) + bx2, by2 = min(width, x2 + pad), min(height, y2 + pad) + if min(x1, y1, x2, y2) < 0: # keep numpy's negative-index slicing of the whole image + gray, ox, oy = opencv_gray(array), 0, 0 + else: # only the grey levels of the box and its frame are needed + gray, ox, oy = opencv_gray(array[by1:max(by2, y2), bx1:max(bx2, x2)]), bx1, by1 + smoke_mean = float(np.mean(gray[y1 - oy:y2 - oy, x1 - ox:x2 - ox])) + frame = gray[by1 - oy:by2 - oy, bx1 - ox:bx2 - ox].copy() + frame[(y1 - by1):(y2 - by1), (x1 - bx1):(x2 - bx1)] = 0 + pixels = frame[frame > 0] + if len(pixels) == 0: + continue + background = float(np.mean(pixels)) + if background != 0: + ratios.append(abs(smoke_mean - background) / background) + return float(np.mean(ratios)) if ratios else 0.0 + + +def assign_bin(value: float, edges: Sequence[float]) -> int: + """Index of the right-closed bin ``(edges[k], edges[k+1]]`` holding ``value``. + + The first bin also takes values at or below ``edges[0]`` and the last bin values above + ``edges[-1]``, as ``pandas.qcut`` assigns the minimum and maximum of the data it was fitted on. + """ + for k in range(len(edges) - 2): + if value <= edges[k + 1]: + return k + return len(edges) - 2 + + +def quantile_edges(values: Sequence[float], q: int = 5) -> List[float]: + """Quantile edges as ``pandas.qcut(values, q)`` computes them (linear interpolation).""" + if not values: + raise ValueError("quantiles of an empty set are undefined") + return [float(v) for v in np.quantile(np.asarray(values, dtype=float), np.linspace(0, 1, q + 1))] + + +def binned_means(values: Sequence[float], keys: Sequence[float], edges: Sequence[float], labels: Sequence[str]) -> Dict[str, Dict[str, float]]: + """Mean of ``values`` per bin of ``keys``: ``{label: {"mean": m, "n": n}}`` (empty bins: mean None).""" + if len(values) != len(keys): + raise ValueError("values and keys must have the same length") + groups: Dict[int, List[float]] = {k: [] for k in range(len(labels))} + for value, key in zip(values, keys): + groups[assign_bin(key, edges)].append(float(value)) + return { + labels[k]: {"mean": (float(np.mean(group)) if group else None), "n": len(group)} + for k, group in groups.items() + } + + +__all__ = [ + "AREA_BIN_EDGES", + "AREA_BIN_LABELS", + "CONTRAST_BIN_EDGES", + "CONTRAST_BIN_EDGES_PRINTED", + "CONTRAST_BIN_LABELS", + "CONTRAST_PAD", + "accuracy", + "assign_bin", + "binned_means", + "box_area", + "box_iou", + "detection_iou", + "mean", + "opencv_gray", + "quantile_edges", + "set_iou", + "smoke_area", + "weber_contrast", +] diff --git a/pyhazards/prompted/parsers.py b/pyhazards/prompted/parsers.py new file mode 100644 index 00000000..0e642443 --- /dev/null +++ b/pyhazards/prompted/parsers.py @@ -0,0 +1,92 @@ +"""Turn SmokeBench model answers into predictions. + +The paper only says that ``True`` maps to 1 and ``False`` to 0 (Sec. 4.4); how other answers are +read is not stated. The rules below follow the authors' evaluation script (github.com/SoraLink/MLLM, +commit 183cdca488e8c7afa5a254f86ac675cb98951c73, ``evaluations.py``; no licence, used only as a test +oracle, nothing is copied): + +* classification: smoke is predicted iff the answer contains the substring ``True`` (case-sensitive). + Every other answer -- ``False``, ``true``, refusals, empty text -- counts as "no smoke", so an + unparseable answer is wrong on a smoke image and right on a smoke-free one; +* tile: a tile is predicted positive iff its answer contains ``True`` or ``true``; +* grid: every run of digits in the answer is a predicted cell id (``[{"region": 3}]`` -> ``{3}``); + ids outside ``1..25`` are kept and only enlarge the union; an answer without digits is the + empty prediction; +* detection: the first ``[[ ... ]]`` span (non-greedy) is decoded as JSON; empty entries are + dropped; an answer without such a span, invalid JSON, or an empty list becomes the single box + ``[0, 0, 0, 0]`` (IoU 0 with any real box). + +:func:`answer_kind` additionally labels classification answers as ``"true"``, ``"false"`` or +``"other"`` for reporting how often a model ignored the requested format; it does not change scores. +""" + +from __future__ import annotations + +import json +import re +from typing import Any, List, Set + +_GRID_NUMBER = re.compile(r"\d+") +_BOX_LIST = re.compile(r"\[\s*\[.*?\]\s*\]", flags=re.DOTALL) +_JSON_FENCE = re.compile(r"```json\s*(.*?)\s*```", flags=re.DOTALL) + +EMPTY_BOX = [0, 0, 0, 0] + + +def parse_classification(answer: str) -> bool: + """SmokeBench classification answer -> smoke predicted (``"True" in answer``).""" + return "True" in answer + + +def answer_kind(answer: str) -> str: + """``"true"``/``"false"`` when the answer contains that word (``True`` wins), else ``"other"``.""" + if "True" in answer: + return "true" + if "False" in answer: + return "false" + return "other" + + +def parse_tile(answer: str) -> bool: + """Tile answer -> tile predicted positive (``"True"`` or ``"true"`` in the answer).""" + return "True" in answer or "true" in answer + + +def parse_grid(answer: str) -> Set[int]: + """Grid answer -> set of predicted cell ids (every run of digits).""" + return {int(token) for token in _GRID_NUMBER.findall(answer)} + + +def parse_detection(answer: str) -> List[Any]: + """Detection answer -> list of predicted boxes (raw JSON values, ``[[0, 0, 0, 0]]`` if none).""" + try: + boxes = json.loads(_BOX_LIST.findall(answer)[0]) + boxes = [box for box in boxes if box] + if len(boxes) == 0: + return [list(EMPTY_BOX)] + boxes = [list(EMPTY_BOX) if len(box) == 0 else box for box in boxes] + except Exception: # noqa: BLE001 - any malformed answer is the empty prediction + return [list(EMPTY_BOX)] + return boxes + + +def strip_json_fence(text: str) -> str: + """Return the content of the first Markdown ```json fence, else the stripped text. + + The authors apply this to Qwen2.5-VL answers before parsing (``QwenVL.extract_json_from_markdown``). + """ + match = _JSON_FENCE.search(text) + if match: + return match.group(1).strip() + return text.strip() + + +__all__ = [ + "EMPTY_BOX", + "answer_kind", + "parse_classification", + "parse_detection", + "parse_grid", + "parse_tile", + "strip_json_fence", +] diff --git a/pyhazards/prompted/prompts.py b/pyhazards/prompted/prompts.py new file mode 100644 index 00000000..2a719b0c --- /dev/null +++ b/pyhazards/prompted/prompts.py @@ -0,0 +1,79 @@ +"""SmokeBench task definitions and the verbatim prompts of the paper. + +Source: Qi, Li & Barnes, "SmokeBench: Evaluating Multimodal Large Language Models for Wildfire +Smoke Detection", WACV 2026, arXiv:2512.11215v1, Section 4.3 "Prompting Design". The strings below +are the prompt boxes of the paper's LaTeX source (``sec/4_experiment.tex``) as rendered text: source +line breaks become single spaces, ``\\textbf``/``\\textit`` markup is dropped, ``$x_1, y_1, ...$`` is +written ``x1, y1, ...`` and ``\\{ \\}`` are braces. The double quotes of the grid prompt are the ASCII +``"`` of the LaTeX source (pdflatex prints them as a closing curly quote, a font artefact); the +authors' released evaluation script also sends ASCII quotes. + +The released script (SoraLink/MLLM, commit 183cdca) words three of the prompts slightly differently +from the paper (e.g. "Do MUST not return any other words"); PyHazards uses the paper's text, which is +the published protocol, and lists the difference in the docs. +""" + +from __future__ import annotations + +from typing import Dict, Tuple + +TASKS: Tuple[str, ...] = ("classification", "tile", "grid", "detection") + +CLASSIFICATION_PROMPT = ( + "Please look at this image. Detect if the image contains smoke. " + "If you can find any smoke, return True. Otherwise, return False. " + "Do not return any other words." +) + +# Tile-based localization reuses the classification prompt on each tile (paper Sec. 4.3). +TILE_PROMPT = CLASSIFICATION_PROMPT + +GRID_PROMPT = ( + "Please look at this image, which is divided into several numbered regions " + "(from left to right, top to bottom). Please output the numbered regions that contain smoke " + 'in JSON format as a list of dicts like [{"region": 1}, {"region": 2}]. ' + "If you cannot find any smoke, return an empty list []. without other words" +) + +DETECTION_PROMPT = ( + "Detect all smoke and output bounding boxes in the format " + "[[x1, y1, x2, y2], [x1, y1, x2, y2]]. " + "If you cannot find any smoke, return an empty list [] without other words. " + "Do not return dictionaries." +) + +PROMPTS: Dict[str, str] = { + "classification": CLASSIFICATION_PROMPT, + "tile": TILE_PROMPT, + "grid": GRID_PROMPT, + "detection": DETECTION_PROMPT, +} + +# Fixed partitions of the paper: 3 x 4 tiles (Sec. 4.3, Figs. 2 and 4, Tables 4-5) and a 5 x 5 +# numbered grid (Figs. 3 and 5, Tables 6-7), both as (rows, columns). +TILE_LAYOUT: Tuple[int, int] = (3, 4) +GRID_LAYOUT: Tuple[int, int] = (5, 5) + +# "All inference is conducted with the decoding temperature fixed at 0.5" (Sec. 4.2). +TEMPERATURE = 0.5 + + +def get_prompt(task: str) -> str: + """Return the verbatim SmokeBench prompt for ``task``.""" + if task not in PROMPTS: + raise ValueError(f"unknown SmokeBench task {task!r}; expected one of {TASKS}") + return PROMPTS[task] + + +__all__ = [ + "CLASSIFICATION_PROMPT", + "DETECTION_PROMPT", + "GRID_LAYOUT", + "GRID_PROMPT", + "PROMPTS", + "TASKS", + "TEMPERATURE", + "TILE_LAYOUT", + "TILE_PROMPT", + "get_prompt", +] diff --git a/pyhazards/prompted/runner.py b/pyhazards/prompted/runner.py new file mode 100644 index 00000000..5c7efad4 --- /dev/null +++ b/pyhazards/prompted/runner.py @@ -0,0 +1,238 @@ +"""Evaluate a prompted backend on SmokeBench and write a report. + +One call runs one task: ``classification`` on every image (smoke and smoke-free); ``tile``, +``grid`` and ``detection`` on the smoke images only, as in the paper (their scores need a ground-truth +box, and the area / contrast bins are defined on boxes). Each image's answer(s), parsed prediction +and score are appended to ``records.jsonl`` as soon as they exist, so an interrupted run resumes +where it stopped (``resume=True``); ``report.json`` holds the aggregate metrics, the per-bin +breakdowns of the paper's tables, answer-format diagnostics, the exact prompt, the backend settings +and, when the backend is one of the SmokeBench models, the numbers the paper reports. +""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter +from pathlib import Path +from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Union + +import numpy as np + +from .backends.base import PromptedBackend, check_image +from .geometry import PROTOCOLS, covered_cells, crop_tiles, draw_grid_overlay +from .metrics import ( + AREA_BIN_EDGES, + AREA_BIN_LABELS, + CONTRAST_BIN_EDGES, + CONTRAST_BIN_LABELS, + binned_means, + detection_iou, + quantile_edges, + set_iou, + smoke_area, + weber_contrast, +) +from .parsers import EMPTY_BOX, answer_kind, parse_classification, parse_detection, parse_grid, parse_tile +from .prompts import GRID_LAYOUT, TASKS, TILE_LAYOUT, get_prompt + +PathLike = Union[str, Path] +BENCHMARK = "SmokeBench (Qi, Li & Barnes, WACV 2026, arXiv:2512.11215)" + + +def _score_sample(backend: PromptedBackend, task: str, protocol: str, sample: Any, image: np.ndarray) -> Dict[str, Any]: + height, width = image.shape[:2] + label = bool(sample.label) + boxes = [list(box) for box in getattr(sample, "boxes", ()) or ()] + record: Dict[str, Any] = {"image_id": sample.image_id, "label": label, "height": height, "width": width} + if label: + if not boxes: + raise ValueError(f"smoke image {sample.image_id} has no ground-truth box") + record.update(boxes=boxes, area=smoke_area(boxes), contrast=weber_contrast(image, boxes)) + prompt = get_prompt(task) + if task == "classification": + answer = backend.generate(image, prompt) + prediction = parse_classification(answer) + record.update(answer=answer, kind=answer_kind(answer), prediction=prediction, correct=prediction == label) + elif task == "tile": + answers = backend.generate_batch(crop_tiles(image, TILE_LAYOUT, protocol=protocol), prompt) + if len(answers) != TILE_LAYOUT[0] * TILE_LAYOUT[1]: + raise RuntimeError(f"backend returned {len(answers)} answers for {TILE_LAYOUT[0] * TILE_LAYOUT[1]} tiles") + predicted = [index + 1 for index, answer in enumerate(answers) if parse_tile(answer)] + target = covered_cells(boxes, height, width, TILE_LAYOUT, protocol=protocol) + record.update(answers=answers, predicted=predicted, target=target, iou=set_iou(predicted, target)) + elif task == "grid": + answer = backend.generate(draw_grid_overlay(image, GRID_LAYOUT), prompt) + predicted = sorted(parse_grid(answer)) + target = covered_cells(boxes, height, width, GRID_LAYOUT, protocol=protocol) + record.update(answer=answer, predicted=predicted, target=target, iou=set_iou(predicted, target)) + elif task == "detection": + answer = backend.generate(image, prompt) + predicted = parse_detection(answer) + score, problem = detection_iou(predicted, boxes) + record.update(answer=answer, predicted=predicted, iou=score, problem=problem) + record["served_model"] = backend.last_served_model + return record + + +def _mean(values: Sequence[float]) -> Optional[float]: + return float(np.mean(values)) if len(values) else None + + +def summarize(records: Sequence[Dict[str, Any]], task: str) -> Dict[str, Any]: + """Aggregate per-image records of one task into the paper's metrics.""" + smoke = [record for record in records if record["label"]] + areas = [record["area"] for record in smoke] + contrasts = [record["contrast"] for record in smoke] + metrics: Dict[str, Any] = {} + if task == "classification": + smoke_free = [record for record in records if not record["label"]] + hits = [float(record["correct"]) for record in smoke] + metrics.update( + accuracy_smoke=_mean(hits), + accuracy_smoke_free=_mean([float(record["correct"]) for record in smoke_free]), + accuracy_all=_mean([float(record["correct"]) for record in records]), + n_smoke=len(smoke), + n_smoke_free=len(smoke_free), + answers=dict(Counter(record["kind"] for record in records)), + ) + else: + hits = [float(record["iou"]) for record in smoke] + metrics.update(miou=_mean(hits), n_smoke=len(smoke)) + if task == "tile": + metrics["mean_predicted_tiles"] = _mean([len(record["predicted"]) for record in smoke]) + elif task == "grid": + metrics["answers_without_ids"] = sum(1 for record in smoke if not record["predicted"]) + metrics["answers_with_out_of_range_ids"] = sum( + 1 for record in smoke if any(not 1 <= cell <= GRID_LAYOUT[0] * GRID_LAYOUT[1] for cell in record["predicted"]) + ) + elif task == "detection": + metrics["empty_predictions"] = sum(1 for record in smoke if record["predicted"] == [EMPTY_BOX]) + metrics["malformed_predictions"] = dict(Counter(record["problem"] for record in smoke if record["problem"])) + if smoke: + metrics["by_area"] = binned_means(hits, areas, AREA_BIN_EDGES, AREA_BIN_LABELS) + metrics["by_contrast"] = binned_means(hits, contrasts, CONTRAST_BIN_EDGES, CONTRAST_BIN_LABELS) + metrics["quintile_edges"] = {"area": quantile_edges(areas), "contrast": quantile_edges(contrasts)} + return metrics + + +def _read_records(path: Path) -> List[Dict[str, Any]]: + if not path.exists(): + return [] + with path.open(encoding="utf-8") as handle: + return [json.loads(line) for line in handle if line.strip()] + + +def _paper_reported(name: str, task: str) -> Optional[Dict[str, Any]]: + from .catalog import load_prompted_cards # noqa: PLC0415 - avoid a cycle at import time + + for card in load_prompted_cards(): + if card.name == name: + reported = card.smokebench_reported.model_dump(exclude_none=True) + return reported.get(task) + return None + + +def evaluate_smokebench( + backend: PromptedBackend, + dataset: Sequence[Any], + task: str, + *, + protocol: str = "paper", + output_dir: Optional[PathLike] = None, + load_image: Optional[Callable[[Any], np.ndarray]] = None, + resume: bool = True, + seed: Optional[int] = 0, + limit: Optional[int] = None, + progress: bool = False, +) -> Dict[str, Any]: + """Run one SmokeBench task with ``backend`` over ``dataset`` and return the report. + + Args: + backend: a :class:`~pyhazards.prompted.backends.PromptedBackend`. + dataset: samples with ``image_id``, ``label`` and ``boxes`` (e.g. + :class:`~pyhazards.datasets.figlib_smokebench.FIgLibSmokeBench`). + task: ``classification``, ``tile``, ``grid`` or ``detection``. + protocol: ``"paper"`` or ``"reference_code"`` (tile crops and box-to-cell labels exactly as + the authors' script, including its two geometry bugs; see :mod:`pyhazards.prompted.geometry`). + output_dir: where ``records.jsonl`` and ``report.json`` are written (nothing is written if None). + load_image: sample -> RGB uint8 array; defaults to ``dataset.load_image``. + resume: reuse the records already in ``output_dir`` for the same task, protocol, prompt and model. + seed: ``torch.manual_seed`` before the first query (sampling backends at temperature 0.5). + limit: evaluate only the first ``limit`` eligible samples. + progress: show a progress bar. + """ + if task not in TASKS: + raise ValueError(f"unknown SmokeBench task {task!r}; expected one of {TASKS}") + if protocol not in PROTOCOLS: + raise ValueError(f"unknown protocol {protocol!r}; expected one of {PROTOCOLS}") + loader = load_image or getattr(dataset, "load_image", None) + if loader is None: + raise ValueError("pass load_image= or a dataset with a load_image(sample) method") + samples: List[Any] = [sample for sample in dataset if task == "classification" or sample.label] + if limit is not None: + samples = samples[: int(limit)] + if not samples: + raise ValueError(f"no samples to evaluate for task {task!r}") + + prompt = get_prompt(task) + run = { + "benchmark": BENCHMARK, + "task": task, + "protocol": protocol, + "prompt": prompt, + "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), + "layout": list(TILE_LAYOUT if task == "tile" else GRID_LAYOUT) if task in {"tile", "grid"} else None, + "backend": backend.describe(), + "dataset": dataset.describe() if hasattr(dataset, "describe") else {"samples": len(samples)}, + "seed": seed, + } + + records_path = run_path = None + done: Dict[str, Dict[str, Any]] = {} + if output_dir is not None: + out = Path(output_dir) + out.mkdir(parents=True, exist_ok=True) + records_path, run_path = out / "records.jsonl", out / "run.json" + if resume and run_path.exists(): + previous = json.loads(run_path.read_text(encoding="utf-8")) + keys = ("task", "protocol", "prompt_sha256") + if any(previous.get(key) != run[key] for key in keys) or previous["backend"].get("model_id") != run["backend"].get("model_id"): + raise ValueError(f"{out} holds a different run ({previous.get('task')}, {previous['backend'].get('model_id')}); use another output_dir or resume=False") + done = {record["image_id"]: record for record in _read_records(records_path)} + elif records_path.exists(): + records_path.unlink() + run_path.write_text(json.dumps(run, indent=2, sort_keys=True), encoding="utf-8") + + if seed is not None: + import torch # noqa: PLC0415 + + torch.manual_seed(seed) + + iterator: Iterable[Any] = samples + if progress: + from tqdm import tqdm # noqa: PLC0415 + + iterator = tqdm(samples, desc=f"SmokeBench {task}") + records: List[Dict[str, Any]] = [] + for sample in iterator: + if sample.image_id in done: + records.append(done[sample.image_id]) + continue + image = check_image(loader(sample)) + record = _score_sample(backend, task, protocol, sample, image) + records.append(record) + if records_path is not None: + with records_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + + report = dict(run) + report["metrics"] = summarize(records, task) + report["served_models"] = sorted({record["served_model"] for record in records if record.get("served_model")}) + report["paper_reported"] = _paper_reported(getattr(backend, "name", ""), task) + if output_dir is not None: + (Path(output_dir) / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8") + return report + + +__all__ = ["BENCHMARK", "evaluate_smokebench", "summarize"] diff --git a/pyhazards/simulators/__init__.py b/pyhazards/simulators/__init__.py new file mode 100644 index 00000000..7a6ada44 --- /dev/null +++ b/pyhazards/simulators/__init__.py @@ -0,0 +1,27 @@ +"""Adapters to external, physics-based fire simulators. + +These are not neural networks and are not in the model registry. Each adapter drives the official +software, which the user installs separately, or reads its outputs; nothing of the simulator is +reimplemented in PyHazards. + +- :class:`ForeFireSimulator` runs ForeFire (GPL-3.0, optional ``pip install forefire``) on rasters. +- WRF-SFIRE outputs (``wrfout`` files) are read by :mod:`pyhazards.datasets.wrf_sfire`. +""" + +from .forefire import ( + FOREFIRE_CHECKED_VERSION, + ForeFireNotInstalledError, + ForeFireResult, + ForeFireSimulator, + forefire_available, + forefire_version, +) + +__all__ = [ + "FOREFIRE_CHECKED_VERSION", + "ForeFireNotInstalledError", + "ForeFireResult", + "ForeFireSimulator", + "forefire_available", + "forefire_version", +] diff --git a/pyhazards/simulators/_forefire_worker.py b/pyhazards/simulators/_forefire_worker.py new file mode 100644 index 00000000..202e6c4d --- /dev/null +++ b/pyhazards/simulators/_forefire_worker.py @@ -0,0 +1,8 @@ +"""Worker process for :class:`pyhazards.simulators.ForeFireSimulator` with ``isolate=True``.""" + +import sys + +from pyhazards.simulators.forefire import worker_main + +if __name__ == "__main__": + raise SystemExit(worker_main(sys.argv[1:])) diff --git a/pyhazards/simulators/forefire.py b/pyhazards/simulators/forefire.py new file mode 100644 index 00000000..48204178 --- /dev/null +++ b/pyhazards/simulators/forefire.py @@ -0,0 +1,682 @@ +"""Adapter that runs the official ForeFire wildland-fire spread simulator on PyHazards rasters. + +ForeFire is a C++ discrete-event front-tracking simulator developed at CNRS / Universite de Corse: + +- Filippi, Baggio, Paugam, Bosseur, Leblanc, Alonso-Pinar, "ForeFire: A Modular, Scriptable C++ + Simulation Engine and Library for Wildland-Fire Spread", Journal of Open Source Software 10(116): + 8680 (2025), doi:10.21105/joss.08680. +- Filippi, Morandini, Balbi, Hill, "Discrete event front-tracking simulation of a physical + fire-spread model", SIMULATION 86(10):629-646, doi:10.1177/0037549709343117. +- Official code: https://github.com/forefireAPI/forefire. Python bindings: module ``pyforefire``, + PyPI distribution ``forefire`` (checked with 2.5.0, tag ``v2.5.0``). + +Licence boundary +---------------- +ForeFire is GPL-3.0 and PyHazards is MIT. This module contains no ForeFire code and does not link +against it: it imports a ``pyforefire`` that the user installed separately (``pip install forefire``) +and drives it only through its public Python API, lazily, at run time. ForeFire is not a PyHazards +dependency. Whoever redistributes PyHazards together with ForeFire must follow the GPL. + +What this adapter does +---------------------- +It turns rasters into ForeFire layers with the same calls as the official Python examples +(``tests/python/percolation.py``, ``idealizedwind.py`` and ``farsite_flat.py`` in the ForeFire repo): +a ``FireDomain`` covering the fuel raster, the propagation model (``addLayer("propagation", ...)``), +the fuel index map (``addIndexLayer("table", "fuel", ...)``), optional altitude and wind +(``addScalarLayer``), ignitions (``startFire[loc=...]``) and wind changes (``trigger[wind;vel=...]``), +then advances the simulation with ``step[dt=...]``: either step by step between wind changes, like the +Python examples, or with the changes scheduled as events (``trigger[...]@t=...``) like +``tests/runff/real_case.ff``. It reads back ForeFire's burning map (``ff["arrival_time"]``: arrival +time of the front in seconds, ``inf`` where the fire never arrived) and, as the only PyHazards-side +post-processing, reduces that map to the requested output grid. + +Checked against the official code (``tests/oracle/test_forefire_oracle.py``): fed the rasters of the +official regression case ``tests/runff`` it reproduces the reference arrival-time map +``ForeFire.0.nc.ref`` within the tolerance of ForeFire's own ``compare_nc.py``, and it reproduces the +official ``tests/python/idealizedwind.py`` run bit for bit. + +What it does not do +------------------- +It does not modify ForeFire's propagation models, fuel tables or parameters, does not calibrate +anything, and has no learned weights. Physical realism depends entirely on the fuel table, the +propagation model and the parameters the user chooses. It is not a ``torch.nn.Module`` and is not in +the model registry. +""" + +from __future__ import annotations + +import contextlib +import importlib +import importlib.metadata +import math +import os +import pickle +import subprocess +import sys +import tempfile +import traceback +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np + +FOREFIRE_DISTRIBUTION = "forefire" +FOREFIRE_MODULE = "pyforefire" +FOREFIRE_CHECKED_VERSION = "2.5.0" +FOREFIRE_REPO = "https://github.com/forefireAPI/forefire" + +# Fuel tables shipped with pyforefire.helpers (read from the installed package at run time). +_HELPER_FUEL_TABLES = ("Rothermel", "RothermelAndrews2018") + +# ForeFire stores fuel properties in a fixed table of 1024 rows (FuelDataLayer::MAXNUMFUELS); a larger +# code would index past it in the C++ core. +_MAX_FUEL_CODE = 1023 + +# Parameters the adapter sets itself; passing them in ``parameters`` would silently fight the inputs. +_RESERVED_PARAMETERS = { + "atmoNX": "set from output_shape", + "atmoNY": "set from output_shape", + "propagationModel": "use ForeFireSimulator(propagation_model=...)", + "fuelsTable": "use ForeFireSimulator(fuels_table=...)", +} + +_ORIGINS = ("upper", "lower") + +ArrayLike = Any + + +class ForeFireNotInstalledError(ImportError): + """Raised when the optional, separately installed ``pyforefire`` module is missing.""" + + +def forefire_available() -> bool: + """Whether ``pyforefire`` can be imported (it is never installed by PyHazards).""" + try: + importlib.import_module(FOREFIRE_MODULE) + except ImportError: + return False + return True + + +def forefire_version() -> Optional[str]: + try: + return importlib.metadata.version(FOREFIRE_DISTRIBUTION) + except importlib.metadata.PackageNotFoundError: + return None + + +def _import_pyforefire(): + try: + return importlib.import_module(FOREFIRE_MODULE) + except ImportError as exc: + raise ForeFireNotInstalledError( + "ForeFireSimulator needs the official ForeFire Python bindings, which PyHazards does not " + "install (ForeFire is GPL-3.0). Install them yourself with `pip install forefire` " + f"(checked with {FOREFIRE_CHECKED_VERSION}); see {FOREFIRE_REPO}." + ) from exc + + +@dataclass +class ForeFireResult: + """Output of :meth:`ForeFireSimulator.run`. + + ``arrival_time`` is on the output grid (default: the fuel grid) with the row order given by + ``origin``: the earliest ForeFire arrival time, in seconds since ``t=0``, of any burning-map cell + inside each output cell, ``inf`` where the front never arrived within ``duration``. + ``arrival_time_native`` is ForeFire's own burning map at ``native_cell_size`` resolution, in the + same row order. + """ + + arrival_time: np.ndarray + arrival_time_native: np.ndarray + duration: float + cell_size: Tuple[float, float] + native_cell_size: Tuple[float, float] + origin: str + engine_version: Optional[str] = None + log: str = "" + commands: List[str] = field(default_factory=list) + + def burned_mask(self, time: Optional[float] = None, native: bool = False) -> np.ndarray: + """Boolean mask of cells reached by the front at ``time`` seconds (default: ``duration``).""" + when = self.duration if time is None else float(time) + grid = self.arrival_time_native if native else self.arrival_time + return grid <= when + + def burned_masks(self, times: Sequence[float], native: bool = False) -> np.ndarray: + """Stack of burned masks, shape ``(len(times), H, W)``, dtype ``float32`` (spread targets).""" + return np.stack([self.burned_mask(t, native=native) for t in times]).astype(np.float32) + + def burned_area(self, time: Optional[float] = None) -> float: + """Burned area in square metres at ``time``, from the native burning map.""" + dy, dx = self.native_cell_size + return float(self.burned_mask(time, native=True).sum()) * dx * dy + + +@contextlib.contextmanager +def _captured_native_stdout() -> Iterator[List[str]]: + """Capture what ForeFire's C++ core writes to ``std::cout`` (file descriptor 1). + + Same technique as the official ``tests/python/test_wheel.py``: ``sys.stdout`` never sees it. + """ + box: List[str] = [] + try: + fd = sys.stdout.fileno() + except (AttributeError, OSError, ValueError): + fd = 1 + with tempfile.TemporaryFile(mode="w+") as tmp: + sys.stdout.flush() + saved = os.dup(fd) + try: + os.dup2(tmp.fileno(), fd) + yield box + finally: + sys.stdout.flush() + os.dup2(saved, fd) + os.close(saved) + tmp.seek(0) + box.append(tmp.read()) + + +def _num(value: float) -> str: + return repr(float(value)) + + +def _as_array(value: ArrayLike, name: str, dtype=np.float64) -> np.ndarray: + if hasattr(value, "detach") and hasattr(value, "cpu"): # torch.Tensor without importing torch + value = value.detach().cpu().numpy() + array = np.asarray(value) + if array.dtype == object: + raise ValueError(f"{name} must be a numeric array, got dtype=object") + return array.astype(dtype, copy=False) + + +def _layer(array: np.ndarray, origin: str) -> np.ndarray: + """(…, H, W) raster -> ForeFire layer array (t, z, y, x) with y increasing northward.""" + if origin == "upper": + array = array[..., ::-1, :] + if array.ndim == 2: + array = array[None, None] + elif array.ndim == 3: + array = array[None] + return np.ascontiguousarray(array) + + +def _reduce_min(native: np.ndarray, shape: Tuple[int, int]) -> np.ndarray: + """Minimum of ``native`` over the native cells whose centres fall in each output cell.""" + hn, wn = native.shape + ho, wo = shape + rows = np.minimum(((np.arange(hn) + 0.5) * ho / hn).astype(np.int64), ho - 1) + cols = np.minimum(((np.arange(wn) + 0.5) * wo / wn).astype(np.int64), wo - 1) + out = np.full(shape, np.inf, dtype=np.float64) + np.minimum.at(out, (rows[:, None], cols[None, :]), native) + return out + + +def _run_job(job: Dict[str, Any]) -> Dict[str, Any]: + """Execute one ForeFire run. Plain data in and out, so it can run in a separate process.""" + pyforefire = _import_pyforefire() + commands: List[str] = [] + + def execute(ff, command: str) -> str: + commands.append(command) + return ff.execute(command) + + with _captured_native_stdout() as captured: + ff = pyforefire.ForeFire() + table = job["fuels_table"] + if table is None and job["propagation_model"] in _HELPER_FUEL_TABLES: + table = pyforefire.helpers.get_fuels_table(job["propagation_model"])() + if table is not None: + ff["fuelsTable"] = table + ff["propagationModel"] = job["propagation_model"] + for key, value in job["parameters"].items(): + ff[key] = value + ff["atmoNX"] = int(job["atmo_nx"]) + ff["atmoNY"] = int(job["atmo_ny"]) + + width, height = float(job["width"]), float(job["height"]) + execute(ff, f"FireDomain[sw=(0.,0.,0.);ne=({_num(width)},{_num(height)},0.);t=0.]") + ff.addLayer("propagation", job["propagation_model"], "propagationModel") + extent = (0.0, 0.0, 0.0, width, height, 0.0) + ff.addIndexLayer("table", "fuel", *extent, job["fuel"]) + if job["altitude"] is not None: + ff.addScalarLayer("data", "altitude", *extent, job["altitude"]) + if job["wind_mode"] == "field": + ff.addScalarLayer("data", "windU", *extent, job["wind_u"]) + ff.addScalarLayer("data", "windV", *extent, job["wind_v"]) + elif job["wind_mode"] == "coefficients": + ff.addScalarLayer("windScalDir", "windU", *extent, job["wind_u"]) + ff.addScalarLayer("windScalDir", "windV", *extent, job["wind_v"]) + + for x, y in job["ignitions"]: + execute(ff, f"startFire[loc=({_num(x)},{_num(y)},0.);t=0.]") + + def trigger(u: float, v: float) -> str: + return f"trigger[wind;loc=(0.,0.,0.);vel=({_num(u)},{_num(v)},0.)]" + + triggers, duration = job["wind_triggers"], float(job["duration"]) + if job["trigger_mode"] == "event": + # .ff-script style (tests/runff/real_case.ff): later triggers are ForeFire events at t. + for t, u, v in triggers: + execute(ff, trigger(u, v) + (f"@t={_num(t)}" if t > 0 else "")) + execute(ff, f"step[dt={_num(duration)}]") + else: + # Python-example style (tests/python/idealizedwind.py, farsite_flat.py): advance to each + # trigger time with step[], then trigger the new wind. + now = 0.0 + for boundary in sorted({t for t, _, _ in triggers} | {duration}): + if boundary > now: + execute(ff, f"step[dt={_num(boundary - now)}]") + now = boundary + for t, u, v in triggers: + if t == boundary: + execute(ff, trigger(u, v)) + native = np.array(ff["arrival_time"], dtype=np.float64) + + return { + "arrival_time_native": native, + "log": captured[0] if captured else "", + "commands": commands, + "engine_version": forefire_version(), + } + + +def worker_main(argv: Sequence[str]) -> int: + """Entry point of the isolated worker: `` `` (both written by this module).""" + if len(argv) != 2: + print("usage: python -m pyhazards.simulators._forefire_worker JOB.pkl OUT.pkl", file=sys.stderr) + return 2 + job_path, out_path = Path(argv[0]), Path(argv[1]) + with job_path.open("rb") as handle: + job = pickle.load(handle) + try: + output = _run_job(job) + except Exception: # reported to the parent, which raises it + output = {"error": traceback.format_exc()} + with out_path.open("wb") as handle: + pickle.dump(output, handle, protocol=pickle.HIGHEST_PROTOCOL) + return 0 + + +class ForeFireSimulator: + """Run the official ForeFire simulator (user-installed ``pyforefire``) on PyHazards rasters. + + Args: + propagation_model: a ForeFire rate-of-spread model name, e.g. ``"Rothermel"``, + ``"RothermelAndrews2018"``, ``"Farsite"``, ``"Balbi2020"``, ``"WindDriven"`` or ``"Iso"``. + fuels_table: ForeFire fuel table: the ``;``-separated text whose ``Index`` column holds the + codes used in the fuel raster, or the name of a table built into ForeFire (for example + ``"STDfarsiteFuelsTable"``). ``None`` uses the table that ``pyforefire.helpers`` ships for + ``Rothermel`` / ``RothermelAndrews2018`` and ForeFire's own default otherwise. + parameters: extra ForeFire parameters set with ``ff[name] = value`` before the domain is + created (for example ``spatialIncrement``, ``perimeterResolution``, + ``minimalPropagativeFrontDepth``, ``windReductionFactor``, ``Iso.speed``). Anything not + given keeps ForeFire's default. + isolate: run each simulation in a fresh process (default). ForeFire keeps its parameters in + a process-wide singleton, so in-process runs (``isolate=False``) inherit parameters set + by earlier runs in the same process. + timeout: optional limit in seconds for an isolated run. + allow_unknown_fuels: ForeFire gives fuel codes that are missing from the table all-zero fuel + properties without a warning. By default the adapter refuses such codes (when the table + text is given); set this to ``True`` to pass them through unchanged. + """ + + def __init__( + self, + propagation_model: str = "Rothermel", + fuels_table: Optional[str] = None, + parameters: Optional[Mapping[str, Union[int, float, str, bool]]] = None, + isolate: bool = True, + timeout: Optional[float] = None, + allow_unknown_fuels: bool = False, + ): + if not isinstance(propagation_model, str) or not propagation_model: + raise ValueError("propagation_model must be a non-empty ForeFire model name") + if fuels_table is not None and not isinstance(fuels_table, str): + raise ValueError("fuels_table must be the table text or the name of a built-in table") + self.propagation_model = propagation_model + self.fuels_table = fuels_table + self.parameters = self._check_parameters(parameters or {}) + self.isolate = bool(isolate) + self.timeout = timeout + self.allow_unknown_fuels = bool(allow_unknown_fuels) + + @staticmethod + def _check_parameters(parameters: Mapping[str, Any]) -> Dict[str, Union[int, float, str]]: + checked: Dict[str, Union[int, float, str]] = {} + for key, value in parameters.items(): + if not isinstance(key, str) or not key: + raise ValueError(f"ForeFire parameter names must be non-empty strings, got {key!r}") + if key in _RESERVED_PARAMETERS: + raise ValueError(f"ForeFire parameter {key!r} is managed by the adapter: {_RESERVED_PARAMETERS[key]}") + if isinstance(value, bool): + value = int(value) + if not isinstance(value, (int, float, str)): + raise ValueError(f"ForeFire parameter {key!r} must be int, float or str, got {type(value).__name__}") + checked[key] = value + return checked + + def run( + self, + fuel: ArrayLike, + cell_size: Union[float, Tuple[float, float]], + duration: float, + *, + ignition_mask: Optional[ArrayLike] = None, + ignition_points: Optional[Sequence[Sequence[float]]] = None, + wind: Optional[Tuple[float, float]] = None, + wind_u: Optional[ArrayLike] = None, + wind_v: Optional[ArrayLike] = None, + wind_triggers: Optional[Sequence[Tuple[float, float, float]]] = None, + altitude: Optional[ArrayLike] = None, + output_shape: Optional[Tuple[int, int]] = None, + origin: str = "upper", + trigger_mode: str = "step", + ) -> ForeFireResult: + """Simulate ``duration`` seconds of spread. + + Rasters are 2-D arrays ``(rows, cols)``. ``origin="upper"`` (default, GeoTIFF / image order) + means row 0 is the northern edge; ``origin="lower"`` means row 0 is the southern edge, which is + ForeFire's own array order. The simulation domain spans ``cols * dx`` by ``rows * dy`` metres of + the fuel raster with its south-west corner at ``(0, 0)``; every other raster covers the same + extent at its own resolution (ForeFire resamples it). + + Args: + fuel: integer fuel codes of the ``fuels_table`` (``Index`` column). + cell_size: fuel-raster cell size in metres, ``dx`` or ``(dy, dx)``. + duration: simulated time in seconds from the ignition at ``t=0``. + ignition_mask: boolean raster over the domain; ForeFire starts a fire + (``startFire[loc=...]``) at the centre of every ``True`` cell at ``t=0``. + ignition_points: ``(x, y)`` ignition locations in metres from the south-west corner, + ignited at ``t=0``. + wind: constant wind ``(u, v)`` in m/s (eastward, northward); shorthand for + ``wind_triggers=[(0, u, v)]``. + wind_u, wind_v: either ``(h, w)`` wind fields in m/s (ForeFire ``windU``/``windV`` data + layers, held constant), or ``(2, h, w)`` ForeFire direction-coefficient fields + (``windScalDir`` layers, as in ForeFire landscape files) that ``wind_triggers`` scale. + wind_triggers: ``(t, u, v)`` uniform wind changes (``trigger[wind;vel=(u,v,0)]`` at + ``t``), as in the official examples. Without ``wind_u``/``wind_v`` the adapter uses + unit direction fields, so the wind is exactly ``(u, v)`` everywhere. + altitude: terrain height in metres. + output_shape: ``(rows, cols)`` of the returned ``arrival_time`` (default: fuel shape). + It is also ForeFire's flux grid (``atmoNX``/``atmoNY``), whose cells ForeFire splits + into burning-map cells of ``max(spatialIncrement / sqrt(2), + minimalPropagativeFrontDepth)`` metres. + origin: row order of every input and output raster, ``"upper"`` or ``"lower"``. + trigger_mode: how wind changes are issued. ``"step"`` (default) advances the simulation + with ``step[dt=...]`` to each trigger time and then triggers the new wind, as the + official Python examples do; ``"event"`` schedules every trigger as a ForeFire event + (``trigger[...]@t=...``) and steps once, as the official ``.ff`` scripts do. ForeFire's + results differ slightly between the two (the extra step boundaries change its + internal time stepping). + """ + job = self._build_job( + fuel=fuel, + cell_size=cell_size, + duration=duration, + ignition_mask=ignition_mask, + ignition_points=ignition_points, + wind=wind, + wind_u=wind_u, + wind_v=wind_v, + wind_triggers=wind_triggers, + altitude=altitude, + output_shape=output_shape, + origin=origin, + trigger_mode=trigger_mode, + ) + if self.isolate: + output = self._run_isolated(job) + else: + output = _run_job(job) + + native = output["arrival_time_native"] + if native.ndim != 2 or native.size == 0: + raise RuntimeError(f"ForeFire returned no burning map (shape {native.shape}); log:\n{output['log']}") + out_shape = (job["atmo_ny"], job["atmo_nx"]) + reduced = _reduce_min(native, out_shape) + if origin == "upper": + native = native[::-1] + reduced = reduced[::-1] + return ForeFireResult( + arrival_time=np.ascontiguousarray(reduced), + arrival_time_native=np.ascontiguousarray(native), + duration=float(job["duration"]), + cell_size=(job["height"] / out_shape[0], job["width"] / out_shape[1]), + native_cell_size=(job["height"] / native.shape[0], job["width"] / native.shape[1]), + origin=origin, + engine_version=output.get("engine_version"), + log=output.get("log", ""), + commands=list(output.get("commands", [])), + ) + + def _run_isolated(self, job: Dict[str, Any]) -> Dict[str, Any]: + """Run the job in a fresh interpreter (``python -m pyhazards.simulators._forefire_worker``). + + A plain subprocess, unlike multiprocessing's spawn start method, does not re-import the + caller's ``__main__``, so scripts need no ``if __name__ == "__main__"`` guard. + """ + _import_pyforefire() # fail fast, in this process, with the installation hint + package_root = str(Path(__file__).resolve().parents[2]) + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join(p for p in (package_root, env.get("PYTHONPATH", "")) if p) + with tempfile.TemporaryDirectory(prefix="pyhazards_forefire_") as tmp: + job_path, out_path = Path(tmp) / "job.pkl", Path(tmp) / "out.pkl" + with job_path.open("wb") as handle: + pickle.dump(job, handle, protocol=pickle.HIGHEST_PROTOCOL) + command = [sys.executable, "-m", "pyhazards.simulators._forefire_worker", str(job_path), str(out_path)] + proc = subprocess.run(command, capture_output=True, text=True, timeout=self.timeout, env=env) + if not out_path.exists(): + raise RuntimeError( + f"ForeFire worker exited with code {proc.returncode} without a result.\n" + f"stderr (tail):\n{proc.stderr[-4000:]}\nstdout (tail):\n{proc.stdout[-4000:]}" + ) + with out_path.open("rb") as handle: + output = pickle.load(handle) + if "error" in output: + raise RuntimeError(f"ForeFire run failed in the worker process:\n{output['error']}") + return output + + def _build_job( + self, + fuel: ArrayLike, + cell_size: Union[float, Tuple[float, float]], + duration: float, + ignition_mask: Optional[ArrayLike], + ignition_points: Optional[Sequence[Sequence[float]]], + wind: Optional[Tuple[float, float]], + wind_u: Optional[ArrayLike], + wind_v: Optional[ArrayLike], + wind_triggers: Optional[Sequence[Tuple[float, float, float]]], + altitude: Optional[ArrayLike], + output_shape: Optional[Tuple[int, int]], + origin: str, + trigger_mode: str = "step", + ) -> Dict[str, Any]: + if origin not in _ORIGINS: + raise ValueError(f"origin must be 'upper' or 'lower', got {origin!r}") + if trigger_mode not in ("step", "event"): + raise ValueError(f"trigger_mode must be 'step' or 'event', got {trigger_mode!r}") + + fuel_values = _as_array(fuel, "fuel") + if fuel_values.ndim != 2 or min(fuel_values.shape) < 2: + raise ValueError(f"fuel must be a 2-D raster (rows, cols) of at least 2x2, got shape {fuel_values.shape}") + if not np.all(np.isfinite(fuel_values)) or not np.all(fuel_values == np.round(fuel_values)): + raise ValueError("fuel must hold integer fuel codes (the Index column of the fuel table)") + if fuel_values.min() < 0 or fuel_values.max() > _MAX_FUEL_CODE: + raise ValueError(f"ForeFire fuel codes must lie in [0, {_MAX_FUEL_CODE}], got [{fuel_values.min():g}, {fuel_values.max():g}]") + self._check_fuel_codes(fuel_values) + + if np.ndim(cell_size) == 0: + dy = dx = float(cell_size) + else: + if len(cell_size) != 2: + raise ValueError(f"cell_size must be a number or (dy, dx), got {cell_size!r}") + dy, dx = (float(v) for v in cell_size) + if not (math.isfinite(dx) and math.isfinite(dy) and dx > 0 and dy > 0): + raise ValueError(f"cell_size must be positive, got {cell_size!r}") + rows, cols = fuel_values.shape + width, height = cols * dx, rows * dy + + duration = float(duration) + if not (math.isfinite(duration) and duration > 0): + raise ValueError(f"duration must be a positive number of seconds, got {duration!r}") + + if output_shape is None: + out_rows, out_cols = rows, cols + else: + if len(output_shape) != 2 or any(int(v) != v or v < 1 for v in output_shape): + raise ValueError(f"output_shape must be (rows, cols) of positive ints, got {output_shape!r}") + out_rows, out_cols = (int(v) for v in output_shape) + + ignitions = self._ignitions(ignition_mask, ignition_points, width, height, origin) + + altitude_layer = None + if altitude is not None: + altitude_values = _as_array(altitude, "altitude") + if altitude_values.ndim != 2 or not np.all(np.isfinite(altitude_values)): + raise ValueError(f"altitude must be a finite 2-D raster, got shape {altitude_values.shape}") + altitude_layer = _layer(altitude_values, origin) + + triggers: List[Tuple[float, float, float]] = [] + if wind is not None: + if wind_triggers is not None: + raise ValueError("give either wind=(u, v) or wind_triggers, not both") + if len(wind) != 2: + raise ValueError(f"wind must be (u, v), got {wind!r}") + triggers = [(0.0, float(wind[0]), float(wind[1]))] + elif wind_triggers is not None: + for trigger in wind_triggers: + if len(trigger) != 3: + raise ValueError(f"wind_triggers entries must be (t, u, v), got {trigger!r}") + t, u, v = (float(item) for item in trigger) + if not (math.isfinite(t) and 0.0 <= t < duration and math.isfinite(u) and math.isfinite(v)): + raise ValueError(f"wind trigger {trigger!r} must have 0 <= t < duration and finite (u, v)") + triggers.append((t, u, v)) + triggers.sort(key=lambda item: item[0]) + + wind_mode = "none" + wind_u_layer = wind_v_layer = None + if (wind_u is None) != (wind_v is None): + raise ValueError("wind_u and wind_v must be given together") + if wind_u is not None: + u_values = _as_array(wind_u, "wind_u") + v_values = _as_array(wind_v, "wind_v") + if u_values.shape != v_values.shape: + raise ValueError(f"wind_u and wind_v shapes differ: {u_values.shape} vs {v_values.shape}") + if not (np.all(np.isfinite(u_values)) and np.all(np.isfinite(v_values))): + raise ValueError("wind_u and wind_v must be finite") + if u_values.ndim == 2: + if triggers: + raise ValueError( + "2-D wind_u/wind_v are fixed wind fields; use (2, h, w) direction-coefficient " + "fields to combine spatial wind with wind/wind_triggers" + ) + wind_mode = "field" + elif u_values.ndim == 3 and u_values.shape[0] == 2: + wind_mode = "coefficients" + else: + raise ValueError( + "wind_u/wind_v must have shape (h, w) (wind field) or (2, h, w) (ForeFire " + f"direction coefficients), got {u_values.shape}" + ) + wind_u_layer = _layer(u_values, origin) + wind_v_layer = _layer(v_values, origin) + elif triggers: + # Unit direction fields, as in the official idealized examples: the effective wind is + # exactly the triggered (u, v). One value per output cell keeps ForeFire's bilinear + # interpolation defined everywhere except half an output cell along the domain edge. + shape = (2, out_rows, out_cols) + unit_u = np.zeros(shape) + unit_u[0] = 1.0 + unit_v = np.zeros(shape) + unit_v[1] = 1.0 + wind_mode = "coefficients" + wind_u_layer = _layer(unit_u, "lower") + wind_v_layer = _layer(unit_v, "lower") + + return { + "propagation_model": self.propagation_model, + "fuels_table": self.fuels_table, + "parameters": dict(self.parameters), + "atmo_nx": out_cols, + "atmo_ny": out_rows, + "width": width, + "height": height, + "duration": duration, + "fuel": _layer(fuel_values.astype(np.int32), origin), + "altitude": altitude_layer, + "wind_mode": wind_mode, + "wind_u": wind_u_layer, + "wind_v": wind_v_layer, + "ignitions": ignitions, + "wind_triggers": triggers, + "trigger_mode": trigger_mode, + } + + def _check_fuel_codes(self, fuel_values: np.ndarray) -> None: + table = self.fuels_table + if self.allow_unknown_fuels or table is None or "\n" not in table: + return # helper or built-in table: resolved inside ForeFire + lines = [line for line in table.strip().splitlines() if line.strip()] + header = [name.strip() for name in lines[0].split(";")] + if "Index" not in header: + raise ValueError("fuels_table must have an 'Index' column (ForeFire table format, ';'-separated)") + column = header.index("Index") + known = set() + for line in lines[1:]: + cells = line.split(";") + if len(cells) > column: + try: + known.add(int(float(cells[column]))) + except ValueError: + continue + unknown = sorted(set(np.unique(fuel_values).astype(np.int64).tolist()) - known) + if unknown: + raise ValueError( + f"fuel codes {unknown[:10]} are not in the Index column of fuels_table; ForeFire would give " + "them all-zero fuel properties (pass allow_unknown_fuels=True to accept that)" + ) + + @staticmethod + def _ignitions( + ignition_mask: Optional[ArrayLike], + ignition_points: Optional[Sequence[Sequence[float]]], + width: float, + height: float, + origin: str, + ) -> List[Tuple[float, float]]: + ignitions: List[Tuple[float, float]] = [] + if ignition_mask is not None: + mask = _as_array(ignition_mask, "ignition_mask", dtype=np.float64) + if mask.ndim != 2: + raise ValueError(f"ignition_mask must be a 2-D raster, got shape {mask.shape}") + mrows, mcols = mask.shape + for r, c in zip(*np.nonzero(mask > 0)): + x = (c + 0.5) * width / mcols + row_from_south = (mrows - 1 - r) if origin == "upper" else r + y = (row_from_south + 0.5) * height / mrows + ignitions.append((float(x), float(y))) + if ignition_points is not None: + for point in ignition_points: + if len(point) != 2: + raise ValueError(f"ignition points must be (x, y) in metres, got {point!r}") + x, y = float(point[0]), float(point[1]) + if not (0.0 < x < width and 0.0 < y < height): + raise ValueError(f"ignition point {point!r} is outside the domain (0, {width}) x (0, {height})") + ignitions.append((x, y)) + if not ignitions: + raise ValueError("give an ignition_mask with at least one True cell or ignition_points") + return ignitions + + +__all__ = [ + "FOREFIRE_CHECKED_VERSION", + "ForeFireNotInstalledError", + "ForeFireResult", + "ForeFireSimulator", + "forefire_available", + "forefire_version", +] diff --git a/pyhazards/tasks.py b/pyhazards/tasks.py index 594a9661..f5f88617 100644 --- a/pyhazards/tasks.py +++ b/pyhazards/tasks.py @@ -25,7 +25,7 @@ class HazardTask: name="earthquake.forecasting", hazard="earthquake", target="forecasting", - description="Earthquake forecasting over spatial or temporal forecast windows.", + description="Ground-motion wavefield forecasting: future frames of gridded velocity wavefields (not earthquake-occurrence forecasting).", ), "wildfire.danger": HazardTask( name="wildfire.danger", @@ -57,6 +57,12 @@ class HazardTask: target="track_intensity", description="Storm-track and intensity forecasting over lead-time horizons.", ), + "tc.intensity": HazardTask( + name="tc.intensity", + hazard="tc", + target="intensity", + description="Storm intensity (or intensity-change) forecasting at a single lead time.", + ), } diff --git a/pyproject.toml b/pyproject.toml index c37903ec..591e6bb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,30 @@ classifiers = [ "Operating System :: OS Independent", ] +[project.optional-dependencies] +# The `xgboost` model (XGBoost on the Kondylatos et al. 2022 instance features). It uses the library +# defaults, which changed in xgboost 2.0 (hist trees, estimated base_score); checked with 3.2.0. +# `pip install xgboost-cpu` provides the same module without the CUDA/NCCL wheels. +xgboost = ["xgboost>=2.0"] +# Reprojecting a LANDFIRE fuel raster onto a Track-O cache grid +# (pyhazards.datasets.wildfire.track_o_cache.align_fuel_to_grid); imported only there. +geo = ["rasterio>=1.3"] +# Loss-curve PNGs written by scripts/run_wildfire_track_o_baselines.py; skipped without it. +plot = ["matplotlib>=3.5"] +# WeatherBench 2 forecast stores (pyhazards.forecasts.weatherbench2): zarr and anonymous Google Cloud +# Storage access. The earth2studio runner (pyhazards.forecasts.earth2studio_runner) is not an extra: +# install earth2studio (Python >= 3.11) and the model's own extra yourself. +weather = ["zarr>=2.16", "gcsfs>=2023.1"] +# Prompted multimodal-LLM baselines (pyhazards.prompted, SmokeBench protocol). Pillow decodes the FIgLib +# frames and OpenCV draws the numbered grid overlay exactly as the SmokeBench authors' script does. +prompted = ["pillow>=9.1", "opencv-python-headless>=4.8"] +# Open-weight backends (Qwen2.5-VL, InternVL3-*-hf, Idefics2). InternVL3 -hf checkpoints need transformers +# 4.52+; transformers 5 needs torchvision for the Qwen2.5-VL processor (install the build matching torch). +prompted-hf = ["pillow>=9.1", "opencv-python-headless>=4.8", "transformers>=4.52", "accelerate>=0.26", "torchvision"] +# Closed backends through the official clients; API keys come from the environment only. +prompted-gemini = ["pillow>=9.1", "opencv-python-headless>=4.8", "google-genai>=1.0"] +prompted-openai = ["pillow>=9.1", "opencv-python-headless>=4.8", "openai>=1.0"] + [project.urls] Homepage = "https://labrai.github.io/PyHazards/" Repository = "https://github.com/LabRAI/PyHazards" diff --git a/scripts/build_wildfire_track_o_cache.py b/scripts/build_wildfire_track_o_cache.py new file mode 100644 index 00000000..5bc73409 --- /dev/null +++ b/scripts/build_wildfire_track_o_cache.py @@ -0,0 +1,115 @@ +"""Build a Track-O wildfire occurrence cache (daily weather + FIRMS labels + optional LANDFIRE fuel). + +Adapted from scripts/build_wildfire_2024_cache.py and scripts/align_wildfire_2024_fuel.py of +PyHazards PR #33 (runyangxu). The defaults reproduce that PR's 2024 setting: the 14 MERRA-2 surface +variables and the January-September / October / November-December split. + +Examples:: + + # MERRA-2 surface files written by `python -m pyhazards.datasets.merra2.inspection YYYYMMDD` + python scripts/build_wildfire_track_o_cache.py --cache-dir data/track_o_2024 \\ + --weather-dir Prithvi-WxC/data/merra-2 --weather-glob 'MERRA2_sfc_2024*.nc' \\ + --firms-dir data/firms_2024 --fuel-raster path/to/LF2024_FBFM13_CONUS.tif + + # add (or redo) the fuel layer of an existing cache + python scripts/build_wildfire_track_o_cache.py --cache-dir data/track_o_2024 --fuel-only \\ + --fuel-raster path/to/LF2024_FBFM40_CONUS.tif +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from pyhazards.datasets.wildfire.track_o import DEFAULT_SPLITS_2024, DEFAULT_WEATHER_VARS # noqa: E402 +from pyhazards.datasets.wildfire.track_o_cache import ( # noqa: E402 + DEFAULT_DATE_PATTERN, + add_fuel_to_cache, + build_track_o_cache, +) + + +def _range(text: str) -> tuple[str, str]: + start, sep, end = text.partition(":") + if not sep: + raise argparse.ArgumentTypeError(f"expected START:END (YYYY-MM-DD:YYYY-MM-DD), got {text!r}") + return start, end + + +def parse_args(argv=None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--cache-dir", required=True, help="Output directory of the cache.") + parser.add_argument("--weather-dir", help="Directory of daily weather NetCDF files.") + parser.add_argument("--weather-glob", default="*.nc*", help="Glob for weather files inside --weather-dir.") + parser.add_argument( + "--weather-date-pattern", + default=DEFAULT_DATE_PATTERN, + help="Regex whose first group is the file's date (YYYYMMDD or YYYY-MM-DD).", + ) + parser.add_argument("--weather-vars", default=",".join(DEFAULT_WEATHER_VARS), help="Comma-separated variables.") + parser.add_argument("--firms-dir", help="Directory of FIRMS CSV files (archive/NRT downloads or one file per day).") + parser.add_argument("--firms-glob", default="*.csv") + parser.add_argument( + "--firms-types", + default="0", + help="Comma-separated FIRMS 'type' values to keep (0 = presumed vegetation fire), or 'all'.", + ) + parser.add_argument("--train", type=_range, default=DEFAULT_SPLITS_2024["train"], help="START:END") + parser.add_argument("--val", type=_range, default=DEFAULT_SPLITS_2024["val"], help="START:END") + parser.add_argument("--test", type=_range, default=DEFAULT_SPLITS_2024["test"], help="START:END") + parser.add_argument("--fuel-raster", help="LANDFIRE fuel-model GeoTIFF (needs pyhazards[geo]).") + parser.add_argument( + "--fuel-nodata", + type=float, + default=-9999, + help="Source value left out of the fuel mode (LANDFIRE's -9999 fill); pass nan to use the file's nodata tag.", + ) + parser.add_argument("--fuel-only", action="store_true", help="Only (re)align the fuel layer of an existing cache.") + parser.add_argument("--limit-days", type=int, default=0, help="Write only the first N days (quick checks).") + args = parser.parse_args(argv) + if args.fuel_nodata != args.fuel_nodata: # nan: use the raster's own nodata tag + args.fuel_nodata = None + return args + + +def main(argv=None) -> int: + args = parse_args(argv) + if args.fuel_only: + if not args.fuel_raster: + raise SystemExit("--fuel-only needs --fuel-raster") + info = add_fuel_to_cache(args.cache_dir, args.fuel_raster, src_nodata=args.fuel_nodata) + print(json.dumps(info, indent=2)) + return 0 + if not args.weather_dir or not args.firms_dir: + raise SystemExit("--weather-dir and --firms-dir are required (unless --fuel-only)") + weather_files = sorted(Path(args.weather_dir).glob(args.weather_glob)) + firms_files = sorted(Path(args.firms_dir).glob(args.firms_glob)) + if not weather_files: + raise SystemExit(f"no weather files match {args.weather_dir}/{args.weather_glob}") + if not firms_files: + raise SystemExit(f"no FIRMS files match {args.firms_dir}/{args.firms_glob}") + firms_types = None if args.firms_types.strip().lower() == "all" else [int(v) for v in args.firms_types.split(",")] + summary = build_track_o_cache( + args.cache_dir, + weather_files, + firms_files, + weather_vars=[v.strip() for v in args.weather_vars.split(",") if v.strip()], + splits={"train": args.train, "val": args.val, "test": args.test}, + weather_date_pattern=args.weather_date_pattern, + firms_types=firms_types, + fuel_raster=args.fuel_raster, + fuel_nodata=args.fuel_nodata, + limit_days=args.limit_days, + ) + print(json.dumps(summary, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/fetch_oracles.py b/scripts/fetch_oracles.py new file mode 100644 index 00000000..27ae8986 --- /dev/null +++ b/scripts/fetch_oracles.py @@ -0,0 +1,110 @@ +"""Fetch the pinned reference implementations used by tests/oracle. + +usage: python scripts/fetch_oracles.py [--dest DIR] [NAME ...] + +DIR defaults to $PYHAZARDS_ORACLE_DIR, then ~/.cache/pyhazards-oracles. Git repositories are +checked out at the pinned commit; assets are downloaded and verified against their sha256 (saved +under the URL's file name, or ``filename`` when the URL has none, e.g. Google Drive downloads). +Assets marked ``large: true`` (multi-GB checkpoints) are fetched only when named explicitly or +with ``--large``; the tests that need them are skipped when they are absent. +Run the oracle tests afterwards with ``PYHAZARDS_ORACLE_DIR=DIR python -m pytest tests/oracle``. +""" + +from __future__ import annotations + +import argparse +import hashlib +import os +import subprocess +import sys +import urllib.request +import zipfile +from pathlib import Path + +import yaml + +MANIFEST = Path(__file__).resolve().parent.parent / "tests" / "oracle" / "repos.yaml" + + +def _git(*args: str, cwd: Path) -> str: + return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() + + +def fetch_repo(dest: Path, name: str, url: str, commit: str) -> None: + target = dest / name + if (target / ".git").exists(): + try: + if _git("rev-parse", "HEAD", cwd=target) == commit: + print(f"ok {name} @ {commit[:7]}") + return + except subprocess.CalledProcessError: + pass + target.mkdir(parents=True, exist_ok=True) + if not (target / ".git").exists(): + _git("init", "-q", cwd=target) + _git("remote", "add", "origin", url, cwd=target) + _git("fetch", "-q", "--depth", "1", "origin", commit, cwd=target) + _git("checkout", "-q", "--detach", "FETCH_HEAD", cwd=target) + head = _git("rev-parse", "HEAD", cwd=target) + if head != commit: + raise RuntimeError(f"{name}: expected {commit}, got {head}") + print(f"fetched {name} @ {commit[:7]}") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def fetch_asset(dest: Path, name: str, url: str, sha256: str, extract: bool = False, filename: str | None = None) -> None: + target = dest / name + target.mkdir(parents=True, exist_ok=True) + archive = target / (filename or Path(url.split("?")[0]).name) + if not archive.exists() or _sha256(archive) != sha256: + print(f"download {name}") + urllib.request.urlretrieve(url, archive) + actual = _sha256(archive) + if actual != sha256: + raise RuntimeError(f"{name}: sha256 mismatch ({actual})") + if extract and zipfile.is_zipfile(archive): + marker = target / ".extracted" + if not marker.exists(): + with zipfile.ZipFile(archive) as zf: + zf.extractall(target) + marker.write_text(sha256) + print(f"ok {name}") + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("names", nargs="*", help="repos/assets to fetch (default: all but large assets)") + parser.add_argument("--large", action="store_true", help="also fetch assets marked large: true") + parser.add_argument( + "--dest", + default=os.environ.get("PYHAZARDS_ORACLE_DIR", str(Path.home() / ".cache" / "pyhazards-oracles")), + ) + args = parser.parse_args(argv) + manifest = yaml.safe_load(MANIFEST.read_text(encoding="utf-8")) + dest = Path(args.dest).expanduser().resolve() + dest.mkdir(parents=True, exist_ok=True) + wanted = set(args.names) + known = set(manifest.get("repos", {})) | set(manifest.get("assets", {})) + unknown = wanted - known + if unknown: + print(f"unknown names: {sorted(unknown)}; known: {sorted(known)}", file=sys.stderr) + return 2 + for name, spec in manifest.get("repos", {}).items(): + if not wanted or name in wanted: + fetch_repo(dest, name, spec["url"], spec["commit"]) + for name, spec in manifest.get("assets", {}).items(): + if name in wanted or (not wanted and (args.large or not spec.get("large", False))): + fetch_asset(dest, name, spec["url"], spec["sha256"], spec.get("extract", False), spec.get("filename")) + print(f"oracles in {dest}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/render_prompted_docs.py b/scripts/render_prompted_docs.py new file mode 100644 index 00000000..cbb74c6c --- /dev/null +++ b/scripts/render_prompted_docs.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import argparse +from pathlib import Path + +from pyhazards.prompted.catalog import sync_prompted_docs + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Render docs/source/pyhazards_prompted.rst from the prompted-baseline cards." + ) + parser.add_argument( + "--check", + action="store_true", + help="Fail if the generated page is out of date instead of writing it.", + ) + args = parser.parse_args() + + changes = sync_prompted_docs(check=args.check) + if changes: + action = "would update" if args.check else "updated" + print(f"Prompted baseline docs {action}:") + for path in changes: + print(f" - {Path(path)}") + return 1 if args.check else 0 + + print("Prompted baseline docs are in sync.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/reproduce_tcbench_tracks.py b/scripts/reproduce_tcbench_tracks.py new file mode 100644 index 00000000..b0939874 --- /dev/null +++ b/scripts/reproduce_tcbench_tracks.py @@ -0,0 +1,93 @@ +"""Reproduce TCBench's published Pangu-Weather cyclone errors end to end from the raw forecast fields. + +TCBench's official notebook (TCBench_Alpha ``dev/Getting_Started.ipynb``) prints the direct position +error (DPE_GCD, km) and absolute wind / pressure errors of sample rows of its 2023 Pangu-Weather +evaluation. For each printed row this script + +1. reads the TempestExtremes variables of the raw Pangu-Weather forecast from TCBench's Hugging Face + dataset (pinned revision; about 200 MB of range requests per forecast, nothing stored), +2. tracks cyclones with :mod:`pyhazards.forecasts.tempest` and checks the tracks against TCBench's + released ``unmatched_tracks`` file (byte for byte), +3. matches tracks to IBTrACS storms (HuracanPy's rule, as TCBench) and +4. scores the row with ``protocol="tcbench"`` against NCEI IBTrACS v04r01, downloaded per basin. + +Usage:: + + python scripts/reproduce_tcbench_tracks.py --cache data/tcbench_repro + +Rows reproduce exactly when NCEI's IBTrACS still has the positions TCBench evaluated against (NCEI +revises best tracks; Cheneso's 2023-01-18 00 UTC longitude changed from 55.8 to 55.9 since). +""" + +from __future__ import annotations + +import argparse +import sys +import tempfile +from pathlib import Path + +import pandas as pd + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +PUBLISHED = [ + # basin, SID, initial time, valid time, DPE_GCD (km), AE_wind (kt), AE_pressure (hPa) + ("SI", "2023013S08081", "2023-01-15 12:00", "2023-01-18 00:00", 216.013123, 4.770411, 6.5610), + ("EP", "2023290N12256", "2023-10-19 12:00", "2023-10-20 00:00", 18.454374, 62.780767, 39.9856), + ("NI", "2023129N08091", "2023-05-07 00:00", "2023-05-12 00:00", 424.145817, 25.624799, 9.5378), + ("NA", "2023193N37305", "2023-07-16 12:00", "2023-07-20 00:00", 302.565885, 21.254614, 9.4880), +] + + +def main(argv=None) -> int: + from pyhazards.datasets.tc.ibtracs import download_ibtracs, read_ibtracs + from pyhazards.forecasts import ( + download_tcbench_file, + forecast_track_errors, + read_tcbench_fields, + tcbench_ibtracs, + tcbench_path, + tempest_forecast_tracks, + write_stitchnodes_csv, + ) + + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--cache", default="data/tcbench_repro", help="directory for IBTrACS and TCBench CSV files") + args = parser.parse_args(argv) + cache = Path(args.cache) + basins = sorted({row[0] for row in PUBLISHED}) + ibtracs = pd.concat( + [read_ibtracs(download_ibtracs(cache / "ibtracs", subset=b), ["USA_WIND", "USA_PRES", "TRACK_TYPE"]) for b in basins], + ignore_index=True, + ) + ibtracs = tcbench_ibtracs(ibtracs, 2023) + ok = True + for basin, sid, init, valid, dpe, ae_wind, ae_pres in PUBLISHED: + fields = read_tcbench_fields("pangu", init) + table, tracks = tempest_forecast_tracks(fields, ibtracs, init, return_tracks=True) + released = download_tcbench_file(tcbench_path("pangu", "unmatched", init), cache) + with tempfile.TemporaryDirectory() as tmp: + ours = Path(tmp) / "tracks.csv" + write_stitchnodes_csv(tracks, ours) + identical = ours.read_text() == released.read_text() + errors = forecast_track_errors(table, ibtracs, protocol="tcbench") + row = errors[(errors["SID"] == sid) & (errors["valid_time"] == pd.Timestamp(valid))] + if row.empty: + print(f"{sid} {init} -> {valid}: storm not matched / no row") + ok = False + continue + row = row.iloc[0] + print( + f"{sid} init {init} valid {valid}: tracks identical to TCBench: {identical}; " + f"forecast ({row.lat:.2f}, {row.lon:.2f}) vs IBTrACS ({row.ref_lat}, {row.ref_lon}); " + f"DPE {row.track_error_km:.6f} km (published {dpe}); " + f"AE wind {abs(row.wind_error_kt):.6f} kt (published {ae_wind}); " + f"AE pressure {abs(row.pres_error_hpa):.4f} hPa (published {ae_pres})" + ) + ok &= identical + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/review_model_pr.py b/scripts/review_model_pr.py index 76b682d1..285295ec 100644 --- a/scripts/review_model_pr.py +++ b/scripts/review_model_pr.py @@ -256,7 +256,11 @@ def main() -> int: "Smoke test failed for `{name}`: {error}".format(name=name, error=exc) ) else: - if not smoke["ok"]: + if smoke.get("skipped"): + warnings.append( + "Smoke test for `{name}` was skipped: {reason}.".format(name=name, reason=smoke["skipped"]) + ) + elif not smoke["ok"]: blockers.append( "Smoke test shape mismatch for `{name}`: expected {expected}, got {actual}.".format( name=name, diff --git a/scripts/run_wildfire_track_o_baselines.py b/scripts/run_wildfire_track_o_baselines.py new file mode 100644 index 00000000..70611d65 --- /dev/null +++ b/scripts/run_wildfire_track_o_baselines.py @@ -0,0 +1,458 @@ +"""Train and score registry models on a Track-O wildfire occurrence cache. + +Adapted from ``pyhazards/benchmarks/wildfire_benchmark/real_runner.py`` and +``scripts/run_wildfire_2024_real_baselines.py`` of PyHazards PR #33 (runyangxu). The PR trained its +own model copies; this script builds the models from the PyHazards registry instead: + +- ``random_forest`` and ``xgboost`` (tabular layout, fitted with ``model.fit``), +- ``logistic_regression`` (raster layout: the WildfireSpreadTS per-pixel 3x3 linear model; PR #33 + used scikit-learn ``LogisticRegression`` on the tabular rows instead), +- ``unet`` (raster layout, the Ronneberger et al. U-Net with ``padding="same"`` and one output + channel, so the grid is cropped to a multiple of 16), +- ``convlstm`` (temporal layout), +- any other registry model given with ``--layout name=raster|temporal|tabular``. + +Gradient-trained models use PR #33's protocol: AdamW (lr 1e-3, weight decay 1e-4), BCE-with-logits +with ``pos_weight = negatives / positives`` of the training split clipped at 50, early stopping on +validation average precision (patience 20, min delta 1e-4) and the best epoch's weights. Test +scores come from the ``wildfire`` benchmark (``wildfire.danger``: accuracy, macro F1, ROC AUC, +PR AUC), plus Brier score, log loss, expected calibration error (15 bins) and the mean absolute +day-to-day change of the predicted probabilities between consecutive days (a smoothness +diagnostic, not a skill score). PR #33's "normalized consistency score" (1 minus that change) is +not reported, and LightGBM is not run because PyHazards has no LightGBM model. + +Per model and seed, ``//seed_/`` gets ``history.csv``, ``metrics.json``, +``experiment_setting.json``, the benchmark report and, when matplotlib is installed +(``pip install 'pyhazards[plot]'``), ``loss_curve.png``. ``/summary.json`` has the mean +and standard deviation over seeds (PR #33 used seeds 42 for the dry run and 42,52,62,72,82 for the +final runs). + +Example:: + + python scripts/run_wildfire_track_o_baselines.py --cache-dir data/track_o_2024 \\ + --output-dir runs/track_o_2024 --models logistic_regression,random_forest,unet,convlstm --seeds 42 +""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +import math +import platform +import sys +import time +from datetime import date +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +REPO_ROOT = Path(__file__).resolve().parent.parent +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +import numpy as np # noqa: E402 +import torch # noqa: E402 +import torch.nn as nn # noqa: E402 +from sklearn.metrics import average_precision_score # noqa: E402 + +import pyhazards # noqa: E402 +from pyhazards.benchmarks import run_benchmark # noqa: E402 +from pyhazards.configs import BenchmarkConfig, DatasetRef, ExperimentConfig, ModelRef, ReportConfig # noqa: E402 +from pyhazards.datasets import load_dataset # noqa: E402 +from pyhazards.models import build_model # noqa: E402 +from pyhazards.utils.hardware import auto_device # noqa: E402 + +LAYOUT_DATASETS = { + "raster": "wildfire_track_o_raster", + "temporal": "wildfire_track_o_temporal", + "tabular": "wildfire_track_o_tabular", +} +MODEL_LAYOUTS = { + "logistic_regression": "raster", + "unet": "raster", + "convlstm": "temporal", + "random_forest": "tabular", + "xgboost": "tabular", +} +MODEL_KWARGS: Dict[str, Dict[str, Any]] = { + # Zero-padded 3x3 convolutions (a PyHazards option of the paper U-Net) and one logit per cell. + "unet": {"padding": "same", "out_channels": 1}, +} +DEFAULT_MODELS = "logistic_regression,random_forest,unet,convlstm" + + +# --------------------------------------------------------------------------------------------- +# Metrics +# --------------------------------------------------------------------------------------------- +def probability_diagnostics(y_true: np.ndarray, prob: np.ndarray, n_bins: int = 15) -> Dict[str, float]: + """Brier score, log loss and expected calibration error (equal-width bins) of binary probabilities.""" + y = np.asarray(y_true, dtype=np.float64).reshape(-1) + p = np.asarray(prob, dtype=np.float64).reshape(-1) + if y.shape != p.shape: + raise ValueError(f"y_true and prob differ in size: {y.shape} vs {p.shape}") + clipped = np.clip(p, 1e-7, 1.0 - 1e-7) + bins = np.minimum((p * n_bins).astype(np.int64), n_bins - 1) + ece = 0.0 + for b in range(n_bins): + in_bin = bins == b + if in_bin.any(): + ece += in_bin.mean() * abs(y[in_bin].mean() - p[in_bin].mean()) + return { + "brier": float(np.mean((p - y) ** 2)), + "nll": float(-np.mean(y * np.log(clipped) + (1.0 - y) * np.log(1.0 - clipped))), + "ece": float(ece), + } + + +def mean_day_to_day_change(prob_by_day: np.ndarray, dates: Sequence[str]) -> float: + """Mean |p(day) - p(day - 1)| over cells and over pairs of consecutive calendar days. + + ``prob_by_day`` is ``(n_days, ...)`` in the order of ``dates``. Returns NaN without such a pair. + """ + flat = np.asarray(prob_by_day, dtype=np.float64).reshape(len(dates), -1) + parsed = [date.fromisoformat(str(day)) for day in dates] + changes = [ + np.mean(np.abs(flat[i] - flat[i - 1])) for i in range(1, len(parsed)) if (parsed[i] - parsed[i - 1]).days == 1 + ] + return float(np.mean(changes)) if changes else float("nan") + + +# --------------------------------------------------------------------------------------------- +# Training +# --------------------------------------------------------------------------------------------- +def _is_estimator(model: nn.Module) -> bool: + return hasattr(model, "custom_fit_reason") and hasattr(model, "fit") + + +@torch.no_grad() +def _predict_logits(model: nn.Module, inputs: torch.Tensor, batch_size: int, device: torch.device) -> torch.Tensor: + model.eval() + return torch.cat([model(chunk.to(device)).float().cpu() for chunk in torch.split(inputs, batch_size)]) + + +def _positive_probability(model: nn.Module, inputs: torch.Tensor, batch_size: int, device: torch.device) -> np.ndarray: + if _is_estimator(model): + return np.asarray(model.predict_proba(inputs))[:, 1] + return torch.sigmoid(_predict_logits(model, inputs, batch_size, device)).numpy() + + +def train_gradient_model( + model: nn.Module, + bundle, + *, + seed: int, + device: torch.device, + max_epochs: int, + patience: int, + min_delta: float = 1e-4, + lr: float = 1e-3, + weight_decay: float = 1e-4, + batch_size: int = 4, + pos_weight_clip: float = 50.0, +) -> Dict[str, Any]: + train, val = bundle.get_split("train"), bundle.get_split("val") + positives = float(train.targets.sum()) + negatives = float(train.targets.numel()) - positives + pos_weight = min(negatives / max(positives, 1.0), pos_weight_clip) + loss_fn = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(pos_weight, device=device)) + model.to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay) + loader = torch.utils.data.DataLoader( + torch.utils.data.TensorDataset(train.inputs, train.targets), + batch_size=batch_size, + shuffle=True, + generator=torch.Generator().manual_seed(seed), + ) + history: List[Dict[str, float]] = [] + best_score, best_epoch, best_state, waited = -math.inf, 0, None, 0 + for epoch in range(1, max_epochs + 1): + model.train() + total, count = 0.0, 0 + for inputs, targets in loader: + inputs, targets = inputs.to(device), targets.to(device) + logits = model(inputs) + if logits.shape != targets.shape: + raise ValueError( + f"model output {tuple(logits.shape)} does not match the targets {tuple(targets.shape)}; " + "Track-O needs one logit per cell (out_channels=1, output size = input size)." + ) + loss = loss_fn(logits, targets) + optimizer.zero_grad() + loss.backward() + optimizer.step() + total += float(loss.detach()) * inputs.shape[0] + count += inputs.shape[0] + val_logits = _predict_logits(model, val.inputs, batch_size, device) + val_loss = float(loss_fn(val_logits.to(device), val.targets.to(device))) + val_targets = val.targets.numpy().reshape(-1) > 0.5 + val_ap = ( + float(average_precision_score(val_targets, torch.sigmoid(val_logits).numpy().reshape(-1))) + if val_targets.any() + else 0.0 + ) + history.append({"step": epoch, "train_loss": total / max(count, 1), "val_loss": val_loss, "val_average_precision": val_ap}) + if val_ap > best_score + min_delta: + best_score, best_epoch, waited = val_ap, epoch, 0 + best_state = copy.deepcopy(model.state_dict()) + else: + waited += 1 + if waited >= patience: + break + if best_state is not None: + model.load_state_dict(best_state) + return {"history": history, "best_step": best_epoch, "steps_run": len(history), "pos_weight": pos_weight, "train_unit": "epoch"} + + +def fit_estimator(model: nn.Module, bundle) -> Dict[str, Any]: + train, val = bundle.get_split("train"), bundle.get_split("val") + model.fit(train.inputs, train.targets) + train_nll = probability_diagnostics(train.targets.numpy(), model.predict_proba(train.inputs)[:, 1])["nll"] + val_nll = probability_diagnostics(val.targets.numpy(), model.predict_proba(val.inputs)[:, 1])["nll"] + return { + "history": [{"step": 1, "train_loss": train_nll, "val_loss": val_nll}], + "best_step": 1, + "steps_run": 1, + "pos_weight": None, + "train_unit": "fit", + } + + +# --------------------------------------------------------------------------------------------- +# Artifacts +# --------------------------------------------------------------------------------------------- +def _write_json(path: Path, payload: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8") + + +def _write_history(path: Path, rows: List[Dict[str, float]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0].keys())) + writer.writeheader() + writer.writerows(rows) + + +def _plot_history(path: Path, rows: List[Dict[str, float]], title: str) -> str: + try: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.ticker import MaxNLocator + except ImportError: + return "skipped: matplotlib is not installed (pip install 'pyhazards[plot]')" + steps = [row["step"] for row in rows] + fig, ax = plt.subplots(figsize=(7, 4)) + ax.plot(steps, [row["train_loss"] for row in rows], marker="o", label="train loss") + ax.plot(steps, [row["val_loss"] for row in rows], marker="s", label="validation loss") + ax.set_xlabel("epoch") + ax.xaxis.set_major_locator(MaxNLocator(integer=True)) + ax.set_ylabel("loss") + ax.set_title(title) + ax.grid(alpha=0.3) + ax.legend() + fig.tight_layout() + fig.savefig(path, dpi=150) + plt.close(fig) + return str(path) + + +def _probability_maps(prob: np.ndarray, split) -> np.ndarray: + days = len(split.metadata["dates"]) + return prob.reshape(days, -1) + + +# --------------------------------------------------------------------------------------------- +# Driver +# --------------------------------------------------------------------------------------------- +def dataset_params(layout: str, args: argparse.Namespace) -> Dict[str, Any]: + params: Dict[str, Any] = {"micro": True} if args.micro else {"cache_dir": args.cache_dir} + params.update( + { + "train_limit_days": args.train_limit_days or None, + "val_limit_days": args.val_limit_days or None, + "test_limit_days": args.test_limit_days or None, + } + ) + if layout == "raster": + params.update({"downsample_factor": args.raster_downsample, "spatial_multiple": 16}) + elif layout == "temporal": + params.update({"downsample_factor": args.temporal_downsample, "history": args.temporal_history}) + else: + params.update({"downsample_factor": args.tabular_downsample}) + return params + + +def run_one(model_name: str, layout: str, bundle, params: Dict[str, Any], seed: int, args, device, out: Path) -> Dict[str, Any]: + torch.manual_seed(seed) + np.random.seed(seed) + kwargs = dict(MODEL_KWARGS.get(model_name, {})) + if layout == "tabular": + kwargs.setdefault("random_state", seed) + kwargs.setdefault("n_jobs", args.n_jobs) + else: + kwargs["in_channels"] = int(bundle.feature_spec.channels) + kwargs.update(args.model_kwargs.get(model_name, {})) + task = "classification" if layout == "tabular" else "segmentation" + model = build_model(name=model_name, task=task, **kwargs) + + started = time.time() + if _is_estimator(model): + fit = fit_estimator(model, bundle) + else: + fit = train_gradient_model( + model, + bundle, + seed=seed, + device=device, + max_epochs=args.max_epochs, + patience=args.patience, + lr=args.lr, + weight_decay=args.weight_decay, + batch_size=args.batch_size, + ) + seconds = time.time() - started + + seed_dir = out / model_name / f"seed_{seed}" + config = ExperimentConfig( + benchmark=BenchmarkConfig( + name="wildfire", + hazard_task="wildfire.danger", + metrics=["accuracy", "macro_f1", "auc", "pr_auc"], + eval_split="test", + params={"batch_size": args.batch_size}, + ), + dataset=DatasetRef(name=LAYOUT_DATASETS[layout], params=params), + model=ModelRef(name=model_name, task=task, params=kwargs), + report=ReportConfig(output_dir=str(seed_dir / "report"), formats=["json"]), + seed=seed, + ) + benchmark = run_benchmark("wildfire", model, bundle, config) + + scores: Dict[str, Dict[str, float]] = {} + for split_name in ("val", "test"): + split = bundle.get_split(split_name) + prob = _positive_probability(model, split.inputs, args.batch_size, device) + y_true = split.targets.numpy().reshape(-1) + split_scores = probability_diagnostics(y_true, prob) + split_scores["average_precision"] = float(average_precision_score(y_true > 0.5, prob.reshape(-1))) if (y_true > 0.5).any() else 0.0 + split_scores["mean_day_to_day_change"] = mean_day_to_day_change(_probability_maps(prob, split), split.metadata["dates"]) + scores[split_name] = split_scores + test_metrics = {**benchmark.metrics, **{k: v for k, v in scores["test"].items() if k != "average_precision"}} + + _write_history(seed_dir / "history.csv", fit["history"]) + curve = ( + _plot_history(seed_dir / "loss_curve.png", fit["history"], f"{model_name} (seed {seed})") + if fit["train_unit"] == "epoch" + else "skipped: fitted in one step" + ) + metrics = { + "test": test_metrics, + "val": scores["val"], + "best_step": fit["best_step"], + "steps_run": fit["steps_run"], + "train_unit": fit["train_unit"], + "loss_curve": curve, + } + _write_json(seed_dir / "metrics.json", metrics) + _write_json( + seed_dir / "experiment_setting.json", + { + "model": {"name": model_name, "task": task, "build_kwargs": kwargs, "layout": layout}, + "dataset": {"name": LAYOUT_DATASETS[layout], "params": params, "metadata": {k: v for k, v in bundle.metadata.items() if k not in ("lat", "lon")}}, + "training": { + "seed": seed, + "device": str(device), + "max_epochs": args.max_epochs, + "patience": args.patience, + "lr": args.lr, + "weight_decay": args.weight_decay, + "batch_size": args.batch_size, + "pos_weight": fit["pos_weight"], + "seconds": seconds, + }, + "software": { + "pyhazards": pyhazards.__version__, + "torch": torch.__version__, + "numpy": np.__version__, + "python": platform.python_version(), + }, + }, + ) + return test_metrics + + +def parse_args(argv=None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Train and score registry models on a Track-O cache.") + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--cache-dir", help="Cache written by scripts/build_wildfire_track_o_cache.py.") + source.add_argument("--micro", action="store_true", help="Use the synthetic micro cache (smoke runs).") + parser.add_argument("--output-dir", required=True) + parser.add_argument("--models", default=DEFAULT_MODELS, help="Comma-separated registry model names.") + parser.add_argument("--layout", action="append", default=[], help="name=raster|temporal|tabular for other models.") + parser.add_argument("--model-kwargs", default="{}", help='JSON, e.g. {"random_forest": {"n_estimators": 500}}.') + parser.add_argument("--seeds", default="42", help="Comma-separated seeds.") + parser.add_argument("--device", default=None) + parser.add_argument("--max-epochs", type=int, default=120) + parser.add_argument("--patience", type=int, default=20) + parser.add_argument("--lr", type=float, default=1e-3) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--batch-size", type=int, default=4) + parser.add_argument("--n-jobs", type=int, default=8, help="Threads for tree models.") + parser.add_argument("--raster-downsample", type=int, default=4) + parser.add_argument("--temporal-downsample", type=int, default=8) + parser.add_argument("--temporal-history", type=int, default=6) + parser.add_argument("--tabular-downsample", type=int, default=8) + parser.add_argument("--train-limit-days", type=int, default=0) + parser.add_argument("--val-limit-days", type=int, default=0) + parser.add_argument("--test-limit-days", type=int, default=0) + args = parser.parse_args(argv) + args.model_kwargs = json.loads(args.model_kwargs) + return args + + +def main(argv=None) -> int: + args = parse_args(argv) + layouts = dict(MODEL_LAYOUTS) + for item in args.layout: + name, _, layout = item.partition("=") + if layout not in LAYOUT_DATASETS: + raise SystemExit(f"--layout expects name=raster|temporal|tabular, got {item!r}") + layouts[name] = layout + models = [name.strip() for name in args.models.split(",") if name.strip()] + unknown = [name for name in models if name not in layouts] + if unknown: + raise SystemExit(f"no layout known for {unknown}; pass --layout name=raster|temporal|tabular") + seeds = [int(seed) for seed in args.seeds.split(",") if seed.strip()] + device = torch.device(args.device) if args.device else auto_device() + out = Path(args.output_dir) + + bundles: Dict[str, Any] = {} + params_by_layout: Dict[str, Dict[str, Any]] = {} + for layout in sorted({layouts[name] for name in models}): + params_by_layout[layout] = dataset_params(layout, args) + bundles[layout] = load_dataset(LAYOUT_DATASETS[layout], **params_by_layout[layout]).load() + + summary: Dict[str, Any] = {"source": "micro_synthetic" if args.micro else args.cache_dir, "seeds": seeds, "models": {}} + for name in models: + layout = layouts[name] + per_seed = [ + run_one(name, layout, bundles[layout], params_by_layout[layout], seed, args, device, out) for seed in seeds + ] + keys = sorted(per_seed[0]) + summary["models"][name] = { + "layout": layout, + "per_seed": per_seed, + "mean": {key: float(np.mean([row[key] for row in per_seed])) for key in keys}, + "std": {key: float(np.std([row[key] for row in per_seed])) for key in keys}, + } + print(f"[done] {name}: " + ", ".join(f"{k}={summary['models'][name]['mean'][k]:.4f}" for k in keys)) + _write_json(out / "summary.json", summary) + print(f"[done] results in {out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/smoke_test_models.py b/scripts/smoke_test_models.py index 01dea5ff..1cce69ca 100644 --- a/scripts/smoke_test_models.py +++ b/scripts/smoke_test_models.py @@ -40,6 +40,9 @@ def main() -> int: for name in selected: card = mapping[name] result = run_smoke_test(card) + if result.get("skipped"): + print("[SKIP] {name}: {reason}".format(name=card.model_name, reason=result["skipped"])) + continue status = "PASS" if result["ok"] else "FAIL" print( "[{status}] {name}: expected {expected}, got {actual}".format( diff --git a/scripts/train_hydrographnet.py b/scripts/train_hydrographnet.py index 9d7ad14e..b66c4f4a 100644 --- a/scripts/train_hydrographnet.py +++ b/scripts/train_hydrographnet.py @@ -1,72 +1,82 @@ #!/usr/bin/env python3 +"""Train HydroGraphNet as the PhysicsNeMo example does, then score autoregressive rollouts. -import torch -import torch.nn.functional as F - -from pyhazards.engine import Trainer -from pyhazards.models import build_model -from pyhazards.datasets import graph_collate -from pyhazards.metrics import RegressionMetrics - -from pyhazards.data.load_hydrograph_data import load_hydrograph_data - - -def main(): - torch.manual_seed(0) - - bundle = load_hydrograph_data( - era5_path="pyhazards/data/era5_subset", - ) +Recipe of examples/weather/flood_modeling/hydrographnet (train.py, conf/config.yaml): batch size 1, Adam +with learning rate 1e-4 (the configured weight decay is not passed to the optimizer), the learning rate +multiplied by 0.9999979 after every batch, 100 epochs, loss = MSE + 1.0 * physics (volume continuity, +delta_t 1200 s), noise_type "none"; inference rolls out 30 steps per test hydrograph. - train_split = "train" +usage: + python scripts/train_hydrographnet.py --data-dir /data/HydroGraphNet --test-ids test.txt + python scripts/train_hydrographnet.py --synthetic --epochs 1 # smoke run on flood_mesh_synthetic +""" - # Infer dimensions from dataset - sample_x, sample_y = bundle.splits[train_split].inputs[0] +from __future__ import annotations - x_tensor = sample_x["x"] +import argparse +import json - node_feats = x_tensor.shape[2] - out_dim = 1 - - print("Dataset shapes:") - print(" x:", x_tensor.shape) - print(" y:", sample_y.shape) - - # Model - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=node_feats, - edge_in_dim=3, - out_dim=out_dim, - ) - # Optimizer + loss - optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) - - def loss_fn(pred, target): - return F.mse_loss(pred, target) - - # Trainer - trainer = Trainer(model=model, metrics=[RegressionMetrics()]) +import torch +from torch.utils.data import DataLoader - trainer.fit( - bundle, - train_split=train_split, - val_split=None, - optimizer=optimizer, - loss_fn=loss_fn, - batch_size=1, - max_epochs=5, - collate_fn=graph_collate, - ) - metrics = trainer.evaluate( - bundle, - split=train_split, - batch_size=1, - collate_fn=graph_collate, - ) - print("Evaluation metrics:", metrics) +from pyhazards.benchmarks.flood import evaluate_inundation +from pyhazards.datasets import load_dataset +from pyhazards.datasets.flood.hydrograph import hydrograph_collate +from pyhazards.models import build_model +from pyhazards.models.hydrographnet import HydroGraphNetLoss + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--data-dir", help="unzipped HydroGraphNet.zip (Zenodo 14969507)") + parser.add_argument("--test-ids", help="file or comma-separated list of test hydrograph ids") + parser.add_argument("--synthetic", action="store_true", help="use flood_mesh_synthetic instead of real data") + parser.add_argument("--epochs", type=int, default=100) + parser.add_argument("--lr", type=float, default=1e-4) + parser.add_argument("--lr-decay-rate", type=float, default=0.9999979) + parser.add_argument("--physics-loss-weight", type=float, default=1.0) + parser.add_argument("--rollout-length", type=int, default=30) + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args(argv) + + torch.manual_seed(args.seed) + if args.synthetic: + data = load_dataset("flood_mesh_synthetic", micro=True).load() + else: + if not args.data_dir or not args.test_ids: + parser.error("--data-dir and --test-ids are required (or pass --synthetic)") + test_ids = args.test_ids if args.test_ids.endswith(".txt") else args.test_ids.split(",") + data = load_dataset( + "hydrographnet_white_river", data_dir=args.data_dir, test_ids=test_ids, rollout_length=args.rollout_length + ).load() + + model = build_model("hydrographnet", task="regression").to(args.device) + optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda step: args.lr_decay_rate**step) + criterion = HydroGraphNetLoss(physics_loss_weight=args.physics_loss_weight, delta_t=1200.0) + loader = DataLoader(data.get_split("train").inputs, batch_size=1, shuffle=True, collate_fn=hydrograph_collate) + + for epoch in range(args.epochs): + model.train() + total, batches = 0.0, 0 + for batch, target in loader: + physics = {key: value.to(args.device) for key, value in batch.pop("physics").items()} + batch = {key: value.to(args.device) for key, value in batch.items()} + optimizer.zero_grad() + loss, _ = criterion(model(batch), target.to(args.device), physics, batch["batch"]) + loss.backward() + optimizer.step() + scheduler.step() + total += float(loss.detach()) + batches += 1 + print(f"epoch {epoch}: mean loss {total / max(batches, 1):.4e}") + + model.eval() + metrics, extra = evaluate_inundation(model, data, "test") + print(json.dumps({"metrics": metrics, "rollout_rmse_per_step_m": extra.get("rollout_rmse_per_step_m")}, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/scripts/verify_table_entries.py b/scripts/verify_table_entries.py index 74b65e8c..d15b2a1c 100644 --- a/scripts/verify_table_entries.py +++ b/scripts/verify_table_entries.py @@ -65,6 +65,9 @@ def verify_models() -> bool: print("\n=== Model Table Verification ===") for card in load_model_cards(): result = run_smoke_test(card) + if result.get("skipped"): + print(f"[model] {card.model_name}: skipped ({result['skipped']})") + continue print( f"[model] {card.model_name}: expected={result['expected_shape']} " f"actual={result['actual_shape']}" diff --git a/scripts/wildfire_aspp_NDWS.py b/scripts/wildfire_aspp_NDWS.py index ef6d3b6f..b32c24c0 100644 --- a/scripts/wildfire_aspp_NDWS.py +++ b/scripts/wildfire_aspp_NDWS.py @@ -27,11 +27,7 @@ import torch.nn as nn import lightning.pytorch as pl from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler -from pyhazards.models.wildfire_aspp import WildfireASPP, TverskyLoss - -# ✅ Use the PyHazards model registry from pyhazards.models import build_model -# keep your loss from pyhazards.models.wildfire_aspp import TverskyLoss @@ -282,14 +278,10 @@ def __init__( # ✅ build from registry (your CNN+ASPP implemented in PyHazards) self.model = build_model( - name="wildfire_cnn_aspp", + name="wildfire_aspp", task="segmentation", in_channels=int(in_channels), - base_channels=32, - aspp_channels=32, - dilations=(1, 3, 6, 12), - dropout=0.0, - ) + ) capped = min(float(pos_weight_value), 25.0) self.register_buffer("pos_weight", torch.tensor([capped], dtype=torch.float32)) @@ -475,9 +467,10 @@ def main(): ap.add_argument("--num_workers", type=int, default=0) ap.add_argument("--lr", type=float, default=4e-4) - ap.add_argument("--loss", type=str, default="bce_tversky", choices=["bce", "tversky", "bce_tversky"]) - ap.add_argument("--tversky_alpha", type=float, default=0.8) - ap.add_argument("--tversky_beta", type=float, default=0.2) + # Marjani et al. (2024) train with the Tversky loss only: 0.7 on false negatives, 0.3 on false positives. + ap.add_argument("--loss", type=str, default="tversky", choices=["bce", "tversky", "bce_tversky"]) + ap.add_argument("--tversky_alpha", type=float, default=0.3, help="weight on false positives") + ap.add_argument("--tversky_beta", type=float, default=0.7, help="weight on false negatives") ap.add_argument("--use_pos_weight", action="store_true", help="Use BCE pos_weight (often hurts precision)") ap.add_argument("--bce_weight", type=float, default=0.5) diff --git a/test.py b/test.py index 99f33f23..f612d3ab 100644 --- a/test.py +++ b/test.py @@ -5,8 +5,8 @@ import torch from torch.utils.data import DataLoader -from pyhazards.data.load_hydrograph_data import load_hydrograph_data -from pyhazards.datasets import graph_collate +from pyhazards.datasets import load_dataset +from pyhazards.datasets.flood import hydrograph_collate from pyhazards.engine import Trainer from pyhazards.metrics import RegressionMetrics from pyhazards.models import build_model @@ -32,14 +32,14 @@ def main() -> None: ) device = torch.device("cuda:0") - print("== PyHazards GPU smoke test (ERA5 + HydroGraphNet) ==") + print("== PyHazards GPU smoke test (synthetic mesh hydrographs + HydroGraphNet) ==") print(f"PyTorch version: {torch.__version__}") print(f"CUDA runtime in torch: {torch.version.cuda}") print(f"Using device: {device} ({torch.cuda.get_device_name(0)})") - data = load_hydrograph_data("pyhazards/data/era5_subset", max_nodes=50) + data = load_dataset("flood_mesh_synthetic", micro=True).load() assert "train" in data.splits, "Expected 'train' split in loaded data." - assert data.feature_spec.input_dim == 2, f"Unexpected input_dim: {data.feature_spec.input_dim}" + assert data.feature_spec.input_dim == 16, f"Unexpected input_dim: {data.feature_spec.input_dim}" assert data.label_spec.task_type == "regression", f"Unexpected task type: {data.label_spec.task_type}" train_inputs = data.get_split("train").inputs @@ -48,18 +48,12 @@ def main() -> None: print(f"Feature spec: {data.feature_spec}") print(f"Label spec: {data.label_spec}") - model = build_model( - name="hydrographnet", - task="regression", - node_in_dim=2, - edge_in_dim=3, - out_dim=1, - ) + model = build_model(name="hydrographnet", task="regression") model = model.to(device) print(f"Model: {type(model).__name__}") # Forward-pass sanity check on one real batch on GPU. - sample_loader = DataLoader(train_inputs, batch_size=1, shuffle=False, collate_fn=graph_collate) + sample_loader = DataLoader(train_inputs, batch_size=1, shuffle=False, collate_fn=hydrograph_collate) batch_x, batch_y = next(iter(sample_loader)) batch_x = _to_device(batch_x, device) batch_y = _to_device(batch_y, device) @@ -78,14 +72,14 @@ def main() -> None: loss_fn=loss_fn, max_epochs=1, batch_size=1, - collate_fn=graph_collate, + collate_fn=hydrograph_collate, ) metrics = trainer.evaluate( data, split="train", batch_size=1, - collate_fn=graph_collate, + collate_fn=hydrograph_collate, ) assert "MAE" in metrics and "RMSE" in metrics, f"Missing expected metrics: {metrics}" diff --git a/tests/fixtures/era5/SOURCE.txt b/tests/fixtures/era5/SOURCE.txt new file mode 100644 index 00000000..12abd51d --- /dev/null +++ b/tests/fixtures/era5/SOURCE.txt @@ -0,0 +1,15 @@ +Real ERA5 values around Hurricane OPHELIA (IBTrACS 2023265N29284, the storm of tests/fixtures/ibtracs) for the +Hurricast reader tests: u, v and geopotential z at 225, 500 and 700 hPa, 3-hourly from 2023-09-22 00 UTC to +2023-09-23 00 UTC (9 times), latitudes 45N-18N and longitudes 89W-63W at whole degrees (the union of the +25 x 25 one-degree maps centred on the storm at those times). + +Values: ERA5 hourly data on pressure levels, read on 2026-10-07 through the NCAR RDA THREDDS server (dataset +ds633.0, files e5.oper.an.pl.128_{129_z,131_u,132_v}.*.2023092200_2023092223.nc and ...2023092300_2023092323.nc), +whose 0.25-degree grid was sampled at whole degrees (every 4th point); no interpolation or other change. +File layout: that of a netCDF download from the current Copernicus Climate Data Store (dimensions valid_time, +pressure_level, latitude [north to south], longitude [-180, 180); float32 variables z, u, v). + +Citation: Hersbach, H. et al. (2023), ERA5 hourly data on pressure levels from 1940 to present, Copernicus +Climate Change Service (C3S) Climate Data Store, doi:10.24381/cds.bd0915c6. Licence: CC BY 4.0. Contains +modified Copernicus Climate Change Service information 2026; neither the European Commission nor ECMWF is +responsible for any use of this information. diff --git a/tests/fixtures/era5/era5.pressure_levels.ophelia_2023092200_2023092300.fixture.nc b/tests/fixtures/era5/era5.pressure_levels.ophelia_2023092200_2023092300.fixture.nc new file mode 100644 index 00000000..bf757a3e Binary files /dev/null and b/tests/fixtures/era5/era5.pressure_levels.ophelia_2023092200_2023092300.fixture.nc differ diff --git a/tests/fixtures/ibtracs/IBTrACS.fixture.v04r01.nc b/tests/fixtures/ibtracs/IBTrACS.fixture.v04r01.nc new file mode 100644 index 00000000..eb9ff9f0 Binary files /dev/null and b/tests/fixtures/ibtracs/IBTrACS.fixture.v04r01.nc differ diff --git a/tests/fixtures/ibtracs/SOURCE.txt b/tests/fixtures/ibtracs/SOURCE.txt new file mode 100644 index 00000000..b650cc83 --- /dev/null +++ b/tests/fixtures/ibtracs/SOURCE.txt @@ -0,0 +1,13 @@ +Real IBTrACS v04r01 rows, cut on 2026-10-07 from NOAA NCEI's ibtracs.last3years.list.v04r01.csv and +IBTrACS.last3years.v04r01.nc (both last modified 2026-10-02): +https://www.ncei.noaa.gov/data/international-best-track-archive-for-climate-stewardship-ibtracs/v04r01/access/ + +Storms: 2023265N29284 (OPHELIA, NA, all rows), 2026058S18168 (URMIL, SP, crosses the dateline, all rows), +2023266N16116 (WP, first 24 rows), 2025214N26167 (WP spur track, first 8 rows). The CSV keeps the +original header, units row and lines byte for byte; the netCDF keeps the original variables used by +the reader (dimensions, types, fill values and attributes), sliced to these storms (numobs and the +blanked slots reflect the truncated tracks). + +Citation: Knapp et al. (2010), BAMS 91, 363-376, doi:10.1175/2009BAMS2755.1; Gahtan et al. (2024), +IBTrACS Version 4r01, NOAA NCEI, doi:10.25921/82ty-9e16. Terms: full and open access (World Data +Center for Meteorology policy; WMO Resolution 40 for commercial use). diff --git a/tests/fixtures/ibtracs/ibtracs.fixture.list.v04r01.csv b/tests/fixtures/ibtracs/ibtracs.fixture.list.v04r01.csv new file mode 100644 index 00000000..f2a73deb --- /dev/null +++ b/tests/fixtures/ibtracs/ibtracs.fixture.list.v04r01.csv @@ -0,0 +1,89 @@ +SID,SEASON,NUMBER,BASIN,SUBBASIN,NAME,ISO_TIME,NATURE,LAT,LON,WMO_WIND,WMO_PRES,WMO_AGENCY,TRACK_TYPE,DIST2LAND,LANDFALL,IFLAG,USA_AGENCY,USA_ATCF_ID,USA_LAT,USA_LON,USA_RECORD,USA_STATUS,USA_WIND,USA_PRES,USA_SSHS,USA_R34_NE,USA_R34_SE,USA_R34_SW,USA_R34_NW,USA_R50_NE,USA_R50_SE,USA_R50_SW,USA_R50_NW,USA_R64_NE,USA_R64_SE,USA_R64_SW,USA_R64_NW,USA_POCI,USA_ROCI,USA_RMW,USA_EYE,TOKYO_LAT,TOKYO_LON,TOKYO_GRADE,TOKYO_WIND,TOKYO_PRES,TOKYO_R50_DIR,TOKYO_R50_LONG,TOKYO_R50_SHORT,TOKYO_R30_DIR,TOKYO_R30_LONG,TOKYO_R30_SHORT,TOKYO_LAND,CMA_LAT,CMA_LON,CMA_CAT,CMA_WIND,CMA_PRES,HKO_LAT,HKO_LON,HKO_CAT,HKO_WIND,HKO_PRES,KMA_LAT,KMA_LON,KMA_CAT,KMA_WIND,KMA_PRES,KMA_R50_DIR,KMA_R50_LONG,KMA_R50_SHORT,KMA_R30_DIR,KMA_R30_LONG,KMA_R30_SHORT,NEWDELHI_LAT,NEWDELHI_LON,NEWDELHI_GRADE,NEWDELHI_WIND,NEWDELHI_PRES,NEWDELHI_CI,NEWDELHI_DP,NEWDELHI_POCI,REUNION_LAT,REUNION_LON,REUNION_TYPE,REUNION_WIND,REUNION_PRES,REUNION_TNUM,REUNION_CI,REUNION_RMW,REUNION_R34_NE,REUNION_R34_SE,REUNION_R34_SW,REUNION_R34_NW,REUNION_R50_NE,REUNION_R50_SE,REUNION_R50_SW,REUNION_R50_NW,REUNION_R64_NE,REUNION_R64_SE,REUNION_R64_SW,REUNION_R64_NW,BOM_LAT,BOM_LON,BOM_TYPE,BOM_WIND,BOM_PRES,BOM_TNUM,BOM_CI,BOM_RMW,BOM_R34_NE,BOM_R34_SE,BOM_R34_SW,BOM_R34_NW,BOM_R50_NE,BOM_R50_SE,BOM_R50_SW,BOM_R50_NW,BOM_R64_NE,BOM_R64_SE,BOM_R64_SW,BOM_R64_NW,BOM_ROCI,BOM_POCI,BOM_EYE,BOM_POS_METHOD,BOM_PRES_METHOD,NADI_LAT,NADI_LON,NADI_CAT,NADI_WIND,NADI_PRES,WELLINGTON_LAT,WELLINGTON_LON,WELLINGTON_WIND,WELLINGTON_PRES,DS824_LAT,DS824_LON,DS824_STAGE,DS824_WIND,DS824_PRES,TD9636_LAT,TD9636_LON,TD9636_STAGE,TD9636_WIND,TD9636_PRES,TD9635_LAT,TD9635_LON,TD9635_WIND,TD9635_PRES,TD9635_ROCI,NEUMANN_LAT,NEUMANN_LON,NEUMANN_CLASS,NEUMANN_WIND,NEUMANN_PRES,MLC_LAT,MLC_LON,MLC_CLASS,MLC_WIND,MLC_PRES,USA_GUST,BOM_GUST,BOM_GUST_PER,REUNION_GUST,REUNION_GUST_PER,USA_SEAHGT,USA_SEARAD_NE,USA_SEARAD_SE,USA_SEARAD_SW,USA_SEARAD_NW,STORM_SPEED,STORM_DIR + ,Year, , , , , , ,degrees_north,degrees_east,kts,mb, , ,km,km, , , ,degrees_north,degrees_east, , ,kts,mb,1,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,mb,nmile,nmile,nmile,degrees_north,degrees_east,1,kts,mb, ,nmile,nmile, ,nmile,nmile,1,degrees_north,degrees_east,1,kts,mb,degrees_north,degrees_east, ,kts,mb,degrees_north,degrees_east, ,kts,mb, ,nmile,nmile, ,nmile,nmile,degrees_north,degrees_east, ,kts,mb,1,mb,mb,degrees_north,degrees_east, ,kts,mb,1,1,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,degrees_north,degrees_east, ,kts,mb,1,1,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,nmile,mb,nmile, , ,degrees_north,degrees_east,1,kts,mb,degrees_north,degrees_east,kts,mb,degrees_north,degrees_east, ,kts,mb,degrees_north,degrees_east, ,kts,mb,degrees_north,degrees_east,kts,mb,nmile,degrees_north,degrees_east, ,kts,mb,degrees_north,degrees_east, ,kts,mb,kts,kts,second,kts,second,ft,nmile,nmile,nmile,nmile,kts,degrees +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-21 12:00:00,ET,28.5,-76.0,30,1012,hurdat_atl,main,428,428,O______________,hurdat_atl,AL162023,28.5,-76.0, ,EX,30,1012,-4, , , , , , , , , , , , ,1013,140,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,40, , , , , , , , , ,6,35 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-21 15:00:00,ET,28.8,-75.8, , , ,main,459,459,P______________, ,AL162023,28.8,-75.8, ,EX,30,1012,-4, , , , , , , , , , , , ,1013,140,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,6,35 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-21 18:00:00,ET,29.0,-75.6,30,1012,hurdat_atl,main,480,480,O______________,hurdat_atl,AL162023,29.0,-75.6, ,EX,30,1012,-4, , , , , , , , , , , , ,1013,140,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,40, , , , , , , , , ,6,35 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-21 21:00:00,ET,29.2,-75.4, , , ,main,502,502,P______________, ,AL162023,29.2,-75.4, ,EX,33,1010,-4, , , , , , , , , , , , ,1013,150,135, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,6,30 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 00:00:00,ET,29.5,-75.3,35,1008,hurdat_atl,main,517,517,O______________,hurdat_atl,AL162023,29.5,-75.3, ,EX,35,1008,-4,210,0,0,180, , , , , , , , ,1012,160,120, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,45, , , , , , , , , ,7,20 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 03:00:00,ET,29.8,-75.1, , , ,main,532,485,P______________, ,AL162023,29.8,-75.1, ,EX,38,1005,-4,210,0,0,180, , , , , , , , ,1012,160,110, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,8,10 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 06:00:00,ET,30.3,-75.1,40,1002,hurdat_atl,main,485,425,O______________,hurdat_atl,AL162023,30.3,-75.1, ,EX,40,1002,-4,210,0,0,180, , , , , , , , ,1011,160,100, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,50, , , , ,12,180, , ,180,11,355 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 09:00:00,ET,30.9,-75.2, , , ,main,425,346,P______________, ,AL162023,30.9,-75.2, ,EX,45,999,-4,225,0,30,180, , , , , , , , ,1011,160,95, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,210, , ,180,13,345 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 12:00:00,ET,31.6,-75.5,50,996,hurdat_atl,main,346,278,O______________,hurdat_atl,AL162023,31.6,-75.5, ,EX,50,996,-4,240,0,60,180,0,0,0,90, , , , ,1010,160,90, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,55, , , , ,12,240,120,160,180,14,340 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 15:00:00,ET,32.2,-75.8, , , ,main,278,221,P______________, ,AL162023,32.2,-75.8, ,EX,55,993,-4,255,35,65,170,0,0,20,85, , , , ,1010,170,75, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,240,120,160,180,12,335 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 18:00:00,TS,32.7,-76.1,60,989,hurdat_atl,main,221,186,O______________,hurdat_atl,AL162023,32.7,-76.1, ,TS,60,989,0,270,70,70,160,0,0,40,80, , , , ,1010,180,60, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,65, , , , ,12,240,120,160,180,10,330 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-22 21:00:00,TS,33.0,-76.4, , , ,main,178,145,P______________, ,AL162023,33.0,-76.4, ,TS,60,986,0,270,80,95,140,0,0,50,70, , , , ,1011,195,50, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,255,135,185,150,7,325 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 00:00:00,TS,33.3,-76.6,60,983,hurdat_atl,main,145,110,O______________,hurdat_atl,AL162023,33.3,-76.6, ,TS,60,983,0,270,90,120,120,0,0,60,60, , , , ,1011,210,40, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,75, , , , ,12,270,150,210,120,6,315 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 03:00:00,TS,33.5,-76.9, , , ,main,110,78,P______________, ,AL162023,33.5,-76.9, ,TS,60,982,0,270,90,120,105,20,20,55,60, , , , ,1011,210,35, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,300,150,195,105,7,320 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 06:00:00,TS,33.8,-77.1,60,981,hurdat_atl,main,78,28,O______________,hurdat_atl,AL162023,33.8,-77.1, ,TS,60,981,0,270,90,120,90,40,40,50,60, , , , ,1011,210,30, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,75, , , , ,12,330,150,180,90,9,350 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 09:00:00,TS,34.4,-77.1, , , ,main,28,0,P______________, ,AL162023,34.4,-77.1, ,TS,60,981,0,270,111,99,83,40,40,50,60, , , , ,1011,210,30, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,13,0 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 10:15:00,TS,34.7,-77.1,60,981,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,34.7,-77.1,L,TS,60,981,0,270,120,90,80,40,40,50,60, , , , ,1011,210,30, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,14,0 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 12:00:00,TS,35.1,-77.1,50,982,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,35.1,-77.1, ,TS,50,982,0,270,120,80,60,40,40,0,40, , , , ,1011,210,40, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,60, , , , , , , , , ,14,355 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 15:00:00,TS,35.8,-77.3, , , ,main,0,0,P______________, ,AL162023,35.8,-77.3, ,TS,45,990,0,270,120,40,50, , , , , , , , ,1011,190,70, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,345 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 18:00:00,TS,36.3,-77.5,40,997,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,36.3,-77.5, ,TS,40,997,0,270,120,0,40, , , , , , , , ,1010,170,100, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,50, , , , ,12,300,230,180, ,9,345 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-23 21:00:00,TS,36.6,-77.6, , , ,main,0,0,P______________, ,AL162023,36.6,-77.6, ,TS,35,1000,0,135,60, ,20, , , , , , , , ,1010,163,125, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,5,350 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 00:00:00,ET,36.8,-77.6,30,1002,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,36.8,-77.6, ,EX,30,1002,-4, , , , , , , , , , , , ,1010,155,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,40, , , , , , , , , ,4,355 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 03:00:00,ET,37.0,-77.6, , , ,main,0,0,P______________, ,AL162023,37.0,-77.6, ,EX,28,1004,-4, , , , , , , , , , , , ,1010,180,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,4,0 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 06:00:00,ET,37.2,-77.6,25,1006,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,37.2,-77.6, ,EX,25,1006,-4, , , , , , , , , , , , ,1010,205,150, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,30, , , , , , , , , ,5,10 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 09:00:00,ET,37.5,-77.5, , , ,main,0,0,P______________, ,AL162023,37.5,-77.5, ,EX,23,1008,-4, , , , , , , , , , , , ,1010,205,175, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,15 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 12:00:00,ET,37.9,-77.4,20,1009,hurdat_atl,main,0,0,O______________,hurdat_atl,AL162023,37.9,-77.4, ,EX,20,1009,-4, , , , , , , , , , , , ,1010,205,200, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,9,20 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 15:00:00,ET,38.4,-77.2, , , ,main,0,0,P______________, ,AL162023,38.4,-77.2, ,EX,20,1010,-4, , , , , , , , , , , , ,1010,205,200, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,11,20 +2023265N29284,2023,62,NA,NA,OPHELIA,2023-09-24 18:00:00,ET,38.9,-76.9,20,1010,hurdat_atl,main,0, ,O______________,hurdat_atl,AL162023,38.9,-76.9, ,EX,20,1010,-4, , , , , , , , , , , , ,1010,205,200, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,11,20 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 00:00:00,DS,15.5,116.1, , , ,main,389,389,O______________,jtwc_wp,WP132023,15.5,116.1, ,DB,15,1010,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,1,205 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 03:00:00,DS,15.4,116.1, , , ,main,391,391,P______________, ,WP132023,15.4,116.1, ,DB,15,1010,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,1,225 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 06:00:00,DS,15.4,116.0, , , ,main,401,401,O______________,jtwc_wp,WP132023,15.4,116.0, ,DB,15,1009,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,4,255 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 09:00:00,DS,15.4,115.7, , , ,main,433,433,P______________, ,WP132023,15.4,115.7, ,DB,15,1008,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,6,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 12:00:00,DS,15.3,115.4, , , ,main,467,467,O______________,jtwc_wp,WP132023,15.3,115.4, ,DB,15,1007,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 15:00:00,DS,15.2,115.1, , , ,main,500,500,P______________, ,WP132023,15.2,115.1, ,DB,15,1006,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 18:00:00,DS,15.2,114.7, , , ,main,543,543,O______________,jtwc_wp,WP132023,15.2,114.7, ,DB,15,1005,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-23 21:00:00,DS,15.2,114.4, , , ,main,568,523,P______________, ,WP132023,15.2,114.4, ,DB,18,1003,-3, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 00:00:00,DS,15.1,114.0, , , ,main,523,468,O______________,jtwc_wp,WP132023,15.1,114.0, ,DB,20,1000,-3, , , , , , , , , , , , ,1006,155,25, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,9,255 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 03:00:00,DS,14.9,113.4, , , ,main,455,390,P______________, ,WP132023,14.9,113.4, ,DB,20,999,-3, , , , , , , , , , , , ,1006,203,43, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,255 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 06:00:00,DS,14.8,112.8, , , ,main,390,328,O______________,jtwc_wp,WP132023,14.8,112.8, ,DB,20,998,-3, , , , , , , , , , , , ,1006,250,60, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,13,260 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 09:00:00,DS,14.8,112.2, , , ,main,328,267,P______________, ,WP132023,14.8,112.2, ,DB,20,998,-3, , , , , , , , , , , , ,1006,230,60, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,270 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 12:00:00,DS,14.8,111.6, , , ,main,267,237,O______________,jtwc_wp,WP132023,14.8,111.6, ,DB,20,998,-3, , , , , , , , , , , , ,1006,210,60, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,9,280 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 15:00:00,DS,14.9,111.2, , , ,main,226,194,P______________, ,WP132023,14.9,111.2, ,DB,20,998,-3, , , , , , , , , , , , ,1006,215,55, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,6,275 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 18:00:00,MX,14.9,110.9, , , ,main,194,173,O_OO___________,jtwc_wp,WP132023,15.0,111.0, ,DB,20,998,-3, , , , , , , , , , , , ,1006,220,50, , , , , , , , , , , , , ,14.6,110.9,1,25,1004,14.5,110.7,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,5,275 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-24 21:00:00,MX,14.9,110.7, , , ,main,173,154,P_PO___________, ,WP132023,15.1,110.8, ,DB,23,998,-3, , , , , , , , , , , , ,1007,235,50, , , , , , , , , , , , , ,14.9,110.6,1,25,1003,14.7,110.6,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,5,300 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 00:00:00,TS,15.1,110.4, , , ,main,146,120,O_OO___________,jtwc_wp,WP132023,15.2,110.5, ,TD,25,997,-1, , , , , , , , , , , , ,1007,250,50, , , , , , , , , , , , , ,15.2,110.3,1,25,1002,14.9,110.5,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,9,305 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 03:00:00,TS,15.5,109.9, , , ,main,112,85,P_PO___________, ,WP132023,15.4,109.9, ,TD,28,996,-1, , , , , , , , , , , , ,1007,250,40, , , , , , , , , , , , , ,15.5,109.9,1,27,1001,15.4,110.0,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,305 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 06:00:00,TS,15.8,109.4, , , ,main,85,54,O_OO___________,jtwc_wp,WP132023,15.7,109.2, ,TD,30,995,-1, , , , , , , , , , , , ,1006,250,30, , , , , , , , , , , , , ,15.8,109.5,1,29,1000,15.8,109.5,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,11,295 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 09:00:00,TS,15.9,108.9, , , ,main,54,21,P_PO___________, ,WP132023,15.9,108.7, ,TD,30,996,-1, , , , , , , , , , , , ,1006,225,25, , , , , , , , , , , , , ,15.9,109.0,1,29,1000,16.0,109.0,TD,25,1000, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,285 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 12:00:00,TS,16.0,108.4, , , ,main,10,0,O_OO___________,jtwc_wp,WP132023,16.0,108.3, ,TD,30,997,-1, , , , , , , , , , , , ,1006,200,20, , , , , , , , , , , , , ,16.0,108.5,1,29,1000,16.1,108.5,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,285 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 15:00:00,TS,16.2,108.0, , , ,main,0,0,P_PO___________, ,WP132023,16.2,107.9, ,TD,30,998,-1, , , , , , , , , , , , ,1006,180,20, , , , , , , , , , , , , ,16.1,108.0,1,29,1000,16.2,108.0,TD,25,1000, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,285 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 18:00:00,TS,16.3,107.5, , , ,main,0,0,O_OO___________,jtwc_wp,WP132023,16.4,107.5, ,TD,30,998,-1, , , , , , , , , , , , ,1005,160,20, , , , , , , , , , , , , ,16.1,107.4,1,29,1000,16.3,107.6,TD,25,1002, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,275 +2023266N16116,2023,63,WP,MM,UNNAMED,2023-09-25 21:00:00,TS,16.3,106.9, , , ,main,0,0,P_P____________, ,WP132023,16.4,107.0, ,TD,30,1000,-1, , , , , , , , , , , , ,1005,160,20, , , , , , , , , , , , , ,16.1,106.8,1,27,1001, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,11,270 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 06:00:00,TS,25.9,166.6, , , ,US-PROVISIONAL_spur,2658,2643,___O___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,25.9,166.6,TD,25,1008, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,3,295 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 09:00:00,TS,26.0,166.5, , , ,US-PROVISIONAL_spur,2643,2633,___P___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,166.5,TD,28,1007, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,3,290 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 12:00:00,TS,26.0,166.3, , , ,US-PROVISIONAL_spur,2633,2629,___O___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,166.3,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,3,280 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 15:00:00,TS,26.0,166.1, , , ,US-PROVISIONAL_spur,2624,2615,___P___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,166.1,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,3,270 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 18:00:00,TS,26.0,166.0, , , ,US-PROVISIONAL_spur,2615,2607,___O___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,166.0,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,2,270 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-02 21:00:00,TS,26.0,165.9, , , ,US-PROVISIONAL_spur,2607,2598,___P___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,165.9,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,2,270 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-03 00:00:00,TS,26.0,165.8, , , ,US-PROVISIONAL_spur,2598,2598,___O___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,165.8,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,1,260 +2025214N26167,2025,61,WP,MM,UNNAMED,2025-08-03 03:00:00,TS,26.0,165.8, , , ,US-PROVISIONAL_spur,2598,2589,___P___________, , , , , , , , ,-5, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26.0,165.8,TD,30,1006, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,1,270 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-26 18:00:00,NR,-18.2,167.9, , , ,US-PROVISIONAL,179,179,O______________,tcvitals,SH232026,-18.2,167.9, , ,35,996,0, , , , , , , , , , , , ,1002,180,30, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,3,195 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-26 21:00:00,NR,-18.3,167.9, , , ,US-PROVISIONAL,190,190,P______________, ,SH232026,-18.3,167.9, , ,40,994,0, , , , , , , , , , , , ,1003,175,25, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,4,0 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 00:00:00,NR,-18.6,167.9, , , ,US-PROVISIONAL,224,224,O______________,tcvitals,SH232026,-18.6,167.9, , ,45,992,0,90,70,40,30, , , , , , , , ,1003,170,20, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,160 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 03:00:00,NR,-19.0,168.1, , , ,US-PROVISIONAL,270,270,P______________, ,SH232026,-19.0,168.1, , ,50,989,0,80,68,43,40, , , , , , , , ,1003,180,18, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,145 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 06:00:00,NR,-19.4,168.5, , , ,US-PROVISIONAL,321,321,O______________,tcvitals,SH232026,-19.4,168.5, , ,54,985,0,70,65,45,50, , , , , , , , ,1002,190,15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,120 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 09:00:00,NR,-19.5,169.0, , , ,US-PROVISIONAL,348,348,P______________, ,SH232026,-19.5,169.0, , ,57,985,0,63,73,55,43, , , , , , , , ,1003,195,13, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,9,95 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 12:00:00,NR,-19.5,169.5, , , ,US-PROVISIONAL,370,370,O______________,tcvitals,SH232026,-19.5,169.5, , ,60,985,0,55,80,65,35, , , , , , , , ,1004,200,10, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,4,90 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 15:00:00,NR,-19.5,169.5, , , ,US-PROVISIONAL,370,370,P______________, ,SH232026,-19.5,169.5, , ,60,985,0,55,80,65,35, , , , , , , , ,1003,208,10, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,1,0 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 18:00:00,NR,-19.6,169.5, , , ,US-PROVISIONAL,380,380,O______________,tcvitals,SH232026,-19.6,169.5, , ,60,984,0,55,80,65,35, , , , , , , , ,1002,215,10, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,7,135 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-27 21:00:00,NR,-20.0,170.0, , , ,US-PROVISIONAL,396,396,P______________, ,SH232026,-20.0,170.0, , ,62,984,0,58,75,63,43, , , , , , , , ,1003,203,10, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,14,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 00:00:00,NR,-20.4,170.7, , , ,US-PROVISIONAL,432,432,O______________,tcvitals,SH232026,-20.4,170.7, , ,64,984,1,60,70,60,50, , , , , , , , ,1003,190,10, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,13,120 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 03:00:00,NR,-20.6,171.2, , , ,US-PROVISIONAL,470,465,P______________, ,SH232026,-20.6,171.2, , ,64,982,1,60,70,60,50, , , , , , , , ,1003,205,13, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,10,115 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 06:00:00,NR,-20.8,171.7, , , ,US-PROVISIONAL,510,510,O______________,tcvitals,SH232026,-20.8,171.7, , ,64,980,1,60,70,60,50, , , , , , , , ,1002,220,15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,12,105 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 09:00:00,NR,-20.9,172.4, , , ,US-PROVISIONAL,576,543,P______________, ,SH232026,-20.9,172.4, , ,64,981,1,60,70,60,50, , , , , , , , ,1003,235,15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,14,100 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 12:00:00,NR,-21.1,173.2, , , ,US-PROVISIONAL,543,505,O______________,tcvitals,SH232026,-21.1,173.2, , ,64,981,1,60,70,60,50, , , , , , , , ,1003,250,15, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,17,110 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 15:00:00,NR,-21.5,174.1, , , ,US-PROVISIONAL,506,493,P______________, ,SH232026,-21.5,174.1, , ,59,984,0,63,75,63,60, , , , , , , , ,1004,250,18, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,20,120 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 18:00:00,NR,-22.1,175.1, , , ,US-PROVISIONAL,502,498,O______________,tcvitals,SH232026,-22.1,175.1, , ,54,987,0,65,80,65,70, , , , , , , , ,1005,250,20, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-02-28 21:00:00,NR,-23.0,176.3, , , ,US-PROVISIONAL,551,551,P______________, ,SH232026,-23.0,176.3, , ,54,987,0,110,118,83,78, , , , , , , , ,1005,250,20, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,29,130 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 00:00:00,NR,-24.0,177.5, , , ,US-PROVISIONAL,638,638,O______________,tcvitals,SH232026,-24.0,177.5, , ,54,986,0,155,155,100,85, , , , , , , , ,1005,250,20, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26,135 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 03:00:00,NR,-24.9,178.4, , , ,US-PROVISIONAL,738,738,P______________, ,SH232026,-24.9,178.4, , ,54,985,0,155,155,100,85, , , , , , , , ,1003,283,23, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,23,135 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 06:00:00,NR,-25.7,179.2,50,983,wellington,US-PROVISIONAL,833,833,O________O_____,tcvitals,SH232026,-25.7,179.2, , ,54,983,0,155,155,100,85, , , , , , , , ,1001,315,25, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-25.5,179.5,50,983, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,24,135 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 09:00:00,NR,-26.5,180.3, , , ,US-PROVISIONAL,941,941,P________P_____, ,SH232026,-26.6,-179.7, , ,53,983,0,210,168,145,113, , , , , , , , ,1002,358,35, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-26.2,-179.5,50,984, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,26,130 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 12:00:00,NR,-27.3,181.5,50,984,wellington,US-PROVISIONAL,1061,1061,O________O_____,tcvitals,SH232026,-27.4,-178.5, , ,51,982,0,265,180,190,140, , , , , , , , ,1002,400,45, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-27.0,-178.5,50,984, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,24,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 15:00:00,NR,-27.9,182.5, , , ,US-PROVISIONAL,1131,1105,P________P_____, ,SH232026,-28.0,-177.5, , ,48,983,0,265,180,190,140, , , , , , , , ,1002,400,45, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-27.8,-177.4,25,984, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,25,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 18:00:00,NR,-28.8,183.8, ,984,wellington,US-PROVISIONAL,1102,1067,O________O_____,tcvitals,SH232026,-28.8,-176.3, , ,45,984,0,265,180,190,140, , , , , , , , ,1002,400,45, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-28.8,-176.1,-1,984, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,35,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-01 21:00:00,NR,-30.1,185.6, , , ,US-PROVISIONAL,1063,1063,P________P_____, ,SH232026,-30.0,-174.4, , ,42,985,0,265,180,190,140, , , , , , , , ,1002,400,48, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-30.1,-174.3,-1,985, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,45,125 +2026058S18168,2026,14,SP,MM,URMIL,2026-03-02 00:00:00,NR,-31.5,187.9, ,985,wellington,US-PROVISIONAL,1093, ,O________O_____,tcvitals,SH232026,-31.5,-172.0, , ,39,986,0,265,180,190,140, , , , , , , , ,1002,400,50, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,-31.6,-172.2,-1,985, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,49,125 diff --git a/tests/fixtures/ships_xu2021/SOURCE.txt b/tests/fixtures/ships_xu2021/SOURCE.txt new file mode 100644 index 00000000..f0a9fb50 --- /dev/null +++ b/tests/fixtures/ships_xu2021/SOURCE.txt @@ -0,0 +1,5 @@ +Ten real rows (header and lines unchanged) of train_global_fill_REA_na_wo_img_scaled.csv from +"Supporting data for Xu et al. 2021 - Weather and Forecasting" (Zenodo, doi:10.5281/zenodo.4784610), +by W. Xu, K. Balaguru, A. August, N. Lalo, N. Hodas, M. DeMaria and D. Judi, licensed CC BY 4.0 +(https://creativecommons.org/licenses/by/4.0/). Rows: 3 EP 1982 reanalysis, 2 AL 2016 reanalysis, +2 AL 2011 operational and 3 AL 2018 operational cases, fetched with HTTP range requests on 2026-10-07. diff --git a/tests/fixtures/ships_xu2021/train_global_fill_REA_na_wo_img_scaled.fixture.csv b/tests/fixtures/ships_xu2021/train_global_fill_REA_na_wo_img_scaled.fixture.csv new file mode 100644 index 00000000..b143ba40 --- /dev/null +++ b/tests/fixtures/ships_xu2021/train_global_fill_REA_na_wo_img_scaled.fixture.csv @@ -0,0 +1,11 @@ +,name,year,month,day,hour,vs0,lat,lon,pressure,HIST_v0,HIST_v1,HIST_v2,HIST_v3,HIST_v4,HIST_v5,HIST_v6,HIST_v7,HIST_v8,HIST_v9,HIST_v10,HIST_v11,HIST_v12,HIST_v13,HIST_v14,HIST_v15,HIST_v16,HIST_v17,HIST_v18,HIST_v19,HIST_v20,HIST_v21,HIST_v22,HIST_v23,PSLV_v0,PSLV_v1,PSLV_v2,PSLV_v3,PSLV_v4,PSLV_v5,PSLV_v6,PSLV_v7,PSLV_v8,PSLV_v9,PSLV_v10,PSLV_v11,PSLV_v12,PSLV_v13,PSLV_v14,PSLV_v15,PSLV_v16,PSLV_v17,PSLV_v18,PSLV_v19,PSLV_v20,PSLV_v21,PSLV_v22,PSLV_v23,MTPW_v0,MTPW_v1,MTPW_v2,MTPW_v3,MTPW_v4,MTPW_v5,MTPW_v6,MTPW_v7,MTPW_v8,MTPW_v9,MTPW_v10,MTPW_v11,MTPW_v12,MTPW_v13,MTPW_v14,MTPW_v15,MTPW_v16,MTPW_v17,MTPW_v18,MTPW_v19,MTPW_v20,MTPW_v21,MTPW_v22,MTPW_v23,IR00_v0,IR00_v1,IR00_v2,IR00_v3,IR00_v4,IR00_v5,IR00_v6,IR00_v7,IR00_v8,IR00_v9,IR00_v10,IR00_v11,IR00_v12,IR00_v13,IR00_v14,IR00_v15,IR00_v16,IR00_v17,IR00_v18,IR00_v19,IR00_v20,IR00_v21,IR00_v22,IR00_v23,IRM1_v0,IRM1_v1,IRM1_v2,IRM1_v3,IRM1_v4,IRM1_v5,IRM1_v6,IRM1_v7,IRM1_v8,IRM1_v9,IRM1_v10,IRM1_v11,IRM1_v12,IRM1_v13,IRM1_v14,IRM1_v15,IRM1_v16,IRM1_v17,IRM1_v18,IRM1_v19,IRM1_v20,IRM1_v21,IRM1_v22,IRM1_v23,IRM3_v0,IRM3_v1,IRM3_v2,IRM3_v3,IRM3_v4,IRM3_v5,IRM3_v6,IRM3_v7,IRM3_v8,IRM3_v9,IRM3_v10,IRM3_v11,IRM3_v12,IRM3_v13,IRM3_v14,IRM3_v15,IRM3_v16,IRM3_v17,IRM3_v18,IRM3_v19,IRM3_v20,IRM3_v21,IRM3_v22,IRM3_v23,PC00_v0,PC00_v1,PC00_v2,PC00_v3,PC00_v4,PC00_v5,PC00_v6,PC00_v7,PC00_v8,PC00_v9,PC00_v10,PC00_v11,PC00_v12,PC00_v13,PC00_v14,PC00_v15,PC00_v16,PC00_v17,PC00_v18,PC00_v19,PC00_v20,PC00_v21,PC00_v22,PC00_v23,PCM1_v0,PCM1_v1,PCM1_v2,PCM1_v3,PCM1_v4,PCM1_v5,PCM1_v6,PCM1_v7,PCM1_v8,PCM1_v9,PCM1_v10,PCM1_v11,PCM1_v12,PCM1_v13,PCM1_v14,PCM1_v15,PCM1_v16,PCM1_v17,PCM1_v18,PCM1_v19,PCM1_v20,PCM1_v21,PCM1_v22,PCM1_v23,PCM3_v0,PCM3_v1,PCM3_v2,PCM3_v3,PCM3_v4,PCM3_v5,PCM3_v6,PCM3_v7,PCM3_v8,PCM3_v9,PCM3_v10,PCM3_v11,PCM3_v12,PCM3_v13,PCM3_v14,PCM3_v15,PCM3_v16,PCM3_v17,PCM3_v18,PCM3_v19,PCM3_v20,PCM3_v21,PCM3_v22,PCM3_v23,MSLP_t-12,MSLP_t-6,MSLP_t0,MSLP_t6,MSLP_t12,MSLP_t18,MSLP_t24,MSLP_t30,MSLP_t36,MSLP_t42,MSLP_t48,MSLP_t54,MSLP_t60,MSLP_t66,MSLP_t72,MSLP_t78,MSLP_t84,MSLP_t90,MSLP_t96,MSLP_t102,MSLP_t108,MSLP_t114,MSLP_t120,LAT_t-12,LAT_t-6,LAT_t0,LAT_t6,LAT_t12,LAT_t18,LAT_t24,LAT_t30,LAT_t36,LAT_t42,LAT_t48,LAT_t54,LAT_t60,LAT_t66,LAT_t72,LAT_t78,LAT_t84,LAT_t90,LAT_t96,LAT_t102,LAT_t108,LAT_t114,LAT_t120,LON_t-12,LON_t-6,LON_t0,LON_t6,LON_t12,LON_t18,LON_t24,LON_t30,LON_t36,LON_t42,LON_t48,LON_t54,LON_t60,LON_t66,LON_t72,LON_t78,LON_t84,LON_t90,LON_t96,LON_t102,LON_t108,LON_t114,LON_t120,CSST_t-12,CSST_t-6,CSST_t0,CSST_t6,CSST_t12,CSST_t18,CSST_t24,CSST_t30,CSST_t36,CSST_t42,CSST_t48,CSST_t54,CSST_t60,CSST_t66,CSST_t72,CSST_t78,CSST_t84,CSST_t90,CSST_t96,CSST_t102,CSST_t108,CSST_t114,CSST_t120,CD20_t-12,CD20_t-6,CD20_t0,CD20_t6,CD20_t12,CD20_t18,CD20_t24,CD20_t30,CD20_t36,CD20_t42,CD20_t48,CD20_t54,CD20_t60,CD20_t66,CD20_t72,CD20_t78,CD20_t84,CD20_t90,CD20_t96,CD20_t102,CD20_t108,CD20_t114,CD20_t120,CD26_t-12,CD26_t-6,CD26_t0,CD26_t6,CD26_t12,CD26_t18,CD26_t24,CD26_t30,CD26_t36,CD26_t42,CD26_t48,CD26_t54,CD26_t60,CD26_t66,CD26_t72,CD26_t78,CD26_t84,CD26_t90,CD26_t96,CD26_t102,CD26_t108,CD26_t114,CD26_t120,COHC_t-12,COHC_t-6,COHC_t0,COHC_t6,COHC_t12,COHC_t18,COHC_t24,COHC_t30,COHC_t36,COHC_t42,COHC_t48,COHC_t54,COHC_t60,COHC_t66,COHC_t72,COHC_t78,COHC_t84,COHC_t90,COHC_t96,COHC_t102,COHC_t108,COHC_t114,COHC_t120,DTL_t-12,DTL_t-6,DTL_t0,DTL_t6,DTL_t12,DTL_t18,DTL_t24,DTL_t30,DTL_t36,DTL_t42,DTL_t48,DTL_t54,DTL_t60,DTL_t66,DTL_t72,DTL_t78,DTL_t84,DTL_t90,DTL_t96,DTL_t102,DTL_t108,DTL_t114,DTL_t120,OAGE_t-12,OAGE_t-6,OAGE_t0,OAGE_t6,OAGE_t12,OAGE_t18,OAGE_t24,OAGE_t30,OAGE_t36,OAGE_t42,OAGE_t48,OAGE_t54,OAGE_t60,OAGE_t66,OAGE_t72,OAGE_t78,OAGE_t84,OAGE_t90,OAGE_t96,OAGE_t102,OAGE_t108,OAGE_t114,OAGE_t120,NAGE_t-12,NAGE_t-6,NAGE_t0,NAGE_t6,NAGE_t12,NAGE_t18,NAGE_t24,NAGE_t30,NAGE_t36,NAGE_t42,NAGE_t48,NAGE_t54,NAGE_t60,NAGE_t66,NAGE_t72,NAGE_t78,NAGE_t84,NAGE_t90,NAGE_t96,NAGE_t102,NAGE_t108,NAGE_t114,NAGE_t120,RSST_t-12,RSST_t-6,RSST_t0,RSST_t6,RSST_t12,RSST_t18,RSST_t24,RSST_t30,RSST_t36,RSST_t42,RSST_t48,RSST_t54,RSST_t60,RSST_t66,RSST_t72,RSST_t78,RSST_t84,RSST_t90,RSST_t96,RSST_t102,RSST_t108,RSST_t114,RSST_t120,U200_t-12,U200_t-6,U200_t0,U200_t6,U200_t12,U200_t18,U200_t24,U200_t30,U200_t36,U200_t42,U200_t48,U200_t54,U200_t60,U200_t66,U200_t72,U200_t78,U200_t84,U200_t90,U200_t96,U200_t102,U200_t108,U200_t114,U200_t120,U20C_t-12,U20C_t-6,U20C_t0,U20C_t6,U20C_t12,U20C_t18,U20C_t24,U20C_t30,U20C_t36,U20C_t42,U20C_t48,U20C_t54,U20C_t60,U20C_t66,U20C_t72,U20C_t78,U20C_t84,U20C_t90,U20C_t96,U20C_t102,U20C_t108,U20C_t114,U20C_t120,V20C_t-12,V20C_t-6,V20C_t0,V20C_t6,V20C_t12,V20C_t18,V20C_t24,V20C_t30,V20C_t36,V20C_t42,V20C_t48,V20C_t54,V20C_t60,V20C_t66,V20C_t72,V20C_t78,V20C_t84,V20C_t90,V20C_t96,V20C_t102,V20C_t108,V20C_t114,V20C_t120,E000_t-12,E000_t-6,E000_t0,E000_t6,E000_t12,E000_t18,E000_t24,E000_t30,E000_t36,E000_t42,E000_t48,E000_t54,E000_t60,E000_t66,E000_t72,E000_t78,E000_t84,E000_t90,E000_t96,E000_t102,E000_t108,E000_t114,E000_t120,EPOS_t-12,EPOS_t-6,EPOS_t0,EPOS_t6,EPOS_t12,EPOS_t18,EPOS_t24,EPOS_t30,EPOS_t36,EPOS_t42,EPOS_t48,EPOS_t54,EPOS_t60,EPOS_t66,EPOS_t72,EPOS_t78,EPOS_t84,EPOS_t90,EPOS_t96,EPOS_t102,EPOS_t108,EPOS_t114,EPOS_t120,ENEG_t-12,ENEG_t-6,ENEG_t0,ENEG_t6,ENEG_t12,ENEG_t18,ENEG_t24,ENEG_t30,ENEG_t36,ENEG_t42,ENEG_t48,ENEG_t54,ENEG_t60,ENEG_t66,ENEG_t72,ENEG_t78,ENEG_t84,ENEG_t90,ENEG_t96,ENEG_t102,ENEG_t108,ENEG_t114,ENEG_t120,EPSS_t-12,EPSS_t-6,EPSS_t0,EPSS_t6,EPSS_t12,EPSS_t18,EPSS_t24,EPSS_t30,EPSS_t36,EPSS_t42,EPSS_t48,EPSS_t54,EPSS_t60,EPSS_t66,EPSS_t72,EPSS_t78,EPSS_t84,EPSS_t90,EPSS_t96,EPSS_t102,EPSS_t108,EPSS_t114,EPSS_t120,ENSS_t-12,ENSS_t-6,ENSS_t0,ENSS_t6,ENSS_t12,ENSS_t18,ENSS_t24,ENSS_t30,ENSS_t36,ENSS_t42,ENSS_t48,ENSS_t54,ENSS_t60,ENSS_t66,ENSS_t72,ENSS_t78,ENSS_t84,ENSS_t90,ENSS_t96,ENSS_t102,ENSS_t108,ENSS_t114,ENSS_t120,RHLO_t-12,RHLO_t-6,RHLO_t0,RHLO_t6,RHLO_t12,RHLO_t18,RHLO_t24,RHLO_t30,RHLO_t36,RHLO_t42,RHLO_t48,RHLO_t54,RHLO_t60,RHLO_t66,RHLO_t72,RHLO_t78,RHLO_t84,RHLO_t90,RHLO_t96,RHLO_t102,RHLO_t108,RHLO_t114,RHLO_t120,RHMD_t-12,RHMD_t-6,RHMD_t0,RHMD_t6,RHMD_t12,RHMD_t18,RHMD_t24,RHMD_t30,RHMD_t36,RHMD_t42,RHMD_t48,RHMD_t54,RHMD_t60,RHMD_t66,RHMD_t72,RHMD_t78,RHMD_t84,RHMD_t90,RHMD_t96,RHMD_t102,RHMD_t108,RHMD_t114,RHMD_t120,RHHI_t-12,RHHI_t-6,RHHI_t0,RHHI_t6,RHHI_t12,RHHI_t18,RHHI_t24,RHHI_t30,RHHI_t36,RHHI_t42,RHHI_t48,RHHI_t54,RHHI_t60,RHHI_t66,RHHI_t72,RHHI_t78,RHHI_t84,RHHI_t90,RHHI_t96,RHHI_t102,RHHI_t108,RHHI_t114,RHHI_t120,Z850_t-12,Z850_t-6,Z850_t0,Z850_t6,Z850_t12,Z850_t18,Z850_t24,Z850_t30,Z850_t36,Z850_t42,Z850_t48,Z850_t54,Z850_t60,Z850_t66,Z850_t72,Z850_t78,Z850_t84,Z850_t90,Z850_t96,Z850_t102,Z850_t108,Z850_t114,Z850_t120,D200_t-12,D200_t-6,D200_t0,D200_t6,D200_t12,D200_t18,D200_t24,D200_t30,D200_t36,D200_t42,D200_t48,D200_t54,D200_t60,D200_t66,D200_t72,D200_t78,D200_t84,D200_t90,D200_t96,D200_t102,D200_t108,D200_t114,D200_t120,REFC_t-12,REFC_t-6,REFC_t0,REFC_t6,REFC_t12,REFC_t18,REFC_t24,REFC_t30,REFC_t36,REFC_t42,REFC_t48,REFC_t54,REFC_t60,REFC_t66,REFC_t72,REFC_t78,REFC_t84,REFC_t90,REFC_t96,REFC_t102,REFC_t108,REFC_t114,REFC_t120,PEFC_t-12,PEFC_t-6,PEFC_t0,PEFC_t6,PEFC_t12,PEFC_t18,PEFC_t24,PEFC_t30,PEFC_t36,PEFC_t42,PEFC_t48,PEFC_t54,PEFC_t60,PEFC_t66,PEFC_t72,PEFC_t78,PEFC_t84,PEFC_t90,PEFC_t96,PEFC_t102,PEFC_t108,PEFC_t114,PEFC_t120,T000_t-12,T000_t-6,T000_t0,T000_t6,T000_t12,T000_t18,T000_t24,T000_t30,T000_t36,T000_t42,T000_t48,T000_t54,T000_t60,T000_t66,T000_t72,T000_t78,T000_t84,T000_t90,T000_t96,T000_t102,T000_t108,T000_t114,T000_t120,R000_t-12,R000_t-6,R000_t0,R000_t6,R000_t12,R000_t18,R000_t24,R000_t30,R000_t36,R000_t42,R000_t48,R000_t54,R000_t60,R000_t66,R000_t72,R000_t78,R000_t84,R000_t90,R000_t96,R000_t102,R000_t108,R000_t114,R000_t120,Z000_t-12,Z000_t-6,Z000_t0,Z000_t6,Z000_t12,Z000_t18,Z000_t24,Z000_t30,Z000_t36,Z000_t42,Z000_t48,Z000_t54,Z000_t60,Z000_t66,Z000_t72,Z000_t78,Z000_t84,Z000_t90,Z000_t96,Z000_t102,Z000_t108,Z000_t114,Z000_t120,TLAT_t-12,TLAT_t-6,TLAT_t0,TLAT_t6,TLAT_t12,TLAT_t18,TLAT_t24,TLAT_t30,TLAT_t36,TLAT_t42,TLAT_t48,TLAT_t54,TLAT_t60,TLAT_t66,TLAT_t72,TLAT_t78,TLAT_t84,TLAT_t90,TLAT_t96,TLAT_t102,TLAT_t108,TLAT_t114,TLAT_t120,TLON_t-12,TLON_t-6,TLON_t0,TLON_t6,TLON_t12,TLON_t18,TLON_t24,TLON_t30,TLON_t36,TLON_t42,TLON_t48,TLON_t54,TLON_t60,TLON_t66,TLON_t72,TLON_t78,TLON_t84,TLON_t90,TLON_t96,TLON_t102,TLON_t108,TLON_t114,TLON_t120,TWAC_t-12,TWAC_t-6,TWAC_t0,TWAC_t6,TWAC_t12,TWAC_t18,TWAC_t24,TWAC_t30,TWAC_t36,TWAC_t42,TWAC_t48,TWAC_t54,TWAC_t60,TWAC_t66,TWAC_t72,TWAC_t78,TWAC_t84,TWAC_t90,TWAC_t96,TWAC_t102,TWAC_t108,TWAC_t114,TWAC_t120,TWXC_t-12,TWXC_t-6,TWXC_t0,TWXC_t6,TWXC_t12,TWXC_t18,TWXC_t24,TWXC_t30,TWXC_t36,TWXC_t42,TWXC_t48,TWXC_t54,TWXC_t60,TWXC_t66,TWXC_t72,TWXC_t78,TWXC_t84,TWXC_t90,TWXC_t96,TWXC_t102,TWXC_t108,TWXC_t114,TWXC_t120,G150_t-12,G150_t-6,G150_t0,G150_t6,G150_t12,G150_t18,G150_t24,G150_t30,G150_t36,G150_t42,G150_t48,G150_t54,G150_t60,G150_t66,G150_t72,G150_t78,G150_t84,G150_t90,G150_t96,G150_t102,G150_t108,G150_t114,G150_t120,G200_t-12,G200_t-6,G200_t0,G200_t6,G200_t12,G200_t18,G200_t24,G200_t30,G200_t36,G200_t42,G200_t48,G200_t54,G200_t60,G200_t66,G200_t72,G200_t78,G200_t84,G200_t90,G200_t96,G200_t102,G200_t108,G200_t114,G200_t120,G250_t-12,G250_t-6,G250_t0,G250_t6,G250_t12,G250_t18,G250_t24,G250_t30,G250_t36,G250_t42,G250_t48,G250_t54,G250_t60,G250_t66,G250_t72,G250_t78,G250_t84,G250_t90,G250_t96,G250_t102,G250_t108,G250_t114,G250_t120,V000_t-12,V000_t-6,V000_t0,V000_t6,V000_t12,V000_t18,V000_t24,V000_t30,V000_t36,V000_t42,V000_t48,V000_t54,V000_t60,V000_t66,V000_t72,V000_t78,V000_t84,V000_t90,V000_t96,V000_t102,V000_t108,V000_t114,V000_t120,V850_t-12,V850_t-6,V850_t0,V850_t6,V850_t12,V850_t18,V850_t24,V850_t30,V850_t36,V850_t42,V850_t48,V850_t54,V850_t60,V850_t66,V850_t72,V850_t78,V850_t84,V850_t90,V850_t96,V850_t102,V850_t108,V850_t114,V850_t120,V500_t-12,V500_t-6,V500_t0,V500_t6,V500_t12,V500_t18,V500_t24,V500_t30,V500_t36,V500_t42,V500_t48,V500_t54,V500_t60,V500_t66,V500_t72,V500_t78,V500_t84,V500_t90,V500_t96,V500_t102,V500_t108,V500_t114,V500_t120,V300_t-12,V300_t-6,V300_t0,V300_t6,V300_t12,V300_t18,V300_t24,V300_t30,V300_t36,V300_t42,V300_t48,V300_t54,V300_t60,V300_t66,V300_t72,V300_t78,V300_t84,V300_t90,V300_t96,V300_t102,V300_t108,V300_t114,V300_t120,TGRD_t-12,TGRD_t-6,TGRD_t0,TGRD_t6,TGRD_t12,TGRD_t18,TGRD_t24,TGRD_t30,TGRD_t36,TGRD_t42,TGRD_t48,TGRD_t54,TGRD_t60,TGRD_t66,TGRD_t72,TGRD_t78,TGRD_t84,TGRD_t90,TGRD_t96,TGRD_t102,TGRD_t108,TGRD_t114,TGRD_t120,TADV_t-12,TADV_t-6,TADV_t0,TADV_t6,TADV_t12,TADV_t18,TADV_t24,TADV_t30,TADV_t36,TADV_t42,TADV_t48,TADV_t54,TADV_t60,TADV_t66,TADV_t72,TADV_t78,TADV_t84,TADV_t90,TADV_t96,TADV_t102,TADV_t108,TADV_t114,TADV_t120,PENC_t-12,PENC_t-6,PENC_t0,PENC_t6,PENC_t12,PENC_t18,PENC_t24,PENC_t30,PENC_t36,PENC_t42,PENC_t48,PENC_t54,PENC_t60,PENC_t66,PENC_t72,PENC_t78,PENC_t84,PENC_t90,PENC_t96,PENC_t102,PENC_t108,PENC_t114,PENC_t120,SHDC_t-12,SHDC_t-6,SHDC_t0,SHDC_t6,SHDC_t12,SHDC_t18,SHDC_t24,SHDC_t30,SHDC_t36,SHDC_t42,SHDC_t48,SHDC_t54,SHDC_t60,SHDC_t66,SHDC_t72,SHDC_t78,SHDC_t84,SHDC_t90,SHDC_t96,SHDC_t102,SHDC_t108,SHDC_t114,SHDC_t120,SDDC_t-12,SDDC_t-6,SDDC_t0,SDDC_t6,SDDC_t12,SDDC_t18,SDDC_t24,SDDC_t30,SDDC_t36,SDDC_t42,SDDC_t48,SDDC_t54,SDDC_t60,SDDC_t66,SDDC_t72,SDDC_t78,SDDC_t84,SDDC_t90,SDDC_t96,SDDC_t102,SDDC_t108,SDDC_t114,SDDC_t120,SHGC_t-12,SHGC_t-6,SHGC_t0,SHGC_t6,SHGC_t12,SHGC_t18,SHGC_t24,SHGC_t30,SHGC_t36,SHGC_t42,SHGC_t48,SHGC_t54,SHGC_t60,SHGC_t66,SHGC_t72,SHGC_t78,SHGC_t84,SHGC_t90,SHGC_t96,SHGC_t102,SHGC_t108,SHGC_t114,SHGC_t120,DIVC_t-12,DIVC_t-6,DIVC_t0,DIVC_t6,DIVC_t12,DIVC_t18,DIVC_t24,DIVC_t30,DIVC_t36,DIVC_t42,DIVC_t48,DIVC_t54,DIVC_t60,DIVC_t66,DIVC_t72,DIVC_t78,DIVC_t84,DIVC_t90,DIVC_t96,DIVC_t102,DIVC_t108,DIVC_t114,DIVC_t120,T150_t-12,T150_t-6,T150_t0,T150_t6,T150_t12,T150_t18,T150_t24,T150_t30,T150_t36,T150_t42,T150_t48,T150_t54,T150_t60,T150_t66,T150_t72,T150_t78,T150_t84,T150_t90,T150_t96,T150_t102,T150_t108,T150_t114,T150_t120,T200_t-12,T200_t-6,T200_t0,T200_t6,T200_t12,T200_t18,T200_t24,T200_t30,T200_t36,T200_t42,T200_t48,T200_t54,T200_t60,T200_t66,T200_t72,T200_t78,T200_t84,T200_t90,T200_t96,T200_t102,T200_t108,T200_t114,T200_t120,T250_t-12,T250_t-6,T250_t0,T250_t6,T250_t12,T250_t18,T250_t24,T250_t30,T250_t36,T250_t42,T250_t48,T250_t54,T250_t60,T250_t66,T250_t72,T250_t78,T250_t84,T250_t90,T250_t96,T250_t102,T250_t108,T250_t114,T250_t120,SHRD_t-12,SHRD_t-6,SHRD_t0,SHRD_t6,SHRD_t12,SHRD_t18,SHRD_t24,SHRD_t30,SHRD_t36,SHRD_t42,SHRD_t48,SHRD_t54,SHRD_t60,SHRD_t66,SHRD_t72,SHRD_t78,SHRD_t84,SHRD_t90,SHRD_t96,SHRD_t102,SHRD_t108,SHRD_t114,SHRD_t120,SHTD_t-12,SHTD_t-6,SHTD_t0,SHTD_t6,SHTD_t12,SHTD_t18,SHTD_t24,SHTD_t30,SHTD_t36,SHTD_t42,SHTD_t48,SHTD_t54,SHTD_t60,SHTD_t66,SHTD_t72,SHTD_t78,SHTD_t84,SHTD_t90,SHTD_t96,SHTD_t102,SHTD_t108,SHTD_t114,SHTD_t120,SHRS_t-12,SHRS_t-6,SHRS_t0,SHRS_t6,SHRS_t12,SHRS_t18,SHRS_t24,SHRS_t30,SHRS_t36,SHRS_t42,SHRS_t48,SHRS_t54,SHRS_t60,SHRS_t66,SHRS_t72,SHRS_t78,SHRS_t84,SHRS_t90,SHRS_t96,SHRS_t102,SHRS_t108,SHRS_t114,SHRS_t120,SHTS_t-12,SHTS_t-6,SHTS_t0,SHTS_t6,SHTS_t12,SHTS_t18,SHTS_t24,SHTS_t30,SHTS_t36,SHTS_t42,SHTS_t48,SHTS_t54,SHTS_t60,SHTS_t66,SHTS_t72,SHTS_t78,SHTS_t84,SHTS_t90,SHTS_t96,SHTS_t102,SHTS_t108,SHTS_t114,SHTS_t120,SHRG_t-12,SHRG_t-6,SHRG_t0,SHRG_t6,SHRG_t12,SHRG_t18,SHRG_t24,SHRG_t30,SHRG_t36,SHRG_t42,SHRG_t48,SHRG_t54,SHRG_t60,SHRG_t66,SHRG_t72,SHRG_t78,SHRG_t84,SHRG_t90,SHRG_t96,SHRG_t102,SHRG_t108,SHRG_t114,SHRG_t120,PENV_t-12,PENV_t-6,PENV_t0,PENV_t6,PENV_t12,PENV_t18,PENV_t24,PENV_t30,PENV_t36,PENV_t42,PENV_t48,PENV_t54,PENV_t60,PENV_t66,PENV_t72,PENV_t78,PENV_t84,PENV_t90,PENV_t96,PENV_t102,PENV_t108,PENV_t114,PENV_t120,VMPI_t-12,VMPI_t-6,VMPI_t0,VMPI_t6,VMPI_t12,VMPI_t18,VMPI_t24,VMPI_t30,VMPI_t36,VMPI_t42,VMPI_t48,VMPI_t54,VMPI_t60,VMPI_t66,VMPI_t72,VMPI_t78,VMPI_t84,VMPI_t90,VMPI_t96,VMPI_t102,VMPI_t108,VMPI_t114,VMPI_t120,VVAV_t-12,VVAV_t-6,VVAV_t0,VVAV_t6,VVAV_t12,VVAV_t18,VVAV_t24,VVAV_t30,VVAV_t36,VVAV_t42,VVAV_t48,VVAV_t54,VVAV_t60,VVAV_t66,VVAV_t72,VVAV_t78,VVAV_t84,VVAV_t90,VVAV_t96,VVAV_t102,VVAV_t108,VVAV_t114,VVAV_t120,VMFX_t-12,VMFX_t-6,VMFX_t0,VMFX_t6,VMFX_t12,VMFX_t18,VMFX_t24,VMFX_t30,VMFX_t36,VMFX_t42,VMFX_t48,VMFX_t54,VMFX_t60,VMFX_t66,VMFX_t72,VMFX_t78,VMFX_t84,VMFX_t90,VMFX_t96,VMFX_t102,VMFX_t108,VMFX_t114,VMFX_t120,VVAC_t-12,VVAC_t-6,VVAC_t0,VVAC_t6,VVAC_t12,VVAC_t18,VVAC_t24,VVAC_t30,VVAC_t36,VVAC_t42,VVAC_t48,VVAC_t54,VVAC_t60,VVAC_t66,VVAC_t72,VVAC_t78,VVAC_t84,VVAC_t90,VVAC_t96,VVAC_t102,VVAC_t108,VVAC_t114,VVAC_t120,HE07_t-12,HE07_t-6,HE07_t0,HE07_t6,HE07_t12,HE07_t18,HE07_t24,HE07_t30,HE07_t36,HE07_t42,HE07_t48,HE07_t54,HE07_t60,HE07_t66,HE07_t72,HE07_t78,HE07_t84,HE07_t90,HE07_t96,HE07_t102,HE07_t108,HE07_t114,HE07_t120,HE05_t-12,HE05_t-6,HE05_t0,HE05_t6,HE05_t12,HE05_t18,HE05_t24,HE05_t30,HE05_t36,HE05_t42,HE05_t48,HE05_t54,HE05_t60,HE05_t66,HE05_t72,HE05_t78,HE05_t84,HE05_t90,HE05_t96,HE05_t102,HE05_t108,HE05_t114,HE05_t120,O500_t-12,O500_t-6,O500_t0,O500_t6,O500_t12,O500_t18,O500_t24,O500_t30,O500_t36,O500_t42,O500_t48,O500_t54,O500_t60,O500_t66,O500_t72,O500_t78,O500_t84,O500_t90,O500_t96,O500_t102,O500_t108,O500_t114,O500_t120,O700_t-12,O700_t-6,O700_t0,O700_t6,O700_t12,O700_t18,O700_t24,O700_t30,O700_t36,O700_t42,O700_t48,O700_t54,O700_t60,O700_t66,O700_t72,O700_t78,O700_t84,O700_t90,O700_t96,O700_t102,O700_t108,O700_t114,O700_t120,CFLX_t-12,CFLX_t-6,CFLX_t0,CFLX_t6,CFLX_t12,CFLX_t18,CFLX_t24,CFLX_t30,CFLX_t36,CFLX_t42,CFLX_t48,CFLX_t54,CFLX_t60,CFLX_t66,CFLX_t72,CFLX_t78,CFLX_t84,CFLX_t90,CFLX_t96,CFLX_t102,CFLX_t108,CFLX_t114,CFLX_t120,RD20_t-12,RD20_t-6,RD20_t0,RD20_t6,RD20_t12,RD20_t18,RD20_t24,RD20_t30,RD20_t36,RD20_t42,RD20_t48,RD20_t54,RD20_t60,RD20_t66,RD20_t72,RD20_t78,RD20_t84,RD20_t90,RD20_t96,RD20_t102,RD20_t108,RD20_t114,RD20_t120,RD26_t-12,RD26_t-6,RD26_t0,RD26_t6,RD26_t12,RD26_t18,RD26_t24,RD26_t30,RD26_t36,RD26_t42,RD26_t48,RD26_t54,RD26_t60,RD26_t66,RD26_t72,RD26_t78,RD26_t84,RD26_t90,RD26_t96,RD26_t102,RD26_t108,RD26_t114,RD26_t120,RHCN_t-12,RHCN_t-6,RHCN_t0,RHCN_t6,RHCN_t12,RHCN_t18,RHCN_t24,RHCN_t30,RHCN_t36,RHCN_t42,RHCN_t48,RHCN_t54,RHCN_t60,RHCN_t66,RHCN_t72,RHCN_t78,RHCN_t84,RHCN_t90,RHCN_t96,RHCN_t102,RHCN_t108,RHCN_t114,RHCN_t120,dt,basin,dvs24,DELV-12,vs0_hurdat2,type,vs0_hurdart2 +0,EP011982,1982.0,5.0,20.0,0.0,-1.0315916181790117,11.0,-104.8,,,,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,-0.4944458290088734,0.07006703825193554,-0.14437389186924848,-0.3893164105228855,0.5099027642365135,-0.13367606434857732,0.3828660700090888,0.0,-0.7636442502969031,0.9955953799463906,1.1861328555190598,0.8359099504351011,0.16387257852206216,-0.12846681238962868,0.41280498181763237,-1.376082186782579,0.06260620475105966,0.3144762802408857,,,,,,,-0.9402457854890202,0.4869366874144954,-0.10926201189019209,-0.596149233987493,0.46459618019767207,-1.0394235158066012,0.5479707063196236,-1.404887088911353,0.5270652096344695,-1.1228927570463492,-0.3152017541810493,-0.7203759300477701,0.13277114832516893,-1.2745168375757843,0.3233729441484971,-1.535507643112255,0.4013449788194634,-1.4443577446507971,-0.4681021309027031,-0.2978654269755266,-0.0369485108476138,,,,-1.0368968505843295,-0.11754250016559273,0.44654432874780986,-0.23637451076469088,0.3537308317172745,0.15818162954262416,0.12689792292266275,0.07023945021636056,0.04313351366892925,0.05070604901929271,0.01437149733511889,-0.27913935966121667,-0.258366685834935,0.23054755152178041,-0.10953892209021478,-0.09749193032214169,-0.3239351143387116,-0.40123727254616703,-0.4121857677746919,-0.27710843483140624,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,110.0,112.0,114.0,116.0,120.0,123.0,,,,,,,,,,,,,,,,,,1048.0,1052.0,1056.0,1058.0,1060.0,1057.0,,,,,,,,,,,,,,,,,,296.0,295.0,295.0,295.0,0.7812241435956742,293.0,,,,,,,,,,,,,,,,,,81.0,84.0,87.0,87.0,-0.5881381431795067,91.0,,,,,,,,,,,,,,,,,,54.0,56.0,58.0,58.0,0.2828759611075288,61.0,,,,,,,,,,,,,,,,,,62.0,65.0,66.0,67.0,0.9392951894908659,69.0,,,,,,,,,,,,,,,,,,807.0,798.0,793.0,781.0,-0.08433541804573744,706.0,,,,,,,,,,,,,,,,,,0.0,52.0,87.0,122.0,129.0,155.0,,,,,,,,,,,,,,,,,,0.0,13.0,22.0,30.0,34.0,43.0,,,,,,,,,,,,,,,,,,301.0,300.0,299.0,299.0,0.9297791942261278,298.0,,,,,,,,,,,,,,,,,,14.0,-35.0,-51.0,-61.0,-0.5921103931845805,-85.0,,,,,,,,,,,,,,,,,,7.0,-49.0,-61.0,-60.0,-0.43344707550482403,-87.0,,,,,,,,,,,,,,,,,,25.0,29.0,66.0,72.0,0.42594286447800916,67.0,,,,,,,,,,,,,,,,,,3517.0,3513.0,3506.0,3507.0,0.262185018840284,3503.0,,,,,,,,,,,,,,,,,,90.0,89.0,86.0,86.0,0.21009550498440782,83.0,,,,,,,,,,,,,,,,,,6.0,7.0,8.0,8.0,-0.41108023865910587,8.0,,,,,,,,,,,,,,,,,,51.0,51.0,49.0,48.0,0.45564177041452597,39.0,,,,,,,,,,,,,,,,,,19.0,19.0,19.0,20.0,-0.5048516901193287,21.0,,,,,,,,,,,,,,,,,,80.0,80.0,81.0,80.0,0.5765125321608614,77.0,,,,,,,,,,,,,,,,,,74.0,77.0,76.0,75.0,0.833652404128912,72.0,,,,,,,,,,,,,,,,,,70.0,75.0,74.0,72.0,0.9864935180154539,70.0,,,,,,,,,,,,,,,,,,22.0,30.0,29.0,32.0,0.024792791330014254,24.0,,,,,,,,,,,,,,,,,,73.0,57.0,69.0,48.0,0.5426046153168167,76.0,,,,,,,,,,,,,,,,,,0.0,0.0,5.0,4.0,0.4137571621744331,4.0,,,,,,,,,,,,,,,,,,0.0,0.0,-1.0,-1.0,-0.1239647560359718,0.0,,,,,,,,,,,,,,,,,,268.0,266.0,263.0,265.0,0.28340235273189146,266.0,,,,,,,,,,,,,,,,,,77.0,78.0,78.0,77.0,-0.22009264815564847,76.0,,,,,,,,,,,,,,,,,,-37.0,-14.0,-26.0,-13.0,-0.12885475902247956,-13.0,,,,,,,,,,,,,,,,,,96.0,104.0,109.0,114.0,-0.1072642969651399,118.0,,,,,,,,,,,,,,,,,,1083.0,1089.0,1093.0,1099.0,0.08022840112357296,1106.0,,,,,,,,,,,,,,,,,,,,,,-0.022873258782612694,,,,,,,,,,,,,,,,,,,,,,,-0.02616517992223538,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.006311918262341462,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.8139984424667978,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.9890844188759867,0.0,,,,,,,,,,,,,,,,,,30.0,38.0,38.0,33.0,-0.12531531421285141,12.0,,,,,,,,,,,,,,,,,,41.0,43.0,51.0,38.0,-0.23871918822725818,18.0,,,,,,,,,,,,,,,,,,-5.0,7.0,0.0,1.0,-0.6187198709039673,-10.0,,,,,,,,,,,,,,,,,,1.0,-7.0,-3.0,4.0,-0.5436283146681776,-22.0,,,,,,,,,,,,,,,,,,22.0,15.0,14.0,13.0,-0.5231862120438843,13.0,,,,,,,,,,,,,,,,,,-9.0,-5.0,-4.0,-4.0,-0.4619541246448418,-3.0,,,,,,,,,,,,,,,,,,86.0,113.0,100.0,114.0,-0.8358856366223678,114.0,,,,,,,,,,,,,,,,,,64.0,56.0,61.0,42.0,-0.605146539777968,121.0,,,,,,,,,,,,,,,,,,156.0,216.0,274.0,272.0,1.0350656986662643,278.0,,,,,,,,,,,,,,,,,,283.0,237.0,212.0,197.0,-0.23887142404507133,280.0,,,,,,,,,,,,,,,,,,,,,,0.0124811395637873,,,,,,,,,,,,,,,,,,,-688.0,-689.0,-690.0,-689.0,-1.2099246457665007,-688.0,,,,,,,,,,,,,,,,,,-529.0,-534.0,-537.0,-536.0,-0.6525019843689088,-536.0,,,,,,,,,,,,,,,,,,-405.0,-410.0,-412.0,-412.0,-0.29720170323503503,-411.0,,,,,,,,,,,,,,,,,,42.0,40.0,72.0,70.0,-0.4420656072995849,145.0,,,,,,,,,,,,,,,,,,168.0,244.0,282.0,287.0,1.4175069440341426,296.0,,,,,,,,,,,,,,,,,,116.0,111.0,109.0,106.0,0.7705098808349518,128.0,,,,,,,,,,,,,,,,,,253.0,258.0,267.0,280.0,1.127644559623935,274.0,,,,,,,,,,,,,,,,,,220.0,181.0,162.0,153.0,-0.5173290848203888,233.0,,,,,,,,,,,,,,,,,,83.0,110.0,96.0,112.0,-0.13915545549866373,111.0,,,,,,,,,,,,,,,,,,165.0,164.0,164.0,163.0,1.1533920652395464,163.0,,,,,,,,,,,,,,,,,,2022.0,2157.0,2201.0,2039.0,1.9557932653376564,1867.0,,,,,,,,,,,,,,,,,,1201.0,1250.0,1275.0,1204.0,1.8209616967726059,1117.0,,,,,,,,,,,,,,,,,,1930.0,2111.0,2222.0,2132.0,1.772459721828486,1837.0,,,,,,,,,,,,,,,,,,-41.0,-16.0,-9.0,0.0,0.3426459038647577,30.0,,,,,,,,,,,,,,,,,,-69.0,-38.0,-16.0,-8.0,0.27536619988852173,50.0,,,,,,,,,,,,,,,,,,-123.0,-121.0,-111.0,-82.0,-0.24221017765167457,-69.0,,,,,,,,,,,,,,,,,,-103.0,-98.0,-92.0,-58.0,-0.02449375507617723,-58.0,,,,,,,,,,,,,,,,,,42.0,39.0,38.0,39.0,-0.9258851174882504,53.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1982-05-20 00:00:00,EP,5.0042583333333335,-0.11210317676512918,25.021291666666666,rea, +1,EP011982,1982.0,5.0,20.0,6.0,-1.0315916181790117,11.2,-105.2,,,,2.0,2.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,0.3696563590666602,0.2060690633905766,-0.14437389186924848,-0.46886971544550266,0.4676374511638913,-0.07664894101011929,0.33919874706083675,0.0,-0.6858662905345365,0.854786956278186,0.8397690718784215,0.2855845505581039,-0.6907425470600721,-1.0045544833460494,-0.28532784761590585,-0.6584388940048674,0.8559104618341395,0.7191645071245517,,,,,,,-0.5136859307537515,-0.6200064401028877,0.03366948498891604,-0.8265627103283022,0.5624398386769307,-0.9120554827757242,0.632099459693117,-1.263819113151065,0.5842841665743422,-1.0907525144977186,-0.08261614003203359,-1.1105330083005909,0.2927758915810643,-1.3201833240856489,0.4548545196539985,-1.494831699251035,0.5047243843416535,-1.3302035905490153,-0.4681021309027031,-0.05128235470877785,0.13756870328336956,,,,-1.0368968505843295,0.006851262380765589,0.5193312061226751,-0.006687699432003248,0.3885391397158638,0.019196832239975092,-0.04527659713076386,-0.05406204693216612,-0.07956320993973821,-0.11527834937216286,-0.12214622168028053,-0.20921891953764896,-0.18869896888038484,0.1277175677892672,-0.035730229070642425,-0.009281437680898657,-0.36002244230646974,-0.5023054665629844,-0.506520224878044,-0.38070683799326227,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,110.0,112.0,114.0,116.0,120.0,123.0,125.0,,,,,,,,,,,,,,,,,1048.0,1052.0,1056.0,1058.0,1060.0,1057.0,1055.0,,,,,,,,,,,,,,,,,296.0,295.0,295.0,295.0,293.0,0.7812241435956742,293.0,,,,,,,,,,,,,,,,,81.0,84.0,87.0,87.0,91.0,-0.5881381431795067,91.0,,,,,,,,,,,,,,,,,54.0,56.0,58.0,58.0,60.0,0.3194837706771795,61.0,,,,,,,,,,,,,,,,,62.0,65.0,66.0,67.0,69.0,0.9392951894908659,68.0,,,,,,,,,,,,,,,,,807.0,798.0,793.0,781.0,750.0,-0.14628817067999436,676.0,,,,,,,,,,,,,,,,,0.0,52.0,87.0,122.0,129.0,155.0,175.0,,,,,,,,,,,,,,,,,0.0,13.0,22.0,30.0,34.0,43.0,49.0,,,,,,,,,,,,,,,,,301.0,300.0,299.0,299.0,298.0,0.9297791942261278,298.0,,,,,,,,,,,,,,,,,,-35.0,-51.0,-61.0,-77.0,-0.6441574606151826,-56.0,,,,,,,,,,,,,,,,,,-49.0,-61.0,-60.0,-75.0,-0.5116201422955093,-73.0,,,,,,,,,,,,,,,,,,29.0,66.0,72.0,77.0,0.3389068372255068,64.0,,,,,,,,,,,,,,,,,,3513.0,3506.0,3507.0,3511.0,0.1576405305253109,3497.0,,,,,,,,,,,,,,,,,,89.0,86.0,86.0,87.0,0.07717603541485121,82.0,,,,,,,,,,,,,,,,,,7.0,8.0,8.0,7.0,-0.36100830134702366,8.0,,,,,,,,,,,,,,,,,,51.0,49.0,48.0,41.0,0.36999451767499464,35.0,,,,,,,,,,,,,,,,,,19.0,19.0,20.0,20.0,-0.47085103250185334,20.0,,,,,,,,,,,,,,,,,,80.0,81.0,80.0,77.0,0.5765125321608614,76.0,,,,,,,,,,,,,,,,,,77.0,76.0,75.0,71.0,0.9144430172824665,70.0,,,,,,,,,,,,,,,,,,75.0,74.0,72.0,68.0,1.124126088888085,67.0,,,,,,,,,,,,,,,,,,30.0,29.0,32.0,29.0,-0.032553116191617354,25.0,,,,,,,,,,,,,,,,,,57.0,69.0,48.0,65.0,0.807403882231412,61.0,,,,,,,,,,,,,,,,,,0.0,5.0,4.0,4.0,0.4137571621744331,4.0,,,,,,,,,,,,,,,,,,0.0,-1.0,-1.0,-1.0,0.10013080822808398,0.0,,,,,,,,,,,,,,,,,,266.0,263.0,265.0,267.0,0.23681726198461595,263.0,,,,,,,,,,,,,,,,,,78.0,78.0,77.0,76.0,-0.22009264815564847,77.0,,,,,,,,,,,,,,,,,,-14.0,-26.0,-13.0,-34.0,0.4531054218495989,-30.0,,,,,,,,,,,,,,,,,,104.0,109.0,114.0,116.0,-0.09484400891658896,116.0,,,,,,,,,,,,,,,,,,1089.0,1093.0,1099.0,1104.0,0.08581022142934905,1110.0,,,,,,,,,,,,,,,,,,,,,,-0.022873258782612694,,,,,,,,,,,,,,,,,,,,,,,-0.02616517992223538,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.006311918262341462,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.8139984424667978,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.9890844188759867,0.0,,,,,,,,,,,,,,,,,,38.0,38.0,33.0,31.0,-0.4361222041456892,6.0,,,,,,,,,,,,,,,,,,43.0,51.0,38.0,31.0,-0.39704628824689064,11.0,,,,,,,,,,,,,,,,,,7.0,0.0,1.0,-2.0,-0.7447421174156942,-13.0,,,,,,,,,,,,,,,,,,-7.0,-3.0,4.0,-14.0,-0.7296940486357019,-14.0,,,,,,,,,,,,,,,,,,15.0,14.0,13.0,11.0,-0.41253904048351164,10.0,,,,,,,,,,,,,,,,,,-5.0,-4.0,-4.0,-4.0,-0.3820690089855971,0.0,,,,,,,,,,,,,,,,,,113.0,100.0,114.0,90.0,-0.12333317745252684,98.0,,,,,,,,,,,,,,,,,,56.0,61.0,42.0,93.0,-0.33286935315929356,107.0,,,,,,,,,,,,,,,,,,216.0,274.0,272.0,268.0,1.1402108021781174,298.0,,,,,,,,,,,,,,,,,,237.0,212.0,197.0,237.0,0.11580496845789838,223.0,,,,,,,,,,,,,,,,,,,,,,0.0124811395637873,,,,,,,,,,,,,,,,,,,-689.0,-690.0,-689.0,-687.0,-1.260941137310942,-686.0,,,,,,,,,,,,,,,,,,-534.0,-537.0,-536.0,-533.0,-0.810923924455043,-537.0,,,,,,,,,,,,,,,,,,-410.0,-412.0,-412.0,-407.0,-0.4883323577799961,-412.0,,,,,,,,,,,,,,,,,,40.0,72.0,70.0,120.0,-0.19518724115201955,118.0,,,,,,,,,,,,,,,,,,244.0,282.0,287.0,291.0,1.4719543849535102,308.0,,,,,,,,,,,,,,,,,,111.0,109.0,106.0,114.0,1.0511921033308216,97.0,,,,,,,,,,,,,,,,,,258.0,267.0,280.0,271.0,1.1595294425886549,284.0,,,,,,,,,,,,,,,,,,181.0,162.0,153.0,195.0,-0.19499485369746425,188.0,,,,,,,,,,,,,,,,,,110.0,96.0,112.0,87.0,0.43135868216819756,92.0,,,,,,,,,,,,,,,,,,164.0,164.0,163.0,162.0,1.1804579171599574,165.0,,,,,,,,,,,,,,,,,,2157.0,2201.0,2039.0,1781.0,2.122514533040954,1943.0,,,,,,,,,,,,,,,,,,1250.0,1275.0,1204.0,1086.0,1.9274431063136688,1160.0,,,,,,,,,,,,,,,,,,2111.0,2222.0,2132.0,1810.0,1.8215132928148094,1900.0,,,,,,,,,,,,,,,,,,-16.0,-9.0,0.0,12.0,0.7735203895258341,27.0,,,,,,,,,,,,,,,,,,-38.0,-16.0,-8.0,14.0,0.8593321944866317,43.0,,,,,,,,,,,,,,,,,,-121.0,-111.0,-82.0,-67.0,-0.2822284229747837,-11.0,,,,,,,,,,,,,,,,,,-98.0,-92.0,-58.0,-50.0,-0.20936773848587845,-7.0,,,,,,,,,,,,,,,,,,39.0,38.0,39.0,56.0,-0.9408288800358652,69.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1982-05-20 06:00:00,EP,5.0042583333333335,-0.11210317676512918,25.021291666666666,rea, +2,EP011982,1982.0,5.0,20.0,12.0,-1.0315916181790117,11.4,-105.6,,,,3.0,3.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,-0.252497216347724,0.07006703825193554,-0.14437389186924848,-0.20369203237011227,0.3408415119460249,-0.04813537934089029,0.2518641011643326,0.0,-0.06364261243560451,0.6576551631426997,0.38949615314559194,0.07392093522079732,-0.13639760073652557,-0.1635103192278855,0.40172350833456033,-0.4690608028551936,-0.06805567288615351,-0.04761318591818389,,,,,,,-0.4852486071047335,-0.9889874826086821,0.047962634676826855,-0.9417694484987068,0.46459618019767207,-1.0394235158066012,0.5199277885284592,-1.263819113151065,0.4841509919295649,-0.9300513017545659,-0.06807953914772011,-1.222006459229968,0.23459234857892053,-1.4115162971053785,0.36720013598366424,-1.4541557553898155,0.41611346532263344,-1.2541008211478275,-0.4681021309027031,0.013607927466682341,0.10848250092820567,,,,-1.0368968505843295,-0.014782435453383685,0.5193312061226751,-0.07048959146886093,0.4059432937151584,0.019196832239975092,-0.002232967117407207,-0.012628214549323892,-0.03866430207018239,-0.07378224977429897,-0.07664031534181405,-0.20921891953764896,-0.1968951708750378,0.1277175677892672,-0.04065080860528058,-0.019082603529925662,-0.3239351143387116,-0.45177136955457564,-0.4541121931539595,-0.3231521695700089,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,110.0,112.0,114.0,116.0,120.0,123.0,125.0,128.0,,,,,,,,,,,,,,,,1048.0,1052.0,1056.0,1058.0,1060.0,1057.0,1055.0,1052.0,,,,,,,,,,,,,,,,296.0,295.0,295.0,295.0,293.0,293.0,0.7812241435956742,293.0,,,,,,,,,,,,,,,,81.0,84.0,87.0,87.0,91.0,91.0,-0.5881381431795067,90.0,,,,,,,,,,,,,,,,54.0,56.0,58.0,58.0,60.0,61.0,0.3194837706771795,61.0,,,,,,,,,,,,,,,,62.0,65.0,66.0,67.0,69.0,69.0,0.9084658885622111,67.0,,,,,,,,,,,,,,,,807.0,798.0,793.0,781.0,750.0,706.0,-0.18852868383971497,632.0,,,,,,,,,,,,,,,,0.0,52.0,87.0,122.0,129.0,155.0,175.0,158.0,,,,,,,,,,,,,,,,0.0,13.0,22.0,30.0,34.0,43.0,49.0,47.0,,,,,,,,,,,,,,,,301.0,300.0,299.0,299.0,298.0,298.0,0.9297791942261278,297.0,,,,,,,,,,,,,,,,,,-51.0,-61.0,-77.0,-85.0,-0.4554868411792499,-79.0,,,,,,,,,,,,,,,,,,-61.0,-60.0,-75.0,-87.0,-0.4204182310397098,-89.0,,,,,,,,,,,,,,,,,,66.0,72.0,77.0,67.0,0.3127960290497561,36.0,,,,,,,,,,,,,,,,,,3506.0,3507.0,3511.0,3503.0,0.07923216428908113,3504.0,,,,,,,,,,,,,,,,,,86.0,86.0,87.0,83.0,0.043946168022462054,86.0,,,,,,,,,,,,,,,,,,8.0,8.0,7.0,8.0,-0.36100830134702366,8.0,,,,,,,,,,,,,,,,,,49.0,48.0,41.0,39.0,0.1987000121959319,33.0,,,,,,,,,,,,,,,,,,19.0,20.0,20.0,21.0,-0.5048516901193287,21.0,,,,,,,,,,,,,,,,,,81.0,80.0,77.0,77.0,0.45398626626717725,75.0,,,,,,,,,,,,,,,,,,76.0,75.0,71.0,72.0,0.7528617909753573,65.0,,,,,,,,,,,,,,,,,,74.0,72.0,68.0,70.0,0.9176772325791384,59.0,,,,,,,,,,,,,,,,,,29.0,32.0,29.0,24.0,-0.021083934687291035,30.0,,,,,,,,,,,,,,,,,,69.0,48.0,65.0,76.0,0.44631397280241836,71.0,,,,,,,,,,,,,,,,,,5.0,4.0,4.0,4.0,0.4137571621744331,1.0,,,,,,,,,,,,,,,,,,-1.0,-1.0,-1.0,0.0,0.10013080822808398,0.0,,,,,,,,,,,,,,,,,,263.0,265.0,267.0,266.0,0.09706198974278943,267.0,,,,,,,,,,,,,,,,,,78.0,77.0,76.0,76.0,0.005111481345015959,75.0,,,,,,,,,,,,,,,,,,-26.0,-13.0,-34.0,-13.0,-0.018005200761131285,-20.0,,,,,,,,,,,,,,,,,,109.0,114.0,116.0,118.0,-0.1072642969651399,116.0,,,,,,,,,,,,,,,,,,1093.0,1099.0,1104.0,1106.0,0.09697386204090122,1113.0,,,,,,,,,,,,,,,,,,,,,,-0.022873258782612694,,,,,,,,,,,,,,,,,,,,,,,-0.02616517992223538,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.006311918262341462,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.8139984424667978,0.0,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,-0.9890844188759867,0.0,,,,,,,,,,,,,,,,,,38.0,33.0,31.0,12.0,-0.5342717483350063,5.0,,,,,,,,,,,,,,,,,,51.0,38.0,31.0,18.0,-0.4822993421036158,3.0,,,,,,,,,,,,,,,,,,0.0,1.0,-2.0,-10.0,-0.7920004598575918,-16.0,,,,,,,,,,,,,,,,,,-3.0,4.0,-14.0,-22.0,-0.5436283146681776,12.0,,,,,,,,,,,,,,,,,,14.0,13.0,11.0,13.0,-0.5785097978240705,6.0,,,,,,,,,,,,,,,,,,-4.0,-4.0,-4.0,-3.0,-0.14241366200786298,0.0,,,,,,,,,,,,,,,,,,100.0,114.0,90.0,114.0,-0.5983681502324208,107.0,,,,,,,,,,,,,,,,,,61.0,42.0,93.0,121.0,-0.46900794646863075,93.0,,,,,,,,,,,,,,,,,,274.0,272.0,268.0,278.0,1.3505010092018235,286.0,,,,,,,,,,,,,,,,,,212.0,197.0,237.0,280.0,-0.35434745881348007,206.0,,,,,,,,,,,,,,,,,,,,,,0.0124811395637873,,,,,,,,,,,,,,,,,,,-690.0,-689.0,-687.0,-688.0,-1.1589081542220594,-684.0,,,,,,,,,,,,,,,,,,-537.0,-536.0,-533.0,-536.0,-0.8637312378170877,-536.0,,,,,,,,,,,,,,,,,,-412.0,-412.0,-407.0,-411.0,-0.5361150214162363,-412.0,,,,,,,,,,,,,,,,,,72.0,70.0,120.0,145.0,-0.4618158765913901,99.0,,,,,,,,,,,,,,,,,,282.0,287.0,291.0,296.0,1.6026282431599923,293.0,,,,,,,,,,,,,,,,,,109.0,106.0,114.0,128.0,0.4296814678042527,71.0,,,,,,,,,,,,,,,,,,267.0,280.0,271.0,274.0,1.2658123858043877,284.0,,,,,,,,,,,,,,,,,,162.0,153.0,195.0,233.0,-0.576706443185138,174.0,,,,,,,,,,,,,,,,,,96.0,112.0,87.0,111.0,-0.020298343484734308,103.0,,,,,,,,,,,,,,,,,,164.0,163.0,162.0,163.0,1.2345896210007794,162.0,,,,,,,,,,,,,,,,,,2201.0,2039.0,1781.0,1867.0,2.2698496068252636,1567.0,,,,,,,,,,,,,,,,,,1275.0,1204.0,1086.0,1117.0,2.0751431259996593,980.0,,,,,,,,,,,,,,,,,,2222.0,2132.0,1810.0,1837.0,1.9359716251162304,1613.0,,,,,,,,,,,,,,,,,,-9.0,0.0,12.0,30.0,0.701707975248988,23.0,,,,,,,,,,,,,,,,,,-16.0,-8.0,14.0,50.0,0.7457832510925547,31.0,,,,,,,,,,,,,,,,,,-111.0,-82.0,-67.0,-69.0,0.8783006913953798,-41.0,,,,,,,,,,,,,,,,,,-92.0,-58.0,-50.0,-58.0,0.9692039057509668,-54.0,,,,,,,,,,,,,,,,,,38.0,39.0,56.0,53.0,-0.8611288131152534,77.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1982-05-20 12:00:00,EP,5.0042583333333335,-0.18864703231774538,25.021291666666666,rea, +54637,AL062016,2016.0,8.0,19.0,0.0,-0.32995603907597554,16.9,-41.5,,,,10.0,10.0,9.0,7.0,4.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,-0.4253176539628307,-0.31073863213625946,0.2717188154300445,-0.46886971544550266,0.4676374511638913,-0.39029811937163844,0.3828660700090888,0.0,0.2474692266138615,0.5450084242081361,0.42413253150965574,0.3279172736255652,0.11767716632843327,0.15188124231642597,0.2133384591223357,-0.34945358739224164,-0.37604438445958455,-0.02631380555588568,,,,,,,0.16880983682267853,0.8559177299202898,-0.26648665845721103,0.6135215168017555,-0.8073713800326902,1.083377034708015,-0.8121108065518516,0.5347975777926052,-1.0750655846819668,0.5162596129338093,-0.16983574533791448,0.8402523829635123,-0.5508854819500205,1.3284728934865064,-0.684652468060347,0.9457249324221448,-0.8392078874468172,0.8387253373848396,-0.4681021309027031,-0.025326241838593774,-0.41506914146474444,,,,0.43975091974138364,-0.4907237878046677,0.06441322252976726,0.8865387890840042,0.8758554516961139,-0.11978796506267399,-0.2174511171841905,-0.13692971169785056,0.0022346057993734296,0.1336982482150205,0.2874069353659177,-1.1453759234143055,-1.0452020773216193,1.4645073563119388,-0.8574670113552146,-0.9452927762629776,-0.9735070177583582,-0.8055100486134362,-0.8000052025329174,-0.7605676495867343,,,,,-115.0,-438.0,186.0,-122.0,271.0,63.0,51.0,45.0,40.0,35.0,28.0,-701.0,-708.0,2.0,-714.0,-583.0,22.0,31.0,54.0,50.0,,,,,-245.0,-333.0,221.0,-114.0,267.0,61.0,48.0,38.0,31.0,24.0,12.0,-533.0,-554.0,10.0,-578.0,-429.0,30.0,35.0,60.0,55.0,,,,,15.0,-12.0,-42.0,-124.0,-236.0,42.0,96.0,-18.0,21.0,-139.0,,,,,,,,,,,,,,,-115.0,13.0,-50.0,-135.0,-240.0,-31.0,101.0,-80.0,16.0,-164.0,,,,,,,,,,,,,,,-245.0,43.0,-17.0,-166.0,-160.0,-65.0,45.0,-96.0,69.0,-144.0,,,,,,,,,,,,,1006.0,1005.0,1004.0,1004.0,1005.0,1006.0,1005.0,1005.0,1004.0,1004.0,1004.0,1005.0,1006.0,1006.0,1007.0,1008.0,1008.0,1009.0,1010.0,1012.0,,,,161.0,165.0,169.0,173.0,177.0,180.0,185.0,192.0,200.0,208.0,215.0,221.0,226.0,231.0,237.0,242.0,245.0,250.0,253.0,256.0,,,,401.0,408.0,415.0,423.0,431.0,439.0,449.0,461.0,472.0,484.0,496.0,511.0,526.0,542.0,559.0,576.0,591.0,605.0,617.0,629.0,,,,267.0,267.0,268.0,268.0,269.0,268.0,-0.2631688671957564,272.0,272.0,274.0,275.0,277.0,278.0,280.0,281.0,283.0,285.0,286.0,286.0,287.0,,,,137.0,147.0,156.0,163.0,172.0,177.0,1.2147665698848784,191.0,195.0,195.0,197.0,198.0,196.0,186.0,173.0,167.0,162.0,170.0,181.0,178.0,,,,51.0,52.0,53.0,54.0,56.0,57.0,0.2828759611075288,61.0,61.0,61.0,61.0,61.0,60.0,54.0,48.0,46.0,44.0,47.0,53.0,51.0,,,,13.0,13.0,14.0,15.0,14.0,16.0,-0.571340556013217,23.0,26.0,28.0,30.0,33.0,35.0,35.0,34.0,34.0,33.0,36.0,42.0,42.0,,,,1814.0,1799.0,1787.0,1767.0,1748.0,1724.0,1.2729930714866187,1723.0,1751.0,1746.0,1701.0,1580.0,1445.0,1309.0,1181.0,1065.0,970.0,918.0,876.0,851.0,,,,61.0,65.0,65.0,61.0,59.0,61.0,50.0,39.0,39.0,37.0,39.0,34.0,35.0,33.0,31.0,31.0,36.0,37.0,44.0,45.0,49.0,55.0,57.0,24.0,26.0,27.0,27.0,25.0,25.0,20.0,16.0,17.0,17.0,17.0,14.0,13.0,12.0,11.0,10.0,11.0,11.0,13.0,12.0,11.0,11.0,11.0,268.0,268.0,268.0,269.0,270.0,271.0,-0.23743144088163468,275.0,277.0,278.0,279.0,279.0,280.0,282.0,285.0,288.0,290.0,293.0,296.0,298.0,,,,,,-53.0,-18.0,-1.0,47.0,0.22763091884740302,78.0,112.0,116.0,120.0,141.0,164.0,150.0,134.0,134.0,84.0,60.0,61.0,34.0,,,,,,-52.0,-32.0,-12.0,36.0,0.30268263677412943,74.0,146.0,167.0,165.0,175.0,206.0,194.0,186.0,177.0,139.0,131.0,133.0,67.0,,,,,,136.0,145.0,150.0,161.0,0.8785302061910214,121.0,130.0,96.0,36.0,12.0,32.0,39.0,36.0,21.0,33.0,55.0,4.0,-37.0,,,,,,3477.0,3465.0,3463.0,3471.0,-0.31280966689206785,3461.0,3457.0,3473.0,3476.0,3475.0,3478.0,3496.0,3497.0,3500.0,3499.0,3512.0,3513.0,3518.0,,,,,,80.0,77.0,79.0,82.0,0.11040590280724036,84.0,85.0,93.0,98.0,101.0,105.0,114.0,117.0,121.0,118.0,120.0,120.0,121.0,,,,,,12.0,14.0,15.0,14.0,-0.06057667747453034,15.0,16.0,14.0,14.0,14.0,14.0,13.0,13.0,13.0,13.0,12.0,12.0,11.0,,,,,,13.0,10.0,8.0,9.0,-0.914714273417976,7.0,3.0,10.0,15.0,18.0,16.0,28.0,33.0,38.0,37.0,43.0,48.0,50.0,,,,,,32.0,35.0,38.0,37.0,0.00515817414280225,34.0,39.0,32.0,33.0,31.0,32.0,29.0,29.0,27.0,28.0,28.0,28.0,26.0,,,,,,61.0,60.0,58.0,58.0,-1.7514865198191378,57.0,54.0,56.0,54.0,55.0,54.0,58.0,58.0,58.0,59.0,61.0,62.0,63.0,,,,,,56.0,52.0,48.0,47.0,-1.1053223115563968,44.0,39.0,40.0,41.0,41.0,37.0,40.0,41.0,42.0,43.0,46.0,51.0,54.0,,,,,,40.0,37.0,32.0,31.0,-1.5597090431282217,31.0,29.0,31.0,31.0,29.0,24.0,25.0,26.0,30.0,35.0,39.0,44.0,47.0,,,,,,28.0,27.0,32.0,29.0,0.0477311543386669,18.0,4.0,-8.0,-23.0,-35.0,-46.0,-44.0,-44.0,-46.0,-48.0,-45.0,-29.0,-30.0,,,,,,-5.0,-2.0,11.0,18.0,-0.733246397998961,-9.0,-8.0,-1.0,0.0,-19.0,-20.0,-22.0,-26.0,-15.0,-10.0,-16.0,-7.0,-3.0,,,,,,2.0,5.0,3.0,3.0,0.5479393550764937,2.0,6.0,8.0,3.0,0.0,0.0,0.0,5.0,7.0,8.0,4.0,13.0,5.0,,,,,,-4.0,-4.0,-4.0,-4.0,-0.5721558845640834,-3.0,-2.0,-2.0,-1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,255.0,252.0,253.0,256.0,-0.2756187362354146,253.0,254.0,259.0,259.0,259.0,262.0,267.0,266.0,266.0,267.0,272.0,272.0,271.0,,,,,,79.0,79.0,78.0,77.0,0.2303156108456804,78.0,76.0,76.0,76.0,76.0,75.0,74.0,75.0,75.0,74.0,73.0,74.0,75.0,,,,,,27.0,11.0,21.0,7.0,1.3953266670710593,10.0,22.0,18.0,33.0,27.0,41.0,42.0,53.0,45.0,51.0,46.0,52.0,46.0,,,,,,169.0,170.0,176.0,180.0,0.30881535266131616,189.0,200.0,209.0,214.0,219.0,226.0,231.0,235.0,242.0,245.0,250.0,253.0,255.0,,,,,,414.0,420.0,430.0,439.0,-1.7450268388652066,460.0,470.0,485.0,496.0,510.0,526.0,540.0,560.0,576.0,592.0,606.0,616.0,629.0,,,,,,69.0,65.0,64.0,60.0,-0.05251250615650376,57.0,64.0,57.0,60.0,54.0,49.0,45.0,43.0,40.0,36.0,32.0,33.0,31.0,,,,,,129.0,123.0,125.0,119.0,0.01775359668971663,108.0,128.0,107.0,134.0,129.0,114.0,112.0,108.0,108.0,99.0,95.0,91.0,94.0,,,,,,-5.0,-5.0,-5.0,-5.0,-1.221578809475514,-4.0,-4.0,-3.0,-4.0,-5.0,-6.0,-6.0,-4.0,-2.0,-2.0,-1.0,2.0,2.0,,,,,,-2.0,-2.0,-2.0,-1.0,-1.0283337635243486,0.0,-1.0,1.0,2.0,1.0,1.0,0.0,0.0,2.0,0.0,0.0,-1.0,0.0,,,,,,2.0,1.0,1.0,2.0,-0.4640802089785069,4.0,4.0,4.0,5.0,4.0,6.0,5.0,1.0,-1.0,-1.0,-3.0,-4.0,-2.0,,,,,,44.0,45.0,42.0,42.0,0.021909002071124346,42.0,40.0,31.0,26.0,23.0,19.0,17.0,11.0,7.0,4.0,4.0,3.0,0.0,,,,,,47.0,46.0,39.0,37.0,-0.15346613437053302,39.0,37.0,29.0,24.0,23.0,17.0,12.0,9.0,5.0,0.0,0.0,2.0,0.0,,,,,,-2.0,-8.0,0.0,1.0,-0.5872143092760356,4.0,3.0,20.0,29.0,28.0,11.0,5.0,-5.0,-10.0,-12.0,-14.0,-12.0,-10.0,,,,,,-54.0,-57.0,-63.0,-62.0,-1.6832809352192635,-67.0,-42.0,-11.0,-32.0,-32.0,-42.0,-43.0,-35.0,-38.0,-26.0,-17.0,1.0,17.0,,,,,,9.0,13.0,17.0,18.0,-0.0252739400222076,23.0,29.0,32.0,26.0,23.0,23.0,18.0,7.0,0.0,3.0,2.0,3.0,6.0,,,,,,3.0,4.0,7.0,8.0,0.6564374945845842,12.0,16.0,19.0,18.0,17.0,17.0,13.0,5.0,0.0,-2.0,0.0,-1.0,-2.0,,,,,,168.0,150.0,161.0,146.0,1.212702683490925,147.0,159.0,154.0,167.0,160.0,176.0,177.0,188.0,178.0,185.0,179.0,188.0,181.0,,,,,,141.0,144.0,175.0,209.0,0.35754779862377367,197.0,286.0,304.0,303.0,315.0,349.0,327.0,317.0,311.0,265.0,233.0,237.0,198.0,,,,,,5.0,13.0,24.0,38.0,-1.2570975578921322,59.0,65.0,74.0,88.0,96.0,91.0,90.0,89.0,96.0,95.0,93.0,98.0,117.0,,,,,,226.0,194.0,258.0,298.0,0.16529469764435928,298.0,386.0,424.0,420.0,451.0,487.0,460.0,435.0,431.0,407.0,360.0,323.0,311.0,,,,,,2.0,10.0,11.0,16.0,-0.9162890109729215,-23.0,-7.0,-26.0,-2.0,-27.0,-39.0,-36.0,-26.0,-16.0,-5.0,8.0,-7.0,2.0,,,,,,-669.0,-667.0,-667.0,-666.0,-0.08756183178879262,-665.0,-662.0,-663.0,-663.0,-662.0,-662.0,-663.0,-664.0,-665.0,-664.0,-665.0,-665.0,-667.0,,,,,,-534.0,-534.0,-534.0,-533.0,-0.7581166110929982,-535.0,-536.0,-536.0,-537.0,-539.0,-541.0,-542.0,-543.0,-545.0,-545.0,-543.0,-541.0,-539.0,,,,,,-407.0,-408.0,-408.0,-408.0,-0.44054969414375583,-413.0,-414.0,-414.0,-416.0,-417.0,-418.0,-420.0,-424.0,-427.0,-428.0,-426.0,-425.0,-422.0,,,,,,156.0,167.0,185.0,216.0,0.328194895080819,206.0,239.0,241.0,245.0,263.0,294.0,265.0,251.0,254.0,203.0,152.0,160.0,155.0,,,,,,359.0,12.0,21.0,35.0,-1.2504176610148678,54.0,63.0,68.0,80.0,87.0,90.0,90.0,90.0,100.0,106.0,103.0,107.0,116.0,,,,,,75.0,61.0,80.0,92.0,0.028706864238724438,69.0,83.0,109.0,108.0,108.0,107.0,85.0,78.0,96.0,100.0,81.0,62.0,75.0,,,,,,344.0,354.0,358.0,9.0,-1.4869158434830954,36.0,41.0,49.0,75.0,93.0,107.0,112.0,116.0,122.0,131.0,140.0,135.0,136.0,,,,,,215.0,204.0,238.0,282.0,0.05099705952792549,261.0,307.0,331.0,336.0,353.0,388.0,352.0,340.0,358.0,326.0,265.0,226.0,244.0,,,,,,159.0,141.0,152.0,136.0,1.4059870006824189,140.0,153.0,149.0,165.0,159.0,174.0,176.0,188.0,179.0,186.0,180.0,187.0,180.0,,,,,,95.0,99.0,100.0,111.0,-0.4164273461442921,124.0,127.0,127.0,128.0,129.0,129.0,130.0,135.0,140.0,143.0,145.0,150.0,152.0,,,,,,175.0,227.0,202.0,185.0,-1.064575747240694,339.0,292.0,306.0,328.0,392.0,309.0,306.0,413.0,642.0,756.0,893.0,1210.0,1418.0,,,,,,186.0,234.0,212.0,195.0,-1.11929916023223,327.0,290.0,299.0,316.0,366.0,302.0,297.0,379.0,527.0,585.0,639.0,801.0,909.0,,,,,,193.0,420.0,211.0,203.0,-0.9472882695243284,449.0,330.0,318.0,352.0,425.0,348.0,326.0,415.0,558.0,644.0,797.0,1063.0,1369.0,,,,,,-16.0,-16.0,-14.0,-7.0,0.007521303906142655,-14.0,-17.0,-11.0,-8.0,-8.0,-7.0,-13.0,-13.0,-9.0,-5.0,-9.0,-5.0,-1.0,,,,,,-14.0,-21.0,-17.0,-10.0,-0.08150190792143439,-24.0,-37.0,-36.0,-30.0,-4.0,8.0,14.0,-1.0,21.0,37.0,38.0,9.0,8.0,,,,,,4.0,12.0,12.0,-7.0,1.0984010406724798,25.0,19.0,-7.0,11.0,34.0,30.0,1.0,11.0,23.0,15.0,-12.0,3.0,6.0,,,,,,4.0,7.0,15.0,-8.0,1.08475014538203,24.0,31.0,5.0,23.0,25.0,26.0,-7.0,9.0,23.0,12.0,-21.0,0.0,-1.0,,,,,,315.0,337.0,366.0,363.0,0.6681162209239845,395.0,426.0,417.0,427.0,419.0,449.0,403.0,410.0,402.0,380.0,342.0,316.0,299.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2016-08-19 00:00:00,AL,-5.004258333333327,0.29832513610892486,45.038325,rea, +54638,AL062016,2016.0,8.0,19.0,6.0,-0.32995603907597554,17.3,-42.30000000000001,,,,11.0,11.0,10.0,8.0,5.0,2.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,-0.26401857885539776,-0.3923398472194441,0.2717188154300445,-0.30976310560026843,0.4676374511638913,-0.2762438726947224,0.33919874706083675,0.0,0.5585810656633275,0.7139785326099816,0.3548597747815281,-0.05307723398158664,-0.7600356653505155,-0.07590155213224342,0.5236197166483527,-0.10027188851109178,-0.46004130579779295,0.16538061770479823,,,,,,,-0.17243804696553644,0.2655480619110188,-0.4380044547121408,0.8439349931425648,-0.9611257005000966,0.7012729356153841,-0.9943897721944205,-0.1705423010088341,-1.1751987593267441,-0.15868548058743248,-0.3878847586026167,0.728778932034135,-0.7399819967069877,1.0088074879174531,-0.8745702993460711,0.4982895499487285,-1.0016612389816872,0.30600595157652427,-0.008195636692224614,-0.5574265556773673,-0.6186725579508917,,,,0.43975091974138364,-0.031007708828995638,-0.9000129026871974,0.8227368970471465,-0.7601350242375827,0.43615122414792235,0.2560288129627327,-0.012628214549323892,-0.4476533807657406,-0.9037042417315768,-1.2597938801419424,-0.4966696178234273,-0.3895059177493824,1.053187421381886,-0.08001544488238584,-0.22980766928400626,-0.3961097702742279,-0.7549759516050275,-0.7580787771536498,-0.7145239148481316,,,,,-115.0,-498.0,86.0,-231.0,154.0,92.0,85.0,73.0,56.0,35.0,15.0,-640.0,-655.0,30.0,-649.0,-594.0,22.0,39.0,68.0,62.0,,,,,-245.0,-550.0,99.0,-244.0,183.0,89.0,82.0,76.0,68.0,54.0,30.0,-709.0,-713.0,30.0,-715.0,-646.0,22.0,39.0,67.0,62.0,,,,,15.0,14.0,9.0,-57.0,-159.0,75.0,67.0,28.0,55.0,-20.0,,,,,,,,,,,,,,,-115.0,-16.0,-3.0,-62.0,-180.0,72.0,94.0,-7.0,58.0,-7.0,,,,,,,,,,,,,,,-245.0,-30.0,-27.0,-82.0,-209.0,88.0,105.0,0.0,46.0,-44.0,,,,,,,,,,,,,1005.0,1004.0,1004.0,1005.0,1006.0,1005.0,1005.0,1004.0,1004.0,1004.0,1005.0,1006.0,1006.0,1007.0,1008.0,1008.0,1009.0,1010.0,1012.0,,,,,165.0,169.0,173.0,177.0,180.0,185.0,192.0,200.0,208.0,215.0,221.0,226.0,231.0,237.0,242.0,245.0,250.0,253.0,256.0,,,,,408.0,415.0,423.0,431.0,439.0,449.0,461.0,472.0,484.0,496.0,511.0,526.0,542.0,559.0,576.0,591.0,605.0,617.0,629.0,,,,,267.0,268.0,268.0,269.0,268.0,270.0,-0.17235208364867546,272.0,274.0,275.0,277.0,278.0,280.0,281.0,283.0,285.0,286.0,286.0,287.0,,,,,147.0,156.0,163.0,172.0,177.0,185.0,1.3298455941230307,195.0,195.0,197.0,198.0,196.0,186.0,173.0,167.0,162.0,170.0,181.0,178.0,,,,,52.0,53.0,54.0,56.0,57.0,60.0,0.3194837706771795,61.0,61.0,61.0,61.0,60.0,54.0,48.0,46.0,44.0,47.0,53.0,51.0,,,,,13.0,14.0,15.0,14.0,16.0,20.0,-0.47885265322725273,26.0,28.0,30.0,33.0,35.0,35.0,34.0,34.0,33.0,36.0,42.0,42.0,,,,,1799.0,1787.0,1767.0,1748.0,1724.0,1714.0,1.2856652254345349,1751.0,1746.0,1701.0,1580.0,1445.0,1309.0,1181.0,1065.0,970.0,918.0,876.0,851.0,,,,,65.0,65.0,61.0,59.0,61.0,50.0,39.0,39.0,37.0,39.0,34.0,35.0,33.0,31.0,31.0,36.0,37.0,44.0,45.0,49.0,55.0,57.0,57.0,26.0,27.0,27.0,25.0,25.0,20.0,16.0,17.0,17.0,17.0,14.0,13.0,12.0,11.0,10.0,11.0,11.0,13.0,12.0,11.0,11.0,11.0,11.0,268.0,268.0,269.0,270.0,271.0,272.0,-0.10275329067689286,277.0,278.0,279.0,279.0,280.0,282.0,285.0,288.0,290.0,293.0,296.0,298.0,,,,,,,-18.0,-1.0,47.0,49.0,0.4163015382833357,112.0,116.0,120.0,141.0,164.0,150.0,134.0,134.0,84.0,60.0,61.0,34.0,,,,,,,-32.0,-12.0,36.0,38.0,0.5372018371461853,146.0,167.0,165.0,175.0,206.0,194.0,186.0,177.0,139.0,131.0,133.0,67.0,,,,,,,145.0,150.0,161.0,129.0,0.8089013843890196,130.0,96.0,36.0,12.0,32.0,39.0,36.0,21.0,33.0,55.0,4.0,-37.0,,,,,,,3465.0,3463.0,3471.0,3467.0,-0.3912180331282976,3457.0,3473.0,3476.0,3475.0,3478.0,3496.0,3497.0,3500.0,3499.0,3512.0,3513.0,3518.0,,,,,,,77.0,79.0,82.0,84.0,0.11040590280724036,85.0,93.0,98.0,101.0,105.0,114.0,117.0,121.0,118.0,120.0,120.0,121.0,,,,,,,14.0,15.0,14.0,14.0,-0.010504740162448126,16.0,14.0,14.0,14.0,14.0,13.0,13.0,13.0,13.0,12.0,12.0,11.0,,,,,,,10.0,8.0,9.0,9.0,-1.0003615261575074,3.0,10.0,15.0,18.0,16.0,28.0,33.0,38.0,37.0,43.0,48.0,50.0,,,,,,,35.0,38.0,37.0,35.0,-0.02884248347467315,39.0,32.0,33.0,31.0,32.0,29.0,29.0,27.0,28.0,28.0,28.0,26.0,,,,,,,60.0,58.0,58.0,58.0,-1.874012785712822,54.0,56.0,54.0,55.0,54.0,58.0,58.0,58.0,59.0,61.0,62.0,63.0,,,,,,,52.0,48.0,47.0,47.0,-1.3476941510170604,39.0,40.0,41.0,41.0,37.0,40.0,41.0,42.0,43.0,46.0,51.0,54.0,,,,,,,37.0,32.0,31.0,31.0,-1.5597090431282217,29.0,31.0,31.0,29.0,24.0,25.0,26.0,30.0,35.0,39.0,44.0,47.0,,,,,,,27.0,32.0,29.0,31.0,-0.1013682052175753,4.0,-8.0,-23.0,-35.0,-46.0,-44.0,-44.0,-46.0,-48.0,-45.0,-29.0,-30.0,,,,,,,-2.0,11.0,18.0,12.0,-1.2387722711995521,-8.0,-1.0,0.0,-19.0,-20.0,-22.0,-26.0,-15.0,-10.0,-16.0,-7.0,-3.0,,,,,,,5.0,3.0,3.0,5.0,0.14539277637031187,6.0,8.0,3.0,0.0,0.0,0.0,5.0,7.0,8.0,4.0,13.0,5.0,,,,,,,-4.0,-4.0,-4.0,-3.0,-0.5721558845640834,-2.0,-2.0,-1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,252.0,253.0,256.0,255.0,-0.36878891772996564,254.0,259.0,259.0,259.0,262.0,267.0,266.0,266.0,267.0,272.0,272.0,271.0,,,,,,,79.0,78.0,77.0,78.0,0.2303156108456804,76.0,76.0,76.0,76.0,75.0,74.0,75.0,75.0,74.0,73.0,74.0,75.0,,,,,,,11.0,21.0,7.0,21.0,1.0904903818523515,22.0,18.0,33.0,27.0,41.0,42.0,53.0,45.0,51.0,46.0,52.0,46.0,,,,,,,170.0,176.0,180.0,183.0,0.34607621680696893,199.0,209.0,214.0,219.0,226.0,231.0,236.0,242.0,245.0,250.0,253.0,255.0,,,,,,,420.0,429.0,440.0,450.0,-1.717117737336326,470.0,485.0,496.0,510.0,526.0,540.0,560.0,577.0,592.0,606.0,616.0,629.0,,,,,,,65.0,64.0,60.0,59.0,-0.07580699226589159,64.0,57.0,60.0,54.0,49.0,45.0,43.0,40.0,36.0,32.0,33.0,31.0,,,,,,,123.0,125.0,119.0,107.0,0.03236945048167875,128.0,107.0,134.0,129.0,114.0,112.0,108.0,110.0,99.0,95.0,91.0,94.0,,,,,,,-5.0,-5.0,-5.0,-5.0,-0.9785254312328794,-4.0,-3.0,-4.0,-5.0,-6.0,-6.0,-4.0,-2.0,-2.0,-1.0,2.0,2.0,,,,,,,-2.0,-2.0,-1.0,-1.0,-0.8139984424667978,-1.0,1.0,2.0,1.0,1.0,0.0,0.0,2.0,0.0,0.0,-1.0,0.0,,,,,,,1.0,1.0,2.0,3.0,-0.28907880567934696,4.0,4.0,5.0,4.0,6.0,5.0,1.0,-1.0,-1.0,-3.0,-4.0,-2.0,,,,,,,45.0,42.0,42.0,40.0,0.054625516800896744,41.0,31.0,26.0,23.0,19.0,17.0,11.0,6.0,4.0,4.0,3.0,0.0,,,,,,,46.0,38.0,37.0,38.0,-0.14128712667671514,37.0,29.0,24.0,23.0,17.0,12.0,9.0,4.0,0.0,0.0,2.0,0.0,,,,,,,-8.0,0.0,1.0,0.0,-0.5242031860201721,3.0,20.0,29.0,28.0,11.0,5.0,-5.0,-10.0,-12.0,-14.0,-12.0,-10.0,,,,,,,-57.0,-64.0,-62.0,-63.0,-1.7763138022030256,-43.0,-11.0,-32.0,-32.0,-42.0,-43.0,-35.0,-38.0,-26.0,-17.0,1.0,17.0,,,,,,,13.0,17.0,18.0,20.0,0.1406968173183513,29.0,32.0,26.0,23.0,23.0,18.0,7.0,0.0,3.0,2.0,3.0,6.0,,,,,,,4.0,7.0,8.0,10.0,0.8162077259030737,16.0,19.0,18.0,17.0,17.0,13.0,5.0,0.0,-2.0,0.0,-1.0,-2.0,,,,,,,150.0,161.0,146.0,159.0,0.8564264539060045,159.0,154.0,167.0,160.0,176.0,177.0,188.0,178.0,185.0,179.0,188.0,181.0,,,,,,,144.0,175.0,210.0,192.0,0.4061687248056798,286.0,304.0,303.0,315.0,349.0,327.0,317.0,311.0,265.0,233.0,237.0,198.0,,,,,,,13.0,25.0,38.0,50.0,-1.1624669647314645,65.0,74.0,88.0,96.0,91.0,90.0,89.0,96.0,95.0,93.0,98.0,117.0,,,,,,,193.0,258.0,298.0,286.0,0.26427415601728105,386.0,424.0,420.0,451.0,487.0,460.0,436.0,432.0,407.0,360.0,323.0,311.0,,,,,,,10.0,11.0,15.0,5.0,-1.5901831616308033,-7.0,-26.0,-2.0,-27.0,-39.0,-36.0,-26.0,-14.0,-5.0,8.0,-7.0,2.0,,,,,,,-667.0,-667.0,-666.0,-665.0,-0.08756183178879262,-662.0,-663.0,-663.0,-662.0,-662.0,-663.0,-664.0,-665.0,-664.0,-665.0,-665.0,-667.0,,,,,,,-534.0,-534.0,-533.0,-535.0,-0.7581166110929982,-536.0,-536.0,-537.0,-539.0,-541.0,-542.0,-543.0,-545.0,-545.0,-543.0,-541.0,-539.0,,,,,,,-408.0,-408.0,-408.0,-410.0,-0.5838976850524766,-414.0,-414.0,-416.0,-417.0,-418.0,-420.0,-424.0,-427.0,-428.0,-426.0,-425.0,-422.0,,,,,,,167.0,185.0,216.0,198.0,0.4071959722480399,239.0,241.0,245.0,263.0,294.0,265.0,251.0,254.0,203.0,152.0,160.0,155.0,,,,,,,12.0,21.0,35.0,46.0,-1.1633017555438798,63.0,68.0,80.0,87.0,90.0,90.0,90.0,100.0,106.0,103.0,107.0,116.0,,,,,,,61.0,80.0,92.0,77.0,-0.13168297718748687,83.0,109.0,108.0,108.0,107.0,85.0,78.0,96.0,100.0,81.0,62.0,75.0,,,,,,,354.0,358.0,9.0,25.0,-1.370004605945789,41.0,49.0,75.0,93.0,107.0,112.0,116.0,122.0,131.0,140.0,135.0,136.0,,,,,,,204.0,238.0,282.0,262.0,0.04251457976153274,307.0,331.0,336.0,353.0,388.0,352.0,340.0,358.0,326.0,265.0,226.0,244.0,,,,,,,141.0,152.0,136.0,152.0,1.1207299318489883,153.0,149.0,165.0,159.0,174.0,176.0,188.0,179.0,186.0,180.0,187.0,180.0,,,,,,,99.0,100.0,111.0,104.0,0.1248896922639281,127.0,127.0,128.0,129.0,129.0,130.0,135.0,140.0,143.0,145.0,150.0,152.0,,,,,,,227.0,202.0,185.0,223.0,-0.8396958977804319,292.0,306.0,328.0,392.0,309.0,306.0,413.0,642.0,756.0,893.0,1210.0,1418.0,,,,,,,234.0,212.0,195.0,230.0,-0.7861153948940651,290.0,299.0,316.0,366.0,302.0,297.0,379.0,527.0,585.0,639.0,801.0,909.0,,,,,,,420.0,211.0,203.0,313.0,-0.7002036156672925,330.0,318.0,352.0,425.0,348.0,326.0,415.0,557.0,644.0,797.0,1063.0,1369.0,,,,,,,-16.0,-14.0,-7.0,-2.0,-0.2797283532012416,-17.0,-11.0,-8.0,-8.0,-7.0,-13.0,-13.0,-9.0,-5.0,-9.0,-5.0,-1.0,,,,,,,-21.0,-17.0,-10.0,-8.0,-0.34104234996503885,-37.0,-36.0,-30.0,-4.0,8.0,14.0,-1.0,21.0,37.0,38.0,9.0,8.0,,,,,,,12.0,12.0,-7.0,0.0,1.5986291072113432,19.0,-7.0,11.0,34.0,30.0,1.0,11.0,23.0,15.0,-12.0,3.0,6.0,,,,,,,7.0,15.0,-8.0,-2.0,1.685590591463559,31.0,5.0,23.0,25.0,26.0,-7.0,9.0,23.0,12.0,-21.0,0.0,-1.0,,,,,,,337.0,366.0,363.0,376.0,0.762760050392211,426.0,417.0,427.0,419.0,449.0,403.0,410.0,402.0,380.0,342.0,316.0,299.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2016-08-19 06:00:00,AL,-5.004258333333327,0.29832513610892486,45.038325,rea, +56910,AL172011,2011.0,10.0,6.0,12.0,0.37167954002706066,27.4,-60.399999999999984,,,,,,,,,,,,,,,,,,,,,,,,,,,,1.0263740220040658,1.1036824293056078,0.9525977910107057,1.7321050540802374,0.8902905818901129,1.4630833891282473,0.5575353618020971,0.0,-1.1525340491087355,-1.2010160292776002,-0.7881407112325778,-0.4340717415887385,0.39484963949020657,1.0630124201111035,-1.548615824686118,-0.4690608028551936,1.3132270335643856,1.2303496358197088,,,,,,,-0.7838405054194216,-0.6200064401028877,-1.2670071366109679,0.6135215168017555,-1.8976292888015722,0.5314488915742148,-2.00393481267634,-0.45267825252940985,-1.8332167641352803,-0.41580742097647694,-1.1728612063555446,0.728778932034135,-1.6272810274896803,1.1001404609371825,-1.8241594557746923,0.4982895499487285,-1.8582334561655476,0.07769764337296062,0.07424043302474795,-0.7001851764633797,-1.4476293250730627,,,,0.43975091974138364,-0.615117550351026,-0.5178817964691548,0.25490005791911324,0.7366222197017567,0.25083816107772355,0.38515970300280267,0.4431439416619406,0.4521225923644875,0.4241709454000677,-0.25866394069567994,-1.1609137989973204,-1.0615944813109253,1.4645073563119388,-0.8623875908898528,-0.9354916104139506,-0.684808394016293,-0.3001690785293497,-0.30736970432652283,-0.3691959043086116,,,,,-115.0,-516.0,133.0,-238.0,256.0,75.0,70.0,65.0,60.0,51.0,36.0,-708.0,-712.0,22.0,-711.0,-658.0,26.0,59.0,100.0,83.0,,,,,-245.0,-473.0,175.0,-202.0,268.0,69.0,63.0,58.0,50.0,43.0,26.0,-728.0,-740.0,30.0,-733.0,-593.0,22.0,56.0,95.0,79.0,,,,,15.0,-41.0,-81.0,-80.0,-162.0,47.0,-84.0,66.0,13.0,160.0,,,,,,,,,,,,,,,-115.0,-27.0,-42.0,-105.0,-200.0,53.0,-43.0,26.0,53.0,135.0,,,,,,,,,,,,,,,-245.0,-11.0,-28.0,-125.0,-204.0,-15.0,-47.0,-27.0,117.0,160.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,259.0,267.0,274.0,280.0,285.0,290.0,295.0,302.0,309.0,321.0,333.0,349.0,365.0,379.0,392.0,403.0,413.0,427.0,441.0,458.0,475.0,496.0,516.0,612.0,608.0,604.0,597.0,590.0,578.0,566.0,551.0,535.0,518.0,501.0,485.0,469.0,458.0,446.0,439.0,432.0,423.0,415.0,404.0,393.0,379.0,366.0,,,279.0,279.0,276.0,273.0,-0.126943691875135,269.0,269.0,262.0,257.0,253.0,245.0,241.0,233.0,228.0,225.0,219.0,199.0,188.0,174.0,150.0,124.0,,,137.0,130.0,124.0,121.0,-0.18536155834597387,104.0,89.0,85.0,80.0,77.0,70.0,81.0,84.0,72.0,73.0,69.0,40.0,34.0,0.0,0.0,0.0,,,40.0,38.0,38.0,39.0,-0.5957114685640881,33.0,27.0,23.0,17.0,16.0,9.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,22.0,20.0,19.0,19.0,-0.7563163615851456,10.0,4.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,1143.0,1231.0,1320.0,1434.0,1.0420782662134793,1707.0,1726.0,1626.0,1511.0,1367.0,1245.0,1154.0,1083.0,1032.0,993.0,958.0,950.0,967.0,1012.0,1101.0,1216.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,281.0,283.0,283.0,284.0,0.3012811599373326,284.0,283.0,279.0,273.0,262.0,252.0,241.0,230.0,225.0,218.0,206.0,189.0,172.0,162.0,139.0,115.0,,,236.0,283.0,362.0,390.0,2.5632430697956736,375.0,410.0,467.0,444.0,356.0,282.0,227.0,166.0,143.0,76.0,92.0,100.0,168.0,297.0,424.0,479.0,,,168.0,243.0,317.0,339.0,1.7684276390994793,272.0,375.0,435.0,387.0,346.0,233.0,178.0,77.0,-45.0,-72.0,86.0,124.0,196.0,324.0,434.0,522.0,,,121.0,194.0,203.0,166.0,1.1744526988495294,249.0,275.0,304.0,372.0,504.0,516.0,544.0,500.0,346.0,255.0,103.0,133.0,136.0,227.0,301.0,364.0,,,3399.0,3406.0,3393.0,3372.0,-2.037793724089123,3328.0,3328.0,3307.0,3271.0,3269.0,3244.0,3196.0,3177.0,3171.0,3146.0,3150.0,3141.0,3131.0,3121.0,3090.0,3061.0,,,66.0,72.0,70.0,57.0,-1.285248527673104,40.0,42.0,38.0,28.0,28.0,24.0,15.0,8.0,7.0,2.0,1.0,0.0,0.0,0.0,0.0,0.0,,,24.0,23.0,27.0,34.0,1.4916533792000184,49.0,49.0,57.0,71.0,72.0,81.0,103.0,114.0,116.0,132.0,128.0,136.0,143.0,144.0,155.0,165.0,,,4.0,8.0,7.0,2.0,-1.300126910745867,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,42.0,40.0,44.0,51.0,1.1951811907544412,75.0,72.0,79.0,95.0,94.0,108.0,135.0,154.0,158.0,180.0,173.0,182.0,192.0,186.0,188.0,194.0,,,59.0,58.0,57.0,60.0,-1.3839077221380853,61.0,62.0,65.0,70.0,69.0,66.0,66.0,65.0,63.0,59.0,63.0,64.0,63.0,67.0,70.0,72.0,,,45.0,44.0,44.0,48.0,-1.0245316984028423,48.0,48.0,49.0,53.0,54.0,49.0,48.0,48.0,45.0,47.0,49.0,47.0,42.0,44.0,48.0,49.0,,,51.0,50.0,54.0,57.0,0.22951437821598286,57.0,54.0,50.0,48.0,51.0,54.0,51.0,50.0,45.0,47.0,44.0,44.0,37.0,38.0,43.0,43.0,,,-30.0,-20.0,-15.0,-8.0,-0.17018329424353323,40.0,62.0,86.0,110.0,134.0,154.0,157.0,162.0,168.0,156.0,132.0,93.0,52.0,60.0,73.0,135.0,,,17.0,49.0,46.0,45.0,-0.2277205247983698,53.0,39.0,44.0,46.0,42.0,40.0,49.0,62.0,38.0,50.0,42.0,32.0,47.0,52.0,54.0,52.0,,,4.0,1.0,7.0,22.0,4.4392229492362505,36.0,39.0,27.0,29.0,36.0,30.0,33.0,23.0,9.0,9.0,6.0,-5.0,-7.0,-10.0,-6.0,12.0,,,-4.0,-5.0,-5.0,-5.0,-1.020347013092195,-6.0,-7.0,-8.0,-8.0,-9.0,-10.0,-9.0,-8.0,-6.0,-4.0,-3.0,-2.0,-4.0,-5.0,-5.0,-6.0,,,248.0,249.0,245.0,240.0,-1.3936609141700267,230.0,228.0,222.0,212.0,210.0,200.0,184.0,176.0,174.0,162.0,161.0,156.0,149.0,142.0,129.0,119.0,,,71.0,71.0,72.0,71.0,-1.5713174251596351,70.0,71.0,71.0,70.0,71.0,72.0,73.0,74.0,73.0,76.0,77.0,79.0,82.0,86.0,87.0,85.0,,,12.0,4.0,13.0,6.0,1.3676142775057223,8.0,14.0,-5.0,1.0,-19.0,-19.0,-44.0,-43.0,-50.0,-37.0,-49.0,-35.0,-49.0,-42.0,-70.0,-78.0,,,268.0,277.0,279.0,286.0,0.9546703311859643,290.0,297.0,307.0,326.0,349.0,368.0,400.0,420.0,424.0,424.0,421.0,426.0,440.0,446.0,459.0,467.0,,,607.0,595.0,590.0,576.0,-1.4240721712830817,550.0,530.0,509.0,487.0,460.0,439.0,431.0,431.0,439.0,437.0,432.0,420.0,413.0,406.0,390.0,367.0,,,74.0,67.0,93.0,84.0,0.43667170214064055,112.0,104.0,118.0,117.0,121.0,145.0,157.0,148.0,152.0,137.0,141.0,134.0,111.0,102.0,81.0,80.0,,,148.0,114.0,181.0,158.0,0.7120066518079174,235.0,188.0,226.0,176.0,162.0,201.0,217.0,203.0,217.0,189.0,207.0,201.0,156.0,153.0,119.0,126.0,,,-7.0,-7.0,-7.0,-7.0,-0.9785254312328794,-2.0,-4.0,-5.0,-4.0,-3.0,1.0,5.0,14.0,29.0,36.0,39.0,38.0,26.0,20.0,14.0,11.0,,,1.0,1.0,0.0,0.0,-0.8139984424667978,3.0,2.0,0.0,2.0,9.0,11.0,11.0,17.0,34.0,43.0,39.0,38.0,31.0,19.0,16.0,10.0,,,8.0,7.0,7.0,5.0,-0.6390816122776668,1.0,4.0,6.0,15.0,24.0,18.0,11.0,13.0,16.0,10.0,15.0,10.0,10.0,6.0,6.0,4.0,,,50.0,55.0,62.0,60.0,0.4472236935581655,69.0,72.0,82.0,96.0,116.0,129.0,127.0,110.0,105.0,107.0,100.0,99.0,82.0,63.0,52.0,62.0,,,39.0,45.0,53.0,48.0,0.053576996424370964,63.0,67.0,77.0,103.0,122.0,143.0,148.0,138.0,140.0,135.0,122.0,118.0,101.0,88.0,61.0,65.0,,,2.0,8.0,19.0,20.0,-0.25640591218275244,15.0,22.0,18.0,20.0,40.0,56.0,81.0,113.0,175.0,178.0,184.0,172.0,139.0,103.0,69.0,60.0,,,-25.0,-26.0,-52.0,-74.0,-1.8693466691867877,-65.0,-66.0,-42.0,-18.0,-10.0,4.0,22.0,49.0,200.0,231.0,239.0,234.0,181.0,138.0,90.0,106.0,,,13.0,26.0,44.0,51.0,2.0216987338446852,76.0,88.0,107.0,107.0,114.0,105.0,117.0,112.0,105.0,44.0,8.0,17.0,20.0,44.0,80.0,93.0,,,4.0,1.0,0.0,-1.0,-0.2222987776671077,-16.0,-24.0,-29.0,-46.0,-6.0,-1.0,-8.0,16.0,-1.0,-9.0,3.0,-2.0,2.0,-11.0,-34.0,-91.0,,,147.0,142.0,153.0,153.0,1.3908407982833852,161.0,177.0,167.0,191.0,177.0,187.0,159.0,165.0,143.0,151.0,132.0,142.0,121.0,131.0,115.0,128.0,,,168.0,282.0,384.0,392.0,1.6703128055352394,359.0,423.0,467.0,450.0,521.0,516.0,554.0,513.0,380.0,262.0,77.0,68.0,87.0,189.0,271.0,363.0,,,69.0,51.0,57.0,62.0,-1.1940104957850204,41.0,46.0,49.0,37.0,30.0,23.0,16.0,11.0,351.0,335.0,347.0,35.0,57.0,51.0,46.0,41.0,,,254.0,385.0,517.0,537.0,2.144883865102795,603.0,599.0,657.0,713.0,773.0,716.0,741.0,647.0,491.0,348.0,158.0,163.0,193.0,276.0,417.0,555.0,,,28.0,33.0,33.0,34.0,-0.5552742874061991,50.0,28.0,48.0,47.0,65.0,81.0,64.0,40.0,59.0,52.0,32.0,8.0,38.0,25.0,24.0,40.0,,,-680.0,-675.0,-669.0,-667.0,0.4736195752000614,-649.0,-644.0,-636.0,-623.0,-620.0,-611.0,-596.0,-591.0,-587.0,-585.0,-585.0,-588.0,-586.0,-583.0,-564.0,-551.0,,,-552.0,-547.0,-544.0,-543.0,-0.9693458645411772,-534.0,-535.0,-531.0,-523.0,-521.0,-519.0,-521.0,-522.0,-528.0,-534.0,-534.0,-538.0,-539.0,-540.0,-532.0,-527.0,,,-431.0,-428.0,-430.0,-431.0,-1.5873336214135223,-433.0,-431.0,-431.0,-433.0,-435.0,-443.0,-451.0,-455.0,-458.0,-460.0,-464.0,-470.0,-471.0,-474.0,-481.0,-485.0,,,253.0,311.0,403.0,420.0,2.905605037661401,422.0,451.0,496.0,505.0,427.0,423.0,424.0,377.0,302.0,182.0,138.0,97.0,125.0,244.0,336.0,379.0,,,60.0,57.0,64.0,67.0,-1.0870753382567653,52.0,54.0,54.0,50.0,40.0,31.0,18.0,15.0,17.0,10.0,8.0,16.0,26.0,37.0,43.0,44.0,,,92.0,99.0,131.0,174.0,2.715236708127764,231.0,237.0,256.0,265.0,219.0,207.0,178.0,155.0,144.0,46.0,61.0,22.0,43.0,107.0,171.0,167.0,,,73.0,63.0,62.0,61.0,-1.14681042519275,61.0,60.0,56.0,50.0,46.0,41.0,32.0,13.0,23.0,4.0,357.0,30.0,71.0,49.0,50.0,51.0,,,333.0,407.0,501.0,537.0,2.782355544306391,573.0,580.0,631.0,640.0,537.0,525.0,531.0,437.0,362.0,216.0,187.0,149.0,189.0,306.0,451.0,512.0,,,141.0,132.0,143.0,135.0,1.4059870006824189,138.0,145.0,122.0,131.0,106.0,106.0,78.0,79.0,70.0,86.0,72.0,90.0,73.0,81.0,48.0,39.0,,,151.0,153.0,149.0,146.0,0.5579433229905043,139.0,137.0,133.0,126.0,112.0,100.0,93.0,78.0,72.0,63.0,48.0,24.0,8.0,5.0,0.0,0.0,,,721.0,833.0,912.0,1040.0,0.6452865564140589,1107.0,1167.0,1236.0,1245.0,1085.0,934.0,845.0,630.0,557.0,469.0,365.0,213.0,137.0,141.0,127.0,96.0,,,605.0,675.0,730.0,812.0,1.0687220616276771,874.0,909.0,958.0,974.0,869.0,784.0,736.0,583.0,526.0,458.0,368.0,229.0,154.0,159.0,144.0,112.0,,,921.0,926.0,970.0,981.0,0.17912706423568825,1015.0,1037.0,1080.0,858.0,1035.0,1117.0,808.0,618.0,606.0,514.0,409.0,213.0,126.0,116.0,97.0,86.0,,,-45.0,-36.0,-33.0,-6.0,-0.42335318175493375,-25.0,-26.0,-54.0,-53.0,-133.0,-101.0,-109.0,-22.0,-8.0,-10.0,-24.0,-31.0,-63.0,-129.0,-222.0,-249.0,,,-67.0,-61.0,-60.0,-21.0,-0.7141317354027203,-57.0,-53.0,-93.0,-101.0,-187.0,-165.0,-178.0,-22.0,-14.0,-8.0,-26.0,-35.0,-81.0,-157.0,-330.0,-382.0,,,-70.0,-85.0,-70.0,-62.0,-0.5423470175749927,-85.0,-67.0,-84.0,-82.0,-90.0,-84.0,-88.0,-63.0,-58.0,-47.0,-37.0,-57.0,-80.0,-134.0,-127.0,-108.0,,,-56.0,-63.0,-47.0,-63.0,-0.4866787136004303,-77.0,-69.0,-104.0,-91.0,-88.0,-87.0,-68.0,-50.0,-46.0,-37.0,-27.0,-50.0,-99.0,-153.0,-134.0,-129.0,,,418.0,436.0,454.0,369.0,0.44894103689230214,328.0,333.0,290.0,199.0,207.0,257.0,247.0,251.0,262.0,284.0,259.0,274.0,310.0,305.0,256.0,213.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,8.0,7.0,14.0,20.0,19.0,13.0,7.0,7.0,5.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2011-10-06 12:00:00,AL,10.008516666666667,0.7852973045355962,,opr,70.0 +56911,AL172011,2011.0,10.0,6.0,18.0,0.7224973295785787,28.3,-59.5,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.42726317160502914,1.4844880996938028,1.2173840592920737,1.9442472005405498,0.8902905818901129,1.8907868141666828,0.7322046535951053,0.0,-1.3080899686334686,-1.595279615548573,-0.3032314141356844,0.5819136120303331,1.1108785284914542,1.5010562555893139,-1.315904881541605,-0.35942085534748763,0.5292557677411066,0.7191645071245517,,,,,,,-0.8407151527174574,0.7821215214191309,-1.5099906813054518,1.3047619458241833,-1.8556962923104614,0.828640968646261,-2.0319777304675046,0.1821276383918855,-2.2337494627143895,0.16271694489887312,-1.3909102196202467,1.5090930885397762,-1.7000104562423601,1.2371399204667768,-1.8825957115549152,0.8236971008384858,-2.050223780706758,0.6484684138818698,-0.09497044692061678,-0.5314704428071833,-1.5785172356713002,,,,3.39304646039281,-0.8152292553169068,-0.8454227446560484,-0.4660613220973785,0.1274768297264441,0.6214642872181211,0.600377853069586,0.6503131035761517,0.7384149474513783,0.5901553437915232,0.1508892163505183,-1.153144861205813,-1.0697906833055784,1.053187421381886,-0.8673081704244909,-1.0139009372061667,-1.1178563296293909,0.019880202523905013,0.0280416987076181,-0.11595536324629689,,,,,-245.0,-594.0,78.0,-363.0,198.0,94.0,91.0,87.0,81.0,72.0,45.0,-667.0,-683.0,6.0,-702.0,-675.0,30.0,75.0,126.0,101.0,,,,,-245.0,-594.0,78.0,-363.0,198.0,94.0,91.0,87.0,81.0,72.0,45.0,-667.0,-683.0,6.0,-702.0,-675.0,30.0,75.0,126.0,101.0,,,,,45.0,-93.0,-86.0,-44.0,-34.0,-45.0,-67.0,22.0,-52.0,10.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-245.0,-74.0,-54.0,-58.0,-102.0,93.0,-72.0,95.0,25.0,165.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,265.0,274.0,283.0,289.0,294.0,301.0,307.0,317.0,326.0,340.0,353.0,368.0,383.0,398.0,412.0,426.0,440.0,455.0,470.0,486.0,502.0,519.0,536.0,609.0,602.0,595.0,586.0,576.0,562.0,548.0,530.0,513.0,497.0,482.0,470.0,459.0,449.0,440.0,431.0,422.0,412.0,403.0,393.0,383.0,373.0,363.0,,,276.0,276.0,273.0,270.0,-0.30857725896929683,265.0,262.0,257.0,249.0,245.0,238.0,233.0,225.0,221.0,199.0,186.0,168.0,165.0,138.0,123.0,106.0,,,120.0,119.0,112.0,101.0,-0.5114187936874052,84.0,84.0,81.0,69.0,79.0,91.0,80.0,72.0,76.0,48.0,36.0,0.0,0.0,0.0,0.0,0.0,,,36.0,38.0,37.0,31.0,-0.8519661355516429,23.0,23.0,16.0,11.0,7.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,18.0,19.0,16.0,9.0,-0.9721214680857289,3.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,1275.0,1378.0,1481.0,1622.0,1.2617289346440266,1664.0,1574.0,1445.0,1332.0,1209.0,1104.0,1016.0,951.0,912.0,903.0,915.0,944.0,1006.0,1078.0,1174.0,1283.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,283.0,283.0,284.0,284.0,0.3012811599373326,282.0,277.0,270.0,261.0,251.0,238.0,229.0,220.0,207.0,189.0,171.0,163.0,153.0,132.0,112.0,102.0,,,265.0,343.0,398.0,384.0,2.4071018675038673,429.0,465.0,439.0,383.0,290.0,231.0,143.0,123.0,109.0,158.0,218.0,306.0,364.0,375.0,332.0,331.0,,,216.0,242.0,312.0,322.0,1.9964324172389782,377.0,468.0,390.0,320.0,251.0,130.0,58.0,20.0,140.0,197.0,267.0,367.0,431.0,417.0,368.0,317.0,,,207.0,217.0,187.0,205.0,2.192774217703807,322.0,370.0,469.0,504.0,512.0,560.0,460.0,261.0,129.0,127.0,106.0,147.0,241.0,367.0,458.0,508.0,,,3399.0,3380.0,3359.0,3336.0,-2.155406273443468,3311.0,3302.0,3255.0,3235.0,3217.0,3182.0,3157.0,3133.0,3140.0,3133.0,3126.0,3130.0,3116.0,3096.0,3065.0,3045.0,,,67.0,64.0,52.0,43.0,-1.3849381298502714,34.0,35.0,24.0,23.0,20.0,14.0,7.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,25.0,31.0,37.0,44.0,1.6919411284483474,54.0,58.0,76.0,85.0,93.0,109.0,122.0,139.0,137.0,143.0,148.0,143.0,145.0,149.0,163.0,170.0,,,5.0,3.0,0.0,0.0,-1.300126910745867,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,43.0,48.0,55.0,69.0,1.433185794076769,83.0,85.0,106.0,115.0,123.0,143.0,164.0,190.0,189.0,192.0,193.0,184.0,179.0,176.0,183.0,188.0,,,60.0,58.0,61.0,61.0,-1.3839077221380853,65.0,64.0,67.0,65.0,66.0,64.0,62.0,59.0,60.0,64.0,66.0,70.0,75.0,77.0,84.0,84.0,,,44.0,44.0,47.0,47.0,-1.2669035378635058,48.0,48.0,49.0,46.0,46.0,46.0,42.0,41.0,44.0,47.0,48.0,48.0,50.0,54.0,64.0,61.0,,,50.0,51.0,54.0,56.0,0.09188180734335175,51.0,50.0,46.0,46.0,46.0,44.0,43.0,44.0,44.0,40.0,39.0,35.0,34.0,37.0,42.0,43.0,,,-18.0,-20.0,-6.0,20.0,0.12801542486895115,61.0,74.0,107.0,125.0,137.0,142.0,146.0,145.0,132.0,128.0,124.0,101.0,149.0,197.0,259.0,241.0,,,60.0,52.0,42.0,35.0,-0.5406651129701643,32.0,40.0,59.0,62.0,26.0,29.0,38.0,43.0,26.0,54.0,42.0,32.0,54.0,49.0,56.0,36.0,,,6.0,27.0,36.0,37.0,4.17085856343213,36.0,48.0,22.0,25.0,37.0,47.0,39.0,15.0,5.0,-1.0,-10.0,-28.0,-11.0,4.0,10.0,28.0,,,-5.0,-6.0,-5.0,-5.0,-1.2444425773562506,-7.0,-7.0,-9.0,-10.0,-10.0,-9.0,-7.0,-5.0,-2.0,-2.0,-2.0,-2.0,-4.0,-6.0,-6.0,-6.0,,,248.0,243.0,237.0,232.0,-1.4402460049173023,223.0,220.0,207.0,199.0,192.0,181.0,169.0,160.0,160.0,154.0,147.0,145.0,137.0,129.0,118.0,110.0,,,71.0,71.0,71.0,70.0,-1.7965215546602995,71.0,71.0,70.0,71.0,71.0,71.0,73.0,73.0,75.0,78.0,82.0,85.0,88.0,89.0,87.0,87.0,,,7.0,15.0,9.0,19.0,1.1182027714176888,13.0,-2.0,8.0,-10.0,-12.0,-28.0,-27.0,-42.0,-40.0,-70.0,-68.0,-94.0,-104.0,-129.0,-135.0,-145.0,,,283.0,280.0,287.0,288.0,0.9670906192345153,297.0,306.0,313.0,333.0,360.0,386.0,406.0,410.0,411.0,424.0,429.0,440.0,450.0,469.0,493.0,523.0,,,599.0,590.0,579.0,567.0,-1.4603540032706261,534.0,515.0,490.0,468.0,451.0,431.0,428.0,439.0,431.0,419.0,409.0,390.0,370.0,340.0,300.0,251.0,,,67.0,93.0,90.0,103.0,0.5182024035234979,90.0,103.0,124.0,124.0,134.0,157.0,178.0,167.0,156.0,127.0,120.0,102.0,90.0,80.0,67.0,55.0,,,113.0,179.0,174.0,209.0,0.8581651897275386,150.0,172.0,223.0,178.0,185.0,226.0,276.0,239.0,223.0,179.0,176.0,144.0,135.0,126.0,109.0,73.0,,,-8.0,-7.0,-7.0,-5.0,-0.735472052990245,-4.0,-5.0,-6.0,-2.0,3.0,4.0,15.0,27.0,30.0,31.0,26.0,18.0,13.0,9.0,6.0,0.0,,,-1.0,-1.0,0.0,1.0,-0.38532780035169606,3.0,2.0,2.0,6.0,19.0,13.0,15.0,26.0,35.0,32.0,30.0,22.0,12.0,7.0,8.0,2.0,,,7.0,6.0,5.0,2.0,-0.6390816122776668,4.0,7.0,13.0,19.0,26.0,17.0,14.0,21.0,8.0,11.0,11.0,7.0,6.0,3.0,-1.0,6.0,,,55.0,63.0,62.0,66.0,0.49629846565282404,70.0,76.0,93.0,108.0,117.0,121.0,126.0,115.0,111.0,97.0,84.0,67.0,58.0,50.0,53.0,52.0,,,47.0,54.0,50.0,56.0,0.13883005028109613,65.0,73.0,88.0,106.0,133.0,143.0,152.0,152.0,142.0,119.0,105.0,88.0,74.0,62.0,54.0,53.0,,,4.0,17.0,22.0,17.0,-0.3981809395084452,17.0,10.0,15.0,55.0,92.0,100.0,145.0,204.0,192.0,171.0,163.0,131.0,102.0,69.0,30.0,13.0,,,-46.0,-52.0,-73.0,-90.0,-1.8228302356949067,-69.0,-37.0,-42.0,-11.0,52.0,51.0,75.0,212.0,235.0,238.0,214.0,161.0,124.0,77.0,31.0,25.0,,,33.0,45.0,55.0,66.0,2.9621996921078524,85.0,98.0,122.0,118.0,90.0,118.0,102.0,62.0,26.0,32.0,20.0,46.0,58.0,56.0,76.0,51.0,,,-1.0,-3.0,-5.0,-9.0,-1.8200010908520021,-29.0,-51.0,-61.0,-51.0,-38.0,-31.0,-4.0,-18.0,-12.0,8.0,7.0,-5.0,4.0,-19.0,-53.0,9.0,,,147.0,155.0,156.0,168.0,1.3314614266858986,182.0,171.0,188.0,177.0,188.0,165.0,171.0,144.0,146.0,117.0,119.0,93.0,98.0,84.0,93.0,81.0,,,273.0,332.0,393.0,395.0,2.3801783277910693,457.0,515.0,571.0,511.0,534.0,562.0,480.0,294.0,114.0,83.0,83.0,137.0,215.0,270.0,331.0,365.0,,,43.0,45.0,55.0,52.0,-1.3727571717551705,41.0,41.0,30.0,22.0,17.0,7.0,5.0,348.0,21.0,44.0,75.0,74.0,62.0,44.0,31.0,25.0,,,371.0,464.0,526.0,589.0,2.8789815147019646,608.0,641.0,774.0,723.0,744.0,711.0,592.0,388.0,230.0,156.0,215.0,292.0,384.0,434.0,478.0,520.0,,,62.0,40.0,33.0,22.0,-0.7237478250706696,7.0,40.0,61.0,60.0,54.0,53.0,29.0,54.0,34.0,47.0,25.0,28.0,53.0,40.0,77.0,60.0,,,-679.0,-674.0,-672.0,-661.0,0.5246360667445027,-646.0,-639.0,-627.0,-619.0,-609.0,-600.0,-595.0,-594.0,-592.0,-590.0,-586.0,-576.0,-562.0,-545.0,-533.0,-526.0,,,-550.0,-545.0,-544.0,-539.0,-0.599694671006864,-533.0,-534.0,-524.0,-517.0,-518.0,-524.0,-525.0,-536.0,-539.0,-534.0,-538.0,-536.0,-529.0,-519.0,-512.0,-514.0,,,-429.0,-430.0,-430.0,-431.0,-1.4917682941410417,-431.0,-431.0,-433.0,-435.0,-444.0,-453.0,-453.0,-457.0,-460.0,-464.0,-470.0,-469.0,-471.0,-475.0,-477.0,-485.0,,,298.0,403.0,441.0,426.0,2.500724517179394,487.0,465.0,531.0,496.0,426.0,418.0,358.0,250.0,112.0,72.0,93.0,162.0,247.0,298.0,309.0,374.0,,,54.0,58.0,61.0,59.0,-1.1633017555438798,54.0,58.0,49.0,41.0,32.0,21.0,13.0,11.0,14.0,33.0,57.0,51.0,45.0,40.0,36.0,33.0,,,104.0,146.0,183.0,197.0,2.815480359019146,263.0,245.0,269.0,241.0,200.0,155.0,117.0,79.0,35.0,25.0,53.0,79.0,139.0,171.0,146.0,173.0,,,61.0,61.0,63.0,61.0,-1.1042972479064568,61.0,57.0,56.0,57.0,53.0,44.0,19.0,15.0,31.0,39.0,91.0,65.0,51.0,43.0,35.0,34.0,,,396.0,516.0,554.0,555.0,2.4515388334170733,641.0,585.0,650.0,609.0,542.0,498.0,406.0,278.0,152.0,87.0,155.0,252.0,367.0,442.0,427.0,472.0,,,136.0,146.0,139.0,150.0,1.1445013542517741,144.0,126.0,139.0,117.0,115.0,96.0,98.0,80.0,82.0,47.0,49.0,19.0,7.0,-21.0,-29.0,-41.0,,,154.0,143.0,145.0,140.0,0.5038116191496822,135.0,129.0,122.0,112.0,101.0,89.0,77.0,65.0,46.0,24.0,11.0,7.0,7.0,0.0,0.0,0.0,,,788.0,888.0,1056.0,1076.0,0.571619019521904,1183.0,1154.0,1147.0,1073.0,950.0,751.0,653.0,484.0,328.0,226.0,158.0,153.0,171.0,115.0,119.0,120.0,,,653.0,723.0,830.0,851.0,1.0137639147677735,926.0,912.0,924.0,883.0,806.0,675.0,606.0,473.0,337.0,242.0,176.0,170.0,188.0,131.0,135.0,137.0,,,849.0,927.0,1012.0,1045.0,0.5806396267533717,1067.0,1058.0,1072.0,1077.0,1110.0,913.0,688.0,561.0,384.0,215.0,132.0,139.0,152.0,110.0,87.0,84.0,,,-53.0,-50.0,-34.0,-34.0,-0.8781651388416256,-25.0,-51.0,-115.0,-130.0,-127.0,-133.0,-51.0,-52.0,-44.0,-71.0,-70.0,-101.0,-133.0,-139.0,-133.0,-163.0,,,-93.0,-92.0,-69.0,-66.0,-1.054778565584951,-63.0,-81.0,-211.0,-234.0,-244.0,-216.0,-73.0,-68.0,-54.0,-70.0,-75.0,-108.0,-190.0,-257.0,-218.0,-296.0,,,-91.0,-70.0,-69.0,-77.0,-0.6223835082212109,-56.0,-86.0,-61.0,-66.0,-49.0,-55.0,-38.0,-46.0,-55.0,-48.0,-71.0,-82.0,-120.0,-109.0,-103.0,-100.0,,,-69.0,-45.0,-63.0,-63.0,-0.902645176272258,-51.0,-96.0,-57.0,-67.0,-39.0,-41.0,-31.0,-37.0,-53.0,-57.0,-82.0,-110.0,-139.0,-121.0,-126.0,-126.0,,,483.0,491.0,420.0,394.0,0.7328725252969815,348.0,348.0,279.0,314.0,292.0,284.0,323.0,326.0,322.0,296.0,305.0,304.0,282.0,246.0,147.0,149.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,10.0,18.0,21.0,16.0,12.0,5.0,6.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2011-10-06 18:00:00,AL,-10.008516666666667,1.2722694729622674,,opr,80.0 +58583,AL012018,2018.0,5.0,28.0,0.0,0.02086175047554257,28.3,-85.60000000000002,,,,,,,,,,,,,,,,,,,,,,,,,,,,1.959604385125642,-0.12033579694216195,0.9525977910107057,0.6448765534711369,0.8480252688174907,0.29402736068985785,0.8632066224398615,0.0,-1.3080899686334686,-2.6654236354269276,-0.026140387223173876,0.11625365828825864,-1.1988920811899897,-1.6528593598538006,-0.8061571013202915,0.6373059401771118,2.1158642819072666,0.8043620285737445,,,,,,,-0.7411845199458947,0.8559177299202898,-0.8525057956615544,0.6711248858869578,-0.47190740810380344,-0.06293526256987776,0.00113380939191709,-0.31161027676912195,0.026399336410583132,-0.41580742097647694,-0.8385193860163346,0.561568755640069,-0.6236149107027001,-0.13285467482916555,-0.3486439973240656,-0.5186090465817632,-0.21893145431367686,-0.6072272812377304,1.2413616305966226,-1.1673952081266932,-0.7786466709042932,,,,-1.0368968505843295,0.23400508963933295,0.04621650318605095,0.2357594903080559,0.023051905730676253,-0.0271314335275746,-0.13136385715747717,-0.1783635440806928,-0.2840577492875173,-0.40575104655721006,-0.5316993787264788,0.10542306101840569,0.1514434138977131,0.024887584056754015,0.2250604862651799,0.24554887439380346,0.00085083737111172,-0.01380919548170075,-0.013884726671649519,-0.10444442956164622,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,268.0,276.0,283.0,290.0,296.0,304.0,311.0,322.0,333.0,346.0,359.0,372.0,384.0,396.0,408.0,422.0,435.0,450.0,465.0,,,,,844.0,850.0,856.0,859.0,862.0,864.0,867.0,869.0,871.0,873.0,874.0,874.0,874.0,870.0,867.0,857.0,848.0,833.0,819.0,,,,,,,261.0,261.0,257.0,254.0,-1.216745094440106,229.0,213.0,199.0,184.0,155.0,141.0,126.0,110.0,83.0,80.0,52.0,54.0,,,,,,,81.0,78.0,72.0,65.0,-1.1827131017432932,18.0,,,,,,,,,,,,,,,,,,19.0,17.0,17.0,15.0,-1.3644754695267527,7.0,,,,,,,,,,,,,,,,,,4.0,2.0,0.0,0.0,-1.1879265745863121,2.0,,,,,,,,,,,,,,,,,,156.0,96.0,77.0,15.0,-1.2375014273061105,-192.0,-301.0,-439.0,-580.0,-718.0,-857.0,-972.0,-986.0,-945.0,-937.0,-905.0,-913.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,259.0,259.0,260.0,262.0,-0.7761440417006019,243.0,223.0,202.0,183.0,164.0,145.0,125.0,102.0,83.0,63.0,39.0,29.0,,,,,,,60.0,103.0,101.0,80.0,0.6570192251498705,151.0,85.0,100.0,175.0,185.0,154.0,154.0,157.0,176.0,181.0,201.0,242.0,,,,,,,-59.0,51.0,59.0,6.0,0.1528509254253159,73.0,38.0,58.0,103.0,117.0,77.0,61.0,84.0,123.0,138.0,156.0,200.0,,,,,,,163.0,159.0,95.0,165.0,1.705372465089794,164.0,152.0,261.0,256.0,260.0,234.0,285.0,254.0,236.0,191.0,188.0,150.0,,,,,,,3465.0,3443.0,3434.0,3468.0,-0.22133323961646642,3427.0,3410.0,3477.0,3510.0,3415.0,3389.0,3469.0,3475.0,3374.0,3347.0,3364.0,3248.0,,,,,,,74.0,61.0,60.0,82.0,0.07717603541485121,51.0,43.0,90.0,111.0,43.0,30.0,83.0,82.0,14.0,6.0,13.0,0.0,,,,,,,19.0,23.0,24.0,19.0,0.18978300908588075,25.0,29.0,20.0,17.0,29.0,36.0,23.0,23.0,45.0,56.0,47.0,128.0,,,,,,,32.0,18.0,14.0,34.0,0.07022913308663482,4.0,3.0,43.0,60.0,6.0,2.0,42.0,42.0,0.0,0.0,0.0,0.0,,,,,,,32.0,34.0,35.0,36.0,-0.06284314109214854,41.0,45.0,41.0,33.0,51.0,60.0,40.0,37.0,73.0,85.0,72.0,161.0,,,,,,,76.0,74.0,73.0,74.0,-0.03611879730755943,70.0,71.0,74.0,71.0,70.0,71.0,75.0,74.0,76.0,78.0,83.0,82.0,,,,,,,68.0,66.0,62.0,61.0,0.10653688574692113,60.0,62.0,60.0,62.0,61.0,64.0,68.0,71.0,73.0,75.0,75.0,75.0,,,,,,,65.0,62.0,58.0,56.0,0.5735958053975606,60.0,62.0,62.0,64.0,65.0,69.0,72.0,75.0,78.0,79.0,78.0,78.0,,,,,,,101.0,103.0,105.0,106.0,0.5982518665463303,43.0,30.0,22.0,4.0,-11.0,13.0,36.0,28.0,31.0,94.0,133.0,116.0,,,,,,,44.0,32.0,30.0,46.0,-0.5406651129701643,0.0,22.0,43.0,17.0,40.0,28.0,53.0,64.0,51.0,55.0,74.0,89.0,,,,,,,23.0,13.0,6.0,7.0,1.487214705390918,7.0,1.0,6.0,21.0,16.0,10.0,15.0,12.0,14.0,6.0,4.0,2.0,,,,,,,-3.0,-3.0,-1.0,-3.0,-0.5721558845640834,-2.0,-2.0,-5.0,-4.0,-4.0,-4.0,-5.0,-5.0,-4.0,-4.0,-4.0,-3.0,,,,,,,257.0,245.0,240.0,266.0,0.0038918082482384203,238.0,230.0,278.0,274.0,230.0,220.0,268.0,258.0,217.0,207.0,230.0,189.0,,,,,,,76.0,81.0,82.0,71.0,-0.4452967776563129,83.0,86.0,65.0,72.0,86.0,89.0,70.0,77.0,89.0,91.0,77.0,82.0,,,,,,,-29.0,-23.0,-26.0,-20.0,-0.045717590326468355,-26.0,-23.0,-21.0,-35.0,-29.0,-28.0,-31.0,-49.0,-48.0,-50.0,-54.0,-41.0,,,,,,,279.0,284.0,293.0,303.0,1.0975036437443,319.0,328.0,339.0,353.0,369.0,384.0,403.0,418.0,434.0,449.0,467.0,477.0,,,,,,,855.0,856.0,857.0,859.0,-0.5923809457224452,866.0,867.0,867.0,866.0,868.0,868.0,865.0,860.0,858.0,848.0,841.0,823.0,,,,,,,116.0,117.0,127.0,121.0,0.5880858618516613,106.0,108.0,88.0,89.0,79.0,75.0,72.0,76.0,74.0,73.0,74.0,86.0,,,,,,,179.0,201.0,219.0,205.0,0.5073846987204478,157.0,157.0,132.0,133.0,115.0,107.0,106.0,106.0,100.0,113.0,127.0,117.0,,,,,,,22.0,23.0,25.0,25.0,4.36864889010508,17.0,16.0,12.0,7.0,7.0,6.0,5.0,0.0,-1.0,-2.0,-2.0,-7.0,,,,,,,13.0,13.0,8.0,6.0,1.3293547681087106,11.0,9.0,7.0,9.0,9.0,5.0,3.0,1.0,2.0,-2.0,1.0,-2.0,,,,,,,4.0,0.0,-2.0,-7.0,-0.8140830155768267,3.0,0.0,3.0,7.0,7.0,10.0,10.0,13.0,15.0,12.0,13.0,11.0,,,,,,,60.0,54.0,58.0,67.0,0.3490741493688483,49.0,44.0,43.0,22.0,18.0,21.0,29.0,38.0,15.0,23.0,44.0,38.0,,,,,,,101.0,92.0,98.0,98.0,0.565095319564722,95.0,103.0,81.0,86.0,78.0,72.0,61.0,69.0,66.0,66.0,65.0,88.0,,,,,,,93.0,103.0,107.0,105.0,0.8935470872367557,92.0,80.0,74.0,68.0,60.0,50.0,48.0,63.0,45.0,43.0,31.0,40.0,,,,,,,111.0,108.0,109.0,92.0,1.433320108736767,62.0,34.0,37.0,27.0,38.0,17.0,12.0,5.0,4.0,5.0,11.0,9.0,,,,,,,22.0,13.0,27.0,28.0,0.08537323153816499,13.0,18.0,42.0,21.0,13.0,31.0,22.0,46.0,16.0,26.0,48.0,57.0,,,,,,,5.0,2.0,5.0,9.0,0.33689703194760534,1.0,5.0,21.0,8.0,8.0,17.0,15.0,34.0,8.0,9.0,27.0,-1.0,,,,,,,117.0,132.0,131.0,135.0,-0.004574434257553335,124.0,121.0,123.0,107.0,114.0,114.0,108.0,84.0,113.0,130.0,136.0,144.0,,,,,,,128.0,108.0,78.0,113.0,0.201960834841674,111.0,69.0,186.0,204.0,189.0,128.0,160.0,123.0,96.0,108.0,119.0,227.0,,,,,,,343.0,30.0,59.0,18.0,-1.6145909098324325,66.0,22.0,31.0,41.0,47.0,26.0,14.0,22.0,11.0,34.0,47.0,49.0,,,,,,,143.0,128.0,123.0,151.0,-0.5688029519548106,206.0,130.0,244.0,285.0,244.0,202.0,243.0,229.0,209.0,215.0,195.0,288.0,,,,,,,47.0,23.0,39.0,75.0,-0.6756125285951066,-6.0,-10.0,22.0,17.0,22.0,16.0,53.0,70.0,48.0,35.0,75.0,65.0,,,,,,,-642.0,-634.0,-632.0,-633.0,1.3919164230000043,-637.0,-636.0,-636.0,-639.0,-635.0,-625.0,-624.0,-617.0,-613.0,-607.0,-607.0,-598.0,,,,,,,-535.0,-541.0,-544.0,-542.0,-0.9165385511791325,-541.0,-543.0,-541.0,-538.0,-541.0,-545.0,-547.0,-547.0,-552.0,-554.0,-554.0,-556.0,,,,,,,-420.0,-425.0,-430.0,-425.0,-1.0617243214148793,-428.0,-431.0,-429.0,-424.0,-428.0,-433.0,-430.0,-425.0,-430.0,-436.0,-435.0,-436.0,,,,,,,115.0,131.0,111.0,119.0,0.07144139428735102,185.0,103.0,164.0,215.0,210.0,143.0,162.0,146.0,86.0,132.0,149.0,266.0,,,,,,,48.0,66.0,74.0,55.0,-1.1197438028083857,79.0,74.0,51.0,63.0,76.0,70.0,58.0,54.0,47.0,39.0,52.0,48.0,,,,,,,49.0,41.0,24.0,33.0,-0.13168297718748687,72.0,41.0,64.0,74.0,73.0,42.0,84.0,107.0,27.0,66.0,82.0,107.0,,,,,,,89.0,104.0,106.0,76.0,-0.5941391204709386,149.0,125.0,117.0,116.0,126.0,118.0,91.0,127.0,183.0,70.0,96.0,87.0,,,,,,,159.0,152.0,122.0,149.0,-0.2204422929966425,259.0,142.0,238.0,288.0,257.0,211.0,249.0,263.0,171.0,212.0,228.0,337.0,,,,,,,93.0,100.0,97.0,103.0,-0.04406976588752019,97.0,101.0,102.0,85.0,94.0,96.0,91.0,70.0,72.0,70.0,65.0,81.0,,,,,,,91.0,91.0,100.0,96.0,-0.7682834211096352,53.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,282.0,544.0,684.0,116.0,-1.2584376864305755,121.0,84.0,47.0,44.0,47.0,45.0,38.0,36.0,38.0,37.0,33.0,34.0,,,,,,,263.0,453.0,545.0,127.0,-1.4456131572129067,133.0,96.0,55.0,52.0,55.0,54.0,46.0,44.0,46.0,45.0,42.0,43.0,,,,,,,333.0,592.0,812.0,169.0,-1.0145098297648456,160.0,107.0,50.0,46.0,47.0,46.0,39.0,37.0,38.0,37.0,33.0,34.0,,,,,,,-9.0,-5.0,-8.0,-2.0,0.19902107531106553,1.0,-6.0,-4.0,-2.0,6.0,-3.0,9.0,30.0,0.0,-59.0,-40.0,-158.0,,,,,,,-16.0,-1.0,1.0,-3.0,-0.2112721289432366,-9.0,-6.0,-29.0,-52.0,-1.0,-21.0,-3.0,37.0,-4.0,-81.0,-53.0,-217.0,,,,,,,-64.0,-42.0,-63.0,-81.0,0.6381912194567253,-29.0,-19.0,-38.0,-18.0,-69.0,-47.0,-82.0,-84.0,-70.0,-100.0,-106.0,-98.0,,,,,,,-55.0,-31.0,-68.0,-75.0,1.2002963850130934,-41.0,-31.0,-38.0,-12.0,-59.0,-64.0,-106.0,-87.0,-96.0,-96.0,-112.0,-76.0,,,,,,,142.0,226.0,264.0,144.0,-0.19364075265513003,303.0,305.0,64.0,174.0,309.0,301.0,66.0,141.0,215.0,202.0,46.0,85.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,3.0,3.0,3.0,1.0,13.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2018-05-28 00:00:00,AL,-25.021291666666666,1.2722694729622666,,opr,55.04684166666666 +58584,AL012018,2018.0,5.0,28.0,6.0,0.02086175047554257,28.6,-86.19999999999997,,,,,,,,,,,,,,,,,,,,,,,,,,,,2.07481801020238,-0.1747366069976184,0.5365050837114127,0.671394321778676,0.7212293295996243,0.29402736068985785,0.9505412683363657,0.0,0.2474692266138615,-2.2993217338895957,-2.3814141159795135,-0.6457353569260451,-0.7138402531568866,-1.6353376064346723,-0.8061571013202915,1.1855056777156414,1.8452075353730393,0.8895595500229374,,,,,,,-0.67009121082335,0.7821215214191309,-0.8953852447252868,0.09509119503493474,-0.7374830525475055,-0.3176713286316317,-0.2232095329373984,-0.10000831312869018,-0.07373383823419413,0.16271694489887312,-0.8530559869006481,0.28288512831662577,-0.7836196539585956,-0.26985413435875977,-0.5385618286097898,-0.43725715885932387,-0.38138480584854695,-0.30281620363297884,0.4126621929154774,-0.8429437972493922,-0.8949914803249487,,,,-1.0368968505843295,0.22318824072225832,0.10080666121719989,0.2931811931412278,0.023051905730676253,0.019196832239975092,-0.08832022714412052,-0.13692971169785056,-0.2840577492875173,-0.447247146155074,-0.6227111914034117,0.10153859212265194,0.14324721190306014,0.024887584056754015,0.1807752704534365,0.22104595977123595,-0.07132381856440458,-0.0643432924901094,-0.06629275839573405,-0.16199909798489956,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,275.0,280.0,286.0,293.0,300.0,310.0,319.0,331.0,342.0,355.0,368.0,383.0,397.0,412.0,426.0,439.0,451.0,462.0,472.0,,,,,849.0,856.0,862.0,865.0,867.0,869.0,871.0,873.0,875.0,876.0,878.0,877.0,876.0,871.0,866.0,855.0,844.0,828.0,811.0,,,,,,,263.0,257.0,254.0,254.0,-1.1713367026665655,213.0,199.0,184.0,169.0,141.0,126.0,86.0,80.0,73.0,43.0,49.0,41.0,,,,,,,90.0,75.0,69.0,61.0,-1.988266271410359,,,,,,,,,,,,,,,,,,,21.0,17.0,16.0,16.0,-1.6573379460839583,,,,,,,,,,,,,,,,,,,6.0,1.0,0.0,0.0,-1.1262679727290026,,,,,,,,,,,,,,,,,,,144.0,110.0,52.0,-54.0,-1.3628149496799484,-269.0,-391.0,-534.0,-678.0,-839.0,-999.0,-999.0,-999.0,-999.0,-983.0,-937.0,-927.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,262.0,262.0,263.0,261.0,-1.2250712090497413,228.0,209.0,190.0,170.0,148.0,125.0,95.0,79.0,59.0,37.0,32.0,22.0,,,,,,,101.0,102.0,78.0,108.0,0.8782192617299296,81.0,85.0,161.0,171.0,141.0,125.0,160.0,183.0,184.0,196.0,236.0,284.0,,,,,,,58.0,33.0,21.0,19.0,0.49160088151828557,36.0,15.0,63.0,87.0,32.0,32.0,63.0,96.0,120.0,141.0,168.0,198.0,,,,,,,111.0,93.0,165.0,218.0,1.4007463697060356,163.0,266.0,256.0,232.0,199.0,231.0,222.0,224.0,203.0,209.0,172.0,134.0,,,,,,,3449.0,3439.0,3469.0,3477.0,-0.7571237422307033,3415.0,3478.0,3510.0,3422.0,3392.0,3474.0,3455.0,3364.0,3325.0,3357.0,3266.0,3128.0,,,,,,,66.0,63.0,82.0,82.0,-0.8864901189644342,47.0,90.0,111.0,46.0,31.0,89.0,71.0,14.0,2.0,14.0,0.0,0.0,,,,,,,22.0,23.0,19.0,19.0,0.49021463295837403,28.0,20.0,17.0,29.0,36.0,23.0,26.0,49.0,67.0,49.0,114.0,219.0,,,,,,,20.0,16.0,34.0,34.0,-1.0003615261575074,4.0,43.0,59.0,9.0,3.0,47.0,31.0,0.0,0.0,0.0,0.0,0.0,,,,,,,34.0,34.0,35.0,32.0,0.14116080461270386,43.0,40.0,34.0,50.0,60.0,41.0,43.0,82.0,106.0,77.0,149.0,253.0,,,,,,,73.0,73.0,74.0,73.0,-0.1586450632012436,71.0,74.0,71.0,70.0,71.0,74.0,72.0,73.0,76.0,80.0,82.0,79.0,,,,,,,64.0,62.0,62.0,64.0,-0.055044340560187935,61.0,60.0,61.0,62.0,65.0,66.0,68.0,69.0,70.0,70.0,73.0,71.0,,,,,,,60.0,58.0,58.0,63.0,0.36714694908861395,61.0,62.0,65.0,66.0,71.0,70.0,72.0,72.0,73.0,71.0,72.0,71.0,,,,,,,96.0,107.0,111.0,90.0,0.4147449624771092,47.0,46.0,22.0,1.0,14.0,40.0,37.0,47.0,97.0,132.0,127.0,91.0,,,,,,,32.0,32.0,44.0,25.0,-1.4794988774855478,26.0,51.0,21.0,40.0,20.0,48.0,44.0,37.0,43.0,64.0,88.0,25.0,,,,,,,13.0,7.0,5.0,25.0,0.8163037408806149,5.0,17.0,21.0,11.0,7.0,11.0,12.0,8.0,8.0,10.0,11.0,10.0,,,,,,,-2.0,-1.0,-3.0,-4.0,-0.5721558845640834,-3.0,-5.0,-4.0,-3.0,-3.0,-4.0,-4.0,-4.0,-3.0,-4.0,-4.0,-3.0,,,,,,,246.0,241.0,266.0,262.0,-0.9743950974445472,231.0,276.0,274.0,234.0,221.0,271.0,254.0,216.0,204.0,228.0,195.0,144.0,,,,,,,81.0,83.0,71.0,75.0,1.3563362583490026,86.0,66.0,72.0,85.0,89.0,68.0,76.0,87.0,88.0,76.0,82.0,86.0,,,,,,,-27.0,-27.0,-22.0,-33.0,0.009707188804205782,-29.0,-26.0,-38.0,-31.0,-32.0,-37.0,-55.0,-56.0,-55.0,-59.0,-50.0,-34.0,,,,,,,284.0,292.0,299.0,313.0,1.1596050839870546,331.0,344.0,359.0,371.0,384.0,398.0,409.0,420.0,434.0,449.0,461.0,473.0,,,,,,,857.0,859.0,857.0,860.0,-0.584008215263781,865.0,867.0,869.0,872.0,876.0,876.0,865.0,858.0,851.0,835.0,824.0,816.0,,,,,,,114.0,120.0,119.0,119.0,0.4949079174141101,113.0,93.0,91.0,83.0,81.0,77.0,78.0,78.0,71.0,66.0,80.0,80.0,,,,,,,188.0,203.0,191.0,199.0,0.36853408769680757,165.0,139.0,133.0,112.0,121.0,121.0,107.0,103.0,96.0,90.0,104.0,100.0,,,,,,,23.0,27.0,23.0,18.0,4.125595511862445,17.0,12.0,9.0,11.0,10.0,9.0,5.0,6.0,5.0,5.0,0.0,-1.0,,,,,,,12.0,9.0,8.0,5.0,1.3293547681087106,9.0,9.0,7.0,10.0,9.0,6.0,2.0,2.0,5.0,6.0,3.0,0.0,,,,,,,0.0,-7.0,-5.0,-1.0,-0.8140830155768267,0.0,7.0,4.0,5.0,9.0,10.0,13.0,10.0,12.0,7.0,9.0,9.0,,,,,,,53.0,57.0,66.0,58.0,0.21820809044975872,44.0,48.0,25.0,18.0,17.0,29.0,29.0,28.0,21.0,32.0,39.0,40.0,,,,,,,92.0,94.0,105.0,102.0,0.5285582964832684,108.0,90.0,89.0,85.0,64.0,65.0,79.0,81.0,70.0,61.0,104.0,83.0,,,,,,,105.0,109.0,100.0,91.0,0.9565582104926191,83.0,95.0,81.0,75.0,57.0,68.0,77.0,70.0,66.0,52.0,44.0,58.0,,,,,,,112.0,118.0,89.0,66.0,1.57286940921241,58.0,50.0,41.0,45.0,23.0,3.0,24.0,21.0,20.0,23.0,10.0,12.0,,,,,,,10.0,19.0,23.0,19.0,-0.3572154547033254,29.0,38.0,16.0,10.0,28.0,17.0,44.0,17.0,20.0,42.0,35.0,69.0,,,,,,,3.0,2.0,8.0,6.0,0.17712680062911587,10.0,18.0,5.0,3.0,11.0,9.0,30.0,13.0,1.0,29.0,13.0,-9.0,,,,,,,129.0,131.0,136.0,120.0,0.23294305213239366,122.0,121.0,105.0,111.0,107.0,102.0,85.0,93.0,122.0,124.0,128.0,150.0,,,,,,,83.0,52.0,110.0,168.0,-0.29397261221376864,91.0,172.0,201.0,160.0,108.0,133.0,103.0,93.0,97.0,87.0,147.0,235.0,,,,,,,57.0,39.0,23.0,20.0,-1.2781265785945028,28.0,17.0,29.0,41.0,3.0,359.0,0.0,340.0,3.0,26.0,37.0,49.0,,,,,,,116.0,109.0,175.0,198.0,-0.5523063755593236,160.0,232.0,246.0,211.0,176.0,210.0,214.0,204.0,192.0,180.0,230.0,270.0,,,,,,,36.0,70.0,81.0,19.0,-2.33628025700203,6.0,57.0,62.0,70.0,22.0,68.0,63.0,9.0,3.0,80.0,118.0,39.0,,,,,,,-632.0,-631.0,-631.0,-635.0,1.6469988807222107,-630.0,-628.0,-634.0,-629.0,-622.0,-615.0,-610.0,-602.0,-601.0,-597.0,-591.0,-586.0,,,,,,,-542.0,-544.0,-542.0,-536.0,-0.8637312378170877,-541.0,-539.0,-536.0,-540.0,-544.0,-547.0,-547.0,-548.0,-550.0,-550.0,-551.0,-554.0,,,,,,,-425.0,-431.0,-427.0,-423.0,-1.2050723123236002,-430.0,-428.0,-424.0,-428.0,-433.0,-431.0,-428.0,-433.0,-437.0,-437.0,-438.0,-445.0,,,,,,,123.0,103.0,107.0,166.0,0.21956841397589025,102.0,164.0,210.0,185.0,121.0,142.0,143.0,90.0,103.0,146.0,228.0,312.0,,,,,,,87.0,85.0,65.0,55.0,-0.9237330154986626,70.0,42.0,55.0,75.0,64.0,46.0,54.0,48.0,43.0,50.0,50.0,59.0,,,,,,,48.0,24.0,32.0,63.0,-0.05148805647438121,48.0,56.0,78.0,80.0,31.0,82.0,103.0,20.0,46.0,82.0,91.0,125.0,,,,,,,113.0,125.0,83.0,99.0,-0.28591858514531315,127.0,116.0,110.0,131.0,123.0,89.0,127.0,172.0,70.0,103.0,104.0,75.0,,,,,,,165.0,119.0,150.0,221.0,-0.1186525357999295,147.0,231.0,272.0,239.0,201.0,240.0,247.0,167.0,180.0,222.0,307.0,366.0,,,,,,,95.0,95.0,101.0,89.0,0.027244501320837465,93.0,95.0,82.0,92.0,91.0,83.0,64.0,62.0,64.0,59.0,71.0,91.0,,,,,,,101.0,103.0,98.0,92.0,-1.4719955710403214,24.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,646.0,786.0,155.0,177.0,-1.1440591423085456,96.0,49.0,46.0,47.0,46.0,38.0,35.0,37.0,36.0,33.0,34.0,38.0,,,,,,,516.0,607.0,161.0,179.0,-1.2498247590245006,108.0,57.0,54.0,56.0,55.0,46.0,43.0,46.0,45.0,42.0,43.0,48.0,,,,,,,676.0,876.0,170.0,264.0,-0.9890746448089742,128.0,53.0,48.0,48.0,46.0,39.0,36.0,38.0,37.0,33.0,34.0,37.0,,,,,,,-9.0,-11.0,0.0,8.0,0.19902107531106553,-3.0,-4.0,-6.0,-8.0,-31.0,-23.0,-7.0,-38.0,-75.0,-34.0,-92.0,-69.0,,,,,,,3.0,-1.0,-2.0,-14.0,-0.03283807503825856,-4.0,-23.0,-55.0,-12.0,-49.0,-60.0,-7.0,-47.0,-90.0,-39.0,-127.0,-120.0,,,,,,,-51.0,-68.0,-71.0,-41.0,0.8783006913953798,-33.0,-46.0,-26.0,-47.0,-49.0,-83.0,-73.0,-58.0,-76.0,-103.0,-103.0,-30.0,,,,,,,-38.0,-78.0,-63.0,-6.0,0.6225651868577771,-50.0,-45.0,-17.0,-52.0,-73.0,-105.0,-81.0,-77.0,-81.0,-117.0,-91.0,-26.0,,,,,,,247.0,278.0,136.0,182.0,0.2945221572336169,312.0,79.0,181.0,299.0,297.0,60.0,157.0,229.0,203.0,79.0,97.0,117.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,3.0,3.0,3.0,11.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2018-05-28 06:00:00,AL,-30.02555,0.7852973045355962,,opr,55.04684166666666 +58585,AL012018,2018.0,5.0,28.0,12.0,-0.15454714430021646,29.0,-86.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.40422044658968154,0.6140751388064998,0.6499849129748563,0.724429858393754,0.8480252688174907,0.778757909066751,0.7758719765433574,0.0,-0.3747544514850705,-0.4406505414692957,-0.580322441048195,-0.010744510914125325,0.0714817541348044,-0.11094505897050025,-0.37397963548048213,0.258549757877764,0.4172598726234954,0.08018309625560538,,,,,,,-0.5421232544027693,-0.3248216060982522,-0.881092095037376,-0.02011554313546989,-0.9052150385119488,-0.5299513836830934,-0.2933168274153095,0.04105966263159767,-0.13095279517406685,0.2591376725447648,-0.8239827851320211,0.17141167738724844,-0.8854408542123472,-0.22418764784889503,-0.626216212280124,-0.31522932727566483,-0.455227238364397,-0.22671343423179094,0.6252604779750383,-0.7520974022037479,-0.9240776826801126,,,,-1.0368968505843295,0.4827926147320496,0.3919541707166609,0.4718264908444293,0.2667100617208013,-0.25877276236532304,-0.3035383772109038,-0.3855327059949039,-0.4476533807657406,-0.6132315445465295,-0.8047348167572776,0.2879930991188325,0.3522503627667107,0.024887584056754015,0.4415659857892588,0.4905780206194786,0.07302549330662801,-0.09803269049571516,-0.08725597108536785,-0.1504881643002489,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,278.0,284.0,290.0,299.0,307.0,319.0,330.0,344.0,357.0,371.0,385.0,399.0,413.0,427.0,440.0,453.0,465.0,477.0,489.0,,,,,860.0,860.0,860.0,861.0,863.0,865.0,866.0,868.0,870.0,871.0,871.0,868.0,865.0,858.0,850.0,836.0,823.0,805.0,788.0,,,,,,,256.0,257.0,254.0,249.0,-2.8968555900611026,198.0,183.0,155.0,141.0,126.0,87.0,83.0,59.0,52.0,49.0,43.0,41.0,,,,,,,78.0,69.0,65.0,18.0,0.00026731598782810063,,,,,,,,,,,,,,,,,,,17.0,15.0,15.0,6.0,0.0204776868654023,,,,,,,,,,,,,,,,,,,2.0,0.0,0.0,1.0,0.014844097715522387,,,,,,,,,,,,,,,,,,,97.0,55.0,-22.0,-150.0,-1.533185019424155,-420.0,-563.0,-716.0,-870.0,-977.0,-980.0,-965.0,-979.0,-939.0,-936.0,-924.0,-786.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,273.0,275.0,276.0,264.0,-1.6291056596639668,219.0,199.0,178.0,157.0,134.0,106.0,92.0,67.0,48.0,40.0,26.0,20.0,,,,,,,111.0,95.0,115.0,154.0,0.4943721394292389,90.0,157.0,159.0,145.0,132.0,151.0,167.0,182.0,176.0,195.0,246.0,280.0,,,,,,,55.0,51.0,32.0,72.0,0.3482835924020292,23.0,65.0,78.0,36.0,36.0,50.0,94.0,121.0,134.0,153.0,184.0,219.0,,,,,,,115.0,165.0,237.0,237.0,1.4616715887827871,243.0,261.0,235.0,200.0,225.0,227.0,243.0,191.0,209.0,179.0,163.0,139.0,,,,,,,3440.0,3468.0,3477.0,3432.0,-1.018484963018136,3471.0,3500.0,3412.0,3386.0,3464.0,3468.0,3377.0,3347.0,3365.0,3266.0,3122.0,3041.0,,,,,,,64.0,81.0,83.0,52.0,-1.2520186602807148,84.0,102.0,37.0,26.0,79.0,77.0,18.0,9.0,17.0,0.0,0.0,0.0,,,,,,,23.0,19.0,18.0,25.0,0.6905023822067029,20.0,18.0,30.0,37.0,24.0,25.0,44.0,55.0,47.0,109.0,212.0,253.0,,,,,,,18.0,33.0,35.0,7.0,-1.17165603163657,39.0,53.0,5.0,2.0,41.0,40.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,34.0,34.0,32.0,38.0,0.24316277746513004,39.0,32.0,51.0,60.0,40.0,39.0,70.0,85.0,70.0,147.0,257.0,305.0,,,,,,,74.0,74.0,74.0,72.0,0.08640746858612475,74.0,72.0,73.0,73.0,77.0,76.0,76.0,78.0,82.0,81.0,72.0,59.0,,,,,,,63.0,63.0,64.0,63.0,0.3489087252075847,62.0,63.0,66.0,68.0,69.0,71.0,70.0,71.0,71.0,69.0,60.0,52.0,,,,,,,60.0,59.0,61.0,61.0,0.6424120908338762,64.0,66.0,69.0,72.0,71.0,72.0,73.0,72.0,70.0,69.0,65.0,62.0,,,,,,,103.0,111.0,102.0,59.0,0.18536133239058275,45.0,30.0,18.0,29.0,43.0,52.0,64.0,102.0,139.0,124.0,69.0,40.0,,,,,,,37.0,73.0,44.0,5.0,-0.34808382794136766,60.0,35.0,37.0,17.0,45.0,41.0,35.0,48.0,82.0,95.0,20.0,4.0,,,,,,,5.0,0.0,22.0,12.0,0.27957496927237246,12.0,18.0,11.0,6.0,9.0,10.0,8.0,10.0,9.0,8.0,15.0,8.0,,,,,,,-2.0,-3.0,-4.0,-3.0,-0.5721558845640834,-5.0,-4.0,-3.0,-3.0,-5.0,-4.0,-4.0,-4.0,-4.0,-4.0,-3.0,-2.0,,,,,,,242.0,263.0,261.0,238.0,-1.4402460049173023,272.0,269.0,229.0,218.0,265.0,255.0,217.0,208.0,231.0,196.0,143.0,115.0,,,,,,,82.0,72.0,75.0,84.0,2.0319486468509957,67.0,74.0,87.0,90.0,71.0,78.0,89.0,90.0,76.0,81.0,85.0,80.0,,,,,,,-24.0,-20.0,-30.0,-26.0,0.092844357500217,-24.0,-38.0,-31.0,-31.0,-38.0,-60.0,-62.0,-63.0,-65.0,-52.0,-26.0,8.0,,,,,,,289.0,298.0,308.0,318.0,1.2154963802055339,343.0,360.0,374.0,390.0,404.0,420.0,438.0,457.0,477.0,490.0,483.0,452.0,,,,,,,859.0,859.0,862.0,866.0,-0.584008215263781,865.0,866.0,868.0,868.0,867.0,857.0,855.0,845.0,851.0,811.0,815.0,835.0,,,,,,,116.0,115.0,114.0,102.0,0.48326067435941616,92.0,81.0,79.0,69.0,71.0,70.0,69.0,71.0,79.0,88.0,62.0,61.0,,,,,,,189.0,185.0,182.0,152.0,0.2881468918410159,142.0,121.0,106.0,107.0,103.0,97.0,88.0,90.0,105.0,107.0,78.0,85.0,,,,,,,29.0,26.0,22.0,19.0,4.125595511862445,10.0,7.0,7.0,8.0,8.0,4.0,2.0,0.0,-2.0,-8.0,-1.0,9.0,,,,,,,8.0,8.0,8.0,9.0,1.3293547681087106,6.0,6.0,6.0,6.0,4.0,-1.0,0.0,3.0,2.0,-3.0,3.0,14.0,,,,,,,-8.0,-6.0,-1.0,2.0,-0.9890844188759867,5.0,9.0,9.0,10.0,8.0,9.0,9.0,12.0,10.0,7.0,7.0,4.0,,,,,,,59.0,66.0,60.0,49.0,0.10370028889555534,46.0,21.0,21.0,14.0,31.0,34.0,19.0,26.0,39.0,40.0,32.0,27.0,,,,,,,93.0,98.0,94.0,87.0,0.565095319564722,79.0,77.0,80.0,59.0,67.0,74.0,73.0,76.0,89.0,102.0,72.0,81.0,,,,,,,106.0,94.0,84.0,96.0,0.7045137174691652,84.0,73.0,58.0,45.0,58.0,49.0,47.0,41.0,63.0,28.0,41.0,61.0,,,,,,,133.0,97.0,79.0,70.0,1.2705125915151834,37.0,35.0,35.0,10.0,2.0,-4.0,-11.0,-18.0,10.0,-38.0,5.0,77.0,,,,,,,15.0,24.0,16.0,16.0,-0.3018918689231391,41.0,24.0,10.0,15.0,25.0,42.0,14.0,29.0,60.0,71.0,72.0,103.0,,,,,,,2.0,6.0,5.0,8.0,0.41678214760685006,25.0,9.0,0.0,9.0,16.0,35.0,10.0,18.0,25.0,20.0,-12.0,-73.0,,,,,,,132.0,137.0,118.0,125.0,0.08449462313867678,122.0,106.0,111.0,114.0,103.0,83.0,102.0,123.0,131.0,140.0,156.0,155.0,,,,,,,79.0,124.0,187.0,152.0,-0.49818050217777443,142.0,178.0,134.0,94.0,102.0,91.0,102.0,67.0,159.0,209.0,277.0,376.0,,,,,,,42.0,32.0,18.0,39.0,-1.5620183580765061,24.0,29.0,33.0,352.0,354.0,336.0,350.0,27.0,37.0,53.0,42.0,32.0,,,,,,,111.0,190.0,215.0,201.0,-0.9729690736442411,226.0,231.0,190.0,165.0,197.0,205.0,195.0,177.0,257.0,306.0,312.0,402.0,,,,,,,46.0,89.0,27.0,-41.0,-0.6756125285951066,70.0,56.0,60.0,14.0,75.0,51.0,65.0,57.0,61.0,79.0,13.0,15.0,,,,,,,-630.0,-632.0,-636.0,-634.0,1.5959823891777696,-633.0,-638.0,-631.0,-623.0,-617.0,-608.0,-600.0,-597.0,-596.0,-588.0,-586.0,-577.0,,,,,,,-543.0,-542.0,-538.0,-540.0,-1.2333824313514008,-541.0,-537.0,-542.0,-544.0,-546.0,-545.0,-548.0,-549.0,-548.0,-547.0,-553.0,-556.0,,,,,,,-431.0,-427.0,-422.0,-425.0,-1.348420303232321,-425.0,-422.0,-428.0,-433.0,-433.0,-431.0,-434.0,-438.0,-437.0,-439.0,-448.0,-456.0,,,,,,,126.0,126.0,168.0,188.0,-0.6296931655717346,168.0,193.0,155.0,119.0,133.0,104.0,86.0,98.0,124.0,215.0,293.0,380.0,,,,,,,70.0,63.0,56.0,74.0,-1.0435173855212712,43.0,55.0,71.0,55.0,48.0,53.0,37.0,49.0,46.0,42.0,51.0,55.0,,,,,,,36.0,42.0,65.0,71.0,-0.7732423428923321,68.0,68.0,56.0,35.0,84.0,94.0,22.0,51.0,66.0,94.0,108.0,187.0,,,,,,,99.0,89.0,101.0,139.0,-0.5516259431846455,108.0,116.0,123.0,99.0,94.0,130.0,140.0,72.0,88.0,86.0,78.0,71.0,,,,,,,134.0,170.0,230.0,239.0,-0.9329705933736335,246.0,246.0,218.0,188.0,236.0,221.0,170.0,177.0,203.0,283.0,328.0,446.0,,,,,,,100.0,103.0,91.0,96.0,0.09855876852919512,98.0,83.0,92.0,92.0,82.0,58.0,55.0,54.0,51.0,68.0,101.0,144.0,,,,,,,123.0,120.0,120.0,95.0,-1.7967857940852536,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,1316.0,592.0,865.0,885.0,-1.1343660453490514,53.0,48.0,51.0,48.0,39.0,37.0,39.0,37.0,34.0,34.0,39.0,40.0,,,,,,,896.0,489.0,637.0,653.0,-1.2292154539520368,62.0,56.0,60.0,57.0,47.0,45.0,47.0,46.0,42.0,43.0,48.0,51.0,,,,,,,1390.0,730.0,1123.0,1087.0,-0.9382042748972316,58.0,51.0,53.0,48.0,40.0,37.0,39.0,37.0,33.0,34.0,38.0,40.0,,,,,,,2.0,3.0,5.0,3.0,-0.20791593892439555,-5.0,-17.0,-21.0,-46.0,-12.0,-3.0,-37.0,-74.0,-52.0,-123.0,-108.0,-162.0,,,,,,,3.0,1.0,-11.0,1.0,-0.2112721289432366,-25.0,-52.0,-29.0,-67.0,-41.0,7.0,-41.0,-90.0,-64.0,-171.0,-168.0,-296.0,,,,,,,-75.0,-101.0,-38.0,-26.0,0.19799052090252536,-56.0,-50.0,-65.0,-33.0,-80.0,-74.0,-63.0,-70.0,-115.0,-83.0,-12.0,16.0,,,,,,,-81.0,-94.0,-5.0,-33.0,-0.09382149885481518,-51.0,-39.0,-72.0,-54.0,-98.0,-81.0,-76.0,-78.0,-129.0,-65.0,-5.0,33.0,,,,,,,233.0,129.0,160.0,261.0,0.05044070228924344,71.0,167.0,248.0,251.0,53.0,125.0,209.0,193.0,57.0,102.0,156.0,165.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,26.0,22.0,28.0,23.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2018-05-28 12:00:00,AL,-25.021291666666666,-0.6756192007444162,,opr,50.04258333333333 diff --git a/tests/fixtures/tcnd/BST_data/EP/test/EP2018BSTCARLOTTA.txt b/tests/fixtures/tcnd/BST_data/EP/test/EP2018BSTCARLOTTA.txt new file mode 100644 index 00000000..93aedc01 --- /dev/null +++ b/tests/fixtures/tcnd/BST_data/EP/test/EP2018BSTCARLOTTA.txt @@ -0,0 +1,18 @@ +0.0 1.0 16.000 2.980 0.960 -0.983 2018061418 CARLOTTA +1.0 1.0 16.000 3.020 0.940 -0.983 2018061500 CARLOTTA +2.0 1.0 16.020 3.080 0.940 -0.983 2018061506 CARLOTTA +3.0 1.0 16.040 3.120 0.940 -0.983 2018061512 CARLOTTA +4.0 1.0 16.080 3.160 0.920 -0.880 2018061518 CARLOTTA +5.0 1.0 16.120 3.180 0.920 -0.880 2018061600 CARLOTTA +6.0 1.0 16.140 3.180 0.800 -0.674 2018061606 CARLOTTA +7.0 1.0 16.160 3.180 0.800 -0.674 2018061612 CARLOTTA +8.0 1.0 16.160 3.200 0.800 -0.674 2018061618 CARLOTTA +9.0 1.0 16.100 3.280 0.740 -0.468 2018061700 CARLOTTA +10.0 1.0 15.920 3.320 0.800 -0.674 2018061706 CARLOTTA +11.0 1.0 15.800 3.360 0.900 -0.880 2018061712 CARLOTTA +12.0 1.0 15.660 3.400 0.940 -1.086 2018061718 CARLOTTA +13.0 1.0 15.560 3.440 0.940 -1.086 2018061800 CARLOTTA +14.0 1.0 15.480 3.480 0.960 -1.086 2018061806 CARLOTTA +15.0 1.0 15.400 3.540 0.960 -1.086 2018061812 CARLOTTA +16.0 1.0 15.340 3.600 0.940 -1.086 2018061818 CARLOTTA +17.0 1.0 15.300 3.620 0.960 -1.188 2018061900 CARLOTTA diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061418.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061418.npy new file mode 100644 index 00000000..9b732523 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061418.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061500.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061500.npy new file mode 100644 index 00000000..80a8e9ca Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061500.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061506.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061506.npy new file mode 100644 index 00000000..c3f2023c Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061506.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061512.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061512.npy new file mode 100644 index 00000000..2b136704 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061512.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061518.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061518.npy new file mode 100644 index 00000000..c238b284 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061518.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061600.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061600.npy new file mode 100644 index 00000000..fd073d14 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061600.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061606.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061606.npy new file mode 100644 index 00000000..3af5d80b Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061606.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061612.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061612.npy new file mode 100644 index 00000000..163768f2 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061612.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061618.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061618.npy new file mode 100644 index 00000000..c38038c1 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061618.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061700.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061700.npy new file mode 100644 index 00000000..4a650274 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061700.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061706.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061706.npy new file mode 100644 index 00000000..369dc0d9 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061706.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061712.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061712.npy new file mode 100644 index 00000000..27a127b7 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061712.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061718.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061718.npy new file mode 100644 index 00000000..fedf3697 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061718.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061800.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061800.npy new file mode 100644 index 00000000..1d4782e9 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061800.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061806.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061806.npy new file mode 100644 index 00000000..33520fb4 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061806.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061812.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061812.npy new file mode 100644 index 00000000..a08fc64c Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061812.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061818.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061818.npy new file mode 100644 index 00000000..1754fa76 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061818.npy differ diff --git a/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061900.npy b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061900.npy new file mode 100644 index 00000000..cc9c0ff5 Binary files /dev/null and b/tests/fixtures/tcnd/Env_data/EP/2018/CARLOTTA/2018061900.npy differ diff --git a/tests/fixtures/tcnd/SOURCE.txt b/tests/fixtures/tcnd/SOURCE.txt new file mode 100644 index 00000000..b7672457 --- /dev/null +++ b/tests/fixtures/tcnd/SOURCE.txt @@ -0,0 +1,8 @@ +Real files of one storm (EP 2018 CARLOTTA) from the TropiCycloneNet training data, Zenodo record +17104690 ("The training data for TCNM", CC BY 4.0, https://creativecommons.org/licenses/by/4.0/), by +C. Huang, P. Mu, J. Zhang, S. Chan, S. Zhang, H. Yan, S. Chen and C. Bai: +- BST_data/EP/test/EP2018BSTCARLOTTA.txt from data1d.zip (identical to Data1D/EP/test/ of the TCND release, + doi:10.5281/zenodo.15009527); +- Env_data/EP/2018/CARLOTTA/*.npy from env_data.zip (all_area_correct_location_includeunder15_2023/EP/2018/CARLOTTA). +The 500 hPa geopotential crops (100 x 100 float64, about 80 kB each) are not vendored; tests write +random crops of that shape. Extracted with HTTP range requests on 2026-10-07; files unchanged. diff --git a/tests/fixtures/wrf_sfire_hill_wrfout_header.json b/tests/fixtures/wrf_sfire_hill_wrfout_header.json new file mode 100644 index 00000000..1cef45ef --- /dev/null +++ b/tests/fixtures/wrf_sfire_hill_wrfout_header.json @@ -0,0 +1,314 @@ +{ + "description": "Layout of a real WRF-SFIRE history file: test/em_fire/hill (namelist.input.hill, history every 30 s instead of 5 s) of WRF-SFIRE W4.4-S0.1 (commit c959580092191b315d936566361314f9cab669ec), built serially with conda-forge gfortran 16.2 and classic NetCDF. Header of wrfout_d01_0001-01-01_00:00:00 (dimensions, selected global attributes, fire-grid variables) plus values observed in it. Used by tests/test_wrf_sfire_reader.py to write synthetic files with the same layout.", + "file": "wrfout_d01_0001-01-01_00:00:00", + "file_format": "NETCDF3_64BIT_OFFSET", + "dimensions": { + "Time": 11, + "DateStrLen": 19, + "west_east": 41, + "south_north": 41, + "bottom_top": 40, + "bottom_top_stag": 41, + "soil_layers_stag": 5, + "west_east_stag": 42, + "south_north_stag": 42, + "west_east_subgrid": 420, + "south_north_subgrid": 420, + "fuel_moisture_classes_stag": 6, + "fuel_moisture_extended_paramete": 2, + "seed_dim_stag": 8 + }, + "global_attributes": { + "TITLE": " OUTPUT FROM WRF V4.4 MODEL", + "SIMULATION_START_DATE": "0001-01-01_00:00:00", + "WEST-EAST_GRID_DIMENSION": 42, + "SOUTH-NORTH_GRID_DIMENSION": 42, + "DX": 60.0, + "DY": 60.0 + }, + "variables": { + "Times": { + "dimensions": [ + "Time", + "DateStrLen" + ], + "dtype": "|S1", + "attributes": {} + }, + "XTIME": { + "dimensions": [ + "Time" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "0 ", + "description": "minutes since 0001-01-01 00:00:00", + "units": "minutes since 0001-01-01 00:00:00", + "stagger": "" + } + }, + "TIGN_G": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "ignition time on ground", + "units": "s", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "LFN": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "level function", + "units": "1", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FIRE_AREA": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fraction of cell area on fire", + "units": "1", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FGRNHFX": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "heat flux from ground fire", + "units": "W/m^2", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "ROS": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "rate of spread", + "units": "m/s", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "F_ROS": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "max spread rate in any direction", + "units": "m/s", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FUEL_FRAC": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fuel remaining", + "units": "1", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "NFUEL_CAT": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fuel data", + "units": "-", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "ZSF": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "height of surface above sea level", + "units": "m", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FXLONG": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "longitude of midpoints of fire cells", + "units": "degrees", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FXLAT": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "latitude of midpoints of fire cells", + "units": "degrees", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "UF": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fire wind", + "units": "m/s", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "VF": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fire wind", + "units": "m/s", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + }, + "FLINEINT": { + "dimensions": [ + "Time", + "south_north_subgrid", + "west_east_subgrid" + ], + "dtype": "float32", + "attributes": { + "FieldType": 104, + "MemoryOrder": "XY ", + "description": "fireline intensity", + "units": "W/m", + "stagger": "Z", + "coordinates": "XLONG XLAT XTIME" + } + } + }, + "observations": { + "sr_x_sr_y_global_attributes": "absent (refinement 10 x 10 follows from 420 = (41 + 1) * 10)", + "fire_dt_s": 0.25, + "TIGN_G_unburned": "frame time + 0.25 s (0.5 s at t = 0)", + "TIGN_G_padding": 0.0, + "LFN_t0": "positive everywhere (no fire)", + "LFN_lt_0_equals_TIGN_G_le_t": true, + "xtime_minutes": [ + 0.0, + 0.5, + 1.0, + 1.5, + 2.0, + 2.5, + 3.0, + 3.5, + 4.0, + 4.5, + 5.0 + ], + "burned_fire_cells_per_frame": [ + 0, + 72, + 470, + 1371, + 2853, + 5031, + 7902, + 11220, + 14441, + 18203, + 23301 + ], + "arrival_time_range_s": [ + 2.0006, + 299.9918 + ] + } +} \ No newline at end of file diff --git a/tests/oracle/oracle_utils.py b/tests/oracle/oracle_utils.py new file mode 100644 index 00000000..b166742a --- /dev/null +++ b/tests/oracle/oracle_utils.py @@ -0,0 +1,133 @@ +"""Shared helpers for oracle tests: locate pinned reference code and import it in isolation. + +The oracle tests are skipped unless ``PYHAZARDS_ORACLE_DIR`` points at a directory filled by +``scripts/fetch_oracles.py``. With ``PYHAZARDS_ORACLE_REQUIRED=1`` (the Oracle CI workflow) a +missing reference fails the test instead. Multi-GB assets (``large: true`` in repos.yaml) are not +fetched in CI: tests that need them skip when the asset is absent, unless +``PYHAZARDS_ORACLE_LARGE=1`` makes them mandatory too. +""" + +from __future__ import annotations + +import ast +import importlib +import importlib.metadata +import os +import subprocess +import sys +from pathlib import Path +from types import ModuleType +from typing import Any, Dict, Iterable, Optional + +import pytest +import yaml + +MANIFEST = yaml.safe_load((Path(__file__).parent / "repos.yaml").read_text(encoding="utf-8")) + + +def missing(reason: str) -> None: + """Skip, or fail when the oracle run is mandatory.""" + if os.environ.get("PYHAZARDS_ORACLE_REQUIRED") == "1": + pytest.fail(reason) + pytest.skip(reason) + + +def oracle_dir() -> Path: + root = os.environ.get("PYHAZARDS_ORACLE_DIR") + if not root: + missing("PYHAZARDS_ORACLE_DIR is not set; run scripts/fetch_oracles.py first") + return Path(root).expanduser() + + +def oracle_repo(name: str) -> Path: + """Path of a pinned reference repository, checked to be at the pinned commit.""" + path = oracle_dir() / name + if not (path / ".git").exists(): + missing(f"oracle repo {name!r} is missing; run scripts/fetch_oracles.py {name}") + head = subprocess.run( + ["git", "rev-parse", "HEAD"], cwd=path, check=True, capture_output=True, text=True + ).stdout.strip() + expected = MANIFEST["repos"][name]["commit"] + assert head == expected, f"oracle repo {name} is at {head}, expected pinned {expected}" + return path + + +def oracle_asset(name: str) -> Path: + path = oracle_dir() / name + if not path.exists(): + missing(f"oracle asset {name!r} is missing; run scripts/fetch_oracles.py {name}") + return path + + +def oracle_large_asset(name: str) -> Path: + """Path of a ``large: true`` asset; skipped when absent unless ``PYHAZARDS_ORACLE_LARGE=1``.""" + path = oracle_dir() / name + if not path.exists(): + reason = f"large oracle asset {name!r} is missing; run scripts/fetch_oracles.py {name}" + if os.environ.get("PYHAZARDS_ORACLE_LARGE") == "1": + pytest.fail(reason) + pytest.skip(reason) + return path + + +def import_from(root: Path, module: str) -> ModuleType: + """Import ``module`` with ``root`` on sys.path, then drop it from sys.modules. + + Reference repositories reuse generic package names such as ``src``; removing them after + import keeps one repository's modules from shadowing another's. + """ + before = set(sys.modules) + sys.path.insert(0, str(root)) + try: + return importlib.import_module(module) + finally: + sys.path.remove(str(root)) + for name in set(sys.modules) - before: + if name.split(".")[0] == module.split(".")[0]: + del sys.modules[name] + + +def load_definitions(path: Path, names: Iterable[str], namespace: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Execute only the named top-level functions / classes of a reference source file. + + For reference files whose module-level imports pull in heavy packages that the needed code does + not use (Lightning, plotting, a vendored library): the definitions are compiled from the file's + own source, unchanged, into ``namespace`` (which must provide the names they use, e.g. ``torch`` + and ``nn``), and returned by name. + """ + wanted = set(names) + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + nodes = [ + node + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in wanted + ] + found = {node.name for node in nodes} + if found != wanted: + raise AssertionError(f"{path} does not define {sorted(wanted - found)}") + scope: Dict[str, Any] = dict(namespace or {}) + exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), scope) + return {name: scope[name] for name in wanted} + + +def oracle_package( + name: str, version: str, requirements: str = "requirements.txt", distribution: str | None = None +) -> ModuleType: + """Import a pip-installed reference package at an exact version (see ``requirements``). + + ``distribution`` is the PyPI name when it differs from the module name (``forefire`` installs + ``pyforefire``). + """ + try: + module = importlib.import_module(name) + except ImportError: + missing(f"{name} is not installed; pip install -r tests/oracle/{requirements}") + found = getattr(module, "__version__", None) + if found is None: + try: + found = importlib.metadata.version(distribution or name) + except importlib.metadata.PackageNotFoundError: + pass + if found != version: + missing(f"needs {name}=={version}, found {found}") + return module diff --git a/tests/oracle/repos.yaml b/tests/oracle/repos.yaml new file mode 100644 index 00000000..efa4d0d4 --- /dev/null +++ b/tests/oracle/repos.yaml @@ -0,0 +1,400 @@ +# Reference implementations that the oracle tests compare PyHazards models against. +# Each entry is pinned to an exact commit or checksum. They are fetched only for testing +# (scripts/fetch_oracles.py) and are never copied into the pyhazards package. +repos: + utae-paps: + url: https://github.com/VSainteuf/utae-paps.git + commit: 987874e27a98bb399277f2d55eb010744d26f881 + license: MIT + WildfireSpreadTS: + url: https://github.com/SebastianGer/WildfireSpreadTS.git + commit: f62dc49f2c2a6d249c071533ae5340c0d01bfb95 + license: MIT + wildfire_forecasting: + # Kondylatos et al., GRL 2022. Model code is identical to the v0.1-alpha release + # (ee4f168, archived as Zenodo 10.5281/zenodo.6524771) that the paper cites. + url: https://github.com/Orion-AI-Lab/wildfire_forecasting.git + commit: 2b18bcf194284d56bd4e1774f7d5315db94cba34 + license: MIT + Swin-Unet: + url: https://github.com/HuCaoFighting/Swin-Unet.git + commit: f48f623e226e25b6e395c37207915c50aaa9c776 + license: none (no LICENSE file; used only as a test oracle, never vendored) + fire-asufm: + url: https://github.com/bronteee/fire-asufm.git + commit: 688dda94dec9e3b22f149f2b9335d3b38fd2277f + license: Apache-2.0 + TS-SatFire: + url: https://github.com/zhaoyutim/TS-SatFire.git + commit: da7573219967edfe17e317310b66fd8a913f4a2e + license: none (no LICENSE file; test-time oracle only, never vendored) + TCN: + url: https://github.com/locuslab/TCN.git + commit: 2f8c2b817050206397458dfd1f5a25ce8a32fe65 + license: MIT + forefire: + # ForeFire v2.5.0, the tag of the PyPI 2.5.0 wheel used by tests/oracle/test_forefire_oracle.py + # (official example scripts and the tests/runff regression case). + url: https://github.com/forefireAPI/forefire.git + commit: ca433e01a9f2a146b1709da816a68feafcbfda41 + license: GPL-3.0 (test oracle only; never vendored, copied or imported by the pyhazards package) + firecastnet: + url: https://github.com/SeasFire/firecastnet.git + commit: dc0d131be7f0638e3a84c16817e7bc9be454e53e + license: none at repo level; seasfire/backbones/graphcast/* carry NVIDIA SPDX Apache-2.0 headers (test oracle only, never vendored) + earth-forecasting-transformer: + # Earthformer (Gao et al., NeurIPS 2022), official code; pyhazards/models/earthformer.py is a port of it. + url: https://github.com/amazon-science/earth-forecasting-transformer.git + commit: 7732b03bdb366110563516c3502315deab4c2026 + license: Apache-2.0 (Copyright Amazon.com, Inc. or its affiliates) + EarthFarseer: + # Wu et al., AAAI 2024. The paper links easylearningscores/EarthFarseer, which now redirects here. + url: https://github.com/Alexander-wu/EarthFarseer.git + commit: 258d4bb56497a6fb4022a5c37dec1e05ab1bedb1 + license: none (no LICENSE file; the README's Apache-2.0 badge links to OpenSTL's licence; test oracle only, never vendored) + Rainformer: + url: https://github.com/Zjut-MultimediaPlus/Rainformer.git + commit: c4e04e9011b7bbc1201a781fe5e0e56530126120 + license: none (no LICENSE file; test oracle only, never vendored) + + uncertainty-wildfires: + # Kondylatos et al., "Uncertainty-Aware Deep Learning for Wildfire Danger Forecasting" + # (arXiv 2509.25017). The repository holds the paper's checkpoints, including the ten + # deep-ensemble LSTMs in trained_models/ensembles/no-noisy (deep_ensemble oracle). + url: https://github.com/Orion-AI-Lab/uncertainty-wildfires.git + commit: fcfbfb894926d173e2f4cafc95b08f02cefe6e00 + SwinLSTM: + # Tang et al., ICCV 2023. The repository also holds the Moving-MNIST SwinLSTM-D weights + # (Pretrained/trained_model_state_dict). + url: https://github.com/SongTang-x/SwinLSTM.git + commit: 4425bcfefbebfac85c9fc6c6659361b8154d5ca3 + license: MIT + HKO-7: + # Shi et al., NeurIPS 2017 (TrajGRU), MXNet code. + url: https://github.com/sxjscience/HKO-7.git + commit: 57b987bd893bd6910996494c247359ace371d333 + license: MIT + SoraLink-MLLM: + # SmokeBench (Qi, Li & Barnes, WACV 2026) evaluation scripts, committed by the first author + # (qitianye1104); the paper links no code. Oracle for pyhazards/prompted (geometry, parsing, + # metrics, contrast). HEAD of master on 2026-10-07. + url: https://github.com/SoraLink/MLLM.git + commit: 183cdca488e8c7afa5a254f86ac675cb98951c73 + license: none (no LICENSE file; test oracle only, never vendored) + + tropicalcyclone_MLP: + # Xu et al., Weather and Forecasting 2021 (24-hour intensity-change MLP, Keras 2.2.4 / TF 1.12). + url: https://github.com/wenweixu/tropicalcyclone_MLP.git + commit: 73800596fc824c6d3f150fc41af0bdb7b9c3a7dc + license: BSD-2-Clause (Copyright (c) 2021, Wenwei Xu) + TI_Prediction: + # SAF-Net (Xu et al., Pattern Recognition Letters 2022): SAF-Net.ipynb and the released checkpoint + # model_saver/SAF_Net.pkl. Read in place by the oracle test; nothing is copied. + url: https://github.com/xuguangning1218/TI_Prediction.git + commit: 651ccc4ec5d2139c758148778d617583052f2eea + license: none (no LICENSE file; test oracle only, never vendored) + TropiCycloneNet: + # Huang et al., Nature Communications 2025. The GitHub repository has no LICENSE file; its model code + # (TCNM/*.py) is identical, up to line endings, to the CC BY 4.0 Zenodo release 10.5281/zenodo.15024028 + # (TropiCycloneNet.zip, git b4e7101) that pyhazards/models/tropicyclonenet.py ports. The GitHub copy + # also holds the evaluation script (scripts/evaluate_model_Me.py) used for the best-of-k metric check. + url: https://github.com/xiaochengfuhuo/TropiCycloneNet.git + commit: de9cf0e949bdee6e32cadf2605063b7bc6d33115 + license: none on GitHub; model code released under CC BY 4.0 on Zenodo (test oracle only, never vendored) + hurricast: + # Boussioux et al., Weather and Forecasting 2022 (Hurricast). The repository has no LICENSE file (its README + # claims MIT and links a LICENSE that does not exist): pyhazards/models/hurricast.py is written from the paper, + # and src/models/experimental_models.py, scripts/config.py, scripts/run_embeddings.py and the Round2 + # notebooks are read in place by the oracle test only. + url: https://github.com/leobix/hurricast.git + commit: b1b303a7a62eea89ddfd357fc99cd0787016a3bc + license: none (no LICENSE file; README claims MIT; test oracle only, never vendored) + TCIF-fusion: + # Wang, Li and Zheng, Environmental Research Letters 2024. Two Keras 2 / TF 1.x notebooks without a LICENSE + # file; the oracle test rebuilds the notebook's TCIF_fusion() graph in Keras 3 (torch backend) from the + # pinned notebook source and compares it with pyhazards/models/tcif_fusion.py. + url: https://github.com/wangchong96/TCIF-fusion.git + commit: 4b5fafcd8accf288f796d0859f22a7d103f40c24 + license: none (no LICENSE file; test oracle only, never vendored) + neuralhydrology: + # NeuralHydrology (Kratzert et al., JOSS 2022), v1.13.0 + 6 commits. Oracle for the CudaLSTM and + # EALSTM ports, the hydrological metrics, and the CAMELS-US / Caravan readers. Its test data + # (test/test_data/camels_us: 4 real CAMELS-US basins, 2000-2002) feed the reader comparison. + url: https://github.com/neuralhydrology/neuralhydrology.git + commit: ea94a40d2f271994e33baa70f5ca1dd82e0e539d + license: BSD-3-Clause (Copyright (c) 2021, NeuralHydrology) + ealstm_regional_modeling: + # Code of Kratzert et al., HESS 2019 (papercode/lstm.py, papercode/ealstm.py, main.py Model): + # the layout of the official HydroShare checkpoints (kratzert2019_hydroshare_runs). + url: https://github.com/kratzert/ealstm_regional_modeling.git + commit: d11815824793737f28f125d55477e42f8900a78e + license: Apache-2.0 + flood-forecasting: + # google-research/flood-forecasting (googlehydrology 1.13.0, a NeuralHydrology fork). Oracle for + # google_flood_forecasting; holds the released FloodHub model (pretrained-models/ + # google-floodhub-settings-110-epochs) and a real Caravan netCDF file in test/test_data/multimet. + url: https://github.com/google-research/flood-forecasting.git + commit: cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1 + license: Apache-2.0 (Copyright 2025 Google LLC) + physicsnemo: + # NVIDIA PhysicsNeMo: MeshGraphKAN (physicsnemo/models/meshgraphnet/meshgraphkan.py, last changed in + # dcad437), MeshGraphNet blocks, KolmogorovArnoldNetwork, HydroGraphDataset and the HydroGraphNet example + # (examples/weather/flood_modeling/hydrographnet, contributed by Taghizadeh et al.). Oracle for + # hydrographnet; test/models/meshgraphnet/data/meshgraphkan_output.pth is PhysicsNeMo's own regression + # output for MeshGraphKAN(4, 3, 2) at seed 0. + url: https://github.com/NVIDIA/physicsnemo.git + commit: eb7a329c246a48b6fb5acd569eaabeac53f915f7 + license: Apache-2.0 (Copyright (c) 2023 - 2026 NVIDIA CORPORATION & AFFILIATES) + UrbanFloodCast: + # Xu et al., J. Hydrology 661:133705 (2025): DNO (DNO/models/DNO.py, the default DNO-3), DNO-4, DNO-5, + # integral_operators.py (derived from U-NO, BSD-2) and the data pipeline / metrics (DNO/utils25.py). + # Oracle for urbanfloodcast. DNO/torch_utils and */training/filtered_networks.py are NVIDIA StyleGAN3 + # code under the NVIDIA Source Code License (non-commercial); they are never imported or copied. + url: https://github.com/HydroPML/UrbanFloodCast.git + commit: f08846a1d0ed5a82d9241d2229df8ec8997ebfd5 + license: none (no LICENSE file; test oracle only, never vendored) + + # Earthquake phase pickers (batch 4). Official TensorFlow / Keras code and released weights; the + # PyTorch ports in pyhazards/models/{phasenet,eqtransformer,gpd}.py are checked against them. + PhaseNet: + # Zhu & Beroza, GJI 2019. TF1 graph code (phasenet/model.py) and the released checkpoint + # model/190703-214543 (model_95.ckpt.*). + url: https://github.com/AI4EPS/PhaseNet.git + commit: 62005c6195638f88d077f8870ea895971062715a + license: MIT (Copyright (c) 2021 Weiqiang Zhu) + EQTransformer: + # Mousavi et al., Nat. Commun. 2020. Keras code (EQTransformer/core/EqT_utils.py), the paper model + # (ModelsAndSampleData/EqT_original_model.h5), the conservative model and 100 STEAD sample traces + # (100samples.hdf5/.csv, STEAD layout, CC BY 4.0 data). + url: https://github.com/smousavi05/EQTransformer.git + commit: a589da6504b11df8341fe1dc859a025f49955409 + license: MIT (Copyright (c) 2020-2025 S. Mostafa Mousavi) + generalized-phase-detection: + # Ross et al., BSSA 2018. Keras 2.2.2 model (model_pol.json + model_pol_best.hdf5), gpd_predict.py and + # the Anza 2016 example (three mseed files and the expected picks anza2016.out). + url: https://github.com/interseismic/generalized-phase-detection.git + commit: ea81ef17d204797de6a99d277fd2b9407fc77df7 + license: MIT (Copyright (c) 2018 Zachary E. Ross) + WaveCastNet: + # Lyu et al., Nat. Commun. 16:10622 (2025). Official PyTorch code (src/models_earthquake: AEConvLEM_dense, + # AEConvLEM_sparse, ConvLEMCell, EncoderDecoder, EncodingSparse, Validation_pixel; earthquake_train.py Huber), + # station grid indices filtered_coord.npy / shakealert_coords.npy. + url: https://github.com/dwlyu/WaveCastNet.git + commit: c859e04c85acd6657306f08bce8c6f9129ba1480 + license: MIT (Copyright (c) 2023 dwlyu) + EQNet: + # Zhu et al., JGR Solid Earth 2022. Academic / non-commercial licence: used only as a test oracle for the + # feature extractor (eqnet/models/resnet1d.py ResNet(BasicBlock, [2, 2, 2, 2])), never copied. + url: https://github.com/AI4EPS/EQNet.git + commit: af94a08a85de4b2c917a1b9429b044e7f38e4c28 + license: Academic and Commercial License (Copyright (c) 2023 Weiqiang Zhu, Zhongwen Zhan; non-commercial use only) + EQNet-2022: + # The author's first EQNet version ("basic version of eqnet", 2022-07-27, before any LICENSE file): its + # PhasePicker / EventDetector at the paper's channel widths are the oracle for the picking and detection heads. + url: https://github.com/AI4EPS/EQNet.git + commit: a9df49a18e05d15c24f98a5e61aa87b0e45cdaeb + license: none at this commit (all rights reserved; test oracle only, never copied) + + tempestextremes: + # TempestExtremes v2.4.2 (tag), the tracker TCBench runs on weather-model output + # (dev/TempestExtremes_example.sh). Built from source by tests/oracle/test_tempest_oracle.py (CMake, + # netCDF C library) and run as a separate program; pyhazards/forecasts/tempest.py is written from + # the published algorithm and copies no code. + url: https://github.com/ClimateGlobalChange/tempestextremes.git + commit: 02aabcaf375dc48b13b95fdc66af105435a32229 + license: BSD-2-Clause (repository LICENSE; some source files still carry an older GPL header) - test oracle only + TCBench_Alpha: + # TCBench evaluation code (Gomez et al., arXiv:2601.23268): dev/metrics_test.py, dev/evaluate_tracks.py, + # dev/utils/{toolbox,constants}.py are the oracle of the TCBench scoring protocol. + url: https://github.com/msgomez06/TCBench_Alpha.git + commit: 93924483baef8f35970c43131b1e2cbc95dee7bd + license: MIT +assets: + utae_pastis_weights: + url: https://zenodo.org/records/5172293/files/UTAE_SemanticSeg_weights.zip + sha256: 43a9db40ca002d9feac3a6b387838f24c3a7191b4257065d83206379f8ef957a + license: CC-BY-4.0 + extract: true + # SegFormer checkpoints from the Hugging Face Hub, pinned to a revision. NVIDIA licenses them for + # non-commercial use only (NVIDIA Source Code License for SegFormer); used here only as test data. + segformer_mit_b0: + url: https://huggingface.co/nvidia/mit-b0/resolve/80983a413c30d36a39c20203974ae7807835e2b4/pytorch_model.bin + sha256: 4af8348c2a802bf76115d34797ff5ce1d9f110bb8593c22d9b66d8bd7fa227fc + license: NVIDIA Source Code License for SegFormer (non-commercial) + segformer_b0_ade: + url: https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/489d5cd81a0b59fab9b7ea758d3548ebe99677da/model.safetensors + sha256: 6ae39addd01de6b1b8bde2cf677d43a5cd733424b8d186de3f95d1c51fee23f9 + license: NVIDIA Source Code License for SegFormer (non-commercial) + swin_tiny_imagenet: + url: https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth + sha256: 9f71c168d837d1b99dd1dc29e14990a7a9e8bdc5f673d46b04fe36fe15590ad3 + license: MIT (microsoft/Swin-Transformer) + firecastnet_global_cls_ts24_h1: + # FireCastNet global classification checkpoint (24 x 8-day input, 1-step horizon), Lightning format. + url: https://huggingface.co/datasets/d-michail/firecastnet-artifacts/resolve/f0bd28428d36b933ef4fb581189c741bf4ed1a10/model_ckpts/firecastnet-cls-ts24-h1.ckpt + sha256: c1e525d8b726f9c725c755da3edeab6f310db82689d4c57a22d001baab724916 + license: Apache-2.0 + firecastnet_global_regr_ts24_h1: + # The same network trained for burned-area regression (log-transformed target, Huber loss). + url: https://huggingface.co/datasets/d-michail/firecastnet-artifacts/resolve/f0bd28428d36b933ef4fb581189c741bf4ed1a10/model_ckpts/firecastnet-regr-ts24-h1.ckpt + sha256: 2b3bcf43fe853bee04b6bf2250facf10184ec9eaa2114633b74b71eec5b6ccb2 + license: Apache-2.0 + firecastnet_lam_aust_cls_ts24_h1: + # FireCastNet local-area model for the GFED AUST region (single 2002-vertex LAM mesh). + url: https://huggingface.co/datasets/d-michail/firecastnet-artifacts/resolve/f0bd28428d36b933ef4fb581189c741bf4ed1a10/lam_model_ckpts/firecastnet-cls-AUST-ts24-h1.ckpt + sha256: 4fea29fb69a4e6e171ae159001129167879424c489ba649ffc1f2017d3e6b126 + license: Apache-2.0 + # Prithvi-EO-2.0 (Hugging Face ibm-nasa-geospatial, Apache-2.0), pinned to a repo revision. + prithvi_eo2_tl_model_code: + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL/resolve/63adbd39c271da4c42f447e69b1a7c91a338cdc9/prithvi_mae.py + sha256: 9cee9a8cb17c3859d6365a7e58f723e0f4c08e3e29aa4b8e6523506db70321da + license: Apache-2.0 + prithvi_burnscars_config: + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars/resolve/a3f2c410e45b8ac7417976614528a872f024d831/burn_scars_config.yaml + sha256: 9b40e6d8c6369b863d29fb1d69b6185aa366f8ee4c2de955bbad28d3ee32f466 + license: Apache-2.0 + prithvi_burnscars_example: + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars/resolve/a3f2c410e45b8ac7417976614528a872f024d831/examples/subsetted_512x512_HLS.S30.T10SEH.2018190.v1.4_merged.tif + sha256: 13bc592a5e569d837bd8bb3524bb0d2f28418830bcc7b0750e74033078f8b17e + license: Apache-2.0 + # Official Earthformer checkpoints (README "Pretrained Weights"). The S3 bucket answered HTTP 403 + # on 2026-10-07; these are the Internet Archive captures of 2025-05-17 (payload SHA-1 identical to the + # archived originals, S3 Last-Modified 2023-07-14). State dicts of CuboidTransformerModel. + earthformer_sevir: + url: https://web.archive.org/web/20250517094035id_/https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_sevir.pt + sha256: 2795b23a32cc03ebd77a6c6b57ebbe133070ff9cae1b365d82bb363fd6967215 + license: Apache-2.0 + earthformer_icarenso2021: + url: https://web.archive.org/web/20250517094035id_/https://earthformer.s3.amazonaws.com/pretrained_checkpoints/earthformer_icarenso2021.pt + sha256: 3428356328ec02291461f737684ea597a3126af86a09fe173b75ed54ffe1511f + license: Apache-2.0 + unet_release: + # Ronneberger et al.'s U-Net release (Caffe/MATLAB, 185 MB): phseg_v5 network definition, + # trained weights, modified Caffe sources and two sample images. No license is stated; it is + # fetched at test time only and nothing from it is vendored (read in place with tarfile). + url: https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/u-net-release-2015-10-02.tar.gz + sha256: 260c51948e9e0f3fe1f1282dbedaf2ca69bea38b8392ef8df6d751e58b234740 + license: none stated (test-time oracle only, never vendored) + # Official HKO-7 (TrajGRU, NIPS 2017) checkpoints in MXNet format, linked from + # experiments/movingmnist/download_pretrained.sh and experiments/hko/download_pretrained.sh of the + # MIT repository. Dropbox serves each shared folder as a zip that is byte-identical across downloads. + hko7_movingmnist_weights: + url: https://www.dropbox.com/sh/n7gxfdd1pdasoio/AAC8uC4yto5Uam_7f3BEl-3La?dl=1 + sha256: 0e7741208adb720c271bee69e38bbe16f7c673554e254c60433e3cd066958aba + license: MIT (sxjscience/HKO-7) + extract: true + hko7_hko_weights: + url: https://www.dropbox.com/sh/cp8zpi08umfiyha/AAAS6HJSsDQPjpKlxnBHtHvga?dl=1 + sha256: 6441a1fd07ec4672603b34448357e2b21f7ee0f0107790a7df0f3ff86a306a81 + license: MIT (sxjscience/HKO-7) + extract: true + # Git LFS files of ForeFire's tests/runff regression case at v2.5.0 (sha256 = the LFS object ids): + # the landscape (fuel, altitude, wind) and the reference arrival-time map written by save[]. + forefire_runff_data: + url: https://media.githubusercontent.com/media/forefireAPI/forefire/ca433e01a9f2a146b1709da816a68feafcbfda41/tests/runff/data.nc + sha256: a6c756c4dfeb1f1a5838b1cfdc2ee130d300aa5d09d0a73475e8d30cd73490fb + license: GPL-3.0 (ForeFire repository test data; test-time only) + forefire_runff_reference: + url: https://media.githubusercontent.com/media/forefireAPI/forefire/ca433e01a9f2a146b1709da816a68feafcbfda41/tests/runff/ForeFire.0.nc.ref + sha256: 45a2b159caad744d15d8cdd1b43d738a6626259ebc8542944d5daa06a2fad42a + license: GPL-3.0 (ForeFire repository test data; test-time only) + # SmokeyNet (Dewangan et al., Remote Sensing 2022) data/metadata.pkl: its bbox_labels are the 5,046 + # SmokeBench smoke boxes (pyhazards.datasets.figlib_smokebench downloads the same pinned file). + smokeynet_metadata: + url: https://gitlab.nrp-nautilus.io/anshumand/pytorch-lightning-smoke-detection/-/raw/d8d52b957891de10d4bef08943535fa4f9c3cd43/data/metadata.pkl + filename: smokeynet_metadata.pkl + sha256: c3465c121669b0f92426451799140b0d30bc7caf7512aff9326fefa698ecb1a6 + license: Apache-2.0 (anshumand/pytorch-lightning-smoke-detection) + # Released FloodHub model of google-research/flood-forecasting (MeanEmbeddingForecastLSTM, Gauch et + # al. 2025 architecture, trained 1982-2023 on Caravan + MultiMet). The repository's Apache-2.0 LICENSE + # is the only licence statement covering it. The flood-forecasting checkout holds the same file. + floodhub_weights: + url: https://raw.githubusercontent.com/google-research/flood-forecasting/cdda28dda4cc6f1c5e3aaafcc69c6602c9e7cda1/pretrained-models/google-floodhub-settings-110-epochs/model_epoch110.pt + sha256: 90280f0687a5a95006580164c243be6f8551580f772be26247c8b0ef3d53fdba + license: Apache-2.0 (google-research/flood-forecasting repository licence) + # Large checkpoints: fetched only when named explicitly (or with --large), never in routine CI. + prithvi_eo2_300m_burnscars_weights: + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-BurnScars/resolve/a3f2c410e45b8ac7417976614528a872f024d831/Prithvi_EO_V2_300M_BurnScars.pt + sha256: 0c5f9334be9a75c9006387ab8f3dc05a55ea7fb5ef7956717316be57c62954d3 + license: Apache-2.0 + large: true + prithvi_eo2_300m_tl_weights: + url: https://huggingface.co/ibm-nasa-geospatial/Prithvi-EO-2.0-300M-TL/resolve/63adbd39c271da4c42f447e69b1a7c91a338cdc9/Prithvi_EO_V2_300M_TL.pt + sha256: 3629cedfbb350faafcb0dac902ae0d3c927e25ce8d9e0024aa1276ec66956ddb + license: Apache-2.0 + large: true + # Official Rainformer KNMI checkpoint (train.py configuration, 288x288, 9 -> 9 frames), from the + # Google Drive link in PreTrainModel/address.txt. No licence is stated: used only as test data. + rainformer_knmi_weights: + url: https://drive.usercontent.google.com/download?id=1LyLOJI9sf1sdZE1FwyTLPEGEcUuvXQc3&export=download&confirm=t + filename: model1_1_100.pt + sha256: e3d5e4e59b32f13a74c7ffdc02ae65f9da3362c036b60e73e46dffe8721ae6b2 + license: none stated (Zjut-MultimediaPlus/Rainformer release; test data only, never redistributed) + large: true + tropicyclonenet_checkpoint: + # Released TCN_M checkpoint (generator g_state / discriminator d_state, args of the paper model). + url: https://zenodo.org/records/15024028/files/checkpoint_with_model_16000.pt?download=1 + sha256: 68575d1d10fcd2d44eba2d54d0625410f5108cd3bf5d7b3e15df7491ba9f6215 + license: CC-BY-4.0 (Huang et al., Zenodo 10.5281/zenodo.15024028) + # Official runs of Kratzert et al., HESS 2019 (HydroShare resource 83ea5312635e44dc824eeb99eda12f06, + # doi 10.4211/hs.83ea5312635e44dc824eeb99eda12f06, CC BY 4.0): 48 runs (EA-LSTM, LSTM with and without + # static inputs; NSE* and MSE loss; 8 seeds), each with model_epoch30.pt, cfg.json and the stored + # 1989-1999 test simulations of the 531 basins. Read in place from the zip (not extracted). + kratzert2019_hydroshare_runs: + url: https://www.hydroshare.org/resource/83ea5312635e44dc824eeb99eda12f06/data/contents/Kratzert_et_al_2019_HESSD_LSTM_4_REGIONAL_MODELING.zip + sha256: 864be7a84256314b04f872cc8eca8382825ed0fdf07c3e3dd4fdb0cef3353f3d + license: CC-BY-4.0 + large: true + # SeisBench conversions of the official picker weights (SeisBench is GPL-3.0: its package and these + # files are used only as a second oracle, never vendored). The weights are the authors' MIT-licensed + # releases converted to SeisBench's PyTorch layout. + seisbench_phasenet_original: + url: https://hifis-storage.desy.de/Helmholtz/HelmholtzAI/SeisBench/models/v3/phasenet/original.pt.v2 + sha256: 184dd85b896eebf8d5967ee15a722a477fa2e4ce479a3b113ecbcb8a6419113f + license: MIT (original PhaseNet weights; SeisBench conversion) + seisbench_eqtransformer_original: + # SeisBench "original" = the conservative Keras model (EqT_model_conservative.h5). + url: https://hifis-storage.desy.de/Helmholtz/HelmholtzAI/SeisBench/models/v3/eqtransformer/original.pt.v3 + sha256: c363c59dfb4562ba3b1356fb03dc9c776bbcfe3384b5db22e5ee3689de0a4df9 + license: MIT (original EQTransformer weights; SeisBench conversion) + seisbench_eqtransformer_original_nonconservative: + # SeisBench "original_nonconservative" = the paper model (EqT_original_model.h5). + url: https://hifis-storage.desy.de/Helmholtz/HelmholtzAI/SeisBench/models/v3/eqtransformer/original_nonconservative.pt.v1 + sha256: 2b9d843994429f73ce6eb5c94d40c75972032d4cdb660d29a1fa8ead6ac357d0 + license: MIT (original EQTransformer weights; SeisBench conversion) + seisbench_gpd_original: + url: https://hifis-storage.desy.de/Helmholtz/HelmholtzAI/SeisBench/models/v3/gpd/original.pt + sha256: 4bb54c3728095e6dc4f7f16f4483c7f6dcb47a794bb5f110725680c16591d46c + license: MIT (original GPD weights; SeisBench conversion) + # Released WaveCastNet checkpoints (authors' Google Drive folder 10pe6Zc1NEzIunwJv80214dB9fmb-X8yw named in the + # README). No licence is stated for them; used as test data only. + wavecastnet_dense_checkpoint: + url: https://drive.usercontent.google.com/download?id=1vFoo1eqO2WoZH0R6kkRZJ8XhNG3zF8nO&export=download&confirm=t + filename: best_lem_dense_.pt + sha256: cccadaa7ae02736eb1835c0dc2b04a6291cdd348c901128fb03c92f4c7647acc + license: none stated (dwlyu/WaveCastNet release; test data only, never redistributed) + wavecastnet_sparse_checkpoint: + # Trained on 558 stations; the repository's filtered_coord.npy lists 564, so its station list is unknown. + url: https://drive.usercontent.google.com/download?id=17ZvAt5f5nVuJuZFUli2FJz1wGQImq8y4&export=download&confirm=t + filename: best_lem_irr_mask_shakealert_.pt + sha256: d559717584c27f158fc41995bc7af701b883b6800655bdc39ed249aa6d473cd6 + license: none stated (dwlyu/WaveCastNet release; test data only, never redistributed) + # TCBench data (Hugging Face dataset TCBench/TCBench, MIT), pinned revision 0124d14d. Released matched + # tracks (winds in m/s, pressures in Pa), TCBench's own 2023 IBTrACS extract, and the TempestExtremes + # tracks of the Pangu-Weather forecast initialised 2023-07-16 12 UTC. + tcbench_matched_pangu: + url: https://huggingface.co/datasets/TCBench/TCBench/resolve/0124d14d7f1f468096f46aec1e79696ab9c880c1/matched_tracks/2023_PANGU.csv + sha256: 0b5f7a51531a34c70b190a9e9bbec10bae3a7a009badfd9995d61b882e34e348 + license: MIT (TCBench) + tcbench_matched_fcnet: + url: https://huggingface.co/datasets/TCBench/TCBench/resolve/0124d14d7f1f468096f46aec1e79696ab9c880c1/matched_tracks/2023_fcnet.csv + sha256: fe4197793b072ce94de6ad0bce4abefa512ba89784f38eb9068e6475fed47323 + license: MIT (TCBench) + tcbench_ibtracs_2023: + url: https://huggingface.co/datasets/TCBench/TCBench/resolve/0124d14d7f1f468096f46aec1e79696ab9c880c1/2023_IBTrACS.csv + sha256: 0e174e00d29d8f92c2e9bc28732d76ee113bdd7d80037ae265cfd953df6e6439 + license: MIT (TCBench); IBTrACS data by NOAA NCEI (open access) + tcbench_pangu_unmatched_20230716_12: + url: https://huggingface.co/datasets/TCBench/TCBench/resolve/0124d14d7f1f468096f46aec1e79696ab9c880c1/unmatched_tracks/2023_pangu/panguweather_2023.07.16-12h00_maxltd-120_timeres-6.csv + sha256: 29d58cbbddcdab24e708aeb615c69000efec824ad008b7351a52c7a05e48d8a2 + license: MIT (TCBench) diff --git a/tests/oracle/requirements-earthformer.txt b/tests/oracle/requirements-earthformer.txt new file mode 100644 index 00000000..e6175e33 --- /dev/null +++ b/tests/oracle/requirements-earthformer.txt @@ -0,0 +1,4 @@ +# Reference stack for tests/oracle/test_earthformer_oracle.py. The official Earthformer model file +# (src/earthformer/cuboid_transformer/cuboid_transformer.py) imports only torch and einops; einops is +# not used by the network itself. CPU torch is installed by the workflow. +einops==0.8.2 diff --git a/tests/oracle/requirements-earthquake.txt b/tests/oracle/requirements-earthquake.txt new file mode 100644 index 00000000..eb46c4d8 --- /dev/null +++ b/tests/oracle/requirements-earthquake.txt @@ -0,0 +1,20 @@ +# Reference stack for the earthquake picker oracle tests (PhaseNet, EQTransformer, GPD, pick metrics and +# the SeisBench-format reader). The official models are TensorFlow 1 graph code (PhaseNet) and Keras +# (EQTransformer, GPD): TensorFlow 2.11 is the release in PhaseNet's env.yaml and still loads the Keras +# 2.2/2.3 HDF5 models; it needs numpy < 1.24 and protobuf < 3.20. SeisBench (GPL-3.0) is a second oracle +# for the three models and for the data format; ObsPy (LGPL) is the reference for trigger_onset and +# reads the GPD example's miniSEED files. None of these is a PyHazards dependency. The WaveCastNet and EQNet +# oracles (official PyTorch code, fetched by scripts/fetch_oracles.py) need nothing beyond torch and numpy. +tensorflow-cpu==2.11.0 +numpy==1.23.5 +seisbench==0.12.6 +obspy==1.5.1 +pandas==2.3.3 +h5py==3.16.0 +# PyHazards dependencies pinned to releases that support numpy 1.23.5 (otherwise `pip install -e .` +# could pull a newer numpy and break TensorFlow 2.11). +scipy==1.15.3 +scikit-learn==1.7.2 +xarray==2024.7.0 +netCDF4==1.7.4 +pyyaml diff --git a/tests/oracle/requirements-farseer-rainformer.txt b/tests/oracle/requirements-farseer-rainformer.txt new file mode 100644 index 00000000..ae7acb66 --- /dev/null +++ b/tests/oracle/requirements-farseer-rainformer.txt @@ -0,0 +1,7 @@ +# Reference stack for tests/oracle/test_earthfarseer_oracle.py and test_rainformer_oracle.py. +# EarthFarseer pins timm 0.9.16 (its requirements.txt), which conflicts with the timm 0.6.12 pin of +# segmentation-models-pytorch (requirements.txt) and the timm 0.4.12 of requirements-swin.txt, so +# the Oracle workflow installs this file in its own job. Rainformer needs einops. torchvision +# (CPU, needed by timm) is installed by the workflow next to torch. +timm==0.9.16 +einops==0.8.2 diff --git a/tests/oracle/requirements-firecastnet.txt b/tests/oracle/requirements-firecastnet.txt new file mode 100644 index 00000000..02005317 --- /dev/null +++ b/tests/oracle/requirements-firecastnet.txt @@ -0,0 +1,13 @@ +# Reference environment for tests/oracle/test_firecastnet_oracle.py (the official FireCastNet code +# needs DGL). DGL 2.4.0 publishes CPU wheels for torch 2.4 only, so this job pins CPU torch 2.4.0. +--extra-index-url https://download.pytorch.org/whl/cpu +--find-links https://data.dgl.ai/wheels/torch-2.4/repo.html +torch==2.4.0+cpu +dgl==2.4.0 +einops==0.8.1 +scikit-learn==1.6.1 +lightning==2.5.1.post0 +torchmetrics==1.7.1 +xarray==2025.3.1 +zarr==2.18.3 +pytest diff --git a/tests/oracle/requirements-flood.txt b/tests/oracle/requirements-flood.txt new file mode 100644 index 00000000..c17c9f78 --- /dev/null +++ b/tests/oracle/requirements-flood.txt @@ -0,0 +1,22 @@ +# Reference stack for tests/oracle/test_neuralhydrology_oracle.py and test_google_flood_forecasting_oracle.py +# (Python 3.12, CPU torch installed by the workflow). NeuralHydrology (ea94a40) and googlehydrology +# (google-research/flood-forecasting cdda28d) are imported from their pinned checkouts, so only their +# dependencies are installed here: the model, dataset, metric and Tester modules import numba, ruamel.yaml, +# xarray/netCDF4, scipy, matplotlib and tensorboard (NeuralHydrology), dask, zarr, more-itertools and +# pydantic (googlehydrology). The official UrbanFloodCast DNO (test_urbanfloodcast_oracle.py; HydroPML/UrbanFloodCast +# f08846a, no licence, imported from its checkout) needs only torch, numpy, scipy and matplotlib. +numpy==2.5.3 +pandas==3.0.6 +xarray==2026.9.0 +netCDF4==1.7.4 +h5py==3.16.0 +scipy==1.18.1 +numba==0.68.0 +ruamel.yaml==0.19.1 +matplotlib==3.11.2 +tensorboard==2.21.0 +tqdm==4.70.1 +dask==2026.8.0 +zarr==3.4.0 +more-itertools==11.1.0 +pydantic==2.13.5 diff --git a/tests/oracle/requirements-forefire.txt b/tests/oracle/requirements-forefire.txt new file mode 100644 index 00000000..10a4ddbf --- /dev/null +++ b/tests/oracle/requirements-forefire.txt @@ -0,0 +1,4 @@ +# Reference engine for tests/oracle/test_forefire_oracle.py: the official ForeFire Python bindings +# (PyPI distribution "forefire", module "pyforefire"; self-contained manylinux wheels with NetCDF). +# ForeFire is GPL-3.0, so it is installed only in this test job and is never a PyHazards dependency. +forefire==2.5.0 diff --git a/tests/oracle/requirements-physicsnemo.txt b/tests/oracle/requirements-physicsnemo.txt new file mode 100644 index 00000000..5ed7efcb --- /dev/null +++ b/tests/oracle/requirements-physicsnemo.txt @@ -0,0 +1,27 @@ +# Reference stack for tests/oracle/test_hydrographnet_oracle.py (Python 3.12; the workflow installs CPU torch +# 2.12.0 and torchvision 0.27.0). NVIDIA PhysicsNeMo @ eb7a329 is imported from its pinned checkout, not +# installed. Its MeshGraphKAN runs on PyTorch Geometric graphs with torch_scatter aggregation; torch_scatter +# has CPU wheels up to torch 2.12, so the suite uses torch 2.12 (PhysicsNeMo declares torch>=2.13, but the +# modules used here run on 2.12, and its stored reference outputs are valid from torch 2.12 on). +# The rest is what `import physicsnemo`, the MeshGraphKAN module and HydroGraphDataset import: warp (top-level +# package), s3fs / fsspec (physicsnemo.core.filesystem), timm, einops, tensordict, nvtx, omegaconf, treelib, +# termcolor and jaxtyping (physicsnemo.nn), scipy (k-d tree graph). The example's training stack (hydra, +# wandb, mlflow) and transformer-engine are not needed. +--find-links https://data.pyg.org/whl/torch-2.12.0+cpu.html +torch-scatter==2.1.2+pt212cpu +torch-geometric==2.8.0.post1 +warp-lang==1.18.0 +s3fs==2026.9.0 +fsspec==2026.9.0 +timm==1.0.30 +einops==0.8.2 +tensordict==0.14.2 +nvtx==0.2.16 +omegaconf==2.3.1 +treelib==1.8.0 +termcolor==3.3.0 +jaxtyping==0.3.11 +numpy==2.5.3 +scipy==1.18.1 +requests==2.34.2 +tqdm==4.70.1 diff --git a/tests/oracle/requirements-prithvi.txt b/tests/oracle/requirements-prithvi.txt new file mode 100644 index 00000000..44b70b27 --- /dev/null +++ b/tests/oracle/requirements-prithvi.txt @@ -0,0 +1,12 @@ +# Reference stack for tests/oracle/test_prithvi_oracle.py. Needs Python >= 3.12 (TerraTorch's +# torchgeo) and CPU torch installed first: +# pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cpu +# TerraTorch 0.99.8 is the release pinned by the official Prithvi-EO-2.0 BurnScars demo Space and the +# stack the burn-scar checkpoint was trained with (it was saved by Lightning 2.5.0.post0, which 0.99.8 +# pins). 0.99.8 leaves smp and timm unpinned; the releases current when the checkpoint was published +# (2025-02-28) are pinned here. smp 0.5.0 changed the U-Net decoder's last upsampling step, which +# changes this model's outputs. +terratorch==0.99.8 +segmentation-models-pytorch==0.4.0 +timm==1.0.15 +pytest diff --git a/tests/oracle/requirements-smokebench.txt b/tests/oracle/requirements-smokebench.txt new file mode 100644 index 00000000..1538f71a --- /dev/null +++ b/tests/oracle/requirements-smokebench.txt @@ -0,0 +1,6 @@ +# Reference stack for tests/oracle/test_smokebench_oracle.py: the SmokeBench authors' scripts +# (SoraLink/MLLM) use OpenCV for image I/O, the grid overlay and the grey conversion, and +# torchvision.ops.box_iou for detection (torchvision is installed by the workflow next to torch). +# Pillow reads frames on the PyHazards side (the `prompted` extra). +opencv-python-headless==4.10.0.84 +pillow==12.3.0 diff --git a/tests/oracle/requirements-swin.txt b/tests/oracle/requirements-swin.txt new file mode 100644 index 00000000..e0f59bff --- /dev/null +++ b/tests/oracle/requirements-swin.txt @@ -0,0 +1,8 @@ +# Reference stack for tests/oracle/test_swin_oracle.py (Swin-Unet and fire-asufm). +# timm 0.4.12 is pinned by fire-asufm and conflicts with the timm 0.6.12 pin of +# segmentation-models-pytorch in requirements.txt, so the Oracle workflow installs this file in +# its own job. torchvision (CPU) is installed by the workflow next to torch. +timm==0.4.12 +einops==0.8.2 +ml-collections==1.1.0 +yacs==0.1.8 diff --git a/tests/oracle/requirements-tc-tracking.txt b/tests/oracle/requirements-tc-tracking.txt new file mode 100644 index 00000000..c2e44616 --- /dev/null +++ b/tests/oracle/requirements-tc-tracking.txt @@ -0,0 +1,5 @@ +# Cyclone tracking and TCBench scoring oracles (tests/oracle/test_tempest_oracle.py, +# tests/oracle/test_tcbench_evaluation_oracle.py). TempestExtremes is built from the pinned source +# (CMake + the netCDF C library, installed by the workflow with apt). TCBench's metric functions run on +# joblib, pinned as in TCBench_Alpha's requirements.txt. +joblib==1.3.2 diff --git a/tests/oracle/requirements-tc.txt b/tests/oracle/requirements-tc.txt new file mode 100644 index 00000000..ab06cfe8 --- /dev/null +++ b/tests/oracle/requirements-tc.txt @@ -0,0 +1,11 @@ +# Reference stack for the tropical cyclone oracle tests (CPU torch is installed by the workflow). +# The official tropicalcyclone_MLP model is Keras 2.2.4 / TensorFlow 1.12 code; its models.mlp is run with +# Keras 3 on the PyTorch backend (KERAS_BACKEND=torch). 3.12.4 is the last Keras release for Python 3.10. +# The TCIF-fusion notebook graph (Keras 2 / TensorFlow 1.x) is rebuilt the same way. +keras==3.12.4 +# SAF-Net (TI_Prediction notebook) and TropiCycloneNet's model code (TCNM/*.py) need only torch and numpy; +# TropiCycloneNet's data loader (TCNM/data/trajectoriesWithMe_unet.py) resizes GPH crops with OpenCV. +opencv-python-headless==5.0.0.93 +# Hurricast's XGBoost stage is compared with xgboost.XGBRegressor fitted the official way (the CPU-only build of +# the same library; 3.2.0 is the last release supporting Python 3.10, as in requirements.txt). +xgboost-cpu==3.2.0 diff --git a/tests/oracle/requirements-trajgru.txt b/tests/oracle/requirements-trajgru.txt new file mode 100644 index 00000000..6f85cc77 --- /dev/null +++ b/tests/oracle/requirements-trajgru.txt @@ -0,0 +1,13 @@ +# Reference stack for tests/oracle/test_trajgru_oracle.py. The official TrajGRU code (sxjscience/HKO-7) +# is MXNet; its authors tested it on MXNet 0.12, and it runs unchanged on MXNet 1.9.1, the last release +# of the retired Apache MXNet project. MXNet 1.9.1 needs numpy < 1.24, so numpy and the PyHazards +# dependencies that would otherwise pull a newer numpy are pinned to releases that support 1.23.5. +mxnet==1.9.1 +numpy==1.23.5 +scipy==1.15.3 +pandas==2.3.3 +xarray==2024.7.0 +scikit-learn==1.7.2 +h5py==3.16.0 +netCDF4==1.7.4 +pyyaml diff --git a/tests/oracle/requirements-tssatfire.txt b/tests/oracle/requirements-tssatfire.txt new file mode 100644 index 00000000..ad67cd3d --- /dev/null +++ b/tests/oracle/requirements-tssatfire.txt @@ -0,0 +1,7 @@ +# Reference stack for the TS-SatFire oracle tests (unet3d, unetr, swin_unetr and the ts_satfire +# preset). monai 1.3.2 is the version in TS-SatFire's environment.yml; MONAI's UNETR and SwinUNETR +# need einops, and TS-SatFire's spatial_models/swinunetr/swinunetr.py imports torchinfo at module +# level (both pinned to the versions in the same environment.yml). +monai==1.3.2 +einops==0.8.0 +torchinfo==1.8.0 diff --git a/tests/oracle/requirements-unet.txt b/tests/oracle/requirements-unet.txt new file mode 100644 index 00000000..f67a5a7a --- /dev/null +++ b/tests/oracle/requirements-unet.txt @@ -0,0 +1,4 @@ +# Reference runtime for tests/oracle/test_unet_oracle.py: OpenCV's Caffe importer (Apache-2.0) runs +# the authors' released Caffe U-Net. OpenCV 5 removed the Caffe importer, so this pins the 4.x +# release the test was written against. +opencv-python-headless==4.10.0.84 diff --git a/tests/oracle/requirements-weather.txt b/tests/oracle/requirements-weather.txt new file mode 100644 index 00000000..c0307144 --- /dev/null +++ b/tests/oracle/requirements-weather.txt @@ -0,0 +1,6 @@ +# Weather-model sources of pyhazards.forecasts (tests/oracle/test_forecasts_weather_oracle.py, Python 3.12): +# NVIDIA earth2studio 0.19.0 (Apache-2.0; needs Python >= 3.11) for the runner, zarr + gcsfs for the +# WeatherBench 2 stores (anonymous reads from gs://weatherbench2). No model weights are downloaded. +earth2studio==0.19.0 +zarr==3.4.0 +gcsfs==2026.10.0 diff --git a/tests/oracle/requirements.txt b/tests/oracle/requirements.txt new file mode 100644 index 00000000..575c0314 --- /dev/null +++ b/tests/oracle/requirements.txt @@ -0,0 +1,11 @@ +# Packages that provide reference implementations for tests/oracle (install next to CPU torch). +segmentation-models-pytorch==0.3.2 +# SegFormer reference. 4.57.6 is the last release line whose module names match the Hub checkpoints +# (transformers 5.9 renamed them); it resolves together with smp 0.3.2 and its timm 0.6.12 pin. +transformers==4.57.6 +# MONAI AttentionUnet (the version in TS-SatFire's environment.yml); also imported by TS-SatFire's copy. +monai==1.3.2 +# XGBoost reference for tests/oracle/test_classical_oracle.py (the `xgboost` model wraps +# xgboost.XGBClassifier with the library defaults of this release). xgboost-cpu is the CPU-only +# build of the same library (no NCCL/CUDA wheels); 3.2.0 is the last release supporting Python 3.10. +xgboost-cpu==3.2.0 diff --git a/tests/oracle/test_attention_unet_oracle.py b/tests/oracle/test_attention_unet_oracle.py new file mode 100644 index 00000000..d80162cd --- /dev/null +++ b/tests/oracle/test_attention_unet_oracle.py @@ -0,0 +1,227 @@ +"""Attention U-Net checked against MONAI 1.3.2 and TS-SatFire's modified copy. + +References: ``monai==1.3.2`` (pinned in requirements.txt; the version in TS-SatFire's +environment.yml) and ``spatial_models/attentionunet.py`` from zhaoyutim/TS-SatFire (pinned in +repos.yaml; no LICENSE, so it is only imported here as an oracle). Each check builds both models +from the same seed, requires identical parameter names and initial values, then compares outputs +in eval mode (with randomised BatchNorm statistics) and train mode. + +Spatial sizes are reduced for CPU speed (the network is fully convolutional; TS-SatFire uses +256x256 tiles): 32x32 with T=2 for the full-width 3D prediction model, 64x64 for the 2D model. +""" + +from __future__ import annotations + +import torch + +from oracle_utils import import_from, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.attention_unet import AttentionUnet, TemporalAttentionUnet + +TS_SATFIRE_CHANNELS = (64, 128, 256, 512, 1024) +SMALL_CHANNELS = (8, 16, 32, 64, 128) + + +def _monai(): + return oracle_package("monai", "1.3.2") + + +def _monai_attention_unet(): + _monai() + from monai.networks.nets import AttentionUnet as MonaiAttentionUnet + + return MonaiAttentionUnet + + +def _ts_satfire_attention_unet(): + _monai() # the TS-SatFire file imports MONAI blocks + module = import_from(oracle_repo("TS-SatFire"), "spatial_models.attentionunet") + return module.AttentionUnet + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _randomise(reference: torch.nn.Module, port: torch.nn.Module, seed: int) -> None: + """Give both models the same non-trivial weights, BatchNorm statistics and PReLU slopes.""" + generator = torch.Generator().manual_seed(seed) + state = reference.state_dict() + for key, value in state.items(): + if not value.is_floating_point(): + continue + if key.endswith("running_var"): + value.copy_(torch.rand(value.shape, generator=generator) + 0.5) + elif key.endswith("running_mean"): + value.copy_(0.1 * torch.randn(value.shape, generator=generator)) + else: + value.add_(0.05 * torch.randn(value.shape, generator=generator)) + reference.load_state_dict(state, strict=True) + port.load_state_dict(state, strict=True) + + +def test_ts_satfire_prediction_model_matches_reference(): + TSAttentionUnet = _ts_satfire_attention_unet() + # run_spatial_temp_model_pred.py: 43 input channels after the land-cover one-hot, 2 classes. + torch.manual_seed(0) + reference = TSAttentionUnet( + spatial_dims=3, in_channels=43, out_channels=2, channels=TS_SATFIRE_CHANNELS, strides=(1, 2, 2) + ) + torch.manual_seed(0) + port = build_model("attention_unet", task="segmentation", in_channels=43) + assert isinstance(port, TemporalAttentionUnet) + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 94_555_506 + + _randomise(reference, port, seed=1) + torch.manual_seed(2) + x = torch.randn(2, 2, 43, 32, 32) # (batch, time, channels, H, W) + x_ref = x.transpose(1, 2).contiguous() # TS-SatFire feeds (batch, channels, time, H, W) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x_ref).mean(2)) + port.time_reduction = "none" # per-date maps, as in the AF/BA scripts + _assert_close(port(x), reference(x_ref)) + port.time_reduction = "mean" + + reference.train() + port.train() + _assert_close(port(x), reference(x_ref).mean(2)) + _assert_same_state(reference, port) # BatchNorm running statistics were updated identically + + +def test_ts_satfire_shared_strides_equal_monai_per_level_strides(): + TSAttentionUnet = _ts_satfire_attention_unet() + MonaiAttentionUnet = _monai_attention_unet() + torch.manual_seed(0) + ts_model = TSAttentionUnet( + spatial_dims=3, in_channels=5, out_channels=2, channels=SMALL_CHANNELS, strides=(1, 2, 2) + ) + torch.manual_seed(0) + monai_model = MonaiAttentionUnet( + spatial_dims=3, in_channels=5, out_channels=2, channels=SMALL_CHANNELS, strides=((1, 2, 2),) * 4 + ) + torch.manual_seed(0) + port_shared = AttentionUnet( + spatial_dims=3, in_channels=5, out_channels=2, channels=SMALL_CHANNELS, strides=(1, 2, 2), stride_mode="shared" + ) + torch.manual_seed(0) + port_per_level = AttentionUnet( + spatial_dims=3, in_channels=5, out_channels=2, channels=SMALL_CHANNELS, strides=((1, 2, 2),) * 4 + ) + for model in (monai_model, port_shared, port_per_level): + _assert_same_state(ts_model, model) + + torch.manual_seed(1) + x = torch.randn(2, 5, 3, 32, 32) + for model in (ts_model, monai_model, port_shared, port_per_level): + model.eval() + with torch.no_grad(): + expected = ts_model(x) + assert expected.shape == (2, 2, 3, 32, 32) # time is never down-sampled + _assert_close(monai_model(x), expected) + _assert_close(port_shared(x), expected) + _assert_close(port_per_level(x), expected) + + +def test_ts_satfire_2d_config_matches_monai(): + MonaiAttentionUnet = _monai_attention_unet() + # run_spatial_model.py: stock MONAI, 2D, strides (2, 2, 2, 2); FireDataset default n_channel=8. + torch.manual_seed(0) + reference = MonaiAttentionUnet( + spatial_dims=2, in_channels=8, out_channels=2, channels=TS_SATFIRE_CHANNELS, strides=(2, 2, 2, 2) + ) + torch.manual_seed(0) + port = build_model("attention_unet", task="segmentation", in_channels=8, spatial_dims=2) + assert type(port) is AttentionUnet + _assert_same_state(reference, port) + assert _n_params(port) == 31_743_282 + + _randomise(reference, port, seed=3) + torch.manual_seed(4) + x = torch.randn(2, 8, 64, 64) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + reference.train() + port.train() + _assert_close(port(x), reference(x)) + + +def test_non_default_configs_match_monai(): + """Per-level non-uniform strides, larger kernels and dropout, in 1D, 2D and 3D.""" + MonaiAttentionUnet = _monai_attention_unet() + configs = [ + dict(spatial_dims=1, in_channels=3, out_channels=1, channels=(4, 8, 16), strides=(2, 2), kernel_size=5), + dict( + spatial_dims=2, + in_channels=3, + out_channels=3, + channels=(4, 8, 16, 32), + strides=((2, 1), 2, (1, 2)), + kernel_size=5, + up_kernel_size=3, + dropout=0.2, + ), + dict( + spatial_dims=3, + in_channels=2, + out_channels=1, + channels=(4, 8, 16), + strides=((1, 2, 2), 2), + kernel_size=(1, 3, 3), + up_kernel_size=(3, 3, 3), + dropout=0.1, + ), + ] + inputs = [(2, 3, 16), (2, 3, 16, 16), (2, 2, 4, 16, 16)] + for config, shape in zip(configs, inputs): + torch.manual_seed(0) + reference = MonaiAttentionUnet(**config) + torch.manual_seed(0) + port = AttentionUnet(**config) + _assert_same_state(reference, port) + _randomise(reference, port, seed=5) + + x = torch.randn(*shape) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + reference.train() + port.train() + torch.manual_seed(6) + expected = reference(x) + torch.manual_seed(6) + _assert_close(port(x), expected) # same dropout masks: same module order + + +def test_ts_satfire_copy_ignores_kernel_size(): + """The TS-SatFire copy predates MONAI 1.3.1 and builds 3x3 blocks whatever ``kernel_size`` is. + + The port follows MONAI 1.3.2 and honours ``kernel_size``; at the default 3 used by TS-SatFire + both are identical (checked above). + """ + TSAttentionUnet = _ts_satfire_attention_unet() + MonaiAttentionUnet = _monai_attention_unet() + config = dict(spatial_dims=2, in_channels=3, out_channels=1, channels=(4, 8, 16), strides=2, kernel_size=5) + ts_model = TSAttentionUnet(**config) + monai_model = MonaiAttentionUnet(**{**config, "strides": (2, 2)}) + port = AttentionUnet(**{**config, "stride_mode": "shared"}) + key = "model.0.conv.0.conv.weight" + assert ts_model.state_dict()[key].shape[-1] == 3 + assert monai_model.state_dict()[key].shape[-1] == 5 + assert port.state_dict()[key].shape[-1] == 5 diff --git a/tests/oracle/test_classical_oracle.py b/tests/oracle/test_classical_oracle.py new file mode 100644 index 00000000..dd237995 --- /dev/null +++ b/tests/oracle/test_classical_oracle.py @@ -0,0 +1,162 @@ +"""random_forest / xgboost checked against the Kondylatos et al. (2022) random-forest notebook. + +Reference (pinned in repos.yaml): Orion-AI-Lab/wildfire_forecasting, ``notebooks/RF.ipynb``. The test +executes the notebook's own code cells (feature construction, hyperparameters, classifier, prediction) +on a synthetic dataset served the way the notebook reads ``FireDataset_npy(access_mode='temporal')`` +(``batch_size=1`` tuples of dynamic ``(1, 10, 10)``, static ``(1, 5)``, land cover ``(1, 10)`` and +label). Cell 0 (imports of the Greek-datacube dataset class) and cells 1-2 (feature names, data +paths) are replaced by that loader. PyHazards gets the same samples as the LSTM's daily tensor +``(batch, 10, 25)``, built by the reference's ``combine_dynamic_static_inputs`` +(``wildfire_forecasting/models/greece_fire_models.py``; only that function is executed, since the +module imports Lightning). + +XGBoost has no reference code (the paper's hyperparameters are in its Supporting Information), so +the ``xgboost`` model is compared with ``xgboost.XGBClassifier()`` at its library defaults, at the +version pinned in requirements.txt, on the notebook's features. +""" + +from __future__ import annotations + +import json +import warnings + +import numpy as np +import pytest +import torch +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import average_precision_score, classification_report, roc_auc_score +from torch.utils.data import DataLoader, TensorDataset + +from oracle_utils import load_definitions, oracle_package, oracle_repo +from pyhazards.models import build_model, kondylatos_instance_features + +XGBOOST_VERSION = "3.2.0" +SPLIT_SIZES = {"train": 300, "val": 60, "test": 150} + + +def _notebook_cells(root) -> dict: + notebook = json.loads((root / "notebooks" / "RF.ipynb").read_text(encoding="utf-8")) + sources = ["".join(cell["source"]) for cell in notebook["cells"] if cell["cell_type"] == "code"] + + def find(marker: str) -> str: + matches = [source for source in sources if marker in source] + assert len(matches) == 1, f"RF.ipynb: expected one cell containing {marker!r}" + return matches[0] + + return { + "features": find("X_train = []"), + "hyperparameters": find("n_est = 100"), + "classifier": find("RandomForestClassifier(n_estimators=n_est"), + "prediction": find("probs_pred = clf.predict_proba"), + } + + +def _synthetic_split(rng: np.random.Generator, n: int): + """Daily covariates with a fire signal; values are float32-representable, stored as float64.""" + dynamic = rng.normal(size=(n, 10, 10)).astype(np.float32).astype(np.float64) + static = rng.uniform(size=(n, 5)).astype(np.float32).astype(np.float64) + land_cover = rng.dirichlet(np.ones(10), size=n).astype(np.float32).astype(np.float64) + score = ( + dynamic[:, -3:, 4].mean(axis=1) # e.g. maximum temperature over the last days + - dynamic[:, -3:, 9].mean(axis=1) # e.g. minimum relative humidity + + static[:, 0] + + rng.normal(scale=0.7, size=n) + ) + labels = (score > np.quantile(score, 2 / 3)).astype(np.int64) # two negatives per positive + # Missing values on earlier days, so that the notebook's np.nanmean matters. + earlier = dynamic[:, :-1] + earlier[rng.uniform(size=earlier.shape) < 0.05] = np.nan + return dynamic, static, land_cover, labels + + +@pytest.fixture(scope="module") +def notebook_run(): + root = oracle_repo("wildfire_forecasting") + cells = _notebook_cells(root) + combine = load_definitions( + root / "wildfire_forecasting" / "models" / "greece_fire_models.py", + ["combine_dynamic_static_inputs"], + {"torch": torch}, + )["combine_dynamic_static_inputs"] + + rng = np.random.default_rng(2022) + splits = {name: _synthetic_split(rng, size) for name, size in SPLIT_SIZES.items()} + # The notebook's training loader shuffles; a fixed order makes the forest comparable. + dataloaders = { + name: DataLoader(TensorDataset(*(torch.from_numpy(a) for a in arrays)), batch_size=1, shuffle=False) + for name, arrays in splits.items() + } + namespace = { + "torch": torch, + "np": np, + "warnings": warnings, + "RandomForestClassifier": RandomForestClassifier, + "classification_report": classification_report, + "roc_auc_score": roc_auc_score, + "average_precision_score": average_precision_score, + "dataloaders": dataloaders, + } + for key in ("features", "hyperparameters", "classifier", "prediction"): + exec(compile(cells[key], f"RF.ipynb[{key}]", "exec"), namespace) + + daily = {} + for name, (dynamic, static, land_cover, _) in splits.items(): + daily[name] = combine(torch.from_numpy(dynamic), torch.from_numpy(static), torch.from_numpy(land_cover), "temporal") + labels = {name: torch.from_numpy(arrays[3]) for name, arrays in splits.items()} + return namespace, daily, labels + + +def test_daily_tensor_is_the_lstm_input(notebook_run): + _, daily, _ = notebook_run + assert daily["train"].shape == (SPLIT_SIZES["train"], 10, 25) + assert daily["train"].dtype == torch.float32 # combine_dynamic_static_inputs ends with .float() + lstm = build_model("wildfire_forecasting", task="classification") + with torch.no_grad(): + assert lstm(torch.nan_to_num(daily["test"][:4])).shape == (4, 2) + + +def test_instance_features_match_notebook(notebook_run): + namespace, daily, _ = notebook_run + for split, notebook_features in (("train", namespace["X_train"]), ("val", namespace["X_val"]), ("test", namespace["X_test"])): + features = kondylatos_instance_features(daily[split]) + assert features.shape == notebook_features.shape == (SPLIT_SIZES[split], 35) + np.testing.assert_array_equal(features, notebook_features) # NaN positions included + assert torch.isnan(daily["train"]).any() # the means must skip missing days, as np.nanmean does + assert not np.isnan(namespace["X_train"]).any() # the last day is always observed + + +def test_random_forest_matches_notebook(notebook_run): + namespace, daily, labels = notebook_run + clf = namespace["clf"] + model = build_model("random_forest", task="classification") + assert model.estimator.get_params() == clf.get_params() + + model.fit(daily["train"], labels["train"]) + probabilities = model.predict_proba(daily["test"]) + np.testing.assert_array_equal(probabilities, clf.predict_proba(namespace["X_test"])) + np.testing.assert_array_equal(probabilities[:, 1], namespace["probs_pred"]) + np.testing.assert_array_equal(model.predict(daily["test"]), namespace["y_pred"]) + assert probabilities[:, 1].std() > 0.1 # a non-trivial forest + # Another seed gives another forest, so the equality above is not vacuous. + other = build_model("random_forest", task="classification", random_state=0).fit(daily["train"], labels["train"]) + assert not np.array_equal(other.predict_proba(daily["test"]), probabilities) + # Ready-made 35-feature rows give the same result. + np.testing.assert_array_equal(model.predict_proba(namespace["X_test"]), probabilities) + + log_probs = model(daily["test"].double()) + assert log_probs.shape == (SPLIT_SIZES["test"], 2) and log_probs.dtype == torch.float64 + torch.testing.assert_close(log_probs.exp(), torch.from_numpy(probabilities), rtol=1e-12, atol=1e-15) + torch.testing.assert_close(model(daily["test"]).exp(), torch.from_numpy(probabilities).float()) + + +def test_xgboost_matches_library_defaults(notebook_run): + xgboost = oracle_package("xgboost", XGBOOST_VERSION) + namespace, daily, labels = notebook_run + assert repr(build_model("xgboost", task="classification").estimator.get_params()) == repr( + xgboost.XGBClassifier().get_params() + ) + + reference = xgboost.XGBClassifier(n_jobs=4).fit(namespace["X_train"], namespace["y_train"].ravel()) + model = build_model("xgboost", task="classification", n_jobs=4).fit(daily["train"], labels["train"]) + assert model.estimator.get_booster().num_boosted_rounds() == 100 + np.testing.assert_array_equal(model.predict_proba(daily["test"]), reference.predict_proba(namespace["X_test"])) diff --git a/tests/oracle/test_convgru_oracle.py b/tests/oracle/test_convgru_oracle.py new file mode 100644 index 00000000..6f83c6e1 --- /dev/null +++ b/tests/oracle/test_convgru_oracle.py @@ -0,0 +1,92 @@ +"""ConvGRU checked against FireCastNet's Conv-GRU baseline. + +Reference (pinned in repos.yaml): SeasFire/firecastnet ``seasfire/backbones/conv_gru.py`` +(``ConvGRUSeg``), the network its ``configs/conv-gru-config.yaml`` trains. The repository has no +license; it is used only here and never vendored. ``seasfire.backbones.conv_gru`` imports only +torch, so this file runs in the ``default`` suite. +""" + +from __future__ import annotations + +import pytest +import torch +import yaml + +from oracle_utils import import_from, oracle_repo +from pyhazards.models import build_model + + +@pytest.fixture() +def conv_gru(): + repo = oracle_repo("firecastnet") + return repo, import_from(repo, "seasfire.backbones.conv_gru") + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def test_official_config_values(conv_gru): + repo, _ = conv_gru + config = yaml.safe_load((repo / "configs" / "conv-gru-config.yaml").read_text()) + model = config["model"] + assert model["class_path"] == "seasfire.conv_gru_lit.ConvGRULit" + assert model["init_args"] == { + "input_dim_grid_nodes": 11, "hidden_layers": 1, "hidden_dim": 128, "kernel_size": [5, 5], + "lr": 0.001, "weight_decay": 1e-08, + } + # ConvGRULit builds ConvGRUSeg(input_dim, hidden_dim, kernel_size, num_layers, num_classes=1) and + # trains it with BCEWithLogitsLoss on every pixel of the 64x64 patch. + source = (repo / "seasfire" / "conv_gru_lit.py").read_text() + assert "num_classes=1" in source and "nn.BCEWithLogitsLoss()" in source + assert (config["data"]["lat_dim"], config["data"]["lon_dim"]) == (64, 64) + + +@pytest.mark.parametrize("hidden_dim, expected", [(128, 1_337_985), (64, 361_793)]) +def test_firecastnet_convgru_matches_reference(conv_gru, hidden_dim, expected): + # 128 hidden channels: configs/conv-gru-config.yaml; 64: the paper (Sec. 5.1) and ConvGRULit's default. + _, module = conv_gru + torch.manual_seed(0) + reference = module.ConvGRUSeg(input_dim=11, hidden_dim=hidden_dim, kernel_size=(5, 5), num_layers=1, num_classes=1) + torch.manual_seed(0) + port = build_model("convgru", task="segmentation", hidden_dim=hidden_dim) + _assert_same_state(reference, port) + assert _n_params(port) == expected + + torch.manual_seed(1) + x = torch.randn(2, 12, 11, 64, 64) # (batch, time, variables, lat, lon) after ConvGRULit's permute + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + # A sequence that starts with an all-zero (padding) step takes the reference's pad-mask + # branch, which never changes the output of the one-layer model. + x[:, :2] = 0 + _assert_close(port(x), reference(x)) + + +def test_multilayer_convgru_matches_reference(conv_gru): + _, module = conv_gru + torch.manual_seed(2) + reference = module.ConvGRUSeg(input_dim=5, hidden_dim=16, kernel_size=(3, 3), num_layers=3, num_classes=2) + port = build_model("convgru", task="segmentation", in_channels=5, out_channels=2, hidden_dim=16, kernel_size=3, num_layers=3) + port.load_state_dict(reference.state_dict(), strict=True) + torch.manual_seed(3) + x = torch.randn(3, 4, 5, 20, 24, requires_grad=True) + expected = reference(x) + actual = port(x) + _assert_close(actual, expected) + grad_ref, = torch.autograd.grad(expected.square().sum(), x) + grad_port, = torch.autograd.grad(actual.square().sum(), x) + _assert_close(grad_port, grad_ref) diff --git a/tests/oracle/test_deep_ensemble_oracle.py b/tests/oracle/test_deep_ensemble_oracle.py new file mode 100644 index 00000000..c337607c --- /dev/null +++ b/tests/oracle/test_deep_ensemble_oracle.py @@ -0,0 +1,170 @@ +"""deep_ensemble checked against the deep ensemble of Kondylatos et al. (2025). + +Reference (pinned in repos.yaml): Orion-AI-Lab/uncertainty-wildfires (MIT), the code of +"Uncertainty-Aware Deep Learning for Wildfire Danger Forecasting" (arXiv 2509.25017): + +- ``models/model.py`` ``SimpleLSTM``, the member (``configs/config_det.json``: ``output_lstm`` 128, + dropout 0.5, 25 features). Only the class is executed (``load_definitions``): the module also + imports the vendored Bayesian-layer library for its other models. +- ``utils/train_functions.py`` ``uncertainties`` (the ensemble aggregation used by ``test.py``) and + ``enable_dropout``; executed the same way, because ``utils/__init__`` imports matplotlib. +- ``trained_models/ensembles/no-noisy/ensembles--checkpoint.pth``: the paper's ten ensemble + members (``configs_test/config_des.json``, ``num_models`` 10), each trained with + ``torch.manual_seed(seed)`` before it was built. The checkpoints also pickle the repository's + ``ConfigParser``; it is unpickled into an inert stand-in. + +PyHazards builds the members as ``wildfire_forecasting`` LSTMs with ``hidden_size=128``: the same +layers and parameter names (that model returns ``log_softmax`` where the reference returns logits; +the ensemble applies a softmax to both). +""" + +from __future__ import annotations + +import pickle +from types import SimpleNamespace + +import pytest +import torch +import torch.nn as nn + +from oracle_utils import load_definitions, oracle_repo +from pyhazards.models import DeepEnsemble, build_model + +SEEDS = (1, 12, 17, 123, 1234, 2222, 12345, 54321, 77777, 87877) +MEMBER_PARAMS = 104_308 # SimpleLSTM(output_lstm=128, len_features=25) +LAG = 45 # days per sample in the paper's next-day setting (dataset "lag": 45) + + +class _Inert: + """Stand-in for non-torch classes pickled in the checkpoints; keeps their state, runs no code.""" + + def __setstate__(self, state): + self.state = state + + +class _CheckpointUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.split(".")[0] in {"torch", "collections", "pathlib", "numpy"}: + return super().find_class(module, name) + return _Inert + + +_PICKLE = SimpleNamespace(Unpickler=_CheckpointUnpickler, load=pickle.load, __name__="pickle") + + +@pytest.fixture(scope="module") +def reference(): + root = oracle_repo("uncertainty-wildfires") + namespace = {"torch": torch, "nn": nn} + lstm = load_definitions(root / "models" / "model.py", ["SimpleLSTM"], namespace)["SimpleLSTM"] + functions = load_definitions(root / "utils" / "train_functions.py", ["uncertainties", "enable_dropout"], namespace) + checkpoints = {} + for seed in SEEDS: + path = root / "trained_models" / "ensembles" / "no-noisy" / f"ensembles-{seed}-checkpoint.pth" + checkpoints[seed] = torch.load(path, map_location="cpu", weights_only=False, pickle_module=_PICKLE) + return SimpleNamespace(SimpleLSTM=lstm, checkpoints=checkpoints, **functions) + + +def _reference_member(reference, seed=None): + if seed is not None: + torch.manual_seed(seed) + return reference.SimpleLSTM(output_lstm=128, dropout=0.5, len_features=25, noisy=False) + + +def _ensemble(**kwargs) -> DeepEnsemble: + return build_model( + "deep_ensemble", + task="classification", + base_model="wildfire_forecasting", + base_kwargs={"hidden_size": 128}, + num_members=len(SEEDS), + seeds=SEEDS, + **kwargs, + ) + + +def _official_pair(reference, **kwargs): + references, ensemble = [], _ensemble(**kwargs) + for seed, member in zip(SEEDS, ensemble.members): + state = reference.checkpoints[seed]["state_dict"] + ref = _reference_member(reference) + ref.load_state_dict(state, strict=True) + member.load_state_dict(state, strict=True) + references.append(ref.eval()) + return references, ensemble.eval() + + +def _assert_close(actual, expected): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def test_checkpoints_are_the_paper_ensemble(reference): + for seed in SEEDS: + config = reference.checkpoints[seed]["config"].state["_config"] + assert config["seed"] == seed + assert dict(config["arch"]["args"]) == {"output_lstm": 128, "dropout": 0.5} + assert config["noisy"] is False + assert len(config["features"]["dynamic"]) + len(config["features"]["static"]) == 25 + assert reference.checkpoints[seed]["epoch"] == 30 + + +def test_members_match_reference_initialisation(reference): + ensemble = _ensemble() + assert ensemble.seeds == list(SEEDS) + for seed, member in zip(SEEDS, ensemble.members): + ref = _reference_member(reference, seed) + assert sum(p.numel() for p in ref.parameters()) == sum(p.numel() for p in member.parameters()) == MEMBER_PARAMS + ref_state, state = ref.state_dict(), member.state_dict() + assert set(ref_state) == set(state) # same names; the reference creates the LSTM before the LayerNorm + for key, value in ref_state.items(): + assert torch.equal(value, state[key]), (seed, key) + assert sum(p.numel() for p in ensemble.parameters()) == len(SEEDS) * MEMBER_PARAMS + + +def test_official_members_load_and_match(reference): + references, ensemble = _official_pair(reference) + torch.manual_seed(0) + x = torch.randn(16, LAG, 25) + with torch.no_grad(): + for ref, member in zip(references, ensemble.members): + _assert_close(member(x), torch.log_softmax(ref(x), dim=1)) + + +def test_ensemble_aggregation_matches_reference(reference): + references, ensemble = _official_pair(reference) + torch.manual_seed(1) + x = torch.randn(32, LAG, 25) + with torch.no_grad(): + outputs, mean, epistemic, aleatoric, mi, entropy = reference.uncertainties([ref(x) for ref in references], 0.000001) + terms = ensemble.predict_uncertainty(x) + log_probs = ensemble(x) + _assert_close(terms["member_probs"], outputs.transpose(0, 1)) + _assert_close(terms["probs"], mean) + _assert_close(terms["epistemic"], epistemic) + _assert_close(terms["aleatoric"], aleatoric) + _assert_close(terms["entropy"], entropy) + _assert_close(terms["mutual_information"], mi) + _assert_close(log_probs.exp(), mean) + assert epistemic.max() > 1e-4 # the trained members disagree + + +def test_mc_dropout_passes_match_reference_loop(reference): + """test.py with ``dropout: true`` and ``forward_passes: 3``: dropout on at test time, passes pooled.""" + references, ensemble = _official_pair(reference, mc_dropout_passes=3) + x = torch.randn(8, LAG, 25) + for ref in references: + reference.enable_dropout(ref) + with torch.no_grad(): + torch.manual_seed(7) + outputs_list = [ref(x) for ref in references for _ in range(3)] + _, mean, epistemic, aleatoric, mi, entropy = reference.uncertainties(outputs_list, 0.000001) + torch.manual_seed(7) + terms = ensemble.predict_uncertainty(x) + assert terms["member_probs"].shape == (3 * len(SEEDS), 8, 2) + assert not torch.equal(terms["member_probs"][0], terms["member_probs"][1]) # dropout was active + _assert_close(terms["probs"], mean) + _assert_close(terms["epistemic"], epistemic) + _assert_close(terms["aleatoric"], aleatoric) + _assert_close(terms["entropy"], entropy) + _assert_close(terms["mutual_information"], mi) + assert not any(m.training for m in ensemble.modules()) # dropout switched back off diff --git a/tests/oracle/test_deeplabv3_oracle.py b/tests/oracle/test_deeplabv3_oracle.py new file mode 100644 index 00000000..e7a9e39e --- /dev/null +++ b/tests/oracle/test_deeplabv3_oracle.py @@ -0,0 +1,138 @@ +"""DeepLabV3 checked against segmentation_models_pytorch 0.3.2 (and its torchvision lineage). + +Shadrin et al. (Sci. Rep. 14:2606, 2024) used DeepLabV3 with "encoder backbone ResNet18, number +of stages used in encoder equals to 3 ... default values for the other hyperparameters", i.e. +``smp.DeepLabV3(encoder_name="resnet18", encoder_depth=3)``. Each check builds smp and the port +from the same seed, requires identical parameter names, initial values and convolution geometry +(stride, dilation, padding, which a state dict does not carry), and compares outputs in eval and +train mode. +""" + +from __future__ import annotations + +import pytest +import torch + +from oracle_utils import missing, oracle_package +from pyhazards.models import build_model +from pyhazards.models.deeplabv3 import DeepLabV3 + +SHADRIN_PARAMETERS = 13_220_609 # 58 channels (3-day horizon); 2,727,169 of them used in forward + + +def _smp(): + return oracle_package("segmentation_models_pytorch", "0.3.2") + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _geometry(model: torch.nn.Module) -> list: + return [(m.stride, m.dilation, m.padding) for m in model.modules() if isinstance(m, torch.nn.Conv2d)] + + +def _assert_same_model(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + assert _geometry(reference) == _geometry(port) + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _compare_forward(reference: torch.nn.Module, port: torch.nn.Module, x: torch.Tensor) -> None: + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + reference.train() + port.train() + torch.manual_seed(7) # ASPP projection dropout + expected = reference(x) + torch.manual_seed(7) + _assert_close(port(x), expected) + + +def test_deeplabv3_shadrin_config_matches_smp(): + smp = _smp() + torch.manual_seed(0) + reference = smp.DeepLabV3(encoder_name="resnet18", encoder_depth=3, encoder_weights=None, in_channels=58, classes=1) + torch.manual_seed(0) + port = build_model("deeplabv3", task="segmentation") + _assert_same_model(reference, port) + assert _n_params(port) == SHADRIN_PARAMETERS + # At encoder_depth=3 the forward pass stops after layer2; layer3/layer4 stay in the model. + unused = sum(p.numel() for n, p in port.named_parameters() if n.startswith(("encoder.layer3", "encoder.layer4"))) + assert SHADRIN_PARAMETERS - unused == 2_727_169 + assert port.encoder.output_stride == reference.encoder.output_stride == 8 + + torch.manual_seed(1) + x = torch.randn(2, 58, 32, 32) # 32 x 32 tiles (21 x 21 km at 650 m) as in the paper + _compare_forward(reference, port, x) + + +@pytest.mark.parametrize( + "encoder_name, encoder_depth, in_channels, size", + [("resnet34", 5, 3, 64), ("resnet18", 4, 7, 40), ("resnet18", 5, 1, 48)], +) +def test_deeplabv3_other_configs_match_smp(encoder_name, encoder_depth, in_channels, size): + smp = _smp() + torch.manual_seed(0) + reference = smp.DeepLabV3( + encoder_name=encoder_name, encoder_depth=encoder_depth, encoder_weights=None, in_channels=in_channels, classes=2 + ) + torch.manual_seed(0) + port = DeepLabV3(in_channels=in_channels, classes=2, encoder_name=encoder_name, encoder_depth=encoder_depth) + _assert_same_model(reference, port) + torch.manual_seed(1) + _compare_forward(reference, port, torch.randn(2, in_channels, size, size)) + + +def test_deeplabv3_smp_defaults_match(): + smp = _smp() + torch.manual_seed(0) + reference = smp.DeepLabV3(encoder_weights=None) + torch.manual_seed(0) + port = DeepLabV3() + _assert_same_model(reference, port) + assert _n_params(port) == 26_007_105 + + +def test_deeplabv3_imagenet_stem_matches_smp(): + smp = _smp() + reference = smp.DeepLabV3(encoder_name="resnet18", encoder_depth=3, encoder_weights="imagenet", in_channels=58) + port = build_model("deeplabv3", task="segmentation", encoder_weights="imagenet") + ref_encoder, port_encoder = reference.encoder.state_dict(), port.encoder.state_dict() + assert list(ref_encoder) == list(port_encoder) + for key, value in ref_encoder.items(): + assert torch.equal(value, port_encoder[key]), key + port.load_state_dict(reference.state_dict(), strict=True) + torch.manual_seed(1) + _compare_forward(reference, port, torch.randn(2, 58, 32, 32)) + + +def test_deeplabv3_decoder_is_torchvision_deeplab_head(): + # smp's DeepLabV3 decoder file is taken from torchvision; its decoder plus the 1x1 head + # convolution is torchvision's DeepLabHead (ASPP rates 12/24/36, 256 channels). + try: + from torchvision.models.segmentation.deeplabv3 import DeepLabHead + except ImportError: + missing("torchvision is not installed (the default oracle suite installs it next to torch)") + + torch.manual_seed(0) + head = DeepLabHead(128, 1) + port = build_model("deeplabv3", task="segmentation", in_channels=4) + state = {f"decoder.{key}": value for key, value in head.state_dict().items() if not key.startswith("4.")} + state["segmentation_head.0.weight"] = head.state_dict()["4.weight"] + state["segmentation_head.0.bias"] = head.state_dict()["4.bias"] + result = port.load_state_dict(state, strict=False) + assert not result.unexpected_keys and all(key.startswith("encoder.") for key in result.missing_keys) + features = torch.randn(2, 128, 6, 6) + head.eval() + port.eval() + with torch.no_grad(): + _assert_close(port.segmentation_head[0](port.decoder(features)), head(features)) diff --git a/tests/oracle/test_earthfarseer_oracle.py b/tests/oracle/test_earthfarseer_oracle.py new file mode 100644 index 00000000..d4092a86 --- /dev/null +++ b/tests/oracle/test_earthfarseer_oracle.py @@ -0,0 +1,199 @@ +"""Earthfarseer checked against the official code (Alexander-wu/EarthFarseer, pinned in repos.yaml). + +The official repository has no license: it is fetched at test time and never vendored. Its stack +(timm 0.9.16) conflicts with the timm pins of the other suites, so the Oracle workflow runs this +file with requirements-farseer-rainformer.txt. + +Each check builds both models from the same seed, requires identical parameter names and initial +values, and compares outputs in eval and train mode (the reference has no dropout, drop path or +BatchNorm, so both modes must agree too). + +The reference hard-codes the FoTF transformer at width 768 and depth 12 (about 78M parameters). +CI compares reduced models in which only those two literals are overridden in the official +``GF_Block`` call; the default 157.5M-parameter model is compared with +``PYHAZARDS_ORACLE_LARGE=1`` (run locally, recorded in the model card). +""" + +from __future__ import annotations + +import importlib +import os +import sys +from importlib import metadata +from pathlib import Path + +import pytest +import torch + +from oracle_utils import missing, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.earthfarseer import Earthfarseer + +REQUIREMENTS = Path(__file__).parent / "requirements-farseer-rainformer.txt" + + +@pytest.fixture(autouse=True) +def _reference_stack(): + for line in REQUIREMENTS.read_text().splitlines(): + if "==" not in line or line.lstrip().startswith("#"): + continue + name, version = line.split("#")[0].strip().split("==") + try: + found = metadata.version(name) + except metadata.PackageNotFoundError: + missing(f"{name} is not installed; pip install -r tests/oracle/{REQUIREMENTS.name}") + if found != version: + missing(f"needs {name}=={version}, found {found}") + + +def _full_size_only() -> None: + if os.environ.get("PYHAZARDS_ORACLE_LARGE") != "1": + pytest.skip("default-size comparison (157.5M parameters) runs with PYHAZARDS_ORACLE_LARGE=1") + + +def _import_reference(root: Path, *modules: str): + """Import top-level modules of a flat reference repo without leaking its generic names. + + EarthFarseer's files are called ``model``, ``modules``, ``utils``...: any module of that name + already imported is set aside during the import and restored afterwards. + """ + names = {path.stem for path in root.glob("*.py")} + saved = {name: sys.modules.pop(name) for name in list(sys.modules) if name.split(".")[0] in names} + sys.path.insert(0, str(root)) + try: + return [importlib.import_module(module) for module in modules] + finally: + sys.path.remove(str(root)) + for name in [name for name in sys.modules if name.split(".")[0] in names]: + del sys.modules[name] + sys.modules.update(saved) + + +@pytest.fixture(scope="module") +def reference(): + model_module, fotf_module = _import_reference(oracle_repo("EarthFarseer"), "model", "FoTF_module") + return model_module, fotf_module + + +def _reference_model(reference, monkeypatch, shape_in, gf=None, **kwargs): + """Official ``Earthfarseer_model``; ``gf=(width, depth)`` overrides the hard-coded GF_Block size.""" + model_module, fotf_module = reference + if gf is not None: + official_gf_block = fotf_module.GF_Block + + def gf_block(**gf_kwargs): + assert (gf_kwargs["embed_dim"], gf_kwargs["depth"]) == (768, 12) # the literals replaced + return official_gf_block(**{**gf_kwargs, "embed_dim": gf[0], "depth": gf[1]}) + + monkeypatch.setattr(fotf_module, "GF_Block", gf_block) + try: + return model_module.Earthfarseer_model(shape_in=shape_in, **kwargs) + finally: + monkeypatch.undo() + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _compare_forward(reference: torch.nn.Module, port: torch.nn.Module, x: torch.Tensor) -> None: + for mode in ("eval", "train"): + getattr(reference, mode)() + getattr(port, mode)() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + + +REDUCED = [ + # shape_in, reference kwargs, (GF width, depth) + ((4, 2, 32, 32), dict(hid_S=16, hid_T=32, N_S=2, N_T=3), (32, 2)), + ((3, 1, 32, 32), dict(hid_S=8, hid_T=16, N_S=4, N_T=2, incep_ker=[3, 5], groups=4), (32, 2)), + ((2, 1, 64, 64), dict(hid_S=8, hid_T=16, N_S=6, N_T=2), (48, 1)), +] + + +@pytest.mark.parametrize("shape_in, kwargs, gf", REDUCED) +def test_earthfarseer_reduced_configs_match_reference(reference, monkeypatch, shape_in, kwargs, gf): + torch.manual_seed(0) + ref = _reference_model(reference, monkeypatch, shape_in, gf=gf, **kwargs) + torch.manual_seed(0) + port = Earthfarseer(shape_in=shape_in, gf_embed_dim=gf[0], gf_depth=gf[1], **kwargs) + _assert_same_state(ref, port) + assert _n_params(port) == _n_params(ref) + assert (port.H1, port.W1) == (ref.H1, ref.W1) + + torch.manual_seed(1) + x = torch.randn(2, *shape_in) + _compare_forward(ref, port, x) + + +def test_earthfarseer_builder_and_official_state_dict(reference, monkeypatch): + shape_in, kwargs, gf = REDUCED[1] + torch.manual_seed(0) + ref = _reference_model(reference, monkeypatch, shape_in, gf=gf, **kwargs) + torch.manual_seed(5) # a different initialisation, overwritten by the official weights + port = build_model( + "earthfarseer", task="forecasting", in_channels=shape_in[1], history=shape_in[0], img_size=shape_in[2], + gf_embed_dim=gf[0], gf_depth=gf[1], **kwargs, + ) + port.load_state_dict(ref.state_dict(), strict=True) + x = torch.randn(1, *shape_in) + _compare_forward(ref, port, x) + + seg = build_model( + "earthfarseer", task="segmentation", in_channels=shape_in[1], history=shape_in[0], img_size=shape_in[2], + gf_embed_dim=gf[0], gf_depth=gf[1], **kwargs, + ) + result = seg.load_state_dict(ref.state_dict(), strict=False) + assert result.unexpected_keys == [] and result.missing_keys == ["segmentation_head.weight", "segmentation_head.bias"] + ref.eval() + seg.eval() + with torch.no_grad(): + _assert_close(seg(x), seg.segmentation_head(ref(x)[:, 0])) + + +def test_earthfarseer_reference_fails_where_the_port_deviates(reference, monkeypatch): + # H divisible by 3: the reference's token-grid formula gives 13 for a 12x12 latent. + ref = _reference_model(reference, monkeypatch, (2, 1, 48, 48), gf=(32, 1), hid_S=8, hid_T=16, N_T=2) + assert ref.H1 == 13 + with pytest.raises(RuntimeError, match="invalid for input of size"): + ref(torch.randn(1, 2, 1, 48, 48)) + # Odd N_S: int(H / 2 ** (N_S / 2)) is not the latent size either. + ref = _reference_model(reference, monkeypatch, (2, 1, 64, 64), gf=(32, 1), hid_S=8, hid_T=16, N_S=3, N_T=2) + assert ref.H1 == 22 # latent 32 + with pytest.raises(RuntimeError, match="invalid for input of size"): + ref(torch.randn(1, 2, 1, 64, 64)) + # Non-square input: FoTF builds its transformer for H x H. + ref = _reference_model(reference, monkeypatch, (2, 1, 32, 64), gf=(32, 1), hid_S=8, hid_T=16, N_T=2) + with pytest.raises(AssertionError): + ref(torch.randn(1, 2, 1, 32, 64)) + + for shape_in, extra in [((2, 1, 48, 48), {}), ((2, 1, 64, 64), {"N_S": 3}), ((2, 1, 32, 64), {})]: + port = Earthfarseer(shape_in=shape_in, hid_S=8, hid_T=16, N_T=2, gf_embed_dim=32, gf_depth=1, **extra).eval() + with torch.no_grad(): + assert port(torch.randn(1, *shape_in)).shape == (1, *shape_in) + + +def test_earthfarseer_default_config_matches_reference(reference, monkeypatch): + _full_size_only() + torch.manual_seed(0) + ref = _reference_model(reference, monkeypatch, (10, 1, 64, 64)) + torch.manual_seed(0) + port = build_model("earthfarseer", task="forecasting") + _assert_same_state(ref, port) + assert _n_params(port) == 157_518_863 + + torch.manual_seed(1) + x = torch.randn(2, 10, 1, 64, 64) + _compare_forward(ref, port, x) diff --git a/tests/oracle/test_earthformer_oracle.py b/tests/oracle/test_earthformer_oracle.py new file mode 100644 index 00000000..3fa9f87b --- /dev/null +++ b/tests/oracle/test_earthformer_oracle.py @@ -0,0 +1,360 @@ +"""Earthformer checked against the official ``CuboidTransformerModel``. + +Reference: amazon-science/earth-forecasting-transformer at 7732b03 (pinned in repos.yaml, Apache-2.0), +``src/earthformer/cuboid_transformer/cuboid_transformer.py``; it needs only torch and einops +(requirements-earthformer.txt). Configurations are the ``model`` sections of the official YAML files, +turned into constructor arguments the way the training scripts do (each pattern repeated once per +hierarchy; ``block_units`` is commented out in every file and defaults to None). + +Checks: + +- the presets equal the official YAML files, and parameter counts at the official configurations + (SEVIR 8,659,677, Moving-MNIST 6,702,109, SEVIR-LR, ICAR-ENSO) and at the configurations that + reproduce the paper's counts (15.1M / 13.1M SEVIR, 7.61M / 6.61M Moving-MNIST, 7.6M / 6.6M ENSO); +- the same seed gives identical parameter names, buffers and initial values; +- outputs in eval mode and in train mode (dropout 0.1, same seed) and input gradients agree, for the + SEVIR, Moving-MNIST and ENSO configurations and for other patterns and options of the class; +- the official SEVIR and ICAR-ENSO checkpoints load with ``strict=True`` and give the same outputs + at their full input sizes (13x384x384 and 12x24x48). + +To keep CPU time low the SEVIR architecture is compared at 13x48x48 and 13x50x50 frames (the 12x +initial down-sampling then gives 4x4 and 5x5 tokens; 50 exercises the padding paths) and +Moving-MNIST at 10x32x32; ENSO and the checkpoints run at their reference sizes. +""" + +from __future__ import annotations + +import pytest +import torch +import yaml + +from oracle_utils import import_from, oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.earthformer import ( + EARTHFORMER_CHECKPOINTS, + EARTHFORMER_CONFIGS, + CuboidTransformerModel, + Earthformer, + EarthformerSegmenter, + earthformer_checkpoint_path, + earthformer_config, +) + +CONFIG_FILES = { + "sevir": "sevir/earthformer_sevir_v1.yaml", + "sevir_cfg": "sevir/cfg_sevir.yaml", + "sevir_lr": "sevir/cfg_sevirlr.yaml", + "moving_mnist": "moving_mnist/cfg.yaml", + "nbody": "nbody/cfg.yaml", + "enso": "enso/earthformer_enso_v1.yaml", + "enso_cfg": "enso/cfg.yaml", +} +PRESET_OF = {"sevir_cfg": "sevir", "enso_cfg": "enso"} + +# Global vectors as implied by the paper's parameter counts: the global vectors share the local +# q/k/v projections, have no FFN of their own and the decoder self-attention does not use them. +PAPER_GLOBAL = dict( + num_global_vectors=8, + use_dec_self_global=False, + use_dec_cross_global=False, + use_global_vector_ffn=False, + use_global_self_attn=False, + separate_global_qkv=False, +) +NO_GLOBAL = dict(num_global_vectors=0) +PAPER_COUNTS = [ + # (official file, overrides, parameters, paper value) + ("sevir", dict(enc_depth=[2, 2], dec_depth=[2, 2], **PAPER_GLOBAL), 15_082_069), # Table 6: 15.1M + ("sevir", dict(enc_depth=[2, 2], dec_depth=[2, 2], **NO_GLOBAL), 13_075_029), # Table 6: 13.1M w/o global + ("moving_mnist", dict(pos_embed_type="t+h+w", **PAPER_GLOBAL), 7_610_781), # Tables 4/5: 7.61M + ("moving_mnist", dict(pos_embed_type="t+h+w"), 6_611_997), # Tables 4/5: 6.61M (Axial, w/o global) + ("enso", dict(enc_depth=[4, 4], dec_depth=[4, 4], **PAPER_GLOBAL), 7_600_077), # Table 7: 7.6M + ("enso", dict(enc_depth=[4, 4], dec_depth=[4, 4]), 6_601_293), # Table 7: 6.6M w/o global +] + + +def _official_module(): + oracle_package("einops", "0.8.2", "requirements-earthformer.txt") + root = oracle_repo("earth-forecasting-transformer") + return import_from(root / "src", "earthformer.cuboid_transformer.cuboid_transformer") + + +def _yaml_model_section(name: str) -> dict: + root = oracle_repo("earth-forecasting-transformer") + path = root / "scripts" / "cuboid_transformer" / CONFIG_FILES[name] + section = yaml.safe_load(path.read_text(encoding="utf-8"))["model"] + section.setdefault("block_units", None) # commented out in the files; the scripts default it to None + return section + + +def _official_kwargs(name: str, **overrides) -> dict: + """Constructor arguments as built by the official training scripts (train_cuboid_*.py).""" + cfg = dict(_yaml_model_section(name)) + cfg.update(overrides) + num_blocks = len(cfg["enc_depth"]) + + def expand(pattern): + return [pattern] * num_blocks if isinstance(pattern, str) else list(pattern) + + kwargs = {key: value for key, value in cfg.items() if key not in ("self_pattern", "cross_self_pattern", "cross_pattern")} + kwargs["enc_attn_patterns"] = expand(cfg["self_pattern"]) + kwargs["dec_self_attn_patterns"] = expand(cfg["cross_self_pattern"]) + kwargs["dec_cross_attn_patterns"] = expand(cfg["cross_pattern"]) + return kwargs + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert value.dtype == port_state[key].dtype, key + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _randomise(reference: torch.nn.Module, port: torch.nn.Module, seed: int) -> None: + """Perturb every floating-point parameter so that zero-initialised biases and vectors matter.""" + generator = torch.Generator().manual_seed(seed) + state = reference.state_dict() + for value in state.values(): + if value.is_floating_point(): + value.add_(0.05 * torch.randn(value.shape, generator=generator)) + reference.load_state_dict(state, strict=True) + port.load_state_dict(state, strict=True) + + +def _build_pair(official, kwargs: dict, port_cls=CuboidTransformerModel): + torch.manual_seed(0) + reference = official.CuboidTransformerModel(**kwargs) + torch.manual_seed(0) + port = port_cls(**kwargs) + return reference, port + + +def _compare(reference, port, batch: int = 2, seed: int = 1, train: bool = True) -> None: + """Seeded weights, then eval outputs, train outputs (dropout) and input gradients.""" + _assert_same_state(reference, port) + _randomise(reference, port, seed) + torch.manual_seed(seed + 1) + x = torch.randn((batch,) + tuple(port.input_shape)) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + if not train: + return + reference.train() + port.train() + x_ref = x.clone().requires_grad_(True) + x_port = x.clone().requires_grad_(True) + torch.manual_seed(seed + 2) + out_ref = reference(x_ref) + torch.manual_seed(seed + 2) + out_port = port(x_port) + _assert_close(out_port, out_ref) + weights = torch.randn(out_ref.shape, generator=torch.Generator().manual_seed(seed + 3)) + (out_ref * weights).sum().backward() + (out_port * weights).sum().backward() + _assert_close(x_port.grad, x_ref.grad) + for (name, p_ref), (_, p_port) in zip(reference.named_parameters(), port.named_parameters()): + if p_ref.grad is None: + assert p_port.grad is None, name + else: + _assert_close(p_port.grad, p_ref.grad) + + +@pytest.mark.parametrize("name", sorted(CONFIG_FILES)) +def test_presets_equal_official_yaml(name): + assert EARTHFORMER_CONFIGS[PRESET_OF.get(name, name)] == _yaml_model_section(name) + + +@pytest.mark.parametrize( + "name, expected", + [("sevir", 8_659_677), ("moving_mnist", 6_702_109), ("sevir_lr", 1_505_069), ("enso", 1_394_325)], +) +def test_parameter_counts_at_official_configs(name, expected): + official = _official_module() + with torch.device("meta"): + reference = official.CuboidTransformerModel(**_official_kwargs(name)) + port = build_model("earthformer", task="forecasting", config=name) + assert _n_params(reference) == _n_params(port) == expected + assert [(k, v.shape) for k, v in reference.state_dict().items()] == [(k, v.shape) for k, v in port.state_dict().items()] + + +@pytest.mark.parametrize("name, overrides, expected", PAPER_COUNTS) +def test_parameter_counts_reproducing_the_paper(name, overrides, expected): + official = _official_module() + with torch.device("meta"): + reference = official.CuboidTransformerModel(**_official_kwargs(name, **overrides)) + port = build_model("earthformer", task="forecasting", config=name, **overrides) + assert _n_params(reference) == _n_params(port) == expected + + +def test_sevir_architecture_matches_reference(): + official = _official_module() + for size in (48, 50): + kwargs = _official_kwargs("sevir", input_shape=[13, size, size, 1], target_shape=[12, size, size, 1]) + assert kwargs == earthformer_config("sevir", input_shape=[13, size, size, 1], target_shape=[12, size, size, 1]) + reference, port = _build_pair(official, kwargs) + _compare(reference, port, seed=size) + + +def test_moving_mnist_architecture_matches_reference(): + official = _official_module() + kwargs = _official_kwargs("moving_mnist", input_shape=[10, 32, 32, 1], target_shape=[10, 32, 32, 1]) + reference, port = _build_pair(official, kwargs) + _compare(reference, port) + + +def test_enso_architecture_matches_reference(): + official = _official_module() + reference, port = _build_pair(official, _official_kwargs("enso")) + _compare(reference, port) + + +SMALL = dict(input_shape=[5, 16, 16, 2], target_shape=[3, 16, 16, 3], base_units=32, num_heads=4) +VARIANTS = { + # The training scripts' own defaults for SEVIR: shared global q/k/v, global FFN, decoder global + # vectors, hierarchical decoder embeddings and gradient checkpointing of FFN and attention. + "sevir_script_defaults": dict( + num_global_vectors=8, + use_dec_self_global=True, + use_dec_cross_global=True, + use_global_vector_ffn=True, + use_global_self_attn=False, + separate_global_qkv=False, + dec_hierarchical_pos_embed=True, + checkpoint_level=2, + pos_embed_type="t+hw", + ), + # Separate global projections with wider global vectors, decoder global self-attention. + "separate_global_ratio2": dict( + num_global_vectors=4, + use_dec_self_global=True, + dec_self_update_global=False, + use_dec_cross_global=True, + use_global_vector_ffn=True, + use_global_self_attn=True, + separate_global_qkv=True, + global_dim_ratio=2, + checkpoint_level=1, + ), + # Shifted windows with masks, dilated cuboids, padding with 'ignore'. + "video_swin_padding_ignore": dict( + self_pattern="video_swin_2x4", + cross_self_pattern="spatial_lg_v1", + cross_pattern="cross_4x4_heter", + padding_type="ignore", + input_shape=[5, 20, 20, 2], + target_shape=[3, 20, 20, 3], + num_global_vectors=2, + ), + "axial_dilate_gated_nearest": dict( + self_pattern="axial_space_dilate_2", + cross_self_pattern="divided_st", + cross_pattern="cross_2x2_lg", + padding_type="nearest", + gated_ffn=True, + ffn_activation="leaky", + z_init_method="nearest_interp", + dec_use_first_self_attn=True, + enc_use_inter_ffn=False, + dec_use_inter_ffn=False, + attn_linear_init_mode="1", + ffn_linear_init_mode="1", + ), + "full_attention_rms_last": dict( + self_pattern="full", + cross_self_pattern="full", + cross_pattern="cross_1x1", + norm_layer="rms_norm", + z_init_method="last", + dec_cross_last_n_frames=2, + use_relative_pos=False, + self_attn_use_final_proj=False, + initial_downsample_scale=[1, 1, 2], + ), + "three_hierarchies_mean": dict( + enc_depth=[1, 1, 1], + dec_depth=[1, 1, 1], + input_shape=[4, 32, 32, 2], + target_shape=[2, 32, 32, 3], + z_init_method="mean", + dec_cross_start=1, + initial_downsample_conv_layers=1, + final_upsample_conv_layers=2, + block_units=[32, 48, 64], + ), +} + + +@pytest.mark.parametrize("variant", sorted(VARIANTS)) +def test_other_patterns_and_options_match_reference(variant): + official = _official_module() + overrides = dict(SMALL) + overrides.update(VARIANTS[variant]) + kwargs = _official_kwargs("moving_mnist", **overrides) + reference, port = _build_pair(official, kwargs) + _compare(reference, port, seed=7) + + +def test_forecasting_and_segmentation_wrappers_keep_the_core_parameters(): + official = _official_module() + kwargs = _official_kwargs("sevir", input_shape=[4, 24, 24, 3], target_shape=[2, 24, 24, 2]) + reference, port = _build_pair(official, kwargs, port_cls=Earthformer) + _assert_same_state(reference, port) + _randomise(reference, port, seed=3) + x = torch.randn(2, 4, 3, 24, 24) # (batch, time, channels, H, W) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x.permute(0, 1, 3, 4, 2)).permute(0, 1, 4, 2, 3)) + + # task="segmentation": the same network with target_shape (1, H, W, 1); logits (batch, 1, H, W). + kwargs = _official_kwargs("sevir", input_shape=[4, 24, 24, 3], target_shape=[1, 24, 24, 1]) + reference, _ = _build_pair(official, kwargs) + torch.manual_seed(0) + port = build_model("earthformer", task="segmentation", history=4, in_channels=3, img_size=24) + assert isinstance(port, EarthformerSegmenter) + _assert_same_state(reference, port) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x.permute(0, 1, 3, 4, 2))[:, 0].permute(0, 3, 1, 2)) + + +@pytest.mark.parametrize("name", sorted(EARTHFORMER_CHECKPOINTS)) +def test_official_checkpoints(name, tmp_path, monkeypatch): + official = _official_module() + spec = EARTHFORMER_CHECKPOINTS[name] + checkpoint = oracle_asset(f"earthformer_{name}") / f"earthformer_{name}.pt" + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + + reference = official.CuboidTransformerModel(**_official_kwargs(spec["config"])) + reference.load_state_dict(state, strict=True) + # pretrained="" finds the sha256-verified file in the torch hub cache without downloading. + hub = tmp_path / "hub" + (hub / "checkpoints").mkdir(parents=True) + (hub / "checkpoints" / f"earthformer_{name}.pt").write_bytes(checkpoint.read_bytes()) + monkeypatch.setattr(torch.hub, "get_dir", lambda: str(hub)) + assert earthformer_checkpoint_path(name) == hub / "checkpoints" / f"earthformer_{name}.pt" + port = build_model("earthformer", task="forecasting", config=spec["config"], pretrained=name) + assert isinstance(port, Earthformer) + _assert_same_state(reference, port) + + T, H, W, C = reference.input_shape + x = torch.rand((1, T, H, W, C), generator=torch.Generator().manual_seed(0)) + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(x) + actual = port(x.permute(0, 1, 4, 2, 3)).permute(0, 1, 3, 4, 2) + _assert_close(actual, expected) + assert expected.shape == (1,) + tuple(reference.target_shape) diff --git a/tests/oracle/test_eqnet_oracle.py b/tests/oracle/test_eqnet_oracle.py new file mode 100644 index 00000000..506f85dd --- /dev/null +++ b/tests/oracle/test_eqnet_oracle.py @@ -0,0 +1,167 @@ +"""EQNet's feature extractor and heads checked against the author's code (test oracle only). + +EQNet is rebuilt from the paper (Zhu et al., JGR Solid Earth 2022); no code of AI4EPS/EQNet was copied (its +licence is academic / non-commercial, and it has no shift-and-stack model). Two pinned commits serve as +oracles, read with ``load_definitions`` so that only the needed classes run: + +- ``EQNet`` at af94a08 (current): ``eqnet/models/resnet1d.py`` ``ResNet(BasicBlock, [2, 2, 2, 2])``, the + network of the paper's Figure 3a (input ``(batch, 3, time, stations)``, output ``{"out": (batch, + stations, 128, time / 32)}``). Checks: 996,960 parameters, parameter names and shapes, identical seeded + initialisation, identical outputs in evaluation and training mode, batch-norm statistics and gradients. +- ``EQNet-2022`` at a9df49a (2022-07-27, the author's first EQNet): ``PhasePicker`` and ``EventDetector`` + instantiated at the paper's widths (Figure 3b ``[64, 32, 16]``, Figure 3c ``[128, 64, 32]``). The + current repository's heads are different networks (dilated 5-tap convolutions, 3-class softmax), so + they are not an oracle. Checks: 7,825 and 31,009 parameters, identical seeded convolution weights, + identical outputs with copied weights in evaluation mode and with batch statistics. + +Not verifiable against any code: the shift-and-stack module and the multi-station wiring (tested from the +paper's description in tests/test_eqnet.py). No EQNet weights were ever released. +""" + +from __future__ import annotations + +import subprocess +import typing + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +from oracle_utils import load_definitions, oracle_repo +from pyhazards.models.eqnet import EQNet, EQNetBackbone, EventDetectionHead, PhasePickingHead + +EXACT = dict(rtol=0, atol=0) + + +@pytest.fixture(scope="module") +def resnet(): + root = oracle_repo("EQNet") + namespace = {"torch": torch, "nn": nn, "F": F, "Tensor": torch.Tensor} + namespace.update({name: getattr(typing, name) for name in ("Any", "Callable", "List", "Optional", "Type", "Union")}) + names = ["conv3x1", "conv1x1", "BasicBlock", "Bottleneck", "ResNet"] + defs = load_definitions(root / "eqnet" / "models" / "resnet1d.py", names, namespace) + return lambda: defs["ResNet"](defs["BasicBlock"], [2, 2, 2, 2]) + + +@pytest.fixture(scope="module") +def heads(): + root = oracle_repo("EQNet-2022") + path = root / "eqnet" / "models" / "eqnet.py" + assert "basic version of eqnet" in subprocess.run( + ["git", "log", "-1", "--format=%s"], cwd=root, check=True, capture_output=True, text=True + ).stdout + return load_definitions(path, ["EventDetector", "PhasePicker"], {"torch": torch, "nn": nn, "F": F}) + + +def _count(model: nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _randomise_batch_norm(module: nn.Module, generator: torch.Generator) -> None: + for bn in module.modules(): + if isinstance(bn, nn.BatchNorm1d): + with torch.no_grad(): + bn.weight.copy_(torch.rand(bn.weight.shape, generator=generator) + 0.5) + bn.bias.copy_(torch.randn(bn.bias.shape, generator=generator) * 0.1) + bn.running_mean.copy_(torch.randn(bn.running_mean.shape, generator=generator) * 0.1) + bn.running_var.copy_(torch.rand(bn.running_var.shape, generator=generator) + 0.5) + + +def test_backbone_matches_the_official_resnet1d(resnet): + torch.manual_seed(0) + reference = resnet() + torch.manual_seed(0) + backbone = EQNetBackbone() + assert _count(reference) == _count(backbone) == 996_960 + ref_state, state = reference.state_dict(), backbone.state_dict() + assert list(ref_state) == list(state) + for key in ref_state: + torch.testing.assert_close(state[key], ref_state[key], **EXACT, msg=key) + # The full EQNet carries the official names under "backbone.". + model_state = EQNet().state_dict() + assert all(f"backbone.{key}" in model_state for key in ref_state) + + _randomise_batch_norm(reference, torch.Generator().manual_seed(1)) + backbone.load_state_dict(reference.state_dict()) + x = torch.randn(2, 3, 3072, 5) # official layout (batch, channel, time, station) + ours = x.permute(0, 3, 1, 2).reshape(10, 3, 3072) + reference.eval(), backbone.eval() + with torch.no_grad(): + expected = reference(x)["out"] + assert expected.shape == (2, 5, 128, 96) + torch.testing.assert_close(backbone(ours).reshape(2, 5, 128, 96), expected, **EXACT) + # Lengths that are not multiples of 32 (e.g. 60-s STEAD windows). + odd = torch.randn(1, 3, 6000, 2) + torch.testing.assert_close( + backbone(odd.permute(0, 3, 1, 2).reshape(2, 3, 6000)).reshape(1, 2, 128, -1), reference(odd)["out"], **EXACT + ) + + reference.train(), backbone.train() + expected = reference(x)["out"] + actual = backbone(ours).reshape(2, 5, 128, 96) + torch.testing.assert_close(actual, expected, **EXACT) + for key, value in reference.state_dict().items(): + torch.testing.assert_close(backbone.state_dict()[key], value, **EXACT, msg=key) + grad = torch.randn_like(expected) + expected.backward(grad) + actual.backward(grad) + for (name, p_ref), p_port in zip(reference.named_parameters(), backbone.parameters()): + torch.testing.assert_close(p_port.grad, p_ref.grad, rtol=1e-5, atol=1e-6, msg=name) + + +def _copy_head(reference: nn.Module, head: nn.Module, picker: bool) -> None: + """Copy the port's weights into the a9df49a head (its ``bn_layers.0`` of the picker is unused).""" + offset = 1 if picker else 0 + pairs = [ + (reference.conv_layers[0], head.conv1), + (reference.conv_layers[1], head.conv2), + (reference.bn_layers[offset], head.bn1), + (reference.bn_layers[offset + 1], head.bn2), + (reference.conv_out, head.conv_out), + ] + for ref_module, module in pairs: + ref_module.load_state_dict(module.state_dict()) + + +@pytest.mark.parametrize("picker", [True, False]) +def test_heads_match_the_author_code_at_the_paper_widths(heads, picker): + if picker: + make_ref, make_head, channels, expected_count = ( + lambda: heads["PhasePicker"](channels=[64, 32, 16]), lambda: PhasePickingHead(64), 64, 7_825 + ) + else: + make_ref, make_head, channels, expected_count = ( + lambda: heads["EventDetector"](channels=[128, 64, 32]), lambda: EventDetectionHead(128), 128, 31_009 + ) + torch.manual_seed(3) + reference = make_ref() + torch.manual_seed(3) + head = make_head() + assert _count(head) == expected_count + unused = 64 * 2 if picker else 0 # PhasePicker(channels=[64, 32, 16]) also builds an unused BatchNorm1d(64) + assert _count(reference) == expected_count + unused + # Same creation order of the convolutions -> same seeded (PyTorch default) initial weights. + torch.testing.assert_close(head.conv1.weight, reference.conv_layers[0].weight, **EXACT) + torch.testing.assert_close(head.conv2.weight, reference.conv_layers[1].weight, **EXACT) + torch.testing.assert_close(head.conv_out.weight, reference.conv_out.weight, **EXACT) + torch.testing.assert_close(head.conv_out.bias, reference.conv_out.bias, **EXACT) + + _randomise_batch_norm(head, torch.Generator().manual_seed(4)) + _copy_head(reference, head, picker) + features = torch.randn(2, 3, channels, 96) + flat = features.reshape(6, channels, 96) + for batch_statistics in (False, True): + reference.eval(), head.eval() + if batch_statistics: # the a9df49a forward has no training branch that returns outputs + for module in list(reference.modules()) + list(head.modules()): + if isinstance(module, nn.BatchNorm1d): + module.train() + with torch.no_grad(): + if picker: + expected, _ = reference({"out": features}) # (batch, stations, 16 * T) + torch.testing.assert_close(head(flat).reshape(2, 3, -1), expected, **EXACT) + assert expected.shape[-1] == 16 * 96 + else: + expected, _ = reference({"out": flat}) # (n, 1, T) + torch.testing.assert_close(head(flat), expected.squeeze(1), **EXACT) diff --git a/tests/oracle/test_eqtransformer_oracle.py b/tests/oracle/test_eqtransformer_oracle.py new file mode 100644 index 00000000..58929747 --- /dev/null +++ b/tests/oracle/test_eqtransformer_oracle.py @@ -0,0 +1,388 @@ +"""EQTransformer checked against the official Keras models and SeisBench's port. + +References (pinned in repos.yaml / requirements-earthquake.txt): + +- smousavi05/EQTransformer at a589da6 (MIT): the released models ``EqT_original_model.h5`` (paper + model) and ``EqT_model_conservative.h5``, loaded with ``tf.keras.models.load_model`` (TensorFlow + 2.11) and the official custom layers of ``EQTransformer/core/EqT_utils.py``; the official ``picker`` + of the same file; the 100 STEAD sample traces ``ModelsAndSampleData/100samples.hdf5``. +- SeisBench 0.12.6 (GPL-3.0, oracle only) ``EQTransformer`` with its conversions of the two models. + +The released graphs call SpatialDropout1D with ``training=True``, so the official models are random at +inference. For deterministic comparisons the Keras models are rebuilt from their stored configuration +with the SpatialDropout1D rate set to 0 (dropout has no weights; the graph is otherwise unchanged). + +Tolerances: both implementations run in float32. In eval mode the outputs agree to ~2e-6 on the same +normalised input (the port's own float32-vs-float64 difference is 1e-6), and to ~1e-5 when ``annotate`` +normalises the raw traces in float32 instead of the reference's float64; rtol 1e-4 / atol 1e-5 is used. +In train mode (BatchNorm on batch statistics over 6000-sample sequences) float32 round-off alone moves +the port's outputs by ~2e-4, so rtol / atol 1e-3 is used there. +""" + +from __future__ import annotations + +import importlib.util +import json +import math +import warnings + +import numpy as np +import pytest +import torch + +from oracle_utils import oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.eqtransformer import ( + EQTransformer, + keras_weight_map, + load_eqtransformer_keras_weights, + read_keras_h5_weights, +) + +REQUIREMENTS = "requirements-earthquake.txt" +MODELS = {"original": "EqT_original_model.h5", "conservative": "EqT_model_conservative.h5"} +SEISBENCH = { + "original": ("seisbench_eqtransformer_original_nonconservative", "original_nonconservative.pt.v1", 2, "non-conservative"), + "conservative": ("seisbench_eqtransformer_original", "original.pt.v3", 3, "conservative"), +} +PARAMETERS = {"original": 371_639, "conservative": 376_423} +EVAL_TOL = dict(rtol=1e-4, atol=1e-5) +TRAIN_TOL = dict(rtol=1e-3, atol=1e-3) + +_CACHE: dict = {} + + +def _tf(): + tf = oracle_package("tensorflow", "2.11.0", REQUIREMENTS) + tf.config.threading.set_inter_op_parallelism_threads(8) + return tf + + +def _official_utils(): + """``EqT_utils.py`` loaded as a standalone module (its package ``__init__`` imports the whole toolbox).""" + if "utils" not in _CACHE: + _tf() + oracle_package("obspy", "1.5.1", REQUIREMENTS) # EqT_utils imports obspy's trigger_onset + path = oracle_repo("EQTransformer") / "EQTransformer" / "core" / "EqT_utils.py" + spec = importlib.util.spec_from_file_location("eqt_utils_official", path) + module = importlib.util.module_from_spec(spec) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + spec.loader.exec_module(module) + _CACHE["utils"] = module + return _CACHE["utils"] + + +def _h5(variant: str): + return oracle_repo("EQTransformer") / "ModelsAndSampleData" / MODELS[variant] + + +def _custom_objects(): + utils = _official_utils() + return { + "SeqSelfAttention": utils.SeqSelfAttention, + "FeedForward": utils.FeedForward, + "LayerNormalization": utils.LayerNormalization, + "f1": utils.f1, + } + + +def _keras(variant: str, all_dropout_off: bool = False): + """The official model with SpatialDropout1D rate 0 (and optionally every other dropout off).""" + key = ("keras", variant, all_dropout_off) + if key not in _CACHE: + tf = _tf() + loaded = tf.keras.models.load_model(str(_h5(variant)), custom_objects=_custom_objects(), compile=False) + config = loaded.get_config() + for layer in config["layers"]: + cfg = layer["config"] + if layer["class_name"] == "SpatialDropout1D": + cfg["rate"] = 0.0 + if all_dropout_off: + if layer["class_name"] == "LSTM": + cfg["dropout"] = cfg["recurrent_dropout"] = 0.0 + if layer["class_name"] == "Bidirectional": + cfg["layer"]["config"]["dropout"] = cfg["layer"]["config"]["recurrent_dropout"] = 0.0 + if layer["class_name"] == "FeedForward": + cfg["dropout_rate"] = 0.0 + model = tf.keras.Model.from_config(config, custom_objects=_custom_objects()) + model.set_weights(loaded.get_weights()) + _CACHE[key] = (model, loaded) + return _CACHE[key][0] + + +def _keras_outputs(model, x_wc: np.ndarray, training: bool = False) -> np.ndarray: + """Keras ``(batch, 6000, 3)`` input -> ``(batch, 3, 6000)`` (detection, P, S).""" + if training: + outputs = [o.numpy() for o in model(x_wc, training=True)] + else: + outputs = model.predict(x_wc, batch_size=16, verbose=0) + return np.concatenate([o[..., 0][:, None, :] for o in outputs], axis=1) + + +def _port(variant: str, **kwargs) -> EQTransformer: + model = EQTransformer(variant=variant, **kwargs) + load_eqtransformer_keras_weights(model, _h5(variant)) + return model.eval() + + +def _stead_samples(count: int = 100): + """The 100 STEAD traces shipped with the official repository, normalised as the official tester does.""" + if "stead" not in _CACHE: + import h5py + + utils = _official_utils() + path = oracle_repo("EQTransformer") / "ModelsAndSampleData" / "100samples.hdf5" + raw, normalised, arrivals = [], [], [] + with h5py.File(path, "r") as handle: + for name in sorted(handle["data"]): + dataset = handle["data"][name] + data = np.array(dataset, dtype=np.float32) # (6000, 3), components E, N, Z + raw.append(data.copy()) + normalised.append(utils.normalize(data.astype(np.float64), mode="std").astype(np.float32)) + arrivals.append((int(dataset.attrs["p_arrival_sample"]), int(dataset.attrs["s_arrival_sample"]))) + _CACHE["stead"] = (np.stack(raw), np.stack(normalised), arrivals) + raw, normalised, arrivals = _CACHE["stead"] + return raw[:count], normalised[:count], arrivals[:count] + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_parameter_counts_and_strict_loading(variant): + keras_model = _keras(variant) + keras_trainable = sum(int(np.prod(w.shape)) for w in keras_model.trainable_weights) + port = build_model("eqtransformer", task="picking", variant=variant) + assert sum(p.numel() for p in port.parameters() if p.requires_grad) == keras_trainable == PARAMETERS[variant] + # Every Keras weight maps to exactly one port tensor (checked inside the loader) and the + # mapping covers every parameter and buffer except BatchNorm's num_batches_tracked. + weights = read_keras_h5_weights(_h5(variant)) + mapping = keras_weight_map(port.lstm_blocks) + assert sorted(set(mapping.values())) == sorted(weights) + load_eqtransformer_keras_weights(port, _h5(variant)) + # The Keras topology agrees with the port: the stored graph's layer names are the ones the map uses. + import h5py + + with h5py.File(_h5(variant), "r") as handle: + layers = {layer["name"]: layer for layer in json.loads(handle.attrs["model_config"])["config"]["layers"]} + inbound = lambda name: layers[name]["inbound_nodes"][0][0][0] # noqa: E731 + lstm_p, lstm_s = mapping["lstm_p.kernel"][0], mapping["lstm_s.kernel"][0] + assert inbound("attentionP") == lstm_p and inbound("attentionS") == lstm_s + decoders = { + branch: [mapping[f"{branch}.convs.{i}.weight"][0] for i in range(7)] + for branch in ("decoder_d", "decoder_p", "decoder_s") + } + assert inbound("detector") == decoders["decoder_d"][-1] + assert inbound("picker_P") == decoders["decoder_p"][-1] + assert inbound("picker_S") == decoders["decoder_s"][-1] + for i in range(len(port.res_cnn)): + conv1 = mapping[f"res_cnn.{i}.conv1.weight"][0] + bn2 = mapping[f"res_cnn.{i}.bn2.weight"][0] + assert inbound(bn2) == conv1 + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_eval_outputs_match_official_keras(variant): + keras_model = _keras(variant) + port = _port(variant) + rng = np.random.default_rng(0) + x_random = rng.standard_normal((2, 6000, 3)).astype(np.float32) + raw, normalised, _ = _stead_samples(24) + x = np.concatenate([x_random, normalised]) + expected = _keras_outputs(keras_model, x) + with torch.no_grad(): + actual = port(torch.from_numpy(x).transpose(1, 2)).numpy() + annotated = port.annotate(torch.from_numpy(raw).transpose(1, 2)).numpy() + np.testing.assert_allclose(actual, expected, **EVAL_TOL) + # annotate() applies the official normalisation (EqT_utils.normalize, mode "std") itself. + np.testing.assert_allclose(annotated, expected[2:], **EVAL_TOL) + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_train_mode_matches_official_keras_without_dropout(variant): + # Dropout masks come from different random generators, so every dropout is switched off on both + # sides; what remains is BatchNorm with batch statistics. + keras_model = _keras(variant, all_dropout_off=True) + port = EQTransformer(variant=variant, drop_rate=0.0) + load_eqtransformer_keras_weights(port, _h5(variant)) + port.train() + x = np.random.default_rng(1).standard_normal((3, 6000, 3)).astype(np.float32) + expected = _keras_outputs(keras_model, x, training=True) + actual = port(torch.from_numpy(x).transpose(1, 2)).detach().numpy() + np.testing.assert_allclose(actual, expected, **TRAIN_TOL) + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_official_graph_applies_spatial_dropout_at_inference(variant): + """The released graphs keep SpatialDropout1D active in predict(); the port does with mc_dropout=True.""" + tf = _tf() + loaded = tf.keras.models.load_model(str(_h5(variant)), custom_objects=_custom_objects(), compile=False) + config = loaded.get_config() + calls = [ + node[0][3] + for layer in config["layers"] + if layer["class_name"] == "SpatialDropout1D" + for node in layer["inbound_nodes"] + ] + assert calls and all(kwargs == {"training": True} for kwargs in calls) + x = np.random.default_rng(2).standard_normal((1, 6000, 3)).astype(np.float32) + first, second = _keras_outputs(loaded, x), _keras_outputs(loaded, x) + assert np.abs(first - second).max() > 1e-4 + port = _port(variant) + xt = torch.from_numpy(x).transpose(1, 2) + with torch.no_grad(): + assert torch.equal(port(xt), port(xt)) + port.mc_dropout = True + assert (port(xt) - port(xt)).abs().max() > 1e-4 + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_outputs_match_seisbench(variant): + sbm = oracle_package("seisbench", "0.12.6", REQUIREMENTS) + import seisbench.models as sb_models + + asset, filename, lstm_blocks, compatible = SEISBENCH[variant] + reference = sb_models.EQTransformer(lstm_blocks=lstm_blocks, original_compatible=compatible) + state = torch.load(oracle_asset(asset) / filename, map_location="cpu", weights_only=True) + reference.load_state_dict(state, strict=True) + reference.eval() + assert sbm.__version__ == "0.12.6" + port = _port(variant) + _, normalised, _ = _stead_samples(8) + x = torch.from_numpy(np.concatenate([normalised, np.random.default_rng(3).standard_normal((2, 6000, 3)).astype(np.float32)])).transpose(1, 2) + with torch.no_grad(): + # SeisBench's converted weights take components in the order Z, N, E. + expected = torch.stack(reference(x[:, [2, 1, 0]]), dim=1) + actual = port(x) + torch.testing.assert_close(actual, expected, **EVAL_TOL) + + +def _official_matches(utils, probabilities: np.ndarray, thresholds): + args = { + "detection_threshold": thresholds[0], + "P_threshold": thresholds[1], + "S_threshold": thresholds[2], + "estimate_uncertainty": False, + } + zeros = np.zeros(probabilities.shape[-1], dtype=probabilities.dtype) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + matches, _, _ = utils.picker(args, probabilities[0], probabilities[1], probabilities[2], zeros, zeros, zeros) + return matches + + +@pytest.mark.parametrize("thresholds", [(0.2, 0.1, 0.1), (0.5, 0.3, 0.3), (0.05, 0.02, 0.02)]) +def test_picks_match_official_picker(thresholds): + """``extract_picks`` / ``extract_detections`` reproduce ``EqT_utils.picker`` on the 100 STEAD traces.""" + utils = _official_utils() + keras_model = _keras("original") + _, normalised, _ = _stead_samples(100) + probabilities = _keras_outputs(keras_model, normalised) + # Synthetic traces with several events and noise exercise the association rules further. + rng = np.random.default_rng(4) + synthetic = np.clip(rng.random((20, 3, 6000)).astype(np.float32) ** 6 + 0.0, 0.0, 1.0) + for trace in synthetic: + for start in rng.integers(0, 5800, size=3): + trace[0, start : start + rng.integers(5, 400)] = rng.uniform(0.0, 1.0) + probabilities = np.concatenate([probabilities, synthetic]) + port = EQTransformer() + tensor = torch.from_numpy(probabilities) + picks_all = port.extract_picks(tensor, *thresholds, all_events=True) + picks_first = port.extract_picks(tensor, *thresholds) + detections = port.extract_detections(tensor, *thresholds) + n_events = 0 + for trace, all_picks, first_picks, events in zip(probabilities, picks_all, picks_first, detections): + matches = _official_matches(utils, trace, thresholds) + n_events += len(matches) + assert [(on, off) for on, off, _ in events] == [(int(on), int(match[0])) for on, match in matches.items()] + for (on, off, probability), match in zip(events, matches.values()): + assert probability == pytest.approx(float(match[1]), abs=1e-3) + expected_p = [float(m[3]) for m in matches.values() if m[3] is not None] + expected_s = [float(m[6]) for m in matches.values() if m[6] is not None] + assert [p for p, _ in all_picks["P"]] == expected_p + assert [s for s, _ in all_picks["S"]] == expected_s + assert [prob for _, prob in all_picks["P"]] == pytest.approx([float(m[4]) for m in matches.values() if m[3] is not None]) + first = list(matches.values())[:1] + assert [p for p, _ in first_picks["P"]] == [float(m[3]) for m in first if m[3] is not None] + assert [s for s, _ in first_picks["S"]] == [float(m[6]) for m in first if m[6] is not None] + assert n_events > 50 + + +def test_port_picks_on_stead_samples_equal_official_pipeline(): + """End to end: raw STEAD traces -> annotate -> extract_picks equals Keras outputs -> official picker.""" + utils = _official_utils() + keras_model = _keras("original") + raw, normalised, arrivals = _stead_samples(100) + expected = _keras_outputs(keras_model, normalised) + port = _port("original") + with torch.no_grad(): + annotations = port.annotate(torch.from_numpy(raw).transpose(1, 2)) + picks = port.extract_picks(annotations) + residuals = [] + for trace_picks, trace, (p_true, s_true) in zip(picks, expected, arrivals): + matches = list(_official_matches(utils, trace, (0.2, 0.1, 0.1)).values())[:1] + assert [p for p, _ in trace_picks["P"]] == [float(m[3]) for m in matches if m[3] is not None] + assert [s for s, _ in trace_picks["S"]] == [float(m[6]) for m in matches if m[6] is not None] + if trace_picks["P"]: + residuals.append(trace_picks["P"][0][0] - p_true) + # The paper model picks these (training-set) traces well: most P picks within 0.1 s. + assert np.mean(np.abs(residuals) <= 10) > 0.9 + + +def _keras_initialised(variant: str): + tf = _tf() + tf.random.set_seed(0) + loaded = _CACHE.get(("keras", variant, False), (None, None))[1] + if loaded is None: + _keras(variant) + loaded = _CACHE[("keras", variant, False)][1] + return tf.keras.Model.from_config(loaded.get_config(), custom_objects=_custom_objects()) + + +@pytest.mark.parametrize("variant", sorted(MODELS)) +def test_initialisation_matches_keras_distributions(variant): + """Same initialisers as Keras (random generators differ, so distributions are compared).""" + fresh = _keras_initialised(variant) + keras_weights = {} + for layer in fresh.layers: + for weight in layer.weights: + name = weight.name.split(":")[0] + short = name[len(layer.name) + 1 :] if name.startswith(layer.name + "/") else name + keras_weights[(layer.name, short)] = weight.numpy() + torch.manual_seed(0) + port = EQTransformer(variant=variant) + state = port.state_dict() + for key, (layer, name) in keras_weight_map(port.lstm_blocks).items(): + if (layer, name) not in keras_weights: + # TF 2.11 names LSTM cell weights ".../lstm_cell_N/kernel"; match by suffix. + candidates = [k for k in keras_weights if k[0] == layer and k[1].split("/")[-1] == name.split("/")[-1] + and (("forward" in k[1]) == ("forward" in name)) and (("backward" in k[1]) == ("backward" in name))] + assert len(candidates) == 1, (key, layer, name) + expected = keras_weights[candidates[0]] + else: + expected = keras_weights[(layer, name)] + actual = state[key].double().numpy() + if expected.ndim == 3: + expected = expected.transpose(2, 1, 0) + assert actual.shape == expected.shape, key + if np.unique(expected).size <= 2: # constants: zeros / ones, LSTM bias with unit forget bias + np.testing.assert_array_equal(actual, expected, err_msg=key) + continue + if name.endswith("recurrent_kernel"): # orthogonal: orthonormal rows on both sides + np.testing.assert_allclose(actual @ actual.T, np.eye(actual.shape[0]), atol=1e-5, err_msg=key) + np.testing.assert_allclose(expected @ expected.T, np.eye(expected.shape[0]), atol=1e-5, err_msg=key) + continue + # Same support (glorot_uniform bound, or glorot_normal truncated at two standard deviations) + # on both sides, and the same spread. + keras_shape = state[key].shape if actual.ndim != 3 else expected.transpose(2, 1, 0).shape + if len(keras_shape) == 3: + fan_in, fan_out = keras_shape[0] * keras_shape[1], keras_shape[0] * keras_shape[2] + else: + fan_in, fan_out = keras_shape + if key.rsplit(".", 1)[-1] in ("Wt", "Wx", "Wa", "W1", "W2"): + bound = 2.0 * math.sqrt(2.0 / (fan_in + fan_out)) / 0.87962566103423978 + else: + bound = math.sqrt(6.0 / (fan_in + fan_out)) + assert np.abs(actual).max() <= bound + 1e-6 and np.abs(expected).max() <= bound + 1e-6, key + assert np.abs(actual).max() > 0.5 * bound, key + if expected.size >= 100: + assert actual.std() == pytest.approx(expected.std(), rel=0.2), key + assert math.isclose(port.transformer_d0.norm1.epsilon, 1e-14, rel_tol=1e-12) diff --git a/tests/oracle/test_firecastnet_oracle.py b/tests/oracle/test_firecastnet_oracle.py new file mode 100644 index 00000000..901097bc --- /dev/null +++ b/tests/oracle/test_firecastnet_oracle.py @@ -0,0 +1,275 @@ +"""FireCastNet checked against the official SeasFire/firecastnet code (PyTorch + Lightning + DGL). + +The reference is pinned in repos.yaml and needs the packages of requirements-firecastnet.txt +(DGL 2.4 with CPU torch 2.4); the Oracle workflow runs this file in its own job. Checks: + +- the generated icospheres equal the official ``icospheres/*.json.gz`` files bit for bit; +- the multi-mesh, grid->mesh and mesh->grid graphs equal those of the official ``GraphBuilder`` + (same edge order, bitwise-equal edge and node features), for the global icosphere mesh and a LAM mesh; +- a small global configuration: same seeded initial weights and parameter names, same outputs and + gradients; and the other supported options (mean aggregation, deeper MLPs, no static channels, no + cube LayerNorm, several output channels); +- the official global (ts24, h1) classification and regression checkpoints and the AUST local-area + checkpoint (Hugging Face d-michail/firecastnet-artifacts, Apache-2.0) load with ``strict=True`` + and give the same outputs as the official model on the full 720 x 1440 grid. + +The official LightningModule reads a SeasFire zarr cube at construction (GFED regions, land-sea +mask); a two-cell stand-in cube is written for it, with the land-sea filter and GFED loss weights +off. Neither affects the network output. +""" + +from __future__ import annotations + +import importlib.util +import os +import re + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, missing, oracle_asset, oracle_repo +from pyhazards.models.firecastnet import FireCastNet, load_official_checkpoint +from pyhazards.models.firecastnet_graph import build_graph, icospheres, latlon_grid, load_icospheres + +GLOBAL_PARAMETERS = 9_087_568 +SMALL_GLOBAL = dict(sp_res=1.25, max_lat=89.375, min_lat=-89.375, max_lon=179.375, min_lon=-179.375) +SMALL_GLOBAL_EMBED = dict( + embed_cube_sp_res=5.0, embed_cube_max_lat=87.5, embed_cube_min_lat=-87.5, embed_cube_max_lon=177.5, embed_cube_min_lon=-177.5 +) + + +def _require_reference_packages() -> None: + for package in ("dgl", "lightning", "sklearn", "einops", "zarr", "torchmetrics"): + if importlib.util.find_spec(package) is None: + missing(f"{package} is not installed; pip install -r tests/oracle/requirements-firecastnet.txt") + os.environ.setdefault("DGLBACKEND", "pytorch") # otherwise DGL writes ~/.dgl/config.json + + +def _official(module: str): + repo = oracle_repo("firecastnet") + _require_reference_packages() + return repo, import_from(repo, f"seasfire.{module}") + + +def _stand_in_cube(tmp_path) -> str: + import xarray as xr + + path = tmp_path / "cube.zarr" + xr.Dataset({"gfed_region": (("latitude", "longitude"), np.zeros((2, 2), dtype=np.float32))}).to_zarr(path, consolidated=False) + return str(path) + + +def _official_model(tmp_path, **hparams): + repo, lit = _official("firecastnet_lit") + hparams["icospheres_graph_path"] = str(repo / hparams["icospheres_graph_path"]) + hparams.update( + cube_path=_stand_in_cube(tmp_path), + lsm_filter_enable=False, + gfed_region_enable_loss_weighting=False, + display_model_example=False, + ) + return lit.FireCastNetLit(**hparams) + + +def _official_logits(reference, x: torch.Tensor) -> torch.Tensor: + """Official forward for PyHazards input (B=1, T, C, H, W); the reference takes (1, C, T, H, W).""" + prepared, _, _ = reference._prepare_data(x.transpose(1, 2).contiguous(), None, None) + return reference(prepared) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor, **tol) -> None: + torch.testing.assert_close(actual, expected, **{"rtol": 1e-5, "atol": 1e-6, **tol}) + + +def test_icospheres_match_official_assets(): + repo = oracle_repo("firecastnet") + files = sorted((repo / "icospheres").glob("icospheres_*.json.gz")) + assert len(files) == 9 + for path in files: + levels = [int(level) for level in re.findall(r"\d+", path.name)] + official = load_icospheres(path) + generated = icospheres(levels) + assert sorted(official) == sorted(generated), path.name + for key, value in official.items(): + assert np.array_equal(generated[key], value), (path.name, key) + + +def _assert_graph_equals_builder(builder, graph) -> None: + for name, dgl_graph in ( + ("mesh", builder.create_mesh_graph()), + ("g2m", builder.create_g2m_graph()), + ("m2g", builder.create_m2g_graph()), + ): + src, dst = dgl_graph.edges() + assert torch.equal(getattr(graph, f"{name}_src"), src.long()), name + assert torch.equal(getattr(graph, f"{name}_dst"), dst.long()), name + assert torch.equal(getattr(graph, f"{name}_edata"), dgl_graph.edata["x"]), name + if name == "mesh": + assert torch.equal(graph.mesh_ndata, dgl_graph.ndata["x"]) + assert graph.num_mesh_nodes == dgl_graph.num_nodes() + + +def test_global_graph_matches_official_graph_builder(): + repo, graph_builder = _official("backbones.graphcast.graph_builder") + latitudes, longitudes = latlon_grid(1.0, 89.5, -89.5, 179.5, -179.5) + grid = torch.stack(torch.meshgrid(latitudes, longitudes, indexing="ij"), dim=-1) + builder = graph_builder.GraphBuilder(str(repo / "icospheres" / "icospheres_0_1_2_3_4_5_6.json.gz"), grid) + graph = build_graph(latitudes, longitudes, icospheres(range(7))) + assert (graph.num_grid_nodes, graph.num_mesh_nodes) == (64_800, 40_962) + assert (graph.mesh_src.numel(), graph.g2m_src.numel(), graph.m2g_src.numel()) == (327_660, 100_160, 64_800) + _assert_graph_equals_builder(builder, graph) + + +def test_lam_graph_matches_official_graph_builder(): + repo, graph_builder = _official("backbones.graphcast.graph_builder") + mesh = repo / "icospheres-lam" / "icospheres" / "icosphere_s3_AUST_6u.json.gz" + latitudes, longitudes = latlon_grid(1.0, 89.5, -89.5, 179.5, -179.5) + grid = torch.stack(torch.meshgrid(latitudes, longitudes, indexing="ij"), dim=-1) + graph = build_graph(latitudes, longitudes, load_icospheres(mesh)) + assert graph.num_mesh_nodes == 2002 + _assert_graph_equals_builder(graph_builder.GraphBuilder(str(mesh), grid), graph) + + +def test_small_global_configuration_matches_reference(tmp_path): + torch.manual_seed(0) + reference = _official_model( + tmp_path, + icospheres_graph_path="icospheres/icospheres_0_1_2_3.json.gz", + embed_cube=True, + embed_cube_time=6, + embed_cube_dim=64, + timeseries_len=6, + input_dim_grid_nodes=11, + output_dim_grid_nodes=16, + processor_layers=12, + hidden_dim=64, + **SMALL_GLOBAL, + **SMALL_GLOBAL_EMBED, + ) + torch.manual_seed(0) + port = FireCastNet(in_channels=11, timeseries_len=6, mesh_levels=(0, 1, 2, 3), **SMALL_GLOBAL) + + ref_state, port_state = reference._net.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + assert [key[len("_net."):] for key in reference.state_dict()] == list(port_state) + assert _n_params(port) == _n_params(reference._net) == 866_896 + + torch.manual_seed(1) + x = torch.randn(1, 6, 11, 144, 288) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), _official_logits(reference, x)) + + # No dropout or batch norm: train mode gives the same outputs; gradients must agree too. + reference.train() + port.train() + target = (torch.rand(1, 1, 144, 288) > 0.9).float() + loss_fn = torch.nn.BCEWithLogitsLoss() + ref_out = _official_logits(reference, x) + out = port(x) + _assert_close(out, ref_out) + loss_fn(ref_out, target).backward() + loss_fn(out, target).backward() + ref_params = dict(reference._net.named_parameters()) + for name, param in port.named_parameters(): + assert param.grad is not None and ref_params[name].grad is not None, name + _assert_close(param.grad, ref_params[name].grad, rtol=1e-4, atol=1e-7) + + +def test_configuration_options_match_reference(tmp_path): + """Mean aggregation, two hidden layers, no static channels, no cube LayerNorm, two output channels.""" + options = dict(aggregation="mean", hidden_layers=2, hidden_dim=32, processor_layers=3, output_dim_grid_nodes=32) + torch.manual_seed(0) + reference = _official_model( + tmp_path, + icospheres_graph_path="icospheres/icospheres_0_1_2_3.json.gz", + lat_lon_static_data=False, + embed_cube=True, + embed_cube_time=3, + embed_cube_dim=16, + embed_cube_layer_norm=False, + timeseries_len=3, + input_dim_grid_nodes=5, + **options, + **SMALL_GLOBAL, + **SMALL_GLOBAL_EMBED, + ) + torch.manual_seed(0) + port = FireCastNet( + in_channels=5, timeseries_len=3, mesh_levels=(0, 1, 2, 3), lat_lon_static_data=False, embed_cube_dim=16, + embed_cube_layer_norm=False, **options, **SMALL_GLOBAL, + ) + ref_state, port_state = reference._net.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + torch.manual_seed(1) + x = torch.randn(1, 3, 5, 144, 288) + reference.eval() + port.eval() + with torch.no_grad(): + out = port(x) + assert out.shape == (1, 2, 144, 288) + _assert_close(out, _official_logits(reference, x)) + + +def _checkpoint_hparams(path) -> dict: + return dict(torch.load(path, map_location="cpu", weights_only=True)["hyper_parameters"]) + + +def _compare_checkpoint(tmp_path, checkpoint, icospheres_graph_path=None) -> None: + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + reference = _official_model(tmp_path, **dict(state["hyper_parameters"])) + reference.load_state_dict({k: v for k, v in state["state_dict"].items() if k.startswith("_net.")}, strict=True) + port = load_official_checkpoint(checkpoint, icospheres_graph_path=icospheres_graph_path) + assert list(port.state_dict()) == list(reference._net.state_dict()) + assert _n_params(port) == GLOBAL_PARAMETERS + del state + + torch.manual_seed(0) + x = torch.randn(1, 24, 11, 720, 1440) + reference.eval() + port.eval() + with torch.no_grad(): + logits = port(x) + _assert_close(logits, _official_logits(reference, x)) + # predict_step: sigmoid for classification, raw values for regression + predictions = reference.predict_step({"x": x.transpose(1, 2).contiguous()}) + expected = logits[:, 0] if reference._task == "regression" else torch.sigmoid(logits[:, 0]) + _assert_close(expected, predictions) + + +@pytest.mark.parametrize( + "asset, filename, task", + [ + ("firecastnet_global_cls_ts24_h1", "firecastnet-cls-ts24-h1.ckpt", "classification"), + ("firecastnet_global_regr_ts24_h1", "firecastnet-regr-ts24-h1.ckpt", "regression"), + ], +) +def test_official_global_checkpoint_matches_reference(tmp_path, asset, filename, task): + _official("firecastnet_lit") + checkpoint = oracle_asset(asset) / filename + hparams = _checkpoint_hparams(checkpoint) + assert hparams["icospheres_graph_path"] == "icospheres/icospheres_0_1_2_3_4_5_6.json.gz" + assert hparams.get("task", "classification") == task + assert (hparams["timeseries_len"], hparams["embed_cube_time"], hparams["processor_layers"], hparams["hidden_dim"]) == (24, 24, 12, 64) + _compare_checkpoint(tmp_path, checkpoint) + + +def test_official_lam_checkpoint_matches_reference(tmp_path): + repo, _ = _official("firecastnet_lit") + checkpoint = oracle_asset("firecastnet_lam_aust_cls_ts24_h1") / "firecastnet-cls-AUST-ts24-h1.ckpt" + mesh = _checkpoint_hparams(checkpoint)["icospheres_graph_path"] + assert mesh == "icospheres-lam/icospheres/icosphere_s3_AUST_6u.json.gz" + with pytest.raises(ValueError, match="icospheres_graph_path"): + load_official_checkpoint(checkpoint) + _compare_checkpoint(tmp_path, checkpoint, icospheres_graph_path=repo / mesh) diff --git a/tests/oracle/test_forecasts_weather_oracle.py b/tests/oracle/test_forecasts_weather_oracle.py new file mode 100644 index 00000000..a0a55695 --- /dev/null +++ b/tests/oracle/test_forecasts_weather_oracle.py @@ -0,0 +1,81 @@ +"""Forecast sources of pyhazards.forecasts against the real packages and stores they wrap. + +1. ``run_earth2studio_forecast`` drives NVIDIA earth2studio 0.19.0 (``tests/oracle/requirements-weather.txt``) + exactly like ``earth2studio.run.deterministic``: earth2studio's own ``Persistence`` prognostic model + (the identity model earth2studio uses in its tests; no weights) is started from a data source that + serves synthetic cyclone fields. The returned fields must equal the source at every lead time, and + the TempestExtremes-rule tracker must find the cyclones at their initial positions. +2. ``read_weatherbench2_forecast`` reads one small slice (one lead time of mean sea-level pressure) of + the public WeatherBench 2 Pangu-Weather and GraphCast stores over the network: the MSLP minimum near + Typhoon Kong-rey 6 h after 2018-09-30 00 UTC (the case of Pangu-Weather's Fig. 1) must lie within + 100 km of the IBTrACS position (14.4 N, 138.0 E, NCEI IBTrACS v04r01). +""" + +from __future__ import annotations + +import ast +from collections import OrderedDict + +import numpy as np +import pandas as pd +import pytest +import xarray as xr + +from oracle_utils import oracle_package + +from pyhazards.forecasts import great_circle_km, read_weatherbench2_forecast, run_earth2studio_forecast, tempest_tracks +from pyhazards.forecasts.synthetic import SyntheticVortex, synthetic_cyclone_fields + +E2S = {"msl": "msl", "u10": "u10m", "v10": "v10m", "z300": "z300", "z500": "z500"} + + +class _SyntheticSource: + """earth2studio DataSource protocol: ``__call__(time, variable) -> DataArray[time, variable, lat, lon]``.""" + + def __init__(self, fields): + self.fields = fields + + def __call__(self, time, variable): + from earth2studio.data.utils import prep_data_inputs + + time, variable = prep_data_inputs(time, variable) + inverse = {v: k for k, v in E2S.items()} + data = np.stack([np.stack([self.fields[inverse[v]].values[0] for v in variable]) for _ in time]) + coords = {"time": time, "variable": variable, "lat": self.fields["lat"].values, "lon": self.fields["lon"].values} + return xr.DataArray(data, dims=list(coords), coords=coords) + + +def test_earth2studio_runner_with_persistence(): + oracle_package("earth2studio", "0.19.0", "requirements-weather.txt") + from earth2studio.models.px import Persistence + + vortices = [SyntheticVortex(15.0, 140.0), SyntheticVortex(-20.0, 80.0)] + fields = synthetic_cyclone_fields(vortices, [0], resolution=1.0) + domain = OrderedDict({"lat": fields["lat"].values, "lon": fields["lon"].values}) + model = Persistence(list(E2S.values()), domain) + out = run_earth2studio_forecast(model, _SyntheticSource(fields), "2020-01-01T00", lead_hours=24, variables=tuple(E2S)) + assert list(out.data_vars) == list(E2S) and out.sizes["time"] == 5 + assert pd.to_datetime(out["time"].values)[-1] == pd.Timestamp("2020-01-02T00") + for name in E2S: + for t in range(out.sizes["time"]): + np.testing.assert_array_equal(out[name].values[t], fields[name].values[0].astype(np.float32)) + tracks = tempest_tracks({k: out[k].values for k in E2S}, out["lat"].values, out["lon"].values, out["time"].values) + assert tracks["track_id"].nunique() == 2 + starts = ast.literal_eval(fields.attrs["tracks"]) + for _, track in tracks.groupby("track_id"): + assert min(float(great_circle_km(track["lat"].iloc[0], track["lon"].iloc[0], s[0][0], s[0][1])) for s in starts) < 80.0 + assert track[["lat", "lon"]].nunique().max() == 1 # persistence: the storm does not move + with pytest.raises(KeyError, match="does not predict"): + run_earth2studio_forecast(model, _SyntheticSource(fields), "2020-01-01T00", lead_hours=6, variables=("t2m",)) + + +@pytest.mark.parametrize("model", ["pangu", "graphcast"]) +def test_weatherbench2_slice_locates_kong_rey(model): + oracle_package("zarr", "3.4.0", "requirements-weather.txt") + oracle_package("gcsfs", "2026.10.0", "requirements-weather.txt") + ds = read_weatherbench2_forecast(model, "2018-09-30T00", variables=("msl",), lead_hours=[6], lat_bounds=(5, 25), lon_bounds=(128, 148)) + msl = ds["msl"].values[0] + j, i = np.unravel_index(np.nanargmin(msl), msl.shape) + distance = float(great_circle_km(ds["lat"].values[j], ds["lon"].values[i], 14.4, 138.0)) + assert distance < 100.0, (model, ds["lat"].values[j], ds["lon"].values[i]) + assert 90000 < msl.min() < 100500 diff --git a/tests/oracle/test_forefire_oracle.py b/tests/oracle/test_forefire_oracle.py new file mode 100644 index 00000000..6fbe3273 --- /dev/null +++ b/tests/oracle/test_forefire_oracle.py @@ -0,0 +1,199 @@ +"""ForeFireSimulator checked against the official ForeFire engine, its reference output and an example. + +ForeFire 2.5.0 (https://github.com/forefireAPI/forefire, GPL-3.0) is installed from its official +wheel (tests/oracle/requirements-forefire.txt) for this test only. The pinned repository supplies the +official inputs; nothing from it is copied into PyHazards. Inputs are parsed from the official files +rather than retyped here. + +1. ``tests/runff`` is ForeFire's own CI regression case (64 km Corsican landscape, Rothermel, three + ignitions, a wind change at t = 1200 s). Fed the case's rasters, parameters (``params.ff``), + ignitions and wind change (``real_case.ff``), the adapter must reproduce the reference + arrival-time map ``ForeFire.0.nc.ref`` within the tolerance of the case's ``compare_nc.py`` + (rtol 1e-5, atol 1e-8), with exactly the same burned cells. The ``.ff`` script schedules the wind + change as an event, hence ``trigger_mode="event"``. +2. ``tests/python/idealizedwind.py`` is run unchanged in a separate process; the adapter run of the + same scenario (``trigger_mode="step"``, the script's own pattern) must give the identical burning + map. +""" + +from __future__ import annotations + +import json +import math +import os +import re +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest + +from oracle_utils import oracle_asset, oracle_package, oracle_repo + +from pyhazards.simulators import ForeFireSimulator + +FOREFIRE_VERSION = "2.5.0" + + +@pytest.fixture(scope="module") +def forefire(): + return oracle_package("pyforefire", FOREFIRE_VERSION, "requirements-forefire.txt", distribution="forefire") + + +def _ff_arguments(text: str, command: str) -> list[str]: + return re.findall(rf"^\s*{command}\[(.*?)\](.*)$", text, flags=re.MULTILINE) + + +def _runff_case(repo: Path): + """Parameters, ignitions, wind change and duration of tests/runff/real_case.ff.""" + case = repo / "tests" / "runff" + params = {} + for argument, _ in _ff_arguments((case / "params.ff").read_text(), "setParameter"): + key, value = argument.split("=", 1) + params[key.strip()] = value.strip() + script = (case / "real_case.ff").read_text() + points = [] + for argument, _ in _ff_arguments(script, "startFire"): + x, y, _z = re.search(r"loc=\(([^)]*)\)", argument).group(1).split(",") + assert re.search(r"t=0\b", argument), argument + points.append((float(x), float(y))) + triggers = [] + for argument, suffix in _ff_arguments(script, "trigger"): + u, v, _w = re.search(r"vel=\(([^)]*)\)", argument).group(1).split(",") + when = float(re.search(r"@t=([0-9.]+)", suffix).group(1)) if suffix.strip() else 0.0 + triggers.append((when, float(u), float(v))) + (step, _), = _ff_arguments(script, "step") + duration = float(step.split("=", 1)[1]) + table = (case / params.pop("fuelsTableFile")).read_text() + model = params.pop("propagationModel") + return model, table, params, points, triggers, duration + + +@pytest.fixture(scope="module") +def runff(forefire): + xr = pytest.importorskip("xarray") + repo = oracle_repo("forefire") + model, table, params, points, triggers, duration = _runff_case(repo) + assert (model, len(points), len(triggers), duration) == ("Rothermel", 3, 1, 2400.0) + data = xr.open_dataset(oracle_asset("forefire_runff_data") / "data.nc") + domain = data["domain"].attrs + fuel = np.asarray(data["fuel"].values[0, 0]) + inputs = dict( + fuel=fuel, + cell_size=(float(domain["Ly"]) / fuel.shape[0], float(domain["Lx"]) / fuel.shape[1]), + duration=duration, + ignition_points=points, + wind_u=np.asarray(data["wind"].values[0], dtype=np.float64), + wind_v=np.asarray(data["wind"].values[1], dtype=np.float64), + wind_triggers=triggers, + altitude=np.asarray(data["altitude"].values[0, 0], dtype=np.float64), + # loadData[] sets ForeFire's flux grid (atmoNX, atmoNY) from the file's nx, ny dimensions. + output_shape=(data.sizes["ny"], data.sizes["nx"]), + origin="lower", # ForeFire landscape files store rows south to north + trigger_mode="event", + ) + reference = xr.open_dataset(oracle_asset("forefire_runff_reference") / "ForeFire.0.nc.ref") + expected = np.asarray(reference["arrival_time_of_front"].values) + return ForeFireSimulator(model, fuels_table=table, parameters=params), inputs, expected + + +def test_runff_reproduces_the_reference_arrival_times(runff): + simulator, inputs, expected = runff + result = simulator.run(**inputs) + native = result.arrival_time_native + assert native.shape == expected.shape == (3200, 3200) + assert result.native_cell_size == (20.0, 20.0) + assert result.engine_version == FOREFIRE_VERSION + # save[] writes -9999 where the front never arrived; the adapter returns inf there. + ours = np.where(np.isinf(native), -9999.0, native) + np.testing.assert_array_equal(ours > -9999, expected > -9999) + assert (expected > -9999).sum() > 900 + np.testing.assert_allclose(ours, expected, rtol=1e-5, atol=1e-8) + + # The output grid is ForeFire's 640 x 640 flux grid: earliest arrival per 5 x 5 burning-map block. + blocks = np.where(expected > -9999, expected, np.inf).reshape(640, 5, 640, 5).min(axis=(1, 3)) + np.testing.assert_allclose(result.arrival_time, blocks, rtol=1e-5, atol=1e-8) + assert result.cell_size == (100.0, 100.0) + np.testing.assert_allclose(result.burned_area(), (expected > -9999).sum() * 400.0) + + +def test_runff_north_up_and_in_process_runs_agree(runff): + simulator, inputs, _ = runff + lower = simulator.run(**inputs) + upper_inputs = dict( + inputs, + fuel=inputs["fuel"][::-1], + altitude=inputs["altitude"][::-1], + wind_u=inputs["wind_u"][:, ::-1], + wind_v=inputs["wind_v"][:, ::-1], + origin="upper", + ) + upper = ForeFireSimulator( + simulator.propagation_model, simulator.fuels_table, simulator.parameters, isolate=False + ).run(**upper_inputs) + np.testing.assert_array_equal(upper.arrival_time_native, lower.arrival_time_native[::-1]) + np.testing.assert_array_equal(upper.arrival_time, lower.arrival_time[::-1]) + + +_IDEALIZED_RUNNER = """ +import json, runpy, sys +import matplotlib +matplotlib.use("Agg") +import numpy as np +g = runpy.run_path(sys.argv[1]) +ff = g["ff"] +np.save("official_arrival.npy", np.array(ff["arrival_time"])) +keys = sys.argv[2].split(",") +json.dump({ + "table": g["VVCoeffTable"](), + "params": {key: ff.getString(key) for key in keys}, + "model": ff.getString("propagationModel"), + "nb_steps_tot": g["nb_steps_tot"], "step_size": g["step_size"], "norm": g["norm"], + "angle_deg": g["angle_deg"], "sim_shape": list(g["sim_shape"]), + "start": [g["startx"], g["starty"]], +}, open("scenario.json", "w")) +""" + +# Parameters idealizedwind.py sets with ff[...] (values are read back from the script's run). +_IDEALIZED_KEYS = ( + "defaultFuelType,spatialIncrement,minimalPropagativeFrontDepth,perimeterResolution," + "initialFrontDepth,relax,smoothing,minSpeed,bmapLayer,windReductionFactor" +) + + +def test_idealized_wind_example_is_reproduced_exactly(forefire, tmp_path): + script = oracle_repo("forefire") / "tests" / "python" / "idealizedwind.py" + env = dict(os.environ, MPLBACKEND="Agg") + subprocess.run( + [sys.executable, "-c", _IDEALIZED_RUNNER, str(script), _IDEALIZED_KEYS], + cwd=tmp_path, env=env, check=True, capture_output=True, text=True, + ) + official = np.load(tmp_path / "official_arrival.npy") + scenario = json.loads((tmp_path / "scenario.json").read_text()) + + width, height = scenario["sim_shape"] + step, norm = float(scenario["step_size"]), float(scenario["norm"]) + triggers = [] + for i in range(scenario["nb_steps_tot"] + 1): # the script triggers, then steps, each iteration + angle = math.radians(i * scenario["angle_deg"]) + triggers.append((i * step, norm * math.cos(angle), norm * math.sin(angle))) + unit_u = np.zeros((2, height, width)) + unit_u[0] = 1.0 + unit_v = np.zeros((2, height, width)) + unit_v[1] = 1.0 + simulator = ForeFireSimulator(scenario["model"], fuels_table=scenario["table"], parameters=scenario["params"]) + result = simulator.run( + np.ones((height, width), dtype=np.int32), + cell_size=1.0, + duration=len(triggers) * step, + ignition_points=[tuple(float(v) for v in scenario["start"])], + wind_u=unit_u, + wind_v=unit_v, + wind_triggers=triggers, + output_shape=(100, 100), # ForeFire's default flux grid (atmoNX = atmoNY = 100), unset by the script + origin="lower", + trigger_mode="step", + ) + assert np.isfinite(official).sum() > 1000 + np.testing.assert_array_equal(result.arrival_time_native, official) diff --git a/tests/oracle/test_google_flood_forecasting_oracle.py b/tests/oracle/test_google_flood_forecasting_oracle.py new file mode 100644 index 00000000..06db6ac8 --- /dev/null +++ b/tests/oracle/test_google_flood_forecasting_oracle.py @@ -0,0 +1,159 @@ +"""google_flood_forecasting against googlehydrology's MeanEmbeddingForecastLSTM and the released FloodHub weights. + +Reference (pinned in repos.yaml): google-research/flood-forecasting @ cdda28d (Apache-2.0), +``googlehydrology/modelzoo/mean_embedding_forecast_lstm.py``, built from the released run configuration +``pretrained-models/google-floodhub-settings-110-epochs/config.yml``. Weights: ``model_epoch110.pt`` of that +run (asset ``floodhub_weights``, sha256-pinned; saved from a ``torch.compile``d model, hence the +``_orig_mod.`` prefix). googlehydrology needs Python >= 3.10 and ruamel.yaml, xarray, dask, zarr, +more-itertools (tests/oracle/requirements-flood.txt). +""" + +from __future__ import annotations + +import hashlib +import sys + +import pytest +import torch + +from oracle_utils import MANIFEST, oracle_asset, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.google_flood_forecasting import FLOODHUB_CONFIG, FLOODHUB_WEIGHTS + +RUN = "pretrained-models/google-floodhub-settings-110-epochs" + + +@pytest.fixture(scope="module") +def gh(): + root = oracle_repo("flood-forecasting") + for package in ("ruamel.yaml", "zarr", "dask", "more_itertools"): + pytest.importorskip(package) + sys.path.insert(0, str(root)) + try: + from ruamel.yaml import YAML + + from googlehydrology.modelzoo.mean_embedding_forecast_lstm import MeanEmbeddingForecastLSTM + from googlehydrology.utils.config import Config + + yield {"root": root, "YAML": YAML, "Config": Config, "Model": MeanEmbeddingForecastLSTM} + finally: + sys.path.remove(str(root)) + for name in [m for m in sys.modules if m.split(".")[0] == "googlehydrology"]: + del sys.modules[name] + + +def _release_config(gh, **overrides): + run = gh["root"] / RUN + raw = gh["YAML"](typ="safe").load((run / "config.yml").read_text()) + raw.update({"run_dir": str(run), "img_log_dir": None, "device": "cpu", "compile": False}) + raw.update(overrides) + return gh["Config"](raw) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _released_state() -> dict: + path = oracle_asset("floodhub_weights") / "model_epoch110.pt" + digest = hashlib.sha256(path.read_bytes()).hexdigest() + assert digest == MANIFEST["assets"]["floodhub_weights"]["sha256"] == FLOODHUB_WEIGHTS["sha256"] + return path, torch.load(path, map_location="cpu", weights_only=True) + + +def _inputs(batch: int = 3): + """Random inputs in googlehydrology's dict layout, with missing products and fully missing steps.""" + torch.manual_seed(11) + hindcast_names = [f for g in FLOODHUB_CONFIG["hindcast_inputs"].values() for f in g] + forecast_names = [f for g in FLOODHUB_CONFIG["forecast_inputs"].values() for f in g] + total = FLOODHUB_CONFIG["seq_length"] + FLOODHUB_CONFIG["lead_time"] + hindcast = {name: torch.randn(batch, FLOODHUB_CONFIG["seq_length"], 1) for name in hindcast_names} + forecast = {name: torch.randn(batch, total, 1) for name in forecast_names} + hindcast["imerg_precipitation"][1] = float("nan") # one product missing for a whole sample + hindcast["cpc_precipitation"][0, 50:80] = float("nan") # a gap in one product + for name in forecast_names: # every product missing on one day: outputs NaN from that step on + forecast[name][2, 300] = float("nan") + x_s = torch.randn(batch, len(FLOODHUB_CONFIG["static_attributes"])) + return {"x_s": x_s, "x_d_hindcast": hindcast, "x_d_forecast": forecast} + + +def _tensor_layout(data, model): + return { + "x_s": data["x_s"], + "x_d_hindcast": torch.cat([data["x_d_hindcast"][f] for f in model.hindcast_features], dim=-1), + "x_d_forecast": torch.cat([data["x_d_forecast"][f] for f in model.forecast_features], dim=-1), + } + + +def _assert_outputs(actual, expected): + assert set(actual) == {"mu", "b", "tau", "pi"} <= set(expected) + for key in actual: + torch.testing.assert_close(actual[key], expected[key], rtol=1e-5, atol=1e-6, equal_nan=True) + + +def test_parameter_count_and_seeded_initialisation(gh): + cfg = _release_config(gh) + for seed in (0, 449153): + torch.manual_seed(seed) + reference = gh["Model"](cfg) + torch.manual_seed(seed) + port = build_model("google_flood_forecasting", task="regression") + assert _n_params(reference) == _n_params(port) == 3_402_832 + _assert_same_state(reference, port) + + +def test_released_floodhub_weights(gh): + path, state = _released_state() + assert all(key.startswith("_orig_mod.") for key in state) + reference = gh["Model"](_release_config(gh)) + reference.load_state_dict({key[len("_orig_mod."):]: value for key, value in state.items()}, strict=True) + port = build_model("google_flood_forecasting", task="regression", weights_path=path) + _assert_same_state(reference, port) + + data = _inputs() + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(data) + _assert_outputs(port(data), expected) + _assert_outputs(port(_tensor_layout(data, port)), expected) + torch.testing.assert_close(port.point_prediction(port(data)), reference.point_prediction(expected), equal_nan=True) + assert torch.isnan(expected["mu"][2, 300:]).all() and not torch.isnan(expected["mu"][2, :300]).any() + assert not torch.isnan(expected["mu"][:2]).any() # a missing product is skipped by the masked mean + + reference.train() + port.train() + torch.manual_seed(3) + expected = reference(data) + torch.manual_seed(3) + _assert_outputs(port(data), expected) + + +def test_streamflow_layout_matches_reference_configuration(gh): + """config='streamflow' (PyHazards layout) equals googlehydrology with one shared group and lead_time 0.""" + features = [f"x_d_{i}" for i in range(5)] + statics = [f"static_{i}" for i in range(27)] + cfg = _release_config( + gh, hindcast_inputs={"x_d": features}, forecast_inputs={"x_d": features}, static_attributes=statics, + lead_time=0, forecast_overlap=30, seq_length=30, hidden_size=32, + ) + torch.manual_seed(4) + reference = gh["Model"](cfg) + torch.manual_seed(4) + port = build_model("google_flood_forecasting", task="regression", config="streamflow", seq_length=30, hidden_size=32) + _assert_same_state(reference, port) + torch.manual_seed(0) + x_d, x_s = torch.randn(4, 30, 5), torch.randn(4, 27) + as_dict = {name: x_d[..., i: i + 1] for i, name in enumerate(features)} + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference({"x_s": x_s, "x_d_hindcast": as_dict, "x_d_forecast": as_dict}) + _assert_outputs(port({"x_d": x_d, "x_s": x_s}), expected) diff --git a/tests/oracle/test_gpd_oracle.py b/tests/oracle/test_gpd_oracle.py new file mode 100644 index 00000000..ddf1abdc --- /dev/null +++ b/tests/oracle/test_gpd_oracle.py @@ -0,0 +1,293 @@ +"""GPD checked against the official Keras model and ``gpd_predict.py`` (interseismic/generalized-phase-detection). + +Reference: interseismic/generalized-phase-detection at ea81ef1 (pinned in repos.yaml, MIT): the network in +``model_pol.json`` with the released weights ``model_pol_best.hdf5``, run on TensorFlow 2.11 / tf.keras +(requirements-earthquake.txt). ``model_pol.json`` wraps the network in Keras' multi-GPU ``Lambda`` layers, +whose functions are stored as Python 3.6 bytecode and cannot be deserialised on Python 3.10; the oracle is +therefore built from the JSON's inner ``Sequential`` config (the network itself, unchanged) and the +weights are copied in by layer name from ``model_pol_best.hdf5``. SeisBench 0.12.6 (GPL-3.0, oracle only) +with its "original" conversion of the same weights is a second reference. + +Checks: parameter count (1,741,003 trainable); Keras-style initialisation bounds; the weight file loads +strictly; eval-mode and train-mode outputs equal Keras on random windows and on real windows of the shipped +Anza 2016 data; BatchNorm moving statistics follow Keras 2.2.2's update; outputs equal SeisBench's GPD; and the ``gpd_predict.py`` pipeline (ObsPy filtering, sliding +windows, ``trigger_onset`` picks) gives identical picks with the official Keras model and with the port on +18 minutes of the Anza aftershock sequence, which are compared with the shipped ``anza2016.out``. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest +import torch + +from oracle_utils import load_definitions, oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.gpd import GPD, load_gpd_keras_weights + +ATOL = 1e-6 # float32 softmax probabilities; the remaining differences are summation-order rounding + + +def _repo(): + return oracle_repo("generalized-phase-detection") + + +def _keras_model(load_weights: bool = True): + tf = oracle_package("tensorflow", "2.11.0", "requirements-earthquake.txt") + import h5py + + root = _repo() + config = json.loads((root / "model_pol.json").read_text()) + assert config["keras_version"] == "2.2.2" + wrapper_layers = [layer["class_name"] for layer in config["config"]["layers"]] + assert wrapper_layers == ["InputLayer", "Lambda", "Lambda", "Lambda", "Sequential", "Concatenate"] + inner = next(layer for layer in config["config"]["layers"] if layer["class_name"] == "Sequential")["config"] + model = tf.keras.Sequential.from_config(inner) + if load_weights: + with h5py.File(root / "model_pol_best.hdf5", "r") as handle: + group = handle["model_weights/sequential_1"] + stored = {name.decode() for name in group.attrs["weight_names"]} + used = set() + for layer in model.layers: + values = [] + for weight in layer.weights: + key = f"{layer.name}_1/{weight.name.split('/')[-1]}" + values.append(np.asarray(group[key])) + used.add(key) + if values: + layer.set_weights(values) + assert used == stored + return model + + +def _port(pretrained: bool = True) -> GPD: + model = GPD() + if pretrained: + load_gpd_keras_weights(model, _repo() / "model_pol_best.hdf5") + return model.eval() + + +def _max_normalised(windows: np.ndarray) -> np.ndarray: + """``gpd_predict.py``: windows (n, 400, 3) divided by their max |amplitude|.""" + return windows / np.max(np.abs(windows), axis=(1, 2))[:, None, None] + + +def _anza_stream(start_offset_s: float, duration_s: float, filtered: bool = True): + """The official pre-processing of ``gpd_predict.py`` on a slice of the Anza day (N, E, Z files).""" + obspy = oracle_package("obspy", "1.5.1", "requirements-earthquake.txt") + root = _repo() + files = (root / "anza2016.in").read_text().split() + assert [name.split(".")[-2] for name in files] == ["HHN", "HHE", "HHZ"] + stream = obspy.Stream() + for name in files: + stream += obspy.read(str(root / name)) + latest_start = np.max([trace.stats.starttime for trace in stream]) + earliest_stop = np.min([trace.stats.endtime for trace in stream]) + stream.trim(latest_start, earliest_stop) + start = latest_start + start_offset_s + stream.trim(start, start + duration_s - stream[0].stats.delta) + stream.detrend(type="linear") + if filtered: + stream.filter(type="bandpass", freqmin=3.0, freqmax=20.0) + return stream + + +def _anza_windows(count: int = 64) -> np.ndarray: + stream = _anza_stream(8 * 3600 + 4 * 60, 120.0) + data = np.stack([trace.data for trace in stream], axis=-1) # (samples, 3) in N, E, Z order + starts = np.linspace(0, data.shape[0] - 400, count).astype(int) + return _max_normalised(np.stack([data[s : s + 400] for s in starts])).astype(np.float32) + + +def test_parameter_count_and_initialisation_match_keras(): + keras_model = _keras_model(load_weights=False) + trainable = sum(int(np.prod(weight.shape)) for weight in keras_model.trainable_weights) + port = build_model("gpd", task="classification") + assert sum(p.numel() for p in port.parameters()) == trainable == 1_741_003 + port_layers = dict(port.named_modules()) + for layer in keras_model.layers: + if not layer.weights: + continue + module = port_layers[layer.name] + for weight in layer.weights: + kind = weight.name.split("/")[-1].split(":")[0] + reference = weight.numpy() + if kind == "kernel": + ours = module.weight.detach().numpy() + fan_in, fan_out = (np.prod(reference.shape[:-1]), reference.shape[-1]) + limit = np.sqrt(6.0 / (fan_in + fan_out)) # glorot_uniform (VarianceScaling fan_avg uniform) + assert np.abs(reference).max() <= limit and np.abs(ours).max() <= limit + assert abs(ours.std() - reference.std()) < 0.1 * limit + else: + target = {"bias": "bias", "gamma": "weight", "beta": "bias", "moving_mean": "running_mean", "moving_variance": "running_var"}[kind] + np.testing.assert_array_equal(getattr(module, target).detach().numpy(), reference) + + +def test_released_weights_match_keras_in_eval_and_train_mode(): + rng = np.random.default_rng(0) + random_windows = _max_normalised(rng.standard_normal((32, 400, 3))).astype(np.float32) + for windows in (random_windows, _anza_windows()): + # Fresh models for every comparison: a train-mode call updates the moving statistics. + keras_model, port = _keras_model(), _port() + expected = keras_model(windows, training=False).numpy() + with torch.no_grad(): + actual = port(torch.from_numpy(windows).permute(0, 2, 1)).numpy() + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=ATOL) + + # Train mode: BatchNorm normalises with batch statistics (GPD has no dropout). + expected_train = keras_model(windows, training=True).numpy() + port.train() + with torch.no_grad(): + actual_train = port(torch.from_numpy(windows).permute(0, 2, 1)).numpy() + # Batch statistics are float32 reductions over thousands of values; TensorFlow's multithreaded + # reduction order varies between runs (observed differences up to 3e-6), hence atol 1e-5. + np.testing.assert_allclose(actual_train, expected_train, rtol=1e-5, atol=1e-5) + + +def test_batchnorm_statistics_follow_keras_2_2_2(): + """Moving statistics of a training step, as Keras 2.2.2 (the version that trained GPD) updates them. + + ``keras/layers/normalization.py`` of Keras 2.2.2 does, after ``tf.nn.moments``:: + + variance *= sample_size / (sample_size - (1.0 + self.epsilon)) + K.moving_average_update(self.moving_variance, variance, self.momentum) + + and its TensorFlow backend's ``moving_average_update`` is ``assign_moving_average(x, value, momentum, + zero_debias=True)``. TensorFlow 2.11's tf.keras no longer does either, so the reference here is that + update built from the same TensorFlow functions. + """ + tf = oracle_package("tensorflow", "2.11.0", "requirements-earthquake.txt") + from tensorflow.python.training import moving_averages + + port = _port() + port.train() + rng = np.random.default_rng(1) + batches = [_max_normalised(rng.standard_normal((8, 400, 3))).astype(np.float32) for _ in range(3)] + # Inputs of batch_normalization_1 (after conv1d_1, 3-D) and batch_normalization_5 (after dense_1, 2-D). + captured = {name: [] for name in ("batch_normalization_1", "batch_normalization_5")} + hooks = [ + getattr(port, name).register_forward_pre_hook(lambda module, args, name=name: captured[name].append(args[0].detach().numpy())) + for name in captured + ] + initial = {name: (getattr(port, name).running_mean.clone(), getattr(port, name).running_var.clone()) for name in captured} + for batch in batches: + port(torch.from_numpy(batch).permute(0, 2, 1)) + for hook in hooks: + hook.remove() + + graph = tf.Graph() + with graph.as_default(): + for name, inputs in captured.items(): + mean0, var0 = initial[name] + moving_mean = tf.compat.v1.Variable(mean0.numpy(), name=f"{name}_mean") + moving_var = tf.compat.v1.Variable(var0.numpy(), name=f"{name}_var") + feed = tf.compat.v1.placeholder(tf.float32, inputs[0].shape) + axes = [0] if len(inputs[0].shape) == 2 else [0, 2] # PyTorch layout (batch, channels[, samples]) + mean, variance = tf.nn.moments(feed, axes) + sample_size = tf.cast(tf.reduce_prod([tf.shape(feed)[axis] for axis in axes]), tf.float32) + variance *= sample_size / (sample_size - (1.0 + 1e-3)) + updates = [ + moving_averages.assign_moving_average(moving_mean, mean, 0.99, zero_debias=True), + moving_averages.assign_moving_average(moving_var, variance, 0.99, zero_debias=True), + ] + with tf.compat.v1.Session(graph=graph) as session: + session.run(tf.compat.v1.global_variables_initializer()) + for value in inputs: + expected_mean, expected_var = session.run(updates, {feed: value}) + module = getattr(port, name) + np.testing.assert_allclose(module.running_mean.numpy(), expected_mean, rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(module.running_var.numpy(), expected_var, rtol=1e-5, atol=1e-6) + assert int(module.num_batches_tracked) == len(inputs) + + +def test_matches_seisbench_original_gpd(): + oracle_package("seisbench", "0.12.6", "requirements-earthquake.txt") + import seisbench.models as sbm + + reference = sbm.GPD(in_channels=3, classes=3, phases="PSN", original_compatible=True) + state = torch.load(oracle_asset("seisbench_gpd_original") / "original.pt", map_location="cpu", weights_only=True) + reference.load_state_dict(state, strict=True) + reference.eval() + port = _port() + windows = torch.from_numpy(_anza_windows()).permute(0, 2, 1) # N, E, Z + with torch.no_grad(): + expected = reference(windows[:, [2, 0, 1]]) # SeisBench's conversion takes Z, N, E + actual = port(windows) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=ATOL) + # SeisBench's conversion permuted the first convolution's input channels from N, E, Z to Z, N, E. + torch.testing.assert_close(state["conv1.weight"], port.conv1d_1.weight[:, [2, 0, 1]], rtol=0, atol=0) + + +def _official_picks(keras_model, stream, trigger_onset): + """``gpd_predict.py`` from the sliding window to the picks (its hyper-parameters).""" + names = load_definitions(_repo() / "gpd_predict.py", ["sliding_window"], {"np": np}) + sliding_window = names["sliding_window"] + n_shift, n_win, n_feat, min_proba = 10, 200, 400, 0.95 + dt = stream[0].stats.delta + tt = (np.arange(0, stream[0].data.size, n_shift) + n_win) * dt + windows = np.zeros((sliding_window(stream[0].data, n_feat, stepsize=n_shift).shape[0], n_feat, 3)) + for channel in range(3): + windows[:, :, channel] = sliding_window(stream[channel].data, n_feat, stepsize=n_shift) + windows = windows / np.max(np.abs(windows), axis=(1, 2))[:, None, None] + tt = tt[: windows.shape[0]] + ts = keras_model.predict(windows, verbose=False, batch_size=3000) + picks = {} + for phase, column in (("P", 0), ("S", 1)): + picks[phase] = [] + for on, off in trigger_onset(ts[:, column], min_proba, 0.1): + if off == on: + continue + pick = np.argmax(ts[on:off, column]) + on + picks[phase].append(round(float(tt[pick]) / dt)) + return picks, ts + + +def test_gpd_predict_pipeline_picks_are_identical_on_anza_data(): + # 08:02-08:20 UTC on 2016-06-10, the first minutes of the Mw 5.2 Anza aftershock sequence. The slice + # starts a multiple of 10 samples after the day start, so window times fall on the official grid. + start_offset, duration = 8 * 3600 + 2 * 60, 18 * 60 + stream = _anza_stream(start_offset, duration) + from obspy.signal.trigger import trigger_onset # the function gpd_predict.py imports + + keras_model = _keras_model() + expected, keras_probabilities = _official_picks(keras_model, stream, trigger_onset) + + port = _port() + waveforms = torch.from_numpy(np.stack([trace.data for trace in stream]))[None] # float64, N, E, Z + with torch.no_grad(): + annotations = port.annotate(waveforms, stride=10) + np.testing.assert_allclose(annotations[0].numpy().T, keras_probabilities, rtol=1e-5, atol=ATOL) + picks = port.extract_picks(annotations)[0] + actual = {phase: [int(sample) for sample, _ in picks[phase]] for phase in ("P", "S")} + assert actual == expected + assert len(expected["P"]) > 30 and len(expected["S"]) > 90 + + # The shipped anza2016.out (the authors' whole-day run with Keras 2.2.2): inside the slice, away from + # the filter edges, the picks are the same to the millisecond (33 P and 96 S picks). + obspy = oracle_package("obspy", "1.5.1", "requirements-earthquake.txt") + t0 = stream[0].stats.starttime + lo, hi = 60.0, duration - 60.0 + shipped = {"P": [], "S": []} + for line in (_repo() / "anza2016.out").read_text().splitlines(): + _, _, phase, stamp = line.split() + offset = obspy.UTCDateTime(stamp) - t0 + if lo <= offset <= hi: + shipped[phase].append(offset) + for phase in ("P", "S"): + ours = np.array([sample * 0.01 for sample in actual[phase] if lo <= sample * 0.01 <= hi]) + theirs = np.array(shipped[phase]) + exact = sum(np.any(np.abs(ours - t) < 1e-3) for t in theirs) + assert len(ours) == len(theirs), (phase, len(ours), len(theirs)) + assert exact == len(theirs), (phase, exact, len(theirs)) + + +def test_zero_window_is_left_at_zero(): + port = _port() + waveforms = torch.zeros(1, 3, 600) + with torch.no_grad(): + annotations = port.annotate(waveforms) + assert torch.isfinite(annotations).all() + with pytest.raises(ValueError): + port.annotate(torch.zeros(1, 3, 399)) diff --git a/tests/oracle/test_hurricast_oracle.py b/tests/oracle/test_hurricast_oracle.py new file mode 100644 index 00000000..6d428adf --- /dev/null +++ b/tests/oracle/test_hurricast_oracle.py @@ -0,0 +1,291 @@ +"""Hurricast checked against the official code (leobix/hurricast, pinned). + +The repository has no licence: pyhazards/models/hurricast.py is written from the paper, and the official +modules are imported from the pinned checkout here only as a test oracle: + +* ``src/models/experimental_models.py`` (``ExperimentalHurricast``, ``CNNEncoder``, ``ExpTRANSFORMER``, + ``ExpLSTM``) with every encoder / decoder preset of ``scripts/config.py``: parameter counts, state-dict + keys, seeded initial weights, outputs and embeddings in eval and train mode, gradients; +* ``src/utils/run.py`` ``compute_l2`` (the L2 term of the training loss) and a training step of + ``src/run.py`` ``train_epoch``; +* the XGBoost stage: the feature-column rule and feature names of notebooks/Compute_results_*_Round2.ipynb, + the default hyperparameters of ``train_xgb_track`` / ``train_xgb_intensity`` in scripts/run_embeddings.py, + and predictions of ``xgboost.XGBRegressor`` fitted the official way; +* ``src/utils/data_processing.py`` (storm selection, wind category, displacements) on real IBTrACS rows. +""" + +from __future__ import annotations + +import ast +import importlib.util +import json +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, load_definitions, oracle_package, oracle_repo +from pyhazards.datasets.tc import read_ibtracs +from pyhazards.datasets.tc.hurricast import hurricast_storms +from pyhazards.models import build_model +from pyhazards.models.hurricast import ( + DECODER_CONFIGS, + ENCODER_CONFIGS, + HURRICAST_STAT_FEATURES, + HURRICAST_XGBOOST_PARAMS, + hurricast_l2_penalty, + hurricast_network, + hurricast_xgboost_columns, +) + +IBTRACS_CSV = Path(__file__).resolve().parents[1] / "fixtures" / "ibtracs" / "ibtracs.fixture.list.v04r01.csv" +PRESETS = [ + (decoder, encoder) + for decoder in DECODER_CONFIGS + for encoder in (["full_encoder_config", "split_encoder_config"] if decoder != "transformer_config_noviz" else [None]) +] + + +def _official(): + repo = oracle_repo("hurricast") + models = import_from(repo, "src.models.experimental_models") + spec = importlib.util.spec_from_file_location("hurricast_official_config", repo / "scripts" / "config.py") + config = importlib.util.module_from_spec(spec) + spec.loader.exec_module(config) + return models, config, repo + + +def _official_network(models, config, decoder, encoder, n_pred): + return models.ExperimentalHurricast( + n_pred=n_pred, + decoder_config=config.create_config(decoder), + encoder_config=config.create_config(encoder) if encoder else None, + decoder_name="ExpTRANSFORMER" if decoder.startswith("transformer") else "ExpLSTM", + encoder_name="CNNEncoder" if encoder else None, + split_cnns=encoder == "split_encoder_config", + ) + + +def _inputs(encoder, batch=4, seed=1): + g = torch.Generator().manual_seed(seed) + stat = torch.randn(batch, 8, 14 if encoder else 10, generator=g) + maps = torch.randn(batch, 8, 9, 25, 25, generator=g) if encoder else None + return stat, maps + + +def test_presets_are_the_official_configurations(): + _, config, _ = _official() + for name, (_, kwargs) in DECODER_CONFIGS.items(): + assert config.create_config(name) == kwargs, name + for name, kwargs in ENCODER_CONFIGS.items(): + official = config.create_config(name) + assert {**official, "hidden_configuration": tuple(official["hidden_configuration"])} == kwargs, name + + +@pytest.mark.parametrize("decoder,encoder", PRESETS) +@pytest.mark.parametrize("target,n_pred", [("intensity", 1), ("displacement", 2)]) +def test_network_matches_official(decoder, encoder, target, n_pred): + models, config, _ = _official() + torch.manual_seed(0) + reference = _official_network(models, config, decoder, encoder, n_pred) + torch.manual_seed(0) + port = hurricast_network(target, decoder, encoder) + assert sum(p.numel() for p in port.parameters()) == sum(p.numel() for p in reference.parameters()) + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + stat, maps = _inputs(encoder) + for mode in ("eval", "train"): + getattr(reference, mode)() + getattr(port, mode)() + with torch.no_grad(): + torch.manual_seed(3) + expected = reference(stat, maps) + torch.manual_seed(3) + actual = port(stat, maps) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + torch.manual_seed(3) + expected = reference.get_embeddings(stat, maps, xgb=True) + torch.manual_seed(3) + actual = port.get_embeddings(stat, maps, xgb=True) + for a, b in zip(actual, expected): + torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-6) + torch.manual_seed(3) + expected = reference.get_embeddings(stat, maps, xgb=False) + torch.manual_seed(3) + torch.testing.assert_close(port.get_embeddings(stat, maps), expected, rtol=1e-5, atol=1e-6) + # BatchNorm running statistics were updated identically in train mode. + for key, value in reference.state_dict().items(): + torch.testing.assert_close(port.state_dict()[key], value, rtol=1e-6, atol=1e-7, msg=key) + + +def test_paper_configuration_counts_and_gradients(): + models, config, _ = _official() + for target, n_pred, count in (("displacement", 2, 2_969_914), ("intensity", 1, 2_969_771)): + torch.manual_seed(0) + reference = _official_network(models, config, "transformer_config", "full_encoder_config", n_pred) + port = build_model("hurricast", task="regression", target=target, predictor="network") + port.network.load_state_dict(reference.state_dict(), strict=True) # official keys under ``network.`` + assert sum(p.numel() for p in port.parameters()) == count + stat, maps = _inputs("full_encoder_config", batch=6) + reference.train() + port.train() + x_stat = torch.cat([stat, torch.randn(6, 8, 16)], dim=-1) # Hurricast takes all 30 features + expected = reference(stat, maps) + actual = port({"x_stat": x_stat, "x_viz": maps}) # target scaling is 0 / 1 before fit() + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + expected.square().sum().backward() + actual.square().sum().backward() + for (name, ref_param), port_param in zip(reference.named_parameters(), port.network.parameters()): + torch.testing.assert_close(port_param.grad, ref_param.grad, rtol=1e-4, atol=1e-6, msg=name) + + +def test_l2_penalty_is_the_official_compute_l2(): + models, config, repo = _official() + compute_l2 = load_definitions(repo / "src" / "utils" / "run.py", ["compute_l2"])["compute_l2"] + torch.manual_seed(0) + reference = _official_network(models, config, "transformer_config", "full_encoder_config", 1) + port = hurricast_network("intensity") + port.load_state_dict(reference.state_dict()) + torch.testing.assert_close(hurricast_l2_penalty(port), compute_l2(reference)) + + +def test_training_step_matches_official_train_epoch(): + """One epoch (one batch) of Hurricast.fit_network equals src/run.py train_epoch: MSE + 2 / B * l2 * sum(W^2), Adam. + + Displacement targets, for which the official loss compares tensors of the same shape (see the card for the + intensity case).""" + models, config, repo = _official() + run = import_from(repo, "src.run") + torch.manual_seed(0) + reference = _official_network(models, config, "transformer_config", "full_encoder_config", 2) + model = build_model("hurricast", task="regression", target="displacement", predictor="network") + model.network.load_state_dict(reference.state_dict()) + stat, maps = _inputs("full_encoder_config", batch=8, seed=5) + targets = torch.randn(8, 2, generator=torch.Generator().manual_seed(6)) + optimizer = torch.optim.Adam(reference.parameters(), lr=4e-4) + # The same sample order as fit_network(seed=0): the conv biases in front of BatchNorm get gradients that + # are zero up to rounding, whose sign (which Adam turns into a full step) depends on the summation order. + order = torch.randperm(8, generator=torch.Generator().manual_seed(0)) + batch = ({"x_stat": stat[order], "x_viz": maps[order]}, {"trg_y": targets[order]}) + run.train_epoch(reference, [batch], optimizer, torch.nn.MSELoss(), 0.01, 0) + x_stat = torch.cat([stat, torch.zeros(8, 8, 16)], dim=-1) + model.fit_network({"x_stat": x_stat, "x_viz": maps}, targets, epochs=1, batch_size=8, learning_rate=4e-4, l2_reg=0.01) + for key, value in reference.state_dict().items(): + torch.testing.assert_close(model.network.state_dict()[key], value, rtol=1e-5, atol=1e-6, msg=key) + + +def _round2_notebook_source(repo: Path, name: str) -> str: + notebook = json.loads((repo / "notebooks" / name).read_text(encoding="utf-8")) + return "".join(notebook["cells"][0]["source"] if notebook["cells"][0]["cell_type"] == "code" else "") + + +def test_xgboost_columns_follow_the_official_notebooks(): + import pandas as pd + + _, _, repo = _official() + for name in ("Compute_results_intensity_24h_Round2.ipynb", "Compute_results_track24_Round2.ipynb"): + notebook = json.loads((repo / "notebooks" / name).read_text(encoding="utf-8")) + source = next("".join(cell["source"]) for cell in notebook["cells"] if cell["cell_type"] == "code" and "names = [" in "".join(cell["source"])) + tree = ast.parse(source) + names = next(ast.literal_eval(node.value) for node in tree.body if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) == "names") + assert tuple(names) == HURRICAST_STAT_FEATURES, name + # The notebook's column rule, executed on a frame with the notebook's column names. + window_size = 8 + names_all = names * window_size + for i in range(len(names_all)): + names_all[i] += "_" + str(i // 30) + frame = pd.DataFrame(np.zeros((1, len(names_all))), columns=names_all) + rule = next(ast.get_source_segment(source, node.value) for node in tree.body if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", None) == "cols") + cols = eval(rule, {"X_train": frame}) + assert cols == hurricast_xgboost_columns(window_size), name + assert len(cols) == 14 * 8 + 16 + + +def test_xgboost_defaults_are_the_official_ones(): + _, _, repo = _official() + tree = ast.parse((repo / "scripts" / "run_embeddings.py").read_text(encoding="utf-8")) + for function in ("train_xgb_track", "train_xgb_intensity"): + node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == function) + defaults = dict(zip([a.arg for a in node.args.args][-len(node.args.defaults) :], [ast.literal_eval(d) for d in node.args.defaults])) + assert {key: defaults[key] for key in HURRICAST_XGBOOST_PARAMS} == HURRICAST_XGBOOST_PARAMS, function + + +@pytest.mark.parametrize("target", ["intensity", "displacement"]) +def test_xgboost_stage_matches_official_regressors(target): + xgboost = oracle_package("xgboost", "3.2.0", "requirements-tc.txt", distribution="xgboost-cpu") + import pandas as pd + + models, config, _ = _official() + n_pred = 1 if target == "intensity" else 2 + torch.manual_seed(0) + reference = _official_network(models, config, "transformer_config", "full_encoder_config", n_pred).eval() + model = build_model("hurricast", task="regression", target=target, n_jobs=1) + model.network.load_state_dict(reference.state_dict()) + g = torch.Generator().manual_seed(4) + n = 160 + x_stat = torch.randn(n, 8, 30, generator=g) + x_viz = torch.randn(n, 8, 9, 25, 25, generator=g) + position = torch.randn(n, 2, generator=g) * 10 + 20 + raw = torch.randn(n, n_pred, generator=g) * 3 + 1 + inputs = {"x_stat": x_stat, "x_viz": x_viz, "position": position} + targets = raw[:, 0] if target == "intensity" else (position + raw).unsqueeze(1) + model.fit(inputs, targets, train_network=False) + + # The official way: embeddings of the frozen network appended to the selected statistical columns, + # standardised targets, one XGBRegressor per target with the run_embeddings.py defaults. + with torch.no_grad(): + embeddings = reference.get_embeddings(x_stat[:, :, :14], x_viz, xgb=True)[0].numpy() + names_all = [f"{name}_{i // 30}" for i, name in enumerate(list(HURRICAST_STAT_FEATURES) * 8)] + frame = pd.DataFrame(x_stat.reshape(n, -1).numpy(), columns=names_all) + cols = [c for c in frame.columns if c.lower()[-2:] == "_0" or c.lower()[:3] != "cat"] + features = np.concatenate((frame[cols], embeddings), axis=1) + mean, std = raw.mean(0), raw.std(0) + expected = [] + for k in range(n_pred): + regressor = xgboost.XGBRegressor(**HURRICAST_XGBOOST_PARAMS, n_jobs=1) + regressor.fit(features, ((raw[:, k] - mean[k]) / std[k]).numpy()) + expected.append(np.array(regressor.predict(features)) * float(std[k]) + float(mean[k])) + expected = np.stack(expected, axis=1) + with torch.no_grad(): + actual = model(inputs).numpy() + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + if target == "displacement": + forecast = model.forecast(inputs) + np.testing.assert_allclose(forecast["lat"].numpy()[:, 0], position[:, 0].numpy() + expected[:, 0], rtol=1e-5) + + +def test_storm_statistics_follow_the_official_data_processing(): + """Storm cut, interpolated WMO wind / pressure, wind category and displacements on real IBTrACS rows.""" + import pandas as pd + + _, _, repo = _official() + processing = import_from(repo, "src.utils.data_processing") + table = read_ibtracs(IBTRACS_CSV) + on_grid = table[(table["ISO_TIME"].dt.hour % 3 == 0) & (table["ISO_TIME"].dt.minute == 0)] + for sid in ("2023265N29284", "2026058S18168"): # OPHELIA (NA), URMIL (SP, crosses the dateline) + rows = on_grid[on_grid["SID"] == sid].reset_index(drop=True) + min_wind, min_steps, max_steps = 34, 5, 120 + # prepare_tabular_data_vision without its tensor stacking, on this storm's 3-hourly rows. + frame = processing.numeric_data(rows[["SID", "ISO_TIME", "LAT", "LON", "WMO_WIND", "WMO_PRES", "DIST2LAND", "STORM_SPEED", "STORM_DIR"]].copy()) + frame = processing.add_storm_category_val(frame) + storms = processing.sort_storm(frame, min_wind, min_steps) + padded = processing.add_displacement_lat_lon2(processing.pad_traj(storms, max_steps)) + official = padded[1] + ours = hurricast_storms(rows, min_wind, min_steps, max_steps) + assert len(ours) == 1 + features = pd.DataFrame(ours[0]["features"], columns=HURRICAST_STAT_FEATURES) + official = official.iloc[: len(features)] + assert (pd.to_datetime(official["ISO_TIME"]).to_numpy("datetime64[ns]") == ours[0]["times"]).all() + pairs = { + "LAT": "LAT", "LON": "LON", "WMO_WIND": "WMO_WIND", "WMO_PRES": "WMO_PRES", "DIST2LAND": "DIST2LAND", + "STORM_SPEED": "STORM_SPEED", "cat_storm_category": "storm_category", + "STORM_DISPLACEMENT_X": "DISPLACEMENT_LAT", "STORM_DISPLACEMENT_Y": "DISPLACEMENT_LON", + } + for ours_name, official_name in pairs.items(): + np.testing.assert_allclose(features[ours_name].to_numpy(), official[official_name].to_numpy(dtype=np.float64), rtol=1e-12, atol=1e-12, err_msg=f"{sid} {ours_name}") + direction = np.deg2rad(official["STORM_DIR"].to_numpy(dtype=np.float64)) + np.testing.assert_allclose(features["COS_STORM_DIR"].to_numpy(), np.cos(direction), atol=1e-12) diff --git a/tests/oracle/test_hydrographnet_oracle.py b/tests/oracle/test_hydrographnet_oracle.py new file mode 100644 index 00000000..5a6d8a00 --- /dev/null +++ b/tests/oracle/test_hydrographnet_oracle.py @@ -0,0 +1,325 @@ +"""HydroGraphNet checked against NVIDIA PhysicsNeMo (pinned in repos.yaml, Apache-2.0). + +The oracle is PhysicsNeMo's own code, imported from the pinned checkout: ``MeshGraphKAN`` (with PyTorch +Geometric graphs and ``torch_scatter`` aggregation), the HydroGraphNet example's +``compute_physics_loss`` (``examples/weather/flood_modeling/hydrographnet/utils.py``) and rollout loop +(``inference.py``; the loop is executed from the file's own source because ``main`` is a Hydra entry +point that also loads a checkpoint and renders animations), and ``HydroGraphDataset``. Data fixtures are +written in the White River release layout (Zenodo 14969507). With ``PYHAZARDS_HYDROGRAPHNET_DATA`` +pointing at a local copy of the release, the reader is also compared on real hydrographs. +""" + +from __future__ import annotations + +import ast +import os +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, missing, oracle_repo +from pyhazards.datasets import load_dataset +from pyhazards.datasets.flood.hydrograph import ( + hydrograph_collate, + knn_edge_index, + synthetic_hydrograph_mesh, + write_hydrograph_files, +) +from pyhazards.models import build_model +from pyhazards.models.hydrographnet import HydroGraphNet, HydroGraphNetLoss, hydrographnet_physics_loss + +EXAMPLE = Path("examples") / "weather" / "flood_modeling" / "hydrographnet" +SMALL = dict( + input_dim_nodes=5, + input_dim_edges=2, + output_dim=3, + processor_size=3, + mlp_activation_fn="silu", + num_layers_node_processor=3, + num_layers_edge_processor=1, + hidden_dim_processor=32, + hidden_dim_node_encoder=48, + num_layers_node_encoder=1, + hidden_dim_edge_encoder=24, + num_layers_edge_encoder=1, + hidden_dim_node_decoder=40, + num_layers_node_decoder=3, + aggregation="mean", + num_harmonics=7, +) + + +def _pyg(): + try: + import torch_geometric # noqa: F401 + import torch_scatter # noqa: F401 + except ImportError: + missing("PhysicsNeMo's MeshGraphKAN needs torch_geometric and torch_scatter; pip install -r tests/oracle/requirements-physicsnemo.txt") + import torch_geometric as pyg + + return pyg + + +def _meshgraphkan(): + _pyg() + os.environ.setdefault("PHYSICSNEMO_FORCE_TE", "False") + return import_from(oracle_repo("physicsnemo"), "physicsnemo.models.meshgraphnet.meshgraphkan").MeshGraphKAN + + +def _hydrograph_dataset_class(): + _pyg() + return import_from(oracle_repo("physicsnemo"), "physicsnemo.datapipes.gnn.hydrographnet_dataset").HydroGraphDataset + + +def _graph(num_nodes: int = 200, seed: int = 0): + rng = np.random.default_rng(seed) + return torch.from_numpy(knn_edge_index(rng.uniform(0, 1, (num_nodes, 2)), k=4)).long() + + +def _assert_same_state(reference, port) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert value.shape == port_state[key].shape and value.dtype == port_state[key].dtype, key + assert torch.equal(value, port_state[key]), key + + +@pytest.mark.parametrize("config", [dict(input_dim_nodes=16, input_dim_edges=3, output_dim=2), SMALL], ids=["hydrographnet", "small_mean_silu"]) +def test_parameters_names_and_seeded_initialisation_match_physicsnemo(config): + MeshGraphKAN = _meshgraphkan() + torch.manual_seed(0) + reference = MeshGraphKAN(**config) + torch.manual_seed(0) + port = HydroGraphNet(**config) + n_ref = sum(p.numel() for p in reference.parameters()) + assert n_ref == sum(p.numel() for p in port.parameters()) + if config["input_dim_nodes"] == 16: + assert n_ref == 2_318_722 + torch.manual_seed(0) + _assert_same_state(reference, build_model("hydrographnet", task="regression")) + _assert_same_state(reference, port) + + +@pytest.mark.parametrize("config", [dict(input_dim_nodes=16, input_dim_edges=3, output_dim=2), SMALL], ids=["hydrographnet", "small_mean_silu"]) +def test_outputs_and_gradients_match_physicsnemo(config): + pyg = _pyg() + MeshGraphKAN = _meshgraphkan() + torch.manual_seed(0) + reference = MeshGraphKAN(**config) + port = HydroGraphNet(**config) + port.load_state_dict(reference.state_dict(), strict=True) + edge_index = _graph() + graph = pyg.data.Data(edge_index=edge_index, num_nodes=200) + generator = torch.Generator().manual_seed(1) + nodes = torch.randn(200, config["input_dim_nodes"], generator=generator) + edges = torch.randn(edge_index.shape[1], config["input_dim_edges"], generator=generator) + for train in (False, True): + reference.train(train) + port.train(train) + expected = reference(nodes, edges, graph) + actual = port(nodes, edges, edge_index) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + torch.testing.assert_close(port(nodes, edges, graph), expected, rtol=1e-5, atol=1e-6) + torch.testing.assert_close( + port({"node_features": nodes, "edge_features": edges, "edge_index": edge_index}), expected, rtol=1e-5, atol=1e-6 + ) + reference.zero_grad() + port.zero_grad() + reference(nodes, edges, graph).square().sum().backward() + port(nodes, edges, edge_index).square().sum().backward() + # Multi-threaded CPU sums make PhysicsNeMo's own gradients differ between two identical calls by up to + # ~5e-7 of the largest entry, so near-zero entries need an absolute tolerance scaled to each tensor. + for (name, ref_param), port_param in zip(reference.named_parameters(), port.parameters()): + scale = float(ref_param.grad.abs().max()) + torch.testing.assert_close(port_param.grad, ref_param.grad, rtol=1e-4, atol=1e-5 * scale, msg=name) + + +def test_batched_graphs_match_pyg_batching(): + pyg = _pyg() + MeshGraphKAN = _meshgraphkan() + torch.manual_seed(0) + reference = MeshGraphKAN(16, 3, 2).eval() + port = HydroGraphNet().eval() + port.load_state_dict(reference.state_dict(), strict=True) + samples, graphs = [], [] + for seed, n in ((0, 40), (1, 25)): + edge_index = _graph(n, seed) + generator = torch.Generator().manual_seed(seed) + nodes, edges = torch.randn(n, 16, generator=generator), torch.randn(edge_index.shape[1], 3, generator=generator) + samples.append(({"node_features": nodes, "edge_features": edges, "edge_index": edge_index}, torch.zeros(n, 2))) + graphs.append(pyg.data.Data(x=nodes, edge_attr=edges, edge_index=edge_index)) + batch = pyg.data.Batch.from_data_list(graphs) + collated, _ = hydrograph_collate(samples) + assert torch.equal(collated["edge_index"], batch.edge_index) + assert torch.equal(collated["batch"], batch.batch) + with torch.no_grad(): + torch.testing.assert_close(port(collated), reference(batch.x, batch.edge_attr, batch), rtol=1e-5, atol=1e-6) + + +def test_physicsnemo_stored_regression_output_is_reproduced(): + """PhysicsNeMo's test_meshgraphkan_forward (MeshGraphKAN(4, 3, 2), seed 0) against its stored output.""" + pyg = _pyg() + MeshGraphKAN = _meshgraphkan() + repo = oracle_repo("physicsnemo") + stored = list(torch.load(repo / "test" / "models" / "meshgraphnet" / "data" / "meshgraphkan_output.pth").values())[0] + + def run(cls): + torch.manual_seed(0) + np.random.seed(0) + model = cls(4, 3, 2) + graphs = [] + for _ in range(2): + src = torch.tensor([np.random.randint(20) for _ in range(12)]) + dst = torch.tensor([np.random.randint(20) for _ in range(12)]) + graphs.append(pyg.data.Data(edge_index=torch.stack([src, dst], dim=0), num_nodes=20)) + graph = pyg.data.Batch.from_data_list(graphs) + with torch.no_grad(): + return model(torch.randn(graph.num_nodes, 4), torch.randn(graph.num_edges, 3), graph) + + port_output = run(HydroGraphNet) + torch.testing.assert_close(port_output, run(MeshGraphKAN), rtol=1e-5, atol=1e-6) + # PhysicsNeMo itself checks this file with rtol = atol = 0.1 (outputs differ across devices). + torch.testing.assert_close(port_output, stored, rtol=1e-4, atol=1e-5) + + +def _fixture(tmp_path: Path, nodes: int = 30, hydrographs: int = 4, steps: int = 60) -> Path: + static, series = synthetic_hydrograph_mesh(nodes=nodes, hydrographs=hydrographs, steps=steps, seed=3) + ids = list(series) + write_hydrograph_files(tmp_path, static, series, extra_cells=5, train_ids=ids[:-1]) + (tmp_path / "test.txt").write_text(f"{ids[-1]}\n", encoding="utf-8") + return tmp_path + + +def _compare_reader(official_cls, data_dir: Path, rollout_length: int, every: int = 1) -> None: + official = official_cls( + data_dir=str(data_dir), prefix="M80", n_time_steps=2, k=4, hydrograph_ids_file="train.txt", split="train", return_physics=True + ) + bundle = load_dataset("hydrographnet_white_river", data_dir=str(data_dir), test_ids="test.txt", rollout_length=rollout_length).load() + windows = bundle.get_split("train").inputs + assert len(windows) == len(official) + for idx in list(range(0, len(official), every)) + [len(official) - 1]: + graph, physics = official[idx] + inputs, target = windows[idx] + assert torch.equal(inputs["node_features"], graph.x) + assert torch.equal(inputs["edge_index"], graph.edge_index) + assert torch.equal(inputs["edge_features"], graph.edge_attr) + assert torch.equal(target, graph.y) + assert set(inputs["physics"]) == set(physics) + for key, value in physics.items(): + assert float(inputs["physics"][key]) == float(value), key + # The test split of the example reads the normalisation statistics its training run wrote to data_dir. + official_test = official_cls( + data_dir=str(data_dir), prefix="M80", n_time_steps=2, hydrograph_ids_file="test.txt", split="test", rollout_length=rollout_length + ) + rollouts = bundle.get_split("test").inputs + assert len(rollouts) == len(official_test) + for idx in range(len(official_test)): + graph, rollout_data = official_test[idx] + inputs, targets = rollouts[idx] + assert torch.equal(inputs["node_features"], graph.x) + assert torch.equal(inputs["edge_features"], graph.edge_attr) + assert torch.equal(inputs["inflow"], rollout_data["inflow"]) + assert torch.equal(inputs["precipitation"], rollout_data["precipitation"]) + assert torch.equal(targets["water_depth"], rollout_data["water_depth_gt"]) + assert torch.equal(targets["volume"], rollout_data["volume_gt"]) + files = load_dataset( + "hydrographnet_white_river", data_dir=str(data_dir), test_ids="test.txt", rollout_length=rollout_length, norm_stats="files" + ).load() + assert files.metadata["dynamic_stats"] == bundle.metadata["dynamic_stats"] + + +def test_reader_matches_hydrographdataset_on_release_layout(tmp_path): + _compare_reader(_hydrograph_dataset_class(), _fixture(tmp_path), rollout_length=20) + + +def test_reader_matches_hydrographdataset_on_real_white_river(tmp_path): + """Local check on the real release: set PYHAZARDS_HYDROGRAPHNET_DATA to the unzipped HydroGraphNet.zip.""" + root = os.environ.get("PYHAZARDS_HYDROGRAPHNET_DATA") + if not root: + pytest.skip("PYHAZARDS_HYDROGRAPHNET_DATA is not set (real White River data, Zenodo 14969507, 8.3 GB)") + official_cls = _hydrograph_dataset_class() + source = Path(root) + # The example writes normalisation statistics into data_dir; work on links to the real files. + for code in ("XY", "CA", "CE", "CS", "A", "CU", "N", "FA", "IP"): + os.symlink(source / f"M80_{code}.txt", tmp_path / f"M80_{code}.txt") + for hid in ("H1", "H2"): + for code in ("WD", "V", "US_InF", "Pr"): + os.symlink(source / f"M80_{code}_{hid}.txt", tmp_path / f"M80_{code}_{hid}.txt") + (tmp_path / "train.txt").write_text("H1\n", encoding="utf-8") + (tmp_path / "test.txt").write_text("H2\n", encoding="utf-8") + _compare_reader(official_cls, tmp_path, rollout_length=30, every=7) + + +def _inference_loop(): + """The ``for t in range(rollout_length)`` loop of the example's inference.py, from its own source.""" + path = oracle_repo("physicsnemo") / EXAMPLE / "inference.py" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + main = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "main") + loops = [ + node + for node in ast.walk(main) + if isinstance(node, ast.For) and isinstance(node.target, ast.Name) and node.target.id == "t" + ] + assert len(loops) == 1, "inference.py rollout loop not found" + return compile(ast.Module(body=loops, type_ignores=[]), str(path), "exec") + + +def test_rollout_matches_inference_script(tmp_path): + MeshGraphKAN = _meshgraphkan() + official_cls = _hydrograph_dataset_class() + data_dir = _fixture(tmp_path) + official_cls(data_dir=str(data_dir), prefix="M80", n_time_steps=2, hydrograph_ids_file="train.txt", split="train") + test_set = official_cls( + data_dir=str(data_dir), prefix="M80", n_time_steps=2, hydrograph_ids_file="test.txt", split="test", rollout_length=20 + ) + torch.manual_seed(0) + reference = MeshGraphKAN(16, 3, 2).eval() + port = HydroGraphNet().eval() + port.load_state_dict(reference.state_dict(), strict=True) + g, rollout_data = test_set[0] + scope = { + "torch": torch, + "model": reference, + "g": g, + "edge_features": g.edge_attr, + "X_iter": g.x.clone(), + "num_nodes": g.x.size(0), + "n_time_steps": 2, + "rollout_length": 20, + "inflow_seq": rollout_data["inflow"], + "precip_seq": rollout_data["precipitation"], + "wd_gt_seq": rollout_data["water_depth_gt"], + "rollout_preds": [], + "ground_truth_list": [], + "rmse_list": [], + } + with torch.no_grad(): + exec(_inference_loop(), scope) + out = port.rollout(g.x, g.edge_attr, g.edge_index, rollout_data["inflow"], rollout_data["precipitation"], n_time_steps=2) + torch.testing.assert_close(out["water_depth"], torch.stack(scope["rollout_preds"]), rtol=1e-5, atol=1e-6) + torch.testing.assert_close(out["volume"][-1].unsqueeze(1), scope["X_iter"][:, -1:], rtol=1e-5, atol=1e-6) + from pyhazards.metrics.inundation import rollout_rmse + + np.testing.assert_allclose(rollout_rmse(out["water_depth"], rollout_data["water_depth_gt"]).numpy(), scope["rmse_list"], rtol=1e-5, atol=1e-7) + + +def test_physics_loss_matches_example(tmp_path): + pyg = _pyg() + compute_physics_loss = import_from(oracle_repo("physicsnemo") / EXAMPLE, "utils").compute_physics_loss + bundle = load_dataset("hydrographnet_white_river", data_dir=str(_fixture(tmp_path)), test_ids="test.txt", rollout_length=20).load() + windows = bundle.get_split("train").inputs + samples = [windows[i] for i in (0, 7, 30, 61)] + collated, target = hydrograph_collate(samples) + batch = pyg.data.Batch.from_data_list( + [pyg.data.Data(x=s[0]["node_features"], edge_index=s[0]["edge_index"], num_nodes=s[0]["node_features"].shape[0]) for s in samples] + ) + generator = torch.Generator().manual_seed(0) + for scale in (0.01, 1.0, 50.0): + pred = scale * torch.randn(target.shape, generator=generator) + expected = compute_physics_loss(pred, collated["physics"], batch, delta_t=1200.0) + torch.testing.assert_close(hydrographnet_physics_loss(pred, collated["physics"], collated["batch"]), expected, rtol=1e-5, atol=0) + loss, parts = HydroGraphNetLoss()(pred, target, collated["physics"], collated["batch"]) + torch.testing.assert_close(loss, torch.nn.functional.mse_loss(pred, target) + expected, rtol=1e-5, atol=0) + assert set(parts) == {"total_loss", "mse_loss", "physics_loss"} diff --git a/tests/oracle/test_neuralhydrology_oracle.py b/tests/oracle/test_neuralhydrology_oracle.py new file mode 100644 index 00000000..4df78b62 --- /dev/null +++ b/tests/oracle/test_neuralhydrology_oracle.py @@ -0,0 +1,531 @@ +"""NeuralHydrology LSTM / EA-LSTM, hydrological metrics and streamflow readers against the official code. + +References (pinned in repos.yaml): neuralhydrology @ ea94a40 (BSD-3-Clause) for ``CudaLSTM``, ``EALSTM``, +``evaluation/metrics.py``, the ``CamelsUS`` / ``Caravan`` datasets and the ``Tester``; the paper code of +Kratzert et al. (2019), kratzert/ealstm_regional_modeling @ d118158 (Apache-2.0), for the layout of the +official HydroShare checkpoints. Real data: the 4 CAMELS-US basins (2000-2002) in NeuralHydrology's +``test/test_data`` and the real Caravan netCDF basin files (ERA5-Land + streamflow, 1981-2020) in +google-research/flood-forecasting's ``test/test_data/multimet``. + +The 939 MB HydroShare archive with the 48 official 2019 runs (``kratzert2019_hydroshare_runs``, +``large: true``) gates the checkpoint and paper-number tests. +""" + +from __future__ import annotations + +import io +import pickle +import sys +import zipfile +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import torch + +from oracle_utils import import_from, oracle_large_asset, oracle_repo +from pyhazards.benchmarks.flood import evaluate_streamflow +from pyhazards.datasets.flood import ( + KRATZERT2019_DYNAMIC_INPUTS, + KRATZERT2019_STATIC_ATTRIBUTES, + CamelsUSStreamflowDataset, + CaravanStreamflowDataset, +) +from pyhazards.metrics import hydrology +from pyhazards.models import build_model +from pyhazards.models.neuralhydrology_lstm import convert_kratzert2019_state_dict + +pytest.importorskip("xarray") + + +@pytest.fixture(scope="module") +def nh(): + """The NeuralHydrology package imported from the pinned checkout (kept importable for the module).""" + root = oracle_repo("neuralhydrology") + pytest.importorskip("ruamel.yaml") + pytest.importorskip("numba") + sys.path.insert(0, str(root)) + try: + import neuralhydrology # noqa: F401 + from neuralhydrology.datasetzoo.camelsus import CamelsUS + from neuralhydrology.datasetzoo.caravan import Caravan + from neuralhydrology.evaluation import metrics + from neuralhydrology.evaluation.tester import RegressionTester + from neuralhydrology.modelzoo.cudalstm import CudaLSTM + from neuralhydrology.modelzoo.ealstm import EALSTM + from neuralhydrology.utils.config import Config + + yield { + "root": root, + "Config": Config, + "CudaLSTM": CudaLSTM, + "EALSTM": EALSTM, + "CamelsUS": CamelsUS, + "Caravan": Caravan, + "metrics": metrics, + "RegressionTester": RegressionTester, + } + finally: + sys.path.remove(str(root)) + for name in [m for m in sys.modules if m.split(".")[0] == "neuralhydrology"]: + del sys.modules[name] + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _config(nh, tmp_path: Path, **overrides): + """A NeuralHydrology run configuration at the Kratzert et al. (2019) model settings.""" + raw = { + "experiment_name": "pyhazards_oracle", + "run_dir": str(tmp_path / "run"), + "model": "cudalstm", + "head": "regression", + "output_activation": "linear", + "hidden_size": 256, + "initial_forget_bias": 5, + "output_dropout": 0.4, + "optimizer": "Adam", + "loss": "MSE", + "learning_rate": 1e-3, + "batch_size": 256, + "epochs": 30, + "seq_length": 270, + "predict_last_n": 1, + "dataset": "camels_us", + "data_dir": str(tmp_path), + "forcings": ["maurer_extended"], + "dynamic_inputs": list(KRATZERT2019_DYNAMIC_INPUTS), + "static_attributes": list(KRATZERT2019_STATIC_ATTRIBUTES), + "target_variables": ["QObs(mm/d)"], + "train_basin_file": str(tmp_path / "basins.txt"), + "validation_basin_file": str(tmp_path / "basins.txt"), + "test_basin_file": str(tmp_path / "basins.txt"), + "train_start_date": "01/10/1999", + "train_end_date": "30/09/2008", + "validation_start_date": "01/10/1980", + "validation_end_date": "30/09/1989", + "test_start_date": "01/10/1989", + "test_end_date": "30/09/1999", + "device": "cpu", + "metrics": ["NSE"], + "verbose": 0, + } + raw.update(overrides) + cfg = nh["Config"](raw) + cfg.train_dir = tmp_path / "run" / "train_data" # where training datasets write their scaler + cfg.train_dir.mkdir(parents=True, exist_ok=True) + return cfg + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert value.shape == port_state[key].shape, key + assert torch.equal(value, port_state[key]), key + + +def _nh_inputs(x_d: torch.Tensor, x_s: torch.Tensor | None, names): + data = {"x_d": {name: x_d[..., i: i + 1] for i, name in enumerate(names)}} + if x_s is not None: + data["x_s"] = x_s + return data + + +def _compare(ref_model, port, x_d, x_s, names, keys): + ref_model.eval() + port.eval() + port_inputs = {"x_d": x_d} if x_s is None else {"x_d": x_d, "x_s": x_s} + with torch.no_grad(): + expected = ref_model(_nh_inputs(x_d, x_s, names)) + actual = port(port_inputs) + for key in keys: + torch.testing.assert_close(actual[key], expected[key], rtol=1e-5, atol=1e-6) + ref_model.train() + port.train() + torch.manual_seed(7) + expected = ref_model(_nh_inputs(x_d, x_s, names)) + torch.manual_seed(7) + actual = port(port_inputs) + for key in keys: + torch.testing.assert_close(actual[key], expected[key], rtol=1e-5, atol=1e-6) + + +@pytest.mark.parametrize( + "model_name, nh_model, statics, expected_params", + [ + ("neuralhydrology_lstm", "cudalstm", True, 297_217), + ("neuralhydrology_lstm", "cudalstm", False, 269_569), + ("neuralhydrology_ealstm", "ealstm", True, 208_641), + ], +) +def test_model_matches_neuralhydrology(nh, tmp_path, model_name, nh_model, statics, expected_params): + static = list(KRATZERT2019_STATIC_ATTRIBUTES) if statics else [] + cfg = _config(nh, tmp_path, model=nh_model, static_attributes=static) + reference_cls = nh["CudaLSTM"] if nh_model == "cudalstm" else nh["EALSTM"] + for seed in (0, 3): + torch.manual_seed(seed) + reference = reference_cls(cfg) + torch.manual_seed(seed) + port = build_model(model_name, task="regression", n_static=len(static)) + assert _n_params(reference) == _n_params(port) == expected_params + _assert_same_state(reference, port) # names, shapes and seeded initial values + + # Trained-like weights: perturb the reference, copy them into the port with strict=True. + with torch.no_grad(): + for parameter in reference.parameters(): + parameter.add_(0.05 * torch.randn_like(parameter)) + port.load_state_dict(reference.state_dict(), strict=True) + torch.manual_seed(1) + x_d = torch.randn(4, 270, 5) + x_s = torch.randn(4, len(static)) if static else None + keys = ["y_hat", "h_n", "c_n"] + (["lstm_output"] if nh_model == "cudalstm" else []) + _compare(reference, port, x_d, x_s, KRATZERT2019_DYNAMIC_INPUTS, keys) + + +def test_metrics_match_neuralhydrology(nh): + import xarray as xr + + metrics = nh["metrics"] + rng = np.random.default_rng(0) + n = 1500 + dates = pd.date_range("1990-01-01", periods=n, freq="1D") + for trial in range(24): + base = np.abs(np.cumsum(rng.normal(size=n))) + rng.gamma(1.0, 2.0, size=n) * (rng.random(n) < 0.1) * 10 + obs = base.copy() + sim = base * rng.uniform(0.7, 1.3) + rng.normal(scale=0.5, size=n) + if trial % 3 == 0: # missing observations and simulations (gaps in the peak windows) + obs[rng.choice(n, 100, replace=False)] = np.nan + sim[rng.choice(n, 20, replace=False)] = np.nan + if trial % 4 == 1: # zero flows and negative simulations (FDC metrics) + obs[rng.choice(n, 50, replace=False)] = 0.0 + sim[rng.choice(n, 50, replace=False)] = -0.3 + observed = xr.DataArray(obs, coords={"date": dates}, dims=["date"]) + simulated = xr.DataArray(sim, coords={"date": dates}, dims=["date"]) + expected = metrics.calculate_all_metrics(observed, simulated) + actual = hydrology.calculate_metrics(obs, sim, dates=dates.values) + assert set(hydrology.NEURALHYDROLOGY_METRIC_NAMES) == set(expected) + for name, value in expected.items(): + np.testing.assert_allclose(actual[hydrology.NEURALHYDROLOGY_METRIC_NAMES[name]], float(value), + rtol=1e-12, atol=1e-12, equal_nan=True, err_msg=name) + # Short series and a fraction that rounds to zero elements (FLV keeps the whole curve, as the reference). + obs, sim = np.array([1.0, 2.0, 0.5]), np.array([0.8, 2.5, 0.4]) + observed = xr.DataArray(obs, coords={"date": dates[:3]}, dims=["date"]) + simulated = xr.DataArray(sim, coords={"date": dates[:3]}, dims=["date"]) + np.testing.assert_allclose(hydrology.fdc_flv(obs, sim, l=0.1), metrics.fdc_flv(observed, simulated, l=0.1)) + np.testing.assert_allclose(hydrology.kge(obs[:1], sim[:1]), metrics.kge(observed[:1], simulated[:1]), equal_nan=True) + + +def _camels_test_data(nh, tmp_path: Path) -> Path: + data_dir = nh["root"] / "test" / "test_data" / "camels_us" + (tmp_path / "basins.txt").write_text((nh["root"] / "test" / "test_data" / "4_basins_test_set.txt").read_text()) + return data_dir + + +def _nh_dataset_samples(dataset, dynamic_inputs): + """(basin, last date) -> (x_d, x_s, y) of every sample of a NeuralHydrology dataset.""" + samples = {} + for i in range(len(dataset)): + sample = dataset[i] + basin, _ = dataset.lookup_table[i] + x_d = torch.cat([sample["x_d"][name] for name in dynamic_inputs], dim=-1) + date = pd.Timestamp(sample["date"][-1]) + samples[(basin, date)] = (x_d, sample.get("x_s"), sample["y"]) + return samples + + +def _assert_windows_match(windows, samples, static: bool): + keys = {(windows.basins[b], pd.Timestamp(d)) for b, d in zip(windows.sample_basin, windows.sample_date)} + assert keys == set(samples) + for i in range(len(windows)): + inputs, y = windows[i] + key = (windows.basins[windows.sample_basin[i]], pd.Timestamp(windows.sample_date[i])) + x_d, x_s, y_ref = samples[key] + torch.testing.assert_close(inputs["x_d"], x_d, rtol=1e-5, atol=1e-6, equal_nan=True) + torch.testing.assert_close(y, y_ref, rtol=1e-5, atol=1e-6, equal_nan=True) + if static: + torch.testing.assert_close(inputs["x_s"], x_s, rtol=1e-5, atol=1e-6) + + +PERIODS = {"train": ("2000-01-01", "2001-12-31"), "test": ("2001-06-01", "2002-12-31")} +NH_PERIODS = { + "train_start_date": "01/01/2000", + "train_end_date": "31/12/2001", + "validation_start_date": "01/06/2001", + "validation_end_date": "31/12/2002", + "test_start_date": "01/06/2001", + "test_end_date": "31/12/2002", +} + + +def test_camels_us_reader_matches_neuralhydrology(nh, tmp_path): + data_dir = _camels_test_data(nh, tmp_path) + cfg = _config(nh, tmp_path, data_dir=str(data_dir), seq_length=90, **NH_PERIODS) + reference_train = nh["CamelsUS"](cfg, is_train=True, period="train") + bundle = CamelsUSStreamflowDataset( + data_dir=data_dir, basins=tmp_path / "basins.txt", periods=PERIODS, seq_length=90 + ).load() + + scaler = bundle.metadata["scaler"] + center, scale = reference_train.scaler["xarray_feature_center"], reference_train.scaler["xarray_feature_scale"] + np.testing.assert_allclose(scaler["dynamic_center"], [float(center[v]) for v in KRATZERT2019_DYNAMIC_INPUTS], rtol=1e-5) + np.testing.assert_allclose(scaler["dynamic_scale"], [float(scale[v]) for v in KRATZERT2019_DYNAMIC_INPUTS], rtol=1e-5) + np.testing.assert_allclose(scaler["target_center"], [float(center["QObs(mm/d)"])], rtol=1e-5) + np.testing.assert_allclose(scaler["target_scale"], [float(scale["QObs(mm/d)"])], rtol=1e-5) + static_names = bundle.metadata["static_attributes"] + assert static_names == sorted(KRATZERT2019_STATIC_ATTRIBUTES) + np.testing.assert_allclose(scaler["static_mean"], reference_train.scaler["attribute_means"][static_names].values, rtol=1e-6) + np.testing.assert_allclose(scaler["static_std"], reference_train.scaler["attribute_stds"][static_names].values, rtol=1e-6) + + train = bundle.get_split("train").inputs + _assert_windows_match(train, _nh_dataset_samples(reference_train, KRATZERT2019_DYNAMIC_INPUTS), static=True) + + test = bundle.get_split("test").inputs + test_samples = {} + for basin in test.basins: + reference_test = nh["CamelsUS"](cfg, is_train=False, period="test", basin=basin, scaler=reference_train.scaler) + test_samples.update(_nh_dataset_samples(reference_test, KRATZERT2019_DYNAMIC_INPUTS)) + _assert_windows_match(test, test_samples, static=True) + + +def test_streamflow_evaluation_matches_neuralhydrology_tester(nh, tmp_path): + """Whole pipeline: CAMELS-US reader + LSTM + rescaling + clipping + per-basin metrics vs. the NH Tester.""" + data_dir = _camels_test_data(nh, tmp_path) + cfg = _config( + nh, tmp_path, data_dir=str(data_dir), seq_length=90, hidden_size=32, + clip_targets_to_zero=["QObs(mm/d)"], metrics=["all"], **NH_PERIODS, + ) + cfg.run_dir.mkdir(parents=True, exist_ok=True) + nh["CamelsUS"](cfg, is_train=True, period="train") # writes the training scaler into the run directory + torch.manual_seed(0) + reference = nh["CudaLSTM"](cfg) + with torch.no_grad(): + reference.head.net[0].bias.fill_(0.3) # an untrained model would predict ~0 everywhere + tester = nh["RegressionTester"](cfg=cfg, run_dir=cfg.run_dir, period="test", init_model=False) + results = tester.evaluate(model=reference, metrics=["all"], save_results=False) + + bundle = CamelsUSStreamflowDataset( + data_dir=data_dir, basins=tmp_path / "basins.txt", periods=PERIODS, seq_length=90 + ).load() + port = build_model("neuralhydrology_lstm", task="regression", hidden_size=32) + port.load_state_dict(reference.state_dict(), strict=True) + port.eval() + summary, per_basin = evaluate_streamflow(port, bundle, "test", clip_negative=True) + + assert set(per_basin) == set(results) + # The Tester computes the metrics on float32 DataArrays, PyHazards in float64 (the definitions agree to + # 1e-12 in test_metrics_match_neuralhydrology); float32 rounding of logs and means needs rtol 2e-4. + for basin, values in per_basin.items(): + expected = results[basin]["1D"] + for nh_name, key in hydrology.NEURALHYDROLOGY_METRIC_NAMES.items(): + np.testing.assert_allclose(values[key], float(expected[nh_name]), rtol=2e-4, atol=1e-5, + equal_nan=True, err_msg=f"{basin} {nh_name}") + nse = [float(results[b]["1D"]["NSE"]) for b in results] + assert summary["nse"] == pytest.approx(float(np.median(nse)), rel=2e-4) + assert summary["n_basins"] == len(results) + + +CARAVAN_BASINS = ["camelsaus_102101A", "hysets_01075000", "lamah_1145"] +CARAVAN_DYNAMIC = ["total_precipitation_sum", "temperature_2m_mean", "potential_evaporation_sum"] + + +def test_caravan_reader_matches_neuralhydrology(nh, tmp_path): + data_dir = oracle_repo("flood-forecasting") / "test" / "test_data" / "multimet" + (tmp_path / "basins.txt").write_text("\n".join(CARAVAN_BASINS) + "\n") + cfg = _config( + nh, tmp_path, dataset="caravan", data_dir=str(data_dir), forcings=None, seq_length=120, + dynamic_inputs=CARAVAN_DYNAMIC, static_attributes=["area", "gauge_lat", "gauge_lon"], + target_variables=["streamflow"], + train_start_date="01/01/2000", train_end_date="31/12/2001", + validation_start_date="01/01/2002", validation_end_date="30/06/2002", + test_start_date="01/01/2002", test_end_date="30/06/2002", + ) + reference_train = nh["Caravan"](cfg, is_train=True, period="train") + bundle = CaravanStreamflowDataset( + data_dir=data_dir, basins=CARAVAN_BASINS, dynamic_inputs=CARAVAN_DYNAMIC, + static_attributes=["area", "gauge_lat", "gauge_lon"], seq_length=120, + periods={"train": ("2000-01-01", "2001-12-31"), "test": ("2002-01-01", "2002-06-30")}, + ).load() + _assert_windows_match(bundle.get_split("train").inputs, _nh_dataset_samples(reference_train, CARAVAN_DYNAMIC), static=True) + test = bundle.get_split("test").inputs + samples = {} + for basin in CARAVAN_BASINS: + reference_test = nh["Caravan"](cfg, is_train=False, period="test", basin=basin, scaler=reference_train.scaler) + samples.update(_nh_dataset_samples(reference_test, CARAVAN_DYNAMIC)) + _assert_windows_match(test, samples, static=True) + + csv_root = tmp_path / "caravan_csv" + for basin in CARAVAN_BASINS: # the same basins in the CSV layout + source = basin.split("_")[0] + frame = __import__("xarray").open_dataset(data_dir / "timeseries" / "netcdf" / source / f"{basin}.nc").to_dataframe() + (csv_root / "timeseries" / "csv" / source).mkdir(parents=True, exist_ok=True) + frame.to_csv(csv_root / "timeseries" / "csv" / source / f"{basin}.csv", index_label="date") + (csv_root / "attributes").mkdir(exist_ok=True) + import shutil + + shutil.copytree(data_dir / "attributes", csv_root / "attributes", dirs_exist_ok=True) + from_csv = CaravanStreamflowDataset( + data_dir=csv_root, basins=CARAVAN_BASINS, dynamic_inputs=CARAVAN_DYNAMIC, filetype="csv", + static_attributes=["area", "gauge_lat", "gauge_lon"], seq_length=120, + periods={"train": ("2000-01-01", "2001-12-31"), "test": ("2002-01-01", "2002-06-30")}, + ).load() + first_nc, first_csv = bundle.get_split("test").inputs[5], from_csv.get_split("test").inputs[5] + torch.testing.assert_close(first_csv[0]["x_d"], first_nc[0]["x_d"], rtol=1e-5, atol=1e-5) + + +# -------------------------------------------------------------------------------------------------- +# Official Kratzert et al. (2019) runs (HydroShare, 939 MB): gated on the large asset. + +RUNS = "Kratzert_et_al_2019_HESSD_LSTM_4_REGIONAL_MODELING/runs" +EALSTM_NSE_RUNS = ["run_1906_1004_seed111", "run_1906_1005_seed222", "run_1906_1005_seed333", "run_1906_1006_seed444", + "run_1906_1006_seed555", "run_1906_1006_seed666", "run_1906_1007_seed777", "run_1906_1007_seed888"] +LSTM_NSE_RUNS = ["run_1906_1009_seed111", "run_1906_1009_seed222", "run_1906_1009_seed333", "run_1906_1010_seed444", + "run_1906_1010_seed555", "run_1906_1010_seed666", "run_1906_1011_seed777", "run_1906_1011_seed888"] +NOSTATIC_NSE_RUN = "run_1606_0921_seed111" + + +@pytest.fixture(scope="module") +def runs_zip(): + path = oracle_large_asset("kratzert2019_hydroshare_runs") / "Kratzert_et_al_2019_HESSD_LSTM_4_REGIONAL_MODELING.zip" + with zipfile.ZipFile(path) as archive: + yield archive + + +@pytest.fixture(scope="module") +def paper_code(): + root = oracle_repo("ealstm_regional_modeling") + lstm = import_from(root, "papercode.lstm") + ealstm = import_from(root, "papercode.ealstm") + source = (root / "main.py").read_text(encoding="utf-8") + start = source.index("class Model(nn.Module)") + end = source.index("###########################\n# Train or evaluate model") + namespace = {"torch": torch, "nn": torch.nn, "Tuple": tuple, "LSTM": lstm.LSTM, "EALSTM": ealstm.EALSTM} + exec(compile(source[start:end], str(root / "main.py"), "exec"), namespace) # the Model wrapper, unchanged + return namespace["Model"] + + +@pytest.mark.parametrize( + "run, model_name, n_static, concat_static, no_static", + [ + (EALSTM_NSE_RUNS[0], "neuralhydrology_ealstm", 27, False, False), + # The 2019 "LSTM with static inputs" concatenates the 27 attributes to the 5 forcings (32 inputs). + (LSTM_NSE_RUNS[0], "neuralhydrology_lstm", 27, True, False), + (NOSTATIC_NSE_RUN, "neuralhydrology_lstm", 0, False, True), + ], +) +def test_official_2019_checkpoints(runs_zip, paper_code, run, model_name, n_static, concat_static, no_static): + state = torch.load(io.BytesIO(runs_zip.read(f"{RUNS}/{run}/model_epoch30.pt")), map_location="cpu", weights_only=True) + reference = paper_code(input_size_dyn=32 if concat_static else 5, input_size_stat=0 if no_static else 27, + hidden_size=256, dropout=0.4, concat_static=concat_static, no_static=no_static) + reference.load_state_dict(state, strict=True) + reference.eval() + port = build_model(model_name, task="regression", n_dynamic=5, n_static=n_static) + port.load_state_dict(convert_kratzert2019_state_dict(state), strict=True) + assert _n_params(port) == sum(v.numel() for v in state.values()) + (1024 if model_name == "neuralhydrology_lstm" else 0) + port.eval() + torch.manual_seed(0) + x_d = torch.randn(8, 270, 5) + x_s = torch.randn(8, 27) + with torch.no_grad(): + if concat_static: + expected = reference(torch.cat([x_d, x_s.unsqueeze(1).repeat(1, 270, 1)], dim=-1))[0] + actual = port({"x_d": x_d, "x_s": x_s})["y_hat"][:, -1] + elif no_static: + expected = reference(x_d)[0] + actual = port({"x_d": x_d})["y_hat"][:, -1] + else: + expected = reference(x_d, x_s)[0] + actual = port({"x_d": x_d, "x_s": x_s})["y_hat"][:, -1] + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def test_official_2019_attribute_order(runs_zip, tmp_path): + """KRATZERT2019_CHECKPOINT_STATIC_ORDER is the column order of the runs' attribute databases.""" + import sqlite3 + + from pyhazards.datasets.flood import KRATZERT2019_CHECKPOINT_STATIC_ORDER + + database = tmp_path / "attributes.db" + database.write_bytes(runs_zip.read(f"{RUNS}/{EALSTM_NSE_RUNS[0]}/attributes.db")) + with sqlite3.connect(database) as connection: + columns = [row[1] for row in connection.execute("PRAGMA table_info('basin_attributes')")] + root = oracle_repo("ealstm_regional_modeling") + invalid = import_from(root, "papercode.datautils").INVALID_ATTR + kept = [c for c in columns if c not in invalid and c not in ("gauge_id", "gauge_lat", "gauge_lon")] + assert kept == KRATZERT2019_CHECKPOINT_STATIC_ORDER + + +def _stored_simulations(runs_zip, run): + names = [n for n in runs_zip.namelist() if n.startswith(f"{RUNS}/{run}/") and n.endswith(".p")] + assert len(names) == 1 + return pickle.loads(runs_zip.read(names[0])) + + +def _nse_summary(observed, simulated): + per_basin = {b: hydrology.calculate_metrics(observed[b], simulated[b], metrics=["nse"]) for b in observed} + return hydrology.aggregate_basin_metrics(per_basin) + + +# Kratzert et al. (2019), Table 2: single model mean NSE, median NSE, basins with NSE <= 0 (averages over +# the 8 seeds), then the same for the ensemble mean of the 8 runs. +TABLE2 = { + ("lstm_no_static", "MSE"): (0.24, 0.60, 44, 0.36, 0.65, 31), + ("lstm_no_static", "NSE*"): (0.39, 0.59, 28, 0.49, 0.64, 20), + ("lstm_static", "MSE"): (0.66, 0.73, 6, 0.71, 0.76, 3), + ("lstm_static", "NSE*"): (0.69, 0.73, 2, 0.72, 0.76, 2), + ("ealstm", "MSE"): (0.63, 0.71, 9, 0.68, 0.74, 6), + ("ealstm", "NSE*"): (0.67, 0.71, 3, 0.70, 0.74, 2), +} + + +@pytest.fixture(scope="module") +def run_groups(runs_zip): + import json + + groups = {} + for name in runs_zip.namelist(): + if name.endswith("/cfg.json"): + cfg = json.loads(runs_zip.read(name)) + kind = "lstm_no_static" if cfg["no_static"] else ("lstm_static" if cfg["concat_static"] else "ealstm") + groups.setdefault((kind, "MSE" if cfg["use_mse"] else "NSE*"), []).append(name.split("/")[2]) + return {key: sorted(runs) for key, runs in groups.items()} + + +@pytest.mark.parametrize("group", sorted(TABLE2)) +def test_official_2019_simulations_reproduce_table2(runs_zip, run_groups, nh, group): + """PyHazards metrics and aggregation on the stored 1989-1999 test simulations give Table 2 of the paper.""" + import xarray as xr + + runs = run_groups[group] + assert len(runs) == 8 + means, medians, below_zero = [], [], [] + observed, ensemble = None, None + for run in runs: + simulations = _stored_simulations(runs_zip, run) + assert len(simulations) == 531 + if observed is None: + observed = {b: df["qobs"].to_numpy(dtype=np.float64) for b, df in simulations.items()} + ensemble = {b: np.zeros(len(df)) for b, df in simulations.items()} + simulated = {b: df["qsim"].to_numpy(dtype=np.float64) for b, df in simulations.items()} + summary = _nse_summary(observed, simulated) + means.append(summary["nse_mean"]) + medians.append(summary["nse"]) + below_zero.append(summary["n_basins_nse_le_0"]) + for b in ensemble: + ensemble[b] += simulated[b] / len(runs) + basin, df = next(iter(simulations.items())) # same value as NeuralHydrology's NSE + obs = xr.DataArray(observed[basin], coords={"date": df.index}, dims=["date"]) + sim = xr.DataArray(simulated[basin], coords={"date": df.index}, dims=["date"]) + assert hydrology.nse(observed[basin], simulated[basin]) == pytest.approx(nh["metrics"].nse(obs, sim), rel=1e-12) + ensemble_summary = _nse_summary(observed, ensemble) + mean, median, n_le_0, ens_mean, ens_median, ens_le_0 = TABLE2[group] + tolerance = 0.005 + 1e-9 # the table rounds to two decimals + assert abs(np.mean(means) - mean) <= tolerance + assert abs(np.mean(medians) - median) <= tolerance + assert abs(np.mean(below_zero) - n_le_0) <= 0.5 + assert abs(ensemble_summary["nse_mean"] - ens_mean) <= tolerance + assert abs(ensemble_summary["nse"] - ens_median) <= tolerance + assert ensemble_summary["n_basins_nse_le_0"] == ens_le_0 diff --git a/tests/oracle/test_phasenet_oracle.py b/tests/oracle/test_phasenet_oracle.py new file mode 100644 index 00000000..8c3ff1e6 --- /dev/null +++ b/tests/oracle/test_phasenet_oracle.py @@ -0,0 +1,224 @@ +"""PhaseNet checked against the official TensorFlow code and its released checkpoint. + +Reference (pinned in repos.yaml): AI4EPS/PhaseNet at 62005c6 (MIT). The official network is built by +``UNet(config, mode="pred")`` from ``phasenet/model.py`` (only ``ModelConfig``, ``crop_and_concat`` +and ``UNet`` are executed, inside a private ``tf.Graph``, so the module's global +``disable_eager_execution()`` call never runs) and restored from ``model/190703-214543/model_95.ckpt`` +with ``tf.compat.v1.train.Saver``, exactly as ``phasenet/predict.py`` does. TensorFlow 2.11 is the +release in the repository's ``env.yaml``. + +Checks: the pure-Python checkpoint reader returns TensorFlow's values; variable names, shapes and the +268,443 trainable parameters; the initialisation scheme; outputs in eval mode (moving statistics) and +in train mode (batch statistics) and the moving-average update, on random input of several lengths and +on 30-s windows of real STEAD traces; the official peak picking on the same probabilities; and the +SeisBench 0.12.6 port (GPL-3.0, second oracle) with its conversion of the same checkpoint. +""" + +from __future__ import annotations + +import logging +import warnings + +import h5py +import numpy as np +import pytest +import torch + +from oracle_utils import load_definitions, oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models._tf_checkpoint import read_tf_checkpoint +from pyhazards.models.phasenet import PhaseNet, load_phasenet_tf_checkpoint, state_dict_from_tf_checkpoint + +CHECKPOINT = "model/190703-214543/model_95.ckpt" +# float32 convolutions in TensorFlow and PyTorch sum in different orders; differences stay ~1e-6. +TOLERANCE = dict(rtol=1e-5, atol=1e-5) + + +@pytest.fixture(scope="module") +def tf(): + module = oracle_package("tensorflow", "2.11.0", "requirements-earthquake.txt") + module.get_logger().setLevel(logging.ERROR) + return module + + +@pytest.fixture(scope="module") +def checkpoint(): + return oracle_repo("PhaseNet") / CHECKPOINT + + +class OfficialPhaseNet: + """The official TF1 graph in its own ``tf.Graph`` / session.""" + + def __init__(self, tf, checkpoint=None): + root = oracle_repo("PhaseNet") + names = ["ModelConfig", "crop_and_concat", "UNet"] + defs = load_definitions(root / "phasenet" / "model.py", names, {"tf": tf, "np": np, "logging": logging}) + self.tf = tf + self.graph = tf.Graph() + with self.graph.as_default(): + # ModelConfig defaults equal model/190703-214543/config.log for every graph-building field. + self.model = defs["UNet"](config=defs["ModelConfig"](), mode="pred") + self.update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS) + self.session = tf.compat.v1.Session(graph=self.graph) + if checkpoint is None: + self.session.run(tf.compat.v1.global_variables_initializer()) + else: + tf.compat.v1.train.Saver(tf.compat.v1.global_variables()).restore(self.session, str(checkpoint)) + + def variables(self): + with self.graph.as_default(): + variables = self.tf.compat.v1.global_variables() + return {v.name[:-2]: value for v, value in zip(variables, self.session.run(variables))} + + def trainable_shapes(self): + with self.graph.as_default(): + variables = self.tf.compat.v1.trainable_variables() + # global_step is created with get_variable and so is "trainable"; it is not a network weight. + return [(v.name[:-2], tuple(v.shape.as_list())) for v in variables if v.name != "global_step:0"] + + def __call__(self, x: np.ndarray, training: bool = False, logits: bool = False, update: bool = False): + feed = { + self.model.X: x.transpose(0, 2, 1)[:, :, None, :], # (batch, samples, 1, channels) + self.model.is_training: training, + self.model.drop_rate: 0.0, + } + fetch = [self.model.logits if logits else self.model.preds] + (self.update_ops if update else []) + out = self.session.run(fetch, feed_dict=feed)[0] + return out[:, :, 0, :].transpose(0, 2, 1) # (batch, classes, samples) + + +def _port(checkpoint) -> PhaseNet: + return load_phasenet_tf_checkpoint(PhaseNet(), checkpoint).eval() + + +def _normalised(batch: int, length: int, seed: int) -> np.ndarray: + x = np.random.default_rng(seed).standard_normal((batch, 3, length)).astype("float32") + x -= x.mean(axis=-1, keepdims=True) + return x / x.std(axis=-1, keepdims=True) + + +def _stead_windows(samples: int = 3000) -> np.ndarray: + path = oracle_repo("EQTransformer") / "ModelsAndSampleData" / "100samples.hdf5" + with h5py.File(path, "r") as handle: + data = np.stack([handle["data"][name][()] for name in sorted(handle["data"])]) + # STEAD traces are (6000, 3) in E, N, Z order (PhaseNet's order); 30-s windows around the P arrivals. + return np.ascontiguousarray(data[:, 300 : 300 + samples].transpose(0, 2, 1)) + + +def test_checkpoint_reader_matches_tensorflow(tf, checkpoint): + reader = tf.train.load_checkpoint(str(checkpoint)) + names = reader.get_variable_to_shape_map() + ours = read_tf_checkpoint(checkpoint) + assert set(ours) == set(names) + for name in names: + np.testing.assert_array_equal(ours[name], reader.get_tensor(name), err_msg=name) + + +def test_names_shapes_and_parameter_count(tf): + official = OfficialPhaseNet(tf) + shapes = official.trainable_shapes() + assert sum(int(np.prod(shape)) for _, shape in shapes) == 268_443 + port = PhaseNet() + assert sum(p.numel() for p in port.parameters() if p.requires_grad) == 268_443 + + converted = state_dict_from_tf_checkpoint(official.variables()) + assert list(converted) == list(port.state_dict()) # same names, same (graph creation) order + trainable = [name for name, _ in port.named_parameters()] + renames = {"kernel": "weight", "gamma": "weight", "beta": "bias", "bias": "bias"} + expected = [f"{n.split('/')[0]}.{n.split('/')[1]}.{renames[n.split('/')[2]]}" for n, _ in shapes] + assert trainable == expected + port.load_state_dict(converted, strict=True) + + +def test_initialisation_matches_reference_scheme(tf): + official = state_dict_from_tf_checkpoint(OfficialPhaseNet(tf).variables()) + torch.manual_seed(0) + port = PhaseNet().state_dict() + for name, value in port.items(): + reference = official[name].float() + if name.endswith("num_batches_tracked"): + continue + if not name.endswith(".weight") or "_bn" in name: + torch.testing.assert_close(value, reference) # zero biases, BN gamma 1 / beta 0, moving 0 / 1 + continue + # Glorot uniform: both inside the same bound, with matching spread. + fans = reference.shape[1] * reference.shape[2] + reference.shape[0] * reference.shape[2] + limit = float(np.sqrt(6.0 / fans)) + assert value.abs().max() <= limit and reference.abs().max() <= limit, name + if value.numel() >= 1000: + assert abs(float(value.std()) / float(reference.std()) - 1) < 0.1, name + assert abs(float(value.std()) - limit / np.sqrt(3)) < 0.1 * limit, name + + +@pytest.mark.parametrize("length", [3000, 3001, 1234]) +def test_pretrained_outputs_match_official_in_eval_mode(tf, checkpoint, length): + official = OfficialPhaseNet(tf, checkpoint) + port = _port(checkpoint) + x = _normalised(4, length, seed=length) + with torch.no_grad(): + for logits in (True, False): + expected = torch.from_numpy(official(x, logits=logits)) + torch.testing.assert_close(port(torch.from_numpy(x), logits=logits), expected, **TOLERANCE) + + +def test_train_mode_batch_statistics_and_moving_averages(tf, checkpoint): + official = OfficialPhaseNet(tf, checkpoint) + port = _port(checkpoint).train() + x = _normalised(6, 3000, seed=1) + expected = torch.from_numpy(official(x, training=True, logits=True, update=True)) + with torch.no_grad(): + actual = port(torch.from_numpy(x), logits=True) + torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-4) # batch statistics in float32 + # One moving-average step (momentum 0.99) from the checkpoint statistics. + updated = state_dict_from_tf_checkpoint(official.variables()) + for name, value in port.state_dict().items(): + if name.endswith("running_mean") or name.endswith("running_var"): + torch.testing.assert_close(value, updated[name], rtol=1e-4, atol=1e-6, msg=name) + + +def test_real_stead_windows_and_official_peak_picking(tf, checkpoint): + root = oracle_repo("PhaseNet") + detect_peaks = load_definitions(root / "phasenet" / "detect_peaks.py", ["detect_peaks"], {"np": np, "warnings": warnings})[ + "detect_peaks" + ] + official = OfficialPhaseNet(tf, checkpoint) + port = _port(checkpoint) + raw = _stead_windows() + normalised = raw - raw.mean(axis=-1, keepdims=True) # phasenet/data_reader.py normalize() + std = raw.std(axis=-1, keepdims=True) + normalised /= np.where(std == 0, 1, std) + expected = official(normalised.astype("float32")) + with torch.no_grad(): + probabilities = port.annotate(torch.from_numpy(raw)) + torch.testing.assert_close(probabilities, torch.from_numpy(expected), **TOLERANCE) + + picks = port.extract_picks(probabilities) + n_picks = 0 + for trace, trace_picks in zip(expected, picks): + for phase, channel in (("P", 1), ("S", 2)): + # phasenet/util.py detect_peaks_thread: mph=0.5, mpd=0.5/dt + index, prob = detect_peaks(trace[channel], mph=0.5, mpd=0.5 / 0.01, show=False) + assert [int(i) for i, _ in trace_picks[phase]] == [int(i) for i in index] + np.testing.assert_allclose([p for _, p in trace_picks[phase]], prob, rtol=1e-4, atol=1e-5) + n_picks += len(index) + assert n_picks > 100 # the pretrained model picks most of the 100 events + + +def test_seisbench_port_agrees(checkpoint): + seisbench_models = oracle_package("seisbench", "0.12.6", "requirements-earthquake.txt") + import seisbench.models as sbm + + _ = seisbench_models + reference = sbm.PhaseNet(in_channels=3, classes=3, phases="NPS", sampling_rate=100, norm="std") + weights = oracle_asset("seisbench_phasenet_original") / "original.pt.v2" + reference.load_state_dict(torch.load(weights, map_location="cpu", weights_only=True)) + reference.eval() + port = _port(checkpoint) + x = torch.from_numpy(_normalised(3, 3001, seed=7)) # SeisBench PhaseNet takes 3001 samples + with torch.no_grad(): + torch.testing.assert_close(port(x), reference(x), **TOLERANCE) + + +def test_builder_loads_a_local_checkpoint(checkpoint): + model = build_model("phasenet", task="picking", pretrained=str(checkpoint)).eval() + torch.testing.assert_close(model.state_dict()["Output.output_conv.bias"], _port(checkpoint).state_dict()["Output.output_conv.bias"]) diff --git a/tests/oracle/test_picking_metrics_oracle.py b/tests/oracle/test_picking_metrics_oracle.py new file mode 100644 index 00000000..d60dcbec --- /dev/null +++ b/tests/oracle/test_picking_metrics_oracle.py @@ -0,0 +1,110 @@ +"""Pick-extraction utilities checked against the code the original pickers use. + +- ``detect_peaks`` against the copies shipped with PhaseNet (``phasenet/detect_peaks.py``, Duarte's + version 1.0.6) and EQTransformer (``EqT_utils._detect_peaks``), both pinned in repos.yaml. +- ``trigger_onset`` (reimplemented from ObsPy's documentation, ObsPy being LGPL) against ObsPy 1.5.1, + which EQTransformer and gpd_predict.py import. +- ``score_picks`` against the official PhaseNet evaluation, ``correct_picks`` + ``metrics`` in + ``phasenet/util.py``. +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import pytest + +from oracle_utils import load_definitions, oracle_package, oracle_repo +from pyhazards.metrics.picking import detect_peaks, score_picks, trigger_onset + + +def _random_traces(seed: int, count: int = 400): + rng = np.random.default_rng(seed) + for _ in range(count): + n = int(rng.integers(0, 300)) + x = rng.random(n) + if rng.random() < 0.3: + x = np.round(x, 1) # plateaus and ties + if rng.random() < 0.1 and n > 5: + x[rng.integers(0, n)] = np.nan + yield x + + +def _eqt_detect_peaks(): + source = oracle_repo("EQTransformer") / "EQTransformer" / "core" / "EqT_utils.py" + return load_definitions(source, ["_detect_peaks"], {"np": np})["_detect_peaks"] + + +def test_detect_peaks_matches_phasenet_copy(): + official = load_definitions( + oracle_repo("PhaseNet") / "phasenet" / "detect_peaks.py", ["detect_peaks"], {"np": np, "warnings": warnings} + )["detect_peaks"] + rng = np.random.default_rng(0) + for x in _random_traces(1): + kwargs = dict(mph=float(rng.choice([0.3, 0.5, 0.9])), mpd=int(rng.choice([1, 2, 5, 50]))) + if rng.random() < 0.3: + kwargs["threshold"] = 0.05 + if rng.random() < 0.3: + kwargs["edge"] = str(rng.choice(["both", "falling"])) + result = official(x.copy(), show=False, **kwargs) + expected = result[0] if isinstance(result, tuple) else result + np.testing.assert_array_equal(detect_peaks(x, **kwargs), expected) + + +def test_detect_peaks_matches_eqtransformer_copy(): + official = _eqt_detect_peaks() + rng = np.random.default_rng(1) + for x in _random_traces(2): + kwargs = dict(mph=float(rng.choice([0.1, 0.3])), mpd=int(rng.choice([1, 3]))) + np.testing.assert_array_equal(detect_peaks(x, **kwargs), official(x.copy(), **kwargs)) + + +def test_trigger_onset_matches_obspy(): + oracle_package("obspy", "1.5.1", "requirements-earthquake.txt") + from obspy.signal.trigger import trigger_onset as obspy_trigger_onset + + rng = np.random.default_rng(3) + for x in _random_traces(4, count=2000): + x = np.nan_to_num(x) + thres1 = float(np.round(rng.random(), 2)) + thres2 = float(np.round(rng.random() * thres1, 2)) + expected = np.array(obspy_trigger_onset(x, thres1, thres2), dtype=int).reshape(-1, 2) + np.testing.assert_array_equal(trigger_onset(x, thres1, thres2), expected) + # The thresholds of EQTransformer (equal on/off) and of gpd_predict.py (0.95 / 0.1). + x = rng.random(5000) + for thres1, thres2 in ((0.2, 0.2), (0.95, 0.1)): + expected = np.array(obspy_trigger_onset(x, thres1, thres2), dtype=int).reshape(-1, 2) + np.testing.assert_array_equal(trigger_onset(x, thres1, thres2), expected) + + +def test_score_picks_matches_official_phasenet_evaluation(): + source = oracle_repo("PhaseNet") / "phasenet" / "util.py" + # correct_picks reads dt from DataConfig (0.01 s); provide just that. + defs = load_definitions(source, ["correct_picks", "metrics"], {"np": np, "DataConfig": lambda: type("C", (), {"dt": 0.01})()}) + rng = np.random.default_rng(5) + picks, true_p, true_s = [], [], [] + for _ in range(300): + tp, ts = [float(rng.integers(100, 2000))], [float(rng.integers(2000, 2900))] + pred_p = [tp[0] + float(rng.normal(0, 15)) for _ in range(int(rng.integers(0, 3)))] + pred_s = [ts[0] + float(rng.normal(0, 30)) for _ in range(int(rng.integers(0, 3)))] + [float(rng.integers(0, 3000))] + picks.append([[pred_p], [pred_s]]) + true_p.append(tp) + true_s.append(ts) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + tp_p, tp_s, np_p, np_s, nt_p, nt_s, diff_p, diff_s = defs["correct_picks"](picks, true_p, true_s, tol=0.1) + for phase, (tp, n_pred, n_true, diffs, manual) in { + "P": (tp_p, np_p, nt_p, diff_p, true_p), + "S": (tp_s, np_s, nt_s, diff_s, true_s), + }.items(): + column = 0 if phase == "P" else 1 + predicted = [trace[column][0] for trace in picks] + score = score_picks(predicted, manual, tolerance=10.0, residual_window=50.0) + assert (score.n_tp, score.n_pred, score.n_true) == (tp, n_pred, n_true) + np.testing.assert_allclose(sorted(score.residuals), sorted(np.concatenate([d.ravel() for d in diffs]))) + precision, recall, f1 = defs["metrics"](tp, n_pred, n_true) + values = score.metrics(100.0) + assert values["precision"] == pytest.approx(precision) + assert values["recall"] == pytest.approx(recall) + assert values["f1"] == pytest.approx(f1) diff --git a/tests/oracle/test_prithvi_oracle.py b/tests/oracle/test_prithvi_oracle.py new file mode 100644 index 00000000..1bb3bf8a --- /dev/null +++ b/tests/oracle/test_prithvi_oracle.py @@ -0,0 +1,356 @@ +"""Prithvi-EO-2.0 ports checked against TerraTorch 0.99.8 and the official ``prithvi_mae.py``. + +References (tests/oracle/requirements-prithvi.txt and repos.yaml): TerraTorch 0.99.8 with smp 0.4.0 and +timm 1.0.15, the stack the BurnScars checkpoint was trained with; ``prithvi_mae.py`` and +``burn_scars_config.yaml`` from the Hugging Face repositories at pinned revisions. The routine checks +use randomly initialised official modules (same seed, same parameter names and values, same outputs). +The two tests at the end load the 1.3 GB official checkpoints and are skipped unless those ``large`` +assets have been fetched. + +Run in the Prithvi oracle environment (Python >= 3.12), not the generic oracle one. +""" + +from __future__ import annotations + +import warnings + +import numpy as np +import pytest +import torch +import yaml + +from oracle_utils import import_from, oracle_asset, oracle_large_asset, oracle_package +from pyhazards.models import build_model +from pyhazards.models.prithvi import ( + PRITHVI_BANDS, + PRITHVI_EO_V2_CONFIGS, + PRITHVI_EO_V2_MEAN, + PRITHVI_EO_V2_STD, + PrithviMAE, + get_3d_sincos_pos_embed, +) +from pyhazards.models.prithvi_burnscars import BURN_SCARS_CLASSES, BURN_SCARS_MEAN, BURN_SCARS_STD + +REQ = "requirements-prithvi.txt" +TINY = dict(embed_dim=64, depth=4, num_heads=2) +TINY_RECIPE = dict(select_indices=[0, 1, 2, 3], decoder_channels=[32, 16, 8, 4]) + + +@pytest.fixture(scope="module") +def terratorch(): + oracle_package("segmentation_models_pytorch", "0.4.0", REQ) + oracle_package("timm", "1.0.15", REQ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + module = oracle_package("terratorch", "0.99.8", REQ) + import terratorch.models # noqa: F401 (registers backbones, necks and decoders) + return module + + +@pytest.fixture(scope="module") +def burn_scars_config(): + path = oracle_asset("prithvi_burnscars_config") / "burn_scars_config.yaml" + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +@pytest.fixture(scope="module") +def reference_mae(): + oracle_package("timm", "1.0.15", REQ) + return import_from(oracle_asset("prithvi_eo2_tl_model_code"), "prithvi_mae") + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _official_segmentation(model_args: dict, seed: int, **overrides): + """TerraTorch EncoderDecoderFactory model, without downloading the backbone weights.""" + from terratorch.models import EncoderDecoderFactory + + args = dict(model_args, backbone_pretrained=False, **overrides) + torch.manual_seed(seed) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return EncoderDecoderFactory().build_model(task="segmentation", **args) + + +def _coords(batch: int, frames: int): + years = torch.tensor([[2018.0 + i for i in range(frames)]] * batch) + days = torch.tensor([[26.0 + 80 * i for i in range(frames)]] * batch) + torch.arange(batch)[:, None] + temporal = torch.stack([years, days], dim=-1) + location = torch.tensor([[25.0 + b, -104.5 + 2 * b] for b in range(batch)]) + return temporal, location + + +def test_burn_scars_recipe_matches_official_config(terratorch, burn_scars_config): + from terratorch.models.backbones import prithvi_vit + + args = burn_scars_config["model"]["init_args"]["model_args"] + assert args["backbone"] == "prithvi_eo_v2_300" + assert args["backbone_bands"] == list(PRITHVI_BANDS) + assert args["necks"] == [ + {"name": "SelectIndices", "indices": [5, 11, 17, 23]}, + {"name": "ReshapeTokensToImage"}, + {"name": "LearnedInterpolateToPyramidal"}, + ] + assert args["decoder"] == "UNetDecoder" + assert args["decoder_channels"] == [512, 256, 128, 64] + assert args["num_classes"] == 2 + assert burn_scars_config["model"]["init_args"]["class_names"] == list(BURN_SCARS_CLASSES) + data = burn_scars_config["data"]["init_args"] + assert data["output_bands"] == list(PRITHVI_BANDS) + assert tuple(data["means"]) == BURN_SCARS_MEAN + assert tuple(data["stds"]) == BURN_SCARS_STD + + assert tuple(prithvi_vit.PRITHVI_V2_MEAN) == PRITHVI_EO_V2_MEAN + assert tuple(prithvi_vit.PRITHVI_V2_STD) == PRITHVI_EO_V2_STD + for variant, names in {"300m": ["prithvi_eo_v2_300", "prithvi_eo_v2_300_tl"], "600m": ["prithvi_eo_v2_600_tl"]}.items(): + ours = PRITHVI_EO_V2_CONFIGS[variant] + for name in names: + cfg = prithvi_vit.prithvi_cfgs[name] + assert (cfg["embed_dim"], cfg["depth"], cfg["num_heads"]) == (ours["embed_dim"], ours["depth"], ours["num_heads"]) + assert tuple(cfg["patch_size"]) == ours["patch_size"] + assert (cfg["img_size"], cfg["in_chans"], cfg["mlp_ratio"]) == (224, 6, 4) + if name.endswith("_tl"): + assert cfg["coords_encoding"] == ["time", "location"] and cfg["coords_scale_learn"] is True + + +def test_burnscars_initialisation_and_forward_match_terratorch(terratorch, burn_scars_config): + model_args = burn_scars_config["model"]["init_args"]["model_args"] + reference = _official_segmentation(model_args, seed=0) + torch.manual_seed(0) + port = build_model("prithvi_burnscars", task="segmentation") + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 324_204_674 + + torch.manual_seed(1) + x = torch.randn(2, 6, 64, 64) + padded = torch.randn(1, 6, 120, 120) # reflect-padded to 128 x 128 and cropped back + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x).output) + _assert_close(port(x[:, :, None]), reference(x).output) + _assert_close(port(padded), reference(padded).output) + reference.train() + port.train() + _assert_close(port(x), reference(x).output) + for key, value in reference.state_dict().items(): # BatchNorm running statistics + assert torch.equal(value, port.state_dict()[key]), key + + +def test_tiny_burnscars_configuration_matches_terratorch(terratorch, burn_scars_config): + model_args = dict(burn_scars_config["model"]["init_args"]["model_args"]) + model_args.update( + necks=[{"name": "SelectIndices", "indices": [0, 1, 2, 3]}, {"name": "ReshapeTokensToImage"}, + {"name": "LearnedInterpolateToPyramidal"}], + decoder_channels=[32, 16, 8, 4], + ) + reference = _official_segmentation( + model_args, seed=3, backbone_embed_dim=64, backbone_depth=4, backbone_num_heads=2 + ).eval() + torch.manual_seed(3) + port = build_model("prithvi_burnscars", task="segmentation", **TINY, **TINY_RECIPE).eval() + _assert_same_state(reference, port) + x = torch.randn(3, 6, 96, 96) + with torch.no_grad(): + _assert_close(port(x), reference(x).output) + + +def test_tl_segmentation_matches_terratorch(terratorch, burn_scars_config): + model_args = dict(burn_scars_config["model"]["init_args"]["model_args"], backbone="prithvi_eo_v2_300_tl") + reference = _official_segmentation(model_args, seed=0) + torch.manual_seed(0) + port = build_model("prithvi_eo_2_tl", task="segmentation") + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 324_204_676 + + torch.manual_seed(1) + x = torch.randn(2, 6, 64, 64) + temporal, location = _coords(2, 1) + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(x, temporal_coords=temporal, location_coords=location).output + _assert_close(port(x, temporal_coords=temporal, location_coords=location), expected) + _assert_close(port(x), reference(x).output) + assert not torch.allclose(port(x), expected) # the coordinates are used + + +def test_multitemporal_tl_segmentation_matches_terratorch_modules(terratorch, burn_scars_config): + # Official multi-temporal recipe: backbone_num_frames = T and ReshapeTokensToImage(effective_time_dim=T). + # TerraTorch 0.99.8's PixelWiseModel cannot pad 5-D input, so the reference modules are chained by hand + # on an input that needs no padding. + frames = 3 + model_args = dict(burn_scars_config["model"]["init_args"]["model_args"], backbone="prithvi_eo_v2_300_tl") + model_args.update( + necks=[{"name": "SelectIndices", "indices": [0, 1, 2, 3]}, + {"name": "ReshapeTokensToImage", "effective_time_dim": frames}, + {"name": "LearnedInterpolateToPyramidal"}], + decoder_channels=[32, 16, 8, 4], + ) + reference = _official_segmentation( + model_args, seed=5, backbone_embed_dim=64, backbone_depth=4, backbone_num_heads=2, backbone_num_frames=frames + ).eval() + torch.manual_seed(5) + port = build_model("prithvi_eo_2_tl", task="segmentation", num_frames=frames, **TINY, **TINY_RECIPE).eval() + _assert_same_state(reference, port) + + x = torch.randn(2, 6, frames, 64, 64) + temporal, location = _coords(2, frames) + with torch.no_grad(): + features = reference.encoder(x, temporal_coords=temporal, location_coords=location) + features = reference.neck(features) + expected = reference.head(reference.decoder([f.clone() for f in features])) + expected = torch.nn.functional.interpolate(expected, size=(64, 64), mode="bilinear") + _assert_close(port(x, temporal_coords=temporal, location_coords=location), expected) + + +def test_600m_tl_encoder_matches_terratorch(terratorch): + from terratorch.registry import BACKBONE_REGISTRY + + torch.manual_seed(7) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + reference = BACKBONE_REGISTRY.build("prithvi_eo_v2_600_tl", pretrained=False, depth=2).eval() + torch.manual_seed(7) + port = build_model( + "prithvi_eo_2_tl", task="segmentation", variant="600m", depth=2, select_indices=[0, 1, 1, 1] + ).encoder.eval() + _assert_same_state(reference, port) + x = torch.randn(1, 6, 56, 56) + temporal, location = _coords(1, 1) + with torch.no_grad(): + for actual, expected in zip( + port.forward_features(x, temporal, location), reference(x, temporal_coords=temporal, location_coords=location) + ): + _assert_close(actual, expected) + + +@pytest.mark.parametrize("coords", [True, False]) +def test_mae_matches_official_prithvi_mae(reference_mae, coords): + config = dict( + img_size=64, num_frames=4, patch_size=[1, 16, 16], in_chans=6, embed_dim=1024, depth=24, num_heads=16, + decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16, mlp_ratio=4, + coords_encoding=["time", "location"], coords_scale_learn=True, + ) + torch.manual_seed(0) + reference = reference_mae.PrithviMAE(**config) + torch.manual_seed(0) + port = PrithviMAE(**config) + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 330_419_716 + + x = torch.randn(2, 6, 4, 64, 64) + temporal, location = _coords(2, 4) if coords else (None, None) + reference.eval() + port.eval() + with torch.no_grad(): + torch.manual_seed(1) + ref_loss, ref_pred, ref_mask = reference(x, temporal, location) + torch.manual_seed(1) + loss, pred, mask = port(x, temporal, location) + _assert_close(loss, ref_loss) + _assert_close(pred, ref_pred) + assert torch.equal(mask, ref_mask) + for actual, expected in zip(port.forward_features(x, temporal, location), + reference.forward_features(x, temporal, location)): + _assert_close(actual, expected) + # One frame instead of four: the time axis of the position table is recomputed. + _assert_close(port.forward_features(x[:, :, :1])[-1], reference.forward_features(x[:, :, :1])[-1]) + assert torch.equal(port.patchify(x), reference.patchify(x)) + assert torch.equal(port.unpatchify(port.patchify(x), image_size=(64, 64)), x) + + +def test_burnscars_official_weights_match_terratorch(terratorch, burn_scars_config): + rasterio = pytest.importorskip("rasterio") + checkpoint = oracle_large_asset("prithvi_eo2_300m_burnscars_weights") / "Prithvi_EO_V2_300M_BurnScars.pt" + chip = oracle_asset("prithvi_burnscars_example") / "subsetted_512x512_HLS.S30.T10SEH.2018190.v1.4_merged.tif" + + reference = _official_segmentation(burn_scars_config["model"]["init_args"]["model_args"], seed=0) + state = torch.load(checkpoint, map_location="cpu", weights_only=True)["state_dict"] + reference.load_state_dict({k[len("model."):]: v for k, v in state.items()}, strict=True) + port = build_model("prithvi_burnscars", task="segmentation", weights_path=str(checkpoint)) + + # Official inference.py preprocessing: reflectance in 0-1 (divide by 10000 if needed), then the + # datamodule's per-band standardisation. + with rasterio.open(chip) as src: + image = src.read().astype("float32") + if image.mean() > 1: + image = image / 10000 + mean = np.array(BURN_SCARS_MEAN, dtype="float32")[:, None, None] + std = np.array(BURN_SCARS_STD, dtype="float32")[:, None, None] + x = torch.from_numpy((image - mean) / std)[None] + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(x).output + actual = port(x) + assert actual.shape == (1, 2, 512, 512) + _assert_close(actual, expected) + assert torch.equal(actual.argmax(1), expected.argmax(1)) + burned = actual.argmax(1).float().mean().item() + assert 0.79 < burned < 0.80, burned # 79.5 % of this chip is predicted burned + + +def test_tl_official_weights_match_reference(terratorch, reference_mae): + checkpoint = oracle_large_asset("prithvi_eo2_300m_tl_weights") / "Prithvi_EO_V2_300M_TL.pt" + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + + # The position tables in the checkpoint are the fixed sin/cos tables (up to float32 rounding, max + # 4.6e-7), so the segmentation encoder rebuilds its own for its frame count, as TerraTorch does. + for key, dim in [("encoder.pos_embed", 1024), ("decoder.decoder_pos_embed", 512)]: + table = torch.from_numpy(get_3d_sincos_pos_embed(dim, (4, 14, 14), add_cls_token=True)).float()[None] + torch.testing.assert_close(state[key], table, rtol=0, atol=1e-6) + + config = dict( + img_size=224, num_frames=4, patch_size=[1, 16, 16], in_chans=6, embed_dim=1024, depth=24, num_heads=16, + decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16, mlp_ratio=4, + coords_encoding=["time", "location"], coords_scale_learn=True, + ) + reference = reference_mae.PrithviMAE(**config).eval() + reference.load_state_dict(state, strict=True) + port = PrithviMAE(**config).eval() + port.load_state_dict(state, strict=True) + + torch.manual_seed(2) + x = torch.randn(1, 6, 4, 224, 224) + temporal, location = _coords(1, 4) + with torch.no_grad(): + for coords in [(temporal, location), (None, None)]: + torch.manual_seed(3) + ref_loss, ref_pred, ref_mask = reference(x, *coords) + torch.manual_seed(3) + loss, pred, mask = port(x, *coords) + _assert_close(loss, ref_loss) + _assert_close(pred, ref_pred) + assert torch.equal(mask, ref_mask) + del reference + + # Encoder loaded through the registry (MAE checkpoint -> encoder keys) vs TerraTorch's backbone loader. + from terratorch.registry import BACKBONE_REGISTRY + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + backbone = BACKBONE_REGISTRY.build("prithvi_eo_v2_300_tl", pretrained=True, ckpt_path=str(checkpoint)).eval() + model = build_model("prithvi_eo_2_tl", task="segmentation", weights_path=str(checkpoint)).eval() + _assert_same_state(backbone, model.encoder) + x = torch.randn(1, 6, 224, 224) + temporal, location = _coords(1, 1) + with torch.no_grad(): + for actual, expected in zip( + model.encoder.forward_features(x, temporal, location), + backbone(x, temporal_coords=temporal, location_coords=location), + ): + _assert_close(actual, expected) diff --git a/tests/oracle/test_rainformer_oracle.py b/tests/oracle/test_rainformer_oracle.py new file mode 100644 index 00000000..77e88776 --- /dev/null +++ b/tests/oracle/test_rainformer_oracle.py @@ -0,0 +1,182 @@ +"""Rainformer checked against the official code (Zjut-MultimediaPlus/Rainformer, pinned in repos.yaml). + +The official repository has no license: it is fetched at test time and never vendored; its KNMI +checkpoint (Google Drive, no licence stated) is used only as test data. The reference needs +einops; the Oracle workflow runs this file with requirements-farseer-rainformer.txt. + +The reference hard-codes its stage feature maps for 288x288 inputs (72/36/18/9), so every +comparison runs at 288x288 with downscaling factors (4, 2, 2, 2). CI compares narrow models; +the default 187.7M-parameter model and the official weights are compared with +``PYHAZARDS_ORACLE_LARGE=1`` / the large ``rainformer_knmi_weights`` asset (run locally, recorded +in the model card). Each check requires identical parameter names and seeded initial values and +compares outputs in eval mode and in train mode (BatchNorm), gradients and running statistics. +""" + +from __future__ import annotations + +import importlib +import os +import sys +from importlib import metadata +from pathlib import Path + +import pytest +import torch + +from oracle_utils import missing, oracle_large_asset, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.rainformer import Rainformer, rainformer_stage_sizes + +REQUIREMENTS = Path(__file__).parent / "requirements-farseer-rainformer.txt" +KNMI_CHECKPOINT = "model1_1_100.pt" +OFFICIAL = dict( + input_channel=9, hidden_dim=96, downscaling_factors=(4, 2, 2, 2), layers=(2, 2, 2, 2), heads=(3, 6, 12, 24), + head_dim=32, window_size=9, relative_pos_embedding=True, +) + + +@pytest.fixture(autouse=True) +def _reference_stack(): + for line in REQUIREMENTS.read_text().splitlines(): + if "==" not in line or line.lstrip().startswith("#"): + continue + name, version = line.split("#")[0].strip().split("==") + try: + found = metadata.version(name) + except metadata.PackageNotFoundError: + missing(f"{name} is not installed; pip install -r tests/oracle/{REQUIREMENTS.name}") + if found != version: + missing(f"needs {name}=={version}, found {found}") + + +def _import_reference(root: Path, module: str): + """Import a module of a flat reference directory without leaking its generic module names.""" + names = {path.stem for path in root.glob("*.py")} + saved = {name: sys.modules.pop(name) for name in list(sys.modules) if name.split(".")[0] in names} + sys.path.insert(0, str(root)) + try: + return importlib.import_module(module) + finally: + sys.path.remove(str(root)) + for name in [name for name in sys.modules if name.split(".")[0] in names]: + del sys.modules[name] + sys.modules.update(saved) + + +@pytest.fixture(scope="module") +def reference(): + return _import_reference(oracle_repo("Rainformer") / "Rainformer", "Rainformer") + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _compare_forward(reference: torch.nn.Module, port: torch.nn.Module, x: torch.Tensor) -> None: + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + reference.train() + port.train() # BatchNorm uses batch statistics and updates its running statistics + expected = reference(x) + actual = port(x) + _assert_close(actual, expected) + expected.square().mean().backward() + actual.square().mean().backward() + ref_params = dict(reference.named_parameters()) + for name, param in port.named_parameters(): + ref_grad = ref_params[name].grad + assert (param.grad is None) == (ref_grad is None), name + if ref_grad is not None: + torch.testing.assert_close(param.grad, ref_grad, rtol=1e-4, atol=1e-6, msg=name) + _assert_same_state(reference, port) # running statistics after one training step + + +REDUCED = [ + dict(input_channel=4, hidden_dim=8, layers=(2, 2, 2, 2), heads=(1, 1, 2, 2), head_dim=8, window_size=9, relative_pos_embedding=True), + dict(input_channel=3, hidden_dim=8, layers=(4, 2, 2, 2), heads=(2, 1, 1, 2), head_dim=4, window_size=3, relative_pos_embedding=False), + dict(input_channel=2, hidden_dim=16, layers=(2, 2, 4, 2), heads=(1, 2, 2, 2), head_dim=8, window_size=3, relative_pos_embedding=True), +] + + +@pytest.mark.parametrize("config", REDUCED) +def test_rainformer_reduced_configs_match_reference(reference, config): + config = {**config, "downscaling_factors": (4, 2, 2, 2)} + torch.manual_seed(0) + ref = reference.Net(**config) + torch.manual_seed(0) + port = Rainformer(**config) + _assert_same_state(ref, port) + assert _n_params(port) == _n_params(ref) + + torch.manual_seed(1) + x = torch.rand(2, config["input_channel"], 288, 288) + _compare_forward(ref, port, x) + + +def test_rainformer_stage_sizes_match_the_hard_coded_reference(reference): + torch.manual_seed(0) + ref = reference.Net(**{**REDUCED[0], "downscaling_factors": (4, 2, 2, 2)}) + gate_maps = [ + tuple(getattr(ref, f"stage{i}").layers[0][4].conv_2[1].normalized_shape[1:]) for i in range(1, 9) + ] + assert gate_maps == rainformer_stage_sizes(288, (4, 2, 2, 2)) + # The reference cannot run Sim2Real-Fire's 256x256 frames (64/32/16/8 maps, window 9). + with pytest.raises(Exception): + ref.eval()(torch.rand(1, 4, 256, 256)) + + +def test_rainformer_builder_time_major_layout(reference): + config = {**REDUCED[0], "downscaling_factors": (4, 2, 2, 2)} + torch.manual_seed(0) + ref = reference.Net(**config).eval() + model = build_model( + "rainformer", task="forecasting", in_channels=2, history=2, hidden_dim=8, heads=(1, 1, 2, 2), head_dim=8 + ).eval() + model.load_state_dict(ref.state_dict(), strict=True) + x = torch.rand(1, 2, 2, 288, 288) # (batch, time, channels) -> 4 stacked frames + with torch.no_grad(): + _assert_close(model(x), ref(x.flatten(1, 2)).reshape(1, 2, 2, 288, 288)) + + +def test_rainformer_default_config_matches_reference(reference): + if os.environ.get("PYHAZARDS_ORACLE_LARGE") != "1": + pytest.skip("default-size comparison (187.7M parameters) runs with PYHAZARDS_ORACLE_LARGE=1") + torch.manual_seed(0) + ref = reference.Net(**OFFICIAL) + torch.manual_seed(0) + port = build_model("rainformer", task="forecasting") + _assert_same_state(ref, port) + assert _n_params(port) == 187_661_990 + + torch.manual_seed(1) + _compare_forward(ref, port, torch.rand(2, 9, 288, 288)) + + +def test_rainformer_knmi_weights_match_reference(reference): + checkpoint = oracle_large_asset("rainformer_knmi_weights") / KNMI_CHECKPOINT + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + ref = reference.Net(**OFFICIAL) + ref.load_state_dict(state, strict=True) + port = build_model("rainformer", task="forecasting") + port.load_state_dict(state, strict=True) + ref.eval() + port.eval() + torch.manual_seed(2) + x = torch.rand(2, 9, 288, 288) * 4 # non-negative rain-like inputs + with torch.no_grad(): + expected = ref(x) + _assert_close(port(x), expected) + _assert_close(port(x.unsqueeze(2)), expected.unsqueeze(2)) # (batch, time, 1, H, W) diff --git a/tests/oracle/test_saf_net_oracle.py b/tests/oracle/test_saf_net_oracle.py new file mode 100644 index 00000000..3d9beeab --- /dev/null +++ b/tests/oracle/test_saf_net_oracle.py @@ -0,0 +1,115 @@ +"""SAF-Net checked against the official notebook network and checkpoint (xuguangning1218/TI_Prediction, pinned). + +The official code has no license: PyHazards' SAF-Net is written from the paper, and the notebook's +``Net`` class is executed here, from the pinned ``SAF-Net.ipynb``, only as a test oracle. The released +checkpoint ``model_saver/SAF_Net.pkl`` is read from the same checkout. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +from oracle_utils import oracle_repo +from pyhazards.models import build_model + + +def _official_net(): + repo = oracle_repo("TI_Prediction") + notebook = json.loads((repo / "SAF-Net.ipynb").read_text(encoding="utf-8")) + cells = ["".join(cell["source"]) for cell in notebook["cells"] if cell["cell_type"] == "code"] + source = next(cell for cell in cells if "class Net(nn.Module)" in cell) + source = source[: source.index("net = Net()")] + # Notebook globals the class uses: ahead_times = [0, 1, 2, 3] (t, t-6 h, t-12 h, t-18 h). + scope = {"torch": torch, "nn": nn, "F": F, "ahead_times": [0, 1, 2, 3]} + exec(compile(source, "SAF-Net.ipynb", "exec"), scope) + return scope["Net"], repo + + +def _inputs(batch: int = 4, seed: int = 1): + generator = torch.Generator().manual_seed(seed) + return torch.rand(batch, 96, generator=generator), torch.rand(batch, 2, 4, 31, 31, 4, generator=generator) + + +def _assert_same_state(reference: nn.Module, port: nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def test_parameters_and_seeded_initialisation_match_official(): + Net, _ = _official_net() + torch.manual_seed(0) + reference = Net() + torch.manual_seed(0) + port = build_model("saf_net", task="regression") + assert sum(p.numel() for p in reference.parameters()) == sum(p.numel() for p in port.parameters()) == 880_233 + _assert_same_state(reference, port) + + +def test_outputs_match_official_in_eval_and_train_mode(): + Net, _ = _official_net() + torch.manual_seed(0) + reference = Net() + port = build_model("saf_net", task="regression") + port.load_state_dict(reference.state_dict(), strict=True) + wide, deep = _inputs() + reference.eval() + port.eval() + with torch.no_grad(): + torch.testing.assert_close(port(wide, deep), reference(wide, deep), rtol=1e-5, atol=1e-6) + torch.testing.assert_close(port({"wide": wide, "deep": deep}), reference(wide, deep), rtol=1e-5, atol=1e-6) + # Train mode: BatchNorm uses batch statistics and updates its running statistics in call order. + reference.train() + port.train() + expected = reference(wide, deep) + actual = port(wide, deep) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + _assert_same_state(reference, port) + expected.sum().backward() + actual.sum().backward() + for (name, ref_param), port_param in zip(reference.named_parameters(), port.parameters()): + torch.testing.assert_close(port_param.grad, ref_param.grad, rtol=1e-4, atol=1e-6, msg=name) + + +def test_released_checkpoint_loads_strictly_and_matches_official(): + Net, repo = _official_net() + state = torch.load(repo / "model_saver" / "SAF_Net.pkl", map_location="cpu", weights_only=True) + reference = Net() + reference.load_state_dict(state, strict=True) + port = build_model("saf_net", task="regression") + port.load_state_dict(state, strict=True) + reference.eval() + port.eval() + + # Wide predictors of real 2015-2018 test cases, scaled as in the notebook (MinMaxScaler fitted on + # the training and test rows together); the ERA-Interim wind cubes are not in the repository. + import pandas as pd + + train = pd.read_csv(repo / "data" / "CMA_train_24h.csv", header=None) + test = pd.read_csv(repo / "data" / "CMA_test_24h.csv", header=None) + features = pd.concat([train, test]).iloc[:, 5:].to_numpy(np.float64) + low, high = features.min(axis=0), features.max(axis=0) + span = np.where(high > low, high - low, 1.0) + wide = torch.as_tensor((test.iloc[:6, 5:].to_numpy(np.float64) - low) / span, dtype=torch.float32) + _, deep = _inputs(batch=6, seed=2) + with torch.no_grad(): + expected = reference(wide, deep) + actual = port(wide, deep) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + assert torch.all(actual >= 0) # final ReLU on the MinMax-scaled intensity + + +def test_input_validation(): + port = build_model("saf_net", task="regression") + wide, deep = _inputs(batch=2) + with pytest.raises(ValueError, match="deep inputs shaped"): + port(wide, deep[..., :3]) + with pytest.raises(ValueError, match="wide inputs shaped"): + port(wide[:, :90], deep) diff --git a/tests/oracle/test_segformer_oracle.py b/tests/oracle/test_segformer_oracle.py new file mode 100644 index 00000000..e57f9081 --- /dev/null +++ b/tests/oracle/test_segformer_oracle.py @@ -0,0 +1,233 @@ +"""SegFormer checked against Hugging Face transformers (pinned in requirements.txt). + +transformers' ``SegformerForSemanticSegmentation`` / ``SegformerModel`` are the reference: same +parameter names, same seeded initialisation, same outputs in eval and train mode. The official +NVIDIA checkpoints ``nvidia/mit-b0`` (ImageNet-1k encoder) and +``nvidia/segformer-b0-finetuned-ade-512-512`` (pinned assets in repos.yaml) must load with +``strict=True`` and give the same outputs as transformers. The first-conv adaptation used with +pretrained weights is compared with segmentation_models_pytorch's ``patch_first_conv``. +""" + +from __future__ import annotations + +import warnings +from pathlib import Path + +import pytest +import torch +import torch.nn.functional as F +import yaml + +from oracle_utils import oracle_asset, oracle_package +from pyhazards.models import build_model +from pyhazards.models.segformer import ( + MIT_IMAGENET_CHECKPOINTS, + SEGFORMER_VARIANTS, + SegFormer, + SegformerConfig, + SegformerModel, + mit_imagenet_url, +) + +TRANSFORMERS_VERSION = "4.57.6" +MANIFEST = yaml.safe_load((Path(__file__).parent / "repos.yaml").read_text(encoding="utf-8")) + + +def _transformers(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return oracle_package("transformers", TRANSFORMERS_VERSION) + + +def _hf_config(variant: str, **kwargs): + spec = SEGFORMER_VARIANTS[variant] + return _transformers().SegformerConfig( + hidden_sizes=list(spec["hidden_sizes"]), + depths=list(spec["depths"]), + decoder_hidden_size=spec["decoder_hidden_size"], + **kwargs, + ) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _mit_b0_state(): + path = oracle_asset("segformer_mit_b0") / "pytorch_model.bin" + return torch.load(path, map_location="cpu", weights_only=True), path + + +@pytest.mark.parametrize( + "variant, expected", + [("b0", 3_752_694), ("b1", 13_715_798), ("b2", 27_461_974)], +) +def test_parameter_counts_match_transformers(variant, expected): + # SegFormer paper Table 1 (ADE20K, 150 classes): B0 3.8M, B1 13.7M, B2 27.5M. + with torch.device("meta"): + reference = _transformers().SegformerForSemanticSegmentation(_hf_config(variant, num_labels=150)) + port = SegFormer(in_channels=3, num_labels=150, variant=variant) + assert _n_params(reference) == _n_params(port) == expected + + +@pytest.mark.parametrize("variant, in_channels, num_labels", [("b0", 3, 150), ("b2", 40, 1)]) +def test_names_initialisation_and_forward_match_transformers(variant, in_channels, num_labels): + hf = _transformers() + torch.manual_seed(0) + reference = hf.SegformerForSemanticSegmentation( + _hf_config(variant, num_channels=in_channels, num_labels=num_labels) + ) + torch.manual_seed(0) + port = SegFormer(in_channels=in_channels, num_labels=num_labels, variant=variant) + _assert_same_state(reference, port) + + torch.manual_seed(1) + x = torch.randn(2, in_channels, 64, 96) + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(pixel_values=x).logits + _assert_close(port.raw_logits(x), expected) + upsampled = F.interpolate(expected, size=x.shape[-2:], mode="bilinear", align_corners=False) + _assert_close(port(x), upsampled) + + # Train mode: stochastic depth (0.1) and decoder dropout (0.1) draw the same random numbers. + reference.train() + port.train() + torch.manual_seed(2) + expected = reference(pixel_values=x).logits + torch.manual_seed(2) + _assert_close(port.raw_logits(x), expected) + for name, buffer in reference.decode_head.batch_norm.named_buffers(): + assert torch.equal(buffer, getattr(port.decode_head.batch_norm, name)), name + + +def test_wildfire_configuration_matches_transformers(): + # WSTS+ (Lahrichi et al., WACV 2026): SegFormer-B2, 40 input channels (one day, all features), one output. + hf = _transformers() + torch.manual_seed(0) + reference = hf.SegformerForSemanticSegmentation(_hf_config("b2", num_channels=40, num_labels=1)) + torch.manual_seed(0) + port = build_model("segformer", task="segmentation", in_channels=40) + _assert_same_state(reference, port) + assert _n_params(port) == 27_463_425 + + +def test_encoder_only_model_matches_transformers(): + hf = _transformers() + torch.manual_seed(0) + reference = hf.SegformerModel(_hf_config("b0", num_channels=5)) + torch.manual_seed(0) + port = SegformerModel(SegformerConfig.from_variant("b0", num_channels=5)) + _assert_same_state(reference, port) + + x = torch.randn(2, 5, 64, 64) + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(pixel_values=x, output_hidden_states=True).hidden_states + actual = port(x) + assert len(actual) == len(expected) == 4 + for a, e in zip(actual, expected): + _assert_close(a, e) + + # A SegformerModel state dict loads into SegFormer.segformer. + full = SegFormer(in_channels=5, num_labels=1, variant="b0") + assert str(full.load_hf_state_dict(reference.state_dict())) == "" + _assert_same_state(reference, full.segformer) + + +def test_official_mit_b0_imagenet_weights_load_strict(): + hf = _transformers() + state, _ = _mit_b0_state() + reference = hf.SegformerForImageClassification(_hf_config("b0", num_labels=1000)) + reference.load_state_dict(state, strict=True) + port = SegFormer(in_channels=3, num_labels=1, variant="b0") + port.load_hf_state_dict(state, strict=True) # drops the "segformer." prefix and the classifier + _assert_same_state(reference.segformer, port.segformer) + + torch.manual_seed(3) + x = torch.randn(2, 3, 128, 128) + reference.eval() + port.eval() + with torch.no_grad(): + out = reference(pixel_values=x, output_hidden_states=True) + features = port.segformer(x) + for a, e in zip(features, out.hidden_states): + _assert_close(a, e) + pooled = features[-1].flatten(2).mean(-1) + _assert_close(F.linear(pooled, state["classifier.weight"], state["classifier.bias"]), out.logits) + + +def test_official_ade20k_segformer_b0_loads_strict_and_matches(): + hf = _transformers() + safetensors = pytest.importorskip("safetensors.torch") + state = safetensors.load_file(str(oracle_asset("segformer_b0_ade") / "model.safetensors")) + reference = hf.SegformerForSemanticSegmentation(_hf_config("b0", num_labels=150)) + reference.load_state_dict(state, strict=True) + port = SegFormer(in_channels=3, num_labels=150, variant="b0") + port.load_state_dict(state, strict=True) + _assert_same_state(reference, port) + + torch.manual_seed(4) + x = torch.randn(2, 3, 128, 160) + reference.eval() + port.eval() + with torch.no_grad(): + outputs = reference(pixel_values=x) + _assert_close(port.raw_logits(x), outputs.logits) + logits = port(x) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + processor = hf.SegformerImageProcessor() + maps = processor.post_process_semantic_segmentation(outputs, target_sizes=[tuple(x.shape[-2:])] * 2) + for i, semantic_map in enumerate(maps): + assert torch.equal(logits[i].argmax(0), semantic_map) + + +def test_pretrained_stem_adaptation_matches_smp_patch_first_conv(): + hf = _transformers() + smp = oracle_package("segmentation_models_pytorch", "0.3.2") + from segmentation_models_pytorch.encoders._utils import patch_first_conv + + state, path = _mit_b0_state() + for in_channels in (1, 7, 40): + reference = hf.SegformerForImageClassification(_hf_config("b0", num_labels=1000)) + reference.load_state_dict(state, strict=True) + patch_first_conv(reference, new_in_channels=in_channels, pretrained=True) + port = build_model("segformer", task="segmentation", variant="b0", in_channels=in_channels, encoder_weights=str(path)) + _assert_same_state(reference.segformer, port.segformer) + x = torch.randn(1, in_channels, 64, 64) + reference.eval() + port.eval() + with torch.no_grad(): + expected = reference(pixel_values=x, output_hidden_states=True).hidden_states + for a, e in zip(port.segformer(x), expected): + _assert_close(a, e) + assert smp.__version__ == "0.3.2" + + +def test_imagenet_download_is_the_pinned_asset(): + asset = MANIFEST["assets"]["segformer_mit_b0"] + revision, sha256 = MIT_IMAGENET_CHECKPOINTS["b0"] + assert mit_imagenet_url("b0") == asset["url"] + assert sha256 == asset["sha256"] + for variant, (revision, sha256) in MIT_IMAGENET_CHECKPOINTS.items(): + assert len(revision) == 40 and len(sha256) == 64, variant + + # encoder_weights="imagenet" downloads through torch.hub (TORCH_HOME), checking the sha256 prefix. + state, _ = _mit_b0_state() + port = build_model("segformer", task="segmentation", variant="b0", in_channels=3, encoder_weights="imagenet") + for key, value in port.segformer.state_dict().items(): + assert torch.equal(value, state["segformer." + key]), key diff --git a/tests/oracle/test_seisbench_reader_oracle.py b/tests/oracle/test_seisbench_reader_oracle.py new file mode 100644 index 00000000..c908eab1 --- /dev/null +++ b/tests/oracle/test_seisbench_reader_oracle.py @@ -0,0 +1,91 @@ +"""The ``seisbench_waveforms`` reader checked against SeisBench's own writer and reader. + +SeisBench 0.12.6 (GPL-3.0, installed only in the oracle job) writes a SeisBench-format dataset with +its ``WaveformDataWriter`` (trace blocks / buckets, ``data_format`` group, its CSV conventions) from the +100 real STEAD traces that EQTransformer ships (``ModelsAndSampleData/100samples.*``, STEAD layout, +CC BY 4.0), converted the way SeisBench converts STEAD (``seisbench/data/stead.py``: E, N, Z -> +Z, N, E, samples x channels -> channels x samples, renamed arrival columns). PyHazards must read the +same waveforms and arrivals as SeisBench's ``WaveformDataset``, and the same waveforms as its own +reading of the original STEAD-layout files. +""" + +from __future__ import annotations + +import csv + +import h5py +import numpy as np +import pytest +import torch + +from oracle_utils import oracle_package, oracle_repo +from pyhazards.datasets import load_dataset + + +@pytest.fixture(scope="module") +def stead_sample(): + return oracle_repo("EQTransformer") / "ModelsAndSampleData" + + +@pytest.fixture(scope="module") +def seisbench_copy(tmp_path_factory, stead_sample): + oracle_package("seisbench", "0.12.6", "requirements-earthquake.txt") + import seisbench.data as sbd + + root = tmp_path_factory.mktemp("stead_seisbench") + with (stead_sample / "100samples.csv").open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + splits = ["train", "dev", "test", "test"] + with h5py.File(stead_sample / "100samples.hdf5", "r") as source, sbd.WaveformDataWriter( + root / "metadata.csv", root / "waveforms.hdf5" + ) as writer: + writer.data_format = { + "dimension_order": "CW", + "component_order": "ZNE", + "sampling_rate": 100, + "measurement": "velocity", + "unit": "counts", + "instrument_response": "not restituted", + } + writer.bucket_size = 16 # several trace blocks + for k, row in enumerate(rows): + waveform = source["data"][row["trace_name"]][()].T[[2, 1, 0]] # (6000, ENZ) -> (ZNE, 6000) + metadata = { + "trace_name_original": row["trace_name"], + "trace_p_arrival_sample": float(row["p_arrival_sample"]), + "trace_s_arrival_sample": float(row["s_arrival_sample"]), + "trace_category": row["trace_category"], + "split": splits[k % 4], + } + writer.add_trace(metadata, waveform) + return root + + +def test_reads_what_seisbench_reads(seisbench_copy): + import seisbench.data as sbd + + reference = sbd.WaveformDataset(seisbench_copy, component_order="ZNE", dimension_order="NCW") + bundle = load_dataset("seisbench_waveforms", path=str(seisbench_copy)).load() + assert bundle.metadata["component_order"] == "ZNE" and bundle.metadata["sampling_rate"] == 100.0 + metadata = reference.metadata + assert any("$" in name for name in metadata["trace_name"]) # trace blocks were written + for split, name in (("train", "train"), ("dev", "val"), ("test", "test")): + mask = (metadata["split"] == split).to_numpy() + expected = reference.get_waveforms(np.flatnonzero(mask)) + data = bundle.get_split(name) + torch.testing.assert_close(data.inputs, torch.from_numpy(expected).float(), rtol=0, atol=0) + arrivals = metadata.loc[mask, ["trace_p_arrival_sample", "trace_s_arrival_sample"]].to_numpy() + np.testing.assert_array_equal(data.targets.numpy(), arrivals.astype("float32")) + assert data.metadata["trace_names"] == list(metadata.loc[mask, "trace_name"]) + + +def test_seisbench_copy_equals_the_original_stead_files(seisbench_copy, stead_sample): + converted = load_dataset("seisbench_waveforms", path=str(seisbench_copy)).load() + original = load_dataset("seisbench_waveforms", path=str(stead_sample), preset="stead").load() + assert original.metadata["component_order"] == "ENZ" + stead = original.get_split("test") + order = [2, 1, 0] # ENZ -> ZNE + for k, split in enumerate(("train", "val", "test")): + indices = [i for i in range(100) if ["train", "val", "test", "test"][i % 4] == split] + torch.testing.assert_close(converted.get_split(split).inputs, stead.inputs[indices][:, order], rtol=0, atol=0) + torch.testing.assert_close(converted.get_split(split).targets, stead.targets[indices], rtol=0, atol=0) diff --git a/tests/oracle/test_smokebench_oracle.py b/tests/oracle/test_smokebench_oracle.py new file mode 100644 index 00000000..86fea315 --- /dev/null +++ b/tests/oracle/test_smokebench_oracle.py @@ -0,0 +1,368 @@ +"""pyhazards.prompted checked against the SmokeBench authors' evaluation scripts. + +Reference (pinned in repos.yaml): SoraLink/MLLM @ 183cdca, the evaluation code of Qi, Li & Barnes, +"SmokeBench" (WACV 2026), committed by the first author. It has no licence, so it is fetched at test +time and nothing is copied. Only its definitions are executed (``load_definitions``): from +``mllm_smoke_locate.py`` the grid overlay (``ImagePreprocess.add_grid``), the box-to-cell labels +(``get_annotation_grid_number``) and the cell IoU; from ``evaluations.py`` the ``Evaluator`` class with +a fake model in place of the MLLM (its module imports Unified-IO 2, Qwen utilities, etc.); from +``summary_evaluation.py`` the smoke area and Weber contrast. ``torchvision.ops.box_iou`` and OpenCV are +the libraries those scripts call. + +Checked: tile crops and tile/grid ground truth (``protocol="reference_code"`` equals the script on +every case, ``protocol="paper"`` wherever the script's geometry bugs do not apply), the grid overlay +pixel for pixel, the parsing and scoring of classification, tile, grid and detection answers +(well-formed and malformed), the cell / box IoUs, smoke area and Weber contrast, OpenCV's grey +conversion on all 2**24 colours, and that SmokeyNet's ``metadata.pkl`` boxes are SmokeBench's 5,046 +(their area quintiles are the paper's bins). With ``PYHAZARDS_SMOKEBENCH_ROOT`` pointing at the +downloaded images (``pyhazards.datasets.figlib_smokebench.download_smokebench``, ~11.4 GB) the contrast +quintiles of all 5,046 images are also compared with the paper's (skipped otherwise; mandatory with +``PYHAZARDS_ORACLE_LARGE=1``). +""" + +from __future__ import annotations + +import json +import os +import re +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from oracle_utils import load_definitions, missing, oracle_asset, oracle_package, oracle_repo +from pyhazards.datasets.figlib_smokebench import ( + FIgLibSmokeBench, + NUM_SEQUENCES, + NUM_SMOKE_IMAGES, + SmokeSample, + load_smokeynet_boxes, +) +from pyhazards.prompted import CLASSIFICATION_PROMPT, DETECTION_PROMPT, GRID_PROMPT +from pyhazards.prompted.geometry import covered_cells, crop_tiles, draw_grid_overlay +from pyhazards.prompted.metrics import ( + AREA_BIN_EDGES, + CONTRAST_BIN_EDGES, + CONTRAST_BIN_EDGES_PRINTED, + box_iou, + detection_iou, + opencv_gray, + quantile_edges, + set_iou, + smoke_area, + weber_contrast, +) +from pyhazards.prompted.parsers import parse_classification, parse_detection, parse_grid, parse_tile + +OPENCV_VERSION = "4.10.0" +SIZES = [(1536, 2048), (2048, 3072), (1200, 1600), (1920, 2560), (37, 53)] # (H, W); FIgLib sizes + odd + + +@pytest.fixture(scope="module") +def ref(): + cv2 = oracle_package("cv2", OPENCV_VERSION, "requirements-smokebench.txt") + try: + from torchvision.ops import box_iou as tv_box_iou + except ImportError: + missing("torchvision is not installed (the authors' detection scoring calls torchvision.ops.box_iou)") + root = oracle_repo("SoraLink-MLLM") + locate = load_definitions( + root / "mllm_smoke_locate.py", + ["ImagePreprocess", "get_annotation_grid_number", "compute_grid_IoU", "add_bbox"], + {"cv2": cv2, "json": json}, + ) + evaluations = load_definitions( + root / "evaluations.py", + ["Evaluator"], + {"re": re, "json": json, "torch": torch, "box_iou": tv_box_iou, "cv2": cv2, "Path": Path, "os": os, **locate}, + ) + summary = load_definitions( + root / "summary_evaluation.py", ["read_area", "compute_luminance_contrast"], {"json": json, "cv2": cv2, "np": np} + ) + return SimpleNamespace(cv2=cv2, tv_box_iou=tv_box_iou, Evaluator=evaluations["Evaluator"], **locate, **summary) + + +class FakeMLLM: + """Stands in for the authors' model wrappers: records inputs (BGR, as they receive them).""" + + def __init__(self, answers): + self.answers = list(answers) + self.images = [] + + def predict(self, image, prompt): + self.images.append(image.copy()) + return self.answers.pop(0) + + def batch_predict(self, images, prompt): + self.images.extend(image.copy() for image in images) + return [self.answers.pop(0) for _ in images] + + +def _random_image(rng, height, width): + return rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8) + + +def _write_frame(ref, directory: Path, name: str, rgb: np.ndarray) -> Path: + path = directory / name + assert ref.cv2.imwrite(str(path), np.ascontiguousarray(rgb[:, :, ::-1])) # PNG: lossless + return path + + +def _write_boxes(directory: Path, boxes) -> Path: + path = directory / "annotation.json" + path.write_text(json.dumps({"det_boxes": [list(map(int, box)) for box in boxes]})) + return path + + +def _boxes(rng, height, width, n=40): + boxes = [] + for _ in range(n): + x1, x2 = sorted(rng.integers(0, width + 1, size=2).tolist()) + y1, y2 = sorted(rng.integers(0, height + 1, size=2).tolist()) + boxes.append([x1, y1, max(x2, x1 + 1), max(y2, y1 + 1)]) + # edge cases: full frame, right / bottom edges, cell boundaries, single pixels in corners + boxes += [ + [0, 0, width, height], + [width - 5, 3, width, 9], + [2, height - 4, 7, height], + [width // 5, height // 5, 2 * (width // 5), 2 * (height // 5)], + [width // 4 - 1, height // 3 - 1, width // 4, height // 3], + [0, 0, 1, 1], + [width - 2, height - 2, width - 1, height - 1], + ] + return boxes + + +# -------------------------------------------------------------------------------------------------- + + +def test_released_prompts_differ_from_the_papers_only_in_wording(ref): + evaluator = ref.Evaluator() + stem = "Please look at this image. Detect if the image contains smoke. If you can find any smoke, return True. Otherwise, return False." + assert evaluator.prompt_classification.startswith(stem) and CLASSIFICATION_PROMPT.startswith(stem) + assert evaluator.prompt_classification != CLASSIFICATION_PROMPT + grid_stem = 'Please output the numbered regions that contain smoke in JSON format as a list of dicts like [{"region": 1}, {"region": 2}].' + assert grid_stem in evaluator.prompt_grid and grid_stem in GRID_PROMPT and evaluator.prompt_grid != GRID_PROMPT + assert "[[x1, y1, x2, y2], [x1, y1, x2, y2]]" in evaluator.prompt_bbox and "[[x1, y1, x2, y2], [x1, y1, x2, y2]]" in DETECTION_PROMPT + + +@pytest.mark.parametrize("height, width", SIZES) +@pytest.mark.parametrize("layout", [(5, 5), (3, 4)]) +def test_cell_ground_truth_matches_the_script(ref, tmp_path, height, width, layout): + rng = np.random.default_rng(height * 7 + width + layout[1]) + rows, cols = layout + shape_only = SimpleNamespace(shape=(height, width, 3)) + for box in _boxes(rng, height, width): + reference = set(ref.get_annotation_grid_number(_write_boxes(tmp_path, [box]), shape_only, rows=rows, cols=cols)) + assert set(covered_cells([box], height, width, layout, protocol="reference_code")) == reference, box + if box[2] < cols * (width // cols) and box[3] < rows * (height // rows): + assert set(covered_cells([box], height, width, layout)) == reference, box + else: # the script's out-of-range row/column ids; the paper protocol clamps them + assert set(covered_cells([box], height, width, layout)) <= set(range(1, rows * cols + 1)) + + +def test_cell_iou_matches_the_script(ref): + rng = np.random.default_rng(0) + for _ in range(200): + pred = set(rng.integers(0, 30, size=rng.integers(0, 8)).tolist()) + target = set(rng.integers(1, 26, size=rng.integers(1, 8)).tolist()) + assert set_iou(pred, target) == ref.compute_grid_IoU(pred, target) + + +@pytest.mark.parametrize("height, width", SIZES) +def test_grid_overlay_is_pixel_identical(ref, tmp_path, height, width): + rgb = _random_image(np.random.default_rng(width), height, width) + reference_bgr = ref.ImagePreprocess.add_grid(str(_write_frame(ref, tmp_path, "frame.png", rgb))) + ours = draw_grid_overlay(rgb) + assert np.array_equal(ours[:, :, ::-1], reference_bgr) + assert not np.array_equal(ours, rgb) + + +GRID_ANSWERS = ['[{"region": 1}, {"region": 7}]', "[]", "no smoke", '```json\n[{"region": 25}, {"region": 26}]\n```', "Regions 3, 3 and 12."] + + +@pytest.mark.parametrize("height, width", [(1536, 2048), (2048, 3072), (37, 53)]) +def test_grid_task_matches_the_script(ref, tmp_path, height, width): + rng = np.random.default_rng(height) + rgb = _random_image(rng, height, width) + frame = _write_frame(ref, tmp_path, "1469223181_+00060.png", rgb) + for box in _boxes(rng, height, width, n=3): + annotation = _write_boxes(tmp_path, [box]) + for answer in GRID_ANSWERS: + evaluator = ref.Evaluator() + evaluator.model = FakeMLLM([answer]) + result = evaluator._evaluate_grid(str(frame), str(annotation)) + assert np.array_equal(evaluator.model.images[0], draw_grid_overlay(rgb)[:, :, ::-1]) + assert set(result["predict_grids"]) == parse_grid(answer) + target = covered_cells([box], height, width, (5, 5), protocol="reference_code") + assert set(result["annotation_grids"]) == set(target) + assert result["iou"] == set_iou(parse_grid(answer), target) + + +TILE_ANSWERS = ["True", "False", "true.", "TRUE", "", "Yes, True", "False.", "I think it is true", "No", "True", "False", "maybe"] + + +@pytest.mark.parametrize("height, width", [(1536, 2048), (2048, 3072), (1200, 1600), (1920, 2560)]) +def test_tile_task_matches_the_script(ref, tmp_path, height, width): + rng = np.random.default_rng(width) + rgb = _random_image(rng, height, width) + frame = _write_frame(ref, tmp_path, "1469223181_+00060.png", rgb) + for box in _boxes(rng, height, width, n=3): + evaluator = ref.Evaluator() + evaluator.model = FakeMLLM(TILE_ANSWERS) + result = evaluator._evaluate_subimage_classification(str(frame), str(_write_boxes(tmp_path, [box]))) + crops = crop_tiles(rgb, protocol="reference_code") + assert len(evaluator.model.images) == 12 + for theirs, ours in zip(evaluator.model.images, crops): + assert np.array_equal(theirs, ours[:, :, ::-1]) + predicted = [i + 1 for i, answer in enumerate(TILE_ANSWERS) if parse_tile(answer)] + assert result["predict_grids"] == predicted + target = covered_cells([box], height, width, (3, 4), protocol="reference_code") + assert set(result["annotation_grids"]) == set(target) + assert result["iou"] == set_iou(predicted, target) + paper_crops = crop_tiles(rgb) + same = all(np.array_equal(a, b) for a, b in zip(paper_crops, crops)) + assert same == (height // 3 == width // 4) # the script's swapped block sizes matter on 3072 x 2048 + + +CLASSIFICATION_ANSWERS = ["True", "False", "true", "True.", "False, not True", "", "There is smoke.", "FALSE", "**True**"] + + +def test_classification_scoring_matches_the_script(ref, tmp_path): + rgb = _random_image(np.random.default_rng(1), 30, 40) + for name in ("1469223181_+00060.png", "1469220001_-01200.png", "1465065600_+00000.png"): + frame = _write_frame(ref, tmp_path, name, rgb) + for answer in CLASSIFICATION_ANSWERS: + evaluator = ref.Evaluator() + evaluator.model = FakeMLLM([answer]) + result = evaluator._evaluate_classification(str(frame)) + assert np.array_equal(evaluator.model.images[0], rgb[:, :, ::-1]) + assert result["prediction"] == parse_classification(answer) + sample = SmokeSample(f"seq/{Path(name).stem}", frame, label=result["label"]) + assert result["label"] == (sample.offset_seconds >= 0) + + +DETECTION_ANSWERS = [ + "[[100, 120, 400, 300]]", + "[[0, 0, 0, 0]]", + "[[10, 20, 30, 40], [150, 100, 380, 290]]", + "```json\n[[110.5, 130.25, 390.75, 280]]\n```", + "Boxes: [[50, 60, 70, 80]] and [[100, 120, 400, 300]]", + "[]", + "[[]]", + "[[], [100, 120, 400, 300]]", + "No smoke detected.", + '[{"bbox": [100, 120, 400, 300]}]', + "[[1, 2, 3, 4], [5, 6", + "[[[100, 120, 400, 300]]]", + "[[100, 120, 400]]", + "[[400, 300, 100, 120]]", + "[[100, 120, 100, 300]]", +] +REFERENCE_CRASHES = ['[["a", "b", "c", "d"]]', "[[1, 2, 3, 4], [5, 6]]", "[[1, 2, 3, 4, 5]]"] + + +def test_detection_parsing_and_scoring_match_the_script(ref, tmp_path): + rgb = _random_image(np.random.default_rng(2), 400, 500) + frame = _write_frame(ref, tmp_path, "1469223181_+00060.png", rgb) + for gt in ([[100, 120, 400, 300]], [[100, 120, 400, 300], [10, 20, 60, 80]]): + annotation = _write_boxes(tmp_path, gt) + for answer in DETECTION_ANSWERS: + evaluator = ref.Evaluator() + assert evaluator._retireve_bbox(answer) == parse_detection(answer), answer + evaluator.model = FakeMLLM([answer]) + result = evaluator._evaluate_coordinate(str(frame), str(annotation)) + score, problem = detection_iou(parse_detection(answer), gt) + assert score == float(np.max(result["iou"])), answer + assert problem in (None, "malformed") + for answer in REFERENCE_CRASHES: # the script crashes; PyHazards scores 0 and flags it + evaluator = ref.Evaluator() + evaluator.model = FakeMLLM([answer]) + with pytest.raises((TypeError, ValueError, RuntimeError)): + evaluator._evaluate_coordinate(str(frame), str(annotation)) + assert detection_iou(parse_detection(answer), gt)[0] == 0.0 + assert detection_iou(parse_detection(answer), gt)[1] is not None + + +def test_grid_number_parsing_matches_the_script(ref): + evaluator = ref.Evaluator() + for answer in GRID_ANSWERS + DETECTION_ANSWERS + CLASSIFICATION_ANSWERS + ["region ١٢", "0007"]: + assert parse_grid(answer) == set(evaluator._retrieve_grid_number(answer)), answer + + +def test_box_iou_matches_torchvision(ref): + generator = torch.Generator().manual_seed(0) + for dtype in (torch.float32, torch.int64): + a = (torch.rand(17, 4, generator=generator) * 500).to(dtype) + b = (torch.rand(5, 4, generator=generator) * 500).to(dtype) + a[:, 2:] += a[:, :2] + b[:, 2:] += b[:, :2] + assert torch.equal(box_iou(a, b), ref.tv_box_iou(a, b)) + + +@pytest.mark.parametrize("height, width", [(1536, 2048), (2048, 3072), (37, 53)]) +def test_area_and_weber_contrast_match_the_script(ref, tmp_path, height, width): + rng = np.random.default_rng(width + 1) + rgb = _random_image(rng, height, width) + rgb[: height // 4] = 0 # black pixels are excluded from the background frame + frame = _write_frame(ref, tmp_path, "frame.png", rgb) + image = FIgLibSmokeBench.load_image(SmokeSample("seq/1_+00000", frame, True)) + assert np.array_equal(image, rgb) + for box in _boxes(rng, height, width, n=12): + if box[2] - box[0] < 1 or box[3] - box[1] < 1 or box[2] > width or box[3] > height: + continue + annotation = _write_boxes(tmp_path, [box]) + assert ref.read_area(annotation) == smoke_area([box]) + _, weber = ref.compute_luminance_contrast(annotation, frame) + assert weber_contrast(image, [box]) == pytest.approx(weber, rel=1e-12, abs=0), box + two = [[5, 5, 30, 30], [width - 20, height - 20, width - 1, height - 1]] + _, weber = ref.compute_luminance_contrast(_write_boxes(tmp_path, two), frame) + assert weber_contrast(image, two) == pytest.approx(weber, rel=1e-12, abs=0) + + +def test_opencv_grey_conversion_on_every_colour(ref): + codes = np.arange(1 << 24, dtype=np.uint32) + for chunk in np.array_split(codes, 16): + rgb = np.stack([(chunk >> 16) & 255, (chunk >> 8) & 255, chunk & 255], axis=-1).astype(np.uint8)[None] + expected = ref.cv2.cvtColor(np.ascontiguousarray(rgb[..., ::-1]), ref.cv2.COLOR_BGR2GRAY) + assert np.array_equal(opencv_gray(rgb), expected) + + +def test_smokeynet_boxes_are_the_smokebench_smoke_set(): + boxes = load_smokeynet_boxes(oracle_asset("smokeynet_metadata") / "smokeynet_metadata.pkl") + assert len(boxes) == NUM_SMOKE_IMAGES + assert len({key.split("/")[0] for key in boxes}) == NUM_SEQUENCES + assert all(len(image_boxes) == 1 and len(image_boxes[0]) == 4 for image_boxes in boxes.values()) + assert all("_+" in key for key in boxes) # every annotated frame is at or after the first plume + areas = [smoke_area(image_boxes) for image_boxes in boxes.values()] + # Paper Sec. 4.2: "(42, 4356], (4356, 11232], (11232, 28565], (28565, 83157], and (83157, 2232020]" + assert quantile_edges(areas) == pytest.approx(list(AREA_BIN_EDGES), rel=1e-12) + + +def _contrast(sample): + return weber_contrast(FIgLibSmokeBench.load_image(sample), sample.boxes) + + +def test_contrast_quintiles_of_all_smokebench_images(ref, tmp_path): + root = os.environ.get("PYHAZARDS_SMOKEBENCH_ROOT") + if not root: + reason = "set PYHAZARDS_SMOKEBENCH_ROOT to the downloaded SmokeBench images (~11.4 GB) to run this check" + if os.environ.get("PYHAZARDS_ORACLE_LARGE") == "1": + pytest.fail(reason) + pytest.skip(reason) + data = FIgLibSmokeBench(root, negatives=0) + assert len(data) == NUM_SMOKE_IMAGES + with ProcessPoolExecutor(max_workers=8) as pool: + contrasts = list(pool.map(_contrast, data.positives, chunksize=32)) + edges = quantile_edges(contrasts) + # Paper Sec. 4.2: "(0, 0.0246], (0.0246, 0.0549], (0.0549, 0.0878], (0.0878, 0.13], and (0.13, 0.728]" + assert [float(f"{edge:.3g}") for edge in edges[1:]] == list(CONTRAST_BIN_EDGES_PRINTED[1:]) + assert edges[1:] == pytest.approx(list(CONTRAST_BIN_EDGES[1:]), rel=1e-9) + # The authors' function (OpenCV decoding) on real FIgLib JPEGs gives the same values. + for index in range(0, NUM_SMOKE_IMAGES, 250): + sample = data.positives[index] + _, weber = ref.compute_luminance_contrast(_write_boxes(tmp_path, sample.boxes), sample.path) + assert contrasts[index] == pytest.approx(weber, rel=1e-12, abs=0), sample.image_id diff --git a/tests/oracle/test_swin_oracle.py b/tests/oracle/test_swin_oracle.py new file mode 100644 index 00000000..65d9b1c7 --- /dev/null +++ b/tests/oracle/test_swin_oracle.py @@ -0,0 +1,242 @@ +"""Swin-Unet and ASUFM checked against their official implementations. + +References (pinned in repos.yaml): HuCaoFighting/Swin-Unet (no license; used only here, never +vendored) with the Swin-T ImageNet checkpoint of microsoft/Swin-Transformer, and bronteee/fire-asufm +(Apache-2.0). Both need timm 0.4.12, einops, ml_collections and yacs (requirements-swin.txt), which +conflict with the segmentation_models_pytorch pin of requirements.txt, so the Oracle workflow runs +this file in its own job. + +Each check builds both models from the same seed, requires identical parameter names and initial +values, and compares outputs in eval mode and in train mode (stochastic depth with a fixed seed). +""" + +from __future__ import annotations + +from importlib import metadata +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +import yaml + +from oracle_utils import import_from, missing, oracle_asset, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.swin_unet import SWIN_TINY_IMAGENET_SHA256, SWIN_TINY_IMAGENET_URL, SwinUnet + +SWIN_UNET_YAML = "configs/swin_tiny_patch4_window7_224_lite.yaml" +SWIN_TINY_CHECKPOINT = "swin_tiny_patch4_window7_224.pth" +REQUIREMENTS = Path(__file__).parent / "requirements-swin.txt" + + +@pytest.fixture(autouse=True) +def _reference_stack(): + # Both references were written against timm 0.4.12 (pinned by fire-asufm and by + # microsoft/Swin-Transformer); its DropPath draws the random numbers the ports reproduce. + for line in REQUIREMENTS.read_text().splitlines(): + if "==" not in line or line.lstrip().startswith("#"): + continue + name, version = line.split("#")[0].strip().split("==") + try: + found = metadata.version(name) + except metadata.PackageNotFoundError: + missing(f"{name} is not installed; pip install -r tests/oracle/requirements-swin.txt") + if found != version: + missing(f"needs {name}=={version}, found {found}") + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _compare_forward(reference: torch.nn.Module, port: torch.nn.Module, x: torch.Tensor, seed: int) -> None: + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + reference.train() + port.train() + torch.manual_seed(seed) + expected = reference(x) + torch.manual_seed(seed) + _assert_close(port(x), expected) + + +# --------------------------------------------------------------------------- Swin-Unet + + +def _swin_unet_reference(in_chans: int, num_classes: int, pretrained: Path | None = None): + """Official ``SwinUnet`` built from the official yaml exactly as train.py does.""" + repo = oracle_repo("Swin-Unet") + config_module = import_from(repo, "config") + opts = ["MODEL.SWIN.IN_CHANS", in_chans] + if pretrained is not None: + opts += ["MODEL.PRETRAIN_CKPT", str(pretrained)] + args = SimpleNamespace( + cfg=str(repo / SWIN_UNET_YAML), opts=opts, batch_size=None, zip=False, cache_mode=None, + resume=None, accumulation_steps=None, use_checkpoint=False, amp_opt_level=None, tag=None, + eval=False, throughput=False, + ) + config = config_module.get_config(args) + vision_transformer = import_from(repo, "networks.vision_transformer") + return vision_transformer.SwinUnet(config, img_size=config.DATA.IMG_SIZE, num_classes=num_classes), config + + +def test_swin_unet_official_config_and_unused_decoder_depths(): + repo = oracle_repo("Swin-Unet") + raw = yaml.safe_load((repo / SWIN_UNET_YAML).read_text())["MODEL"] + assert raw["DROP_PATH_RATE"] == 0.2 + assert raw["SWIN"]["DEPTHS"] == [2, 2, 2, 2] + assert raw["SWIN"]["DECODER_DEPTHS"] == [2, 2, 2, 1] + # vision_transformer.py never passes DECODER_DEPTHS, and SwinTransformerSys ignores its own + # depths_decoder argument: the decoder mirrors the encoder depths. + source = (repo / "networks" / "vision_transformer.py").read_text() + assert "DECODER_DEPTHS" not in source + sys_module = import_from(repo, "networks.swin_transformer_unet_skip_expand_decoder_sys") + a = sys_module.SwinTransformerSys(in_chans=3, num_classes=9, depths_decoder=[1, 2, 2, 2]) + b = sys_module.SwinTransformerSys(in_chans=3, num_classes=9, depths_decoder=[2, 2, 2, 1]) + assert list(a.state_dict()) == list(b.state_dict()) + assert [len(layer.blocks) for layer in list(a.layers_up)[1:]] == [2, 2, 2] + + +def test_swin_unet_wsts_plus_config_matches_reference(): + torch.manual_seed(0) + reference, _ = _swin_unet_reference(in_chans=40, num_classes=1) + torch.manual_seed(0) + port = build_model("swin_unet", task="segmentation", in_channels=40) + _assert_same_state(reference.swin_unet, port) + assert _n_params(port) == 27_224_964 + + torch.manual_seed(1) + x = torch.randn(2, 40, 224, 224) + _compare_forward(reference, port, x, seed=2) + + +def test_swin_unet_synapse_config_matches_reference(): + torch.manual_seed(0) + reference, _ = _swin_unet_reference(in_chans=3, num_classes=9) + torch.manual_seed(0) + port = build_model("swin_unet", task="segmentation", in_channels=3, out_channels=9) + _assert_same_state(reference.swin_unet, port) + assert _n_params(port) == 27_168_900 + + torch.manual_seed(3) + grey = torch.randn(1, 1, 224, 224) # the official wrapper repeats one channel to RGB + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(grey), reference(grey)) + + +@pytest.mark.parametrize("in_chans", [40, 3]) +def test_swin_unet_imagenet_initialisation_matches_load_from(in_chans): + checkpoint = oracle_asset("swin_tiny_imagenet") / SWIN_TINY_CHECKPOINT + torch.manual_seed(0) + reference, config = _swin_unet_reference(in_chans=in_chans, num_classes=1, pretrained=checkpoint) + reference.load_from(config) + torch.manual_seed(0) + port = build_model("swin_unet", task="segmentation", in_channels=in_chans, pretrained=str(checkpoint)) + _assert_same_state(reference.swin_unet, port) + + imagenet = torch.load(checkpoint, map_location="cpu", weights_only=True)["model"] + state = port.state_dict() + # Encoder stage i also initialises decoder stage 3 - i; the stem only matches for RGB input. + assert torch.equal(state["layers_up.1.blocks.0.attn.qkv.weight"], imagenet["layers.2.blocks.0.attn.qkv.weight"]) + assert torch.equal(state["layers_up.3.blocks.1.mlp.fc2.weight"], imagenet["layers.0.blocks.1.mlp.fc2.weight"]) + assert torch.equal(state["norm.weight"], imagenet["norm.weight"]) + stem_loaded = torch.equal(state["patch_embed.proj.weight"], imagenet["patch_embed.proj.weight"]) if in_chans == 3 else False + assert stem_loaded == (in_chans == 3) + + torch.manual_seed(4) + x = torch.randn(1, in_chans, 224, 224) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + + +def test_swin_unet_imagenet_keyword_uses_pinned_checkpoint(tmp_path, monkeypatch): + manifest = yaml.safe_load((Path(__file__).parent / "repos.yaml").read_text())["assets"]["swin_tiny_imagenet"] + assert SWIN_TINY_IMAGENET_URL == manifest["url"] + assert SWIN_TINY_IMAGENET_SHA256 == manifest["sha256"] + + checkpoint = oracle_asset("swin_tiny_imagenet") / SWIN_TINY_CHECKPOINT + (tmp_path / "checkpoints").mkdir() + (tmp_path / "checkpoints" / SWIN_TINY_CHECKPOINT).symlink_to(checkpoint) + monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path)) + torch.manual_seed(0) + by_name = build_model("swin_unet", task="segmentation", in_channels=7, pretrained="imagenet") + torch.manual_seed(0) + by_path = SwinUnet(in_chans=7, drop_path_rate=0.2) + by_path.load_swin_pretrained(str(checkpoint)) + _assert_same_state(by_path, by_name) + + +# --------------------------------------------------------------------------- ASUFM + + +def _asufm_reference(config_name: str): + repo = oracle_repo("fire-asufm") + configs = import_from(repo, "configs.asufm") + asufm = import_from(repo, "model.asufm.asufm") + config = getattr(configs, config_name)() + return asufm.ASUFM(config=config, num_classes=1), config + + +@pytest.mark.parametrize( + "config_name, in_chans, expected", + [("get_asfum_6_configs", 6, 35_047_840), ("get_asufm_12_configs", 12, 35_057_056)], +) +def test_asufm_matches_reference(config_name, in_chans, expected): + torch.manual_seed(0) + reference, config = _asufm_reference(config_name) + assert (config.in_chans, config.image_size, config.window_size, config.focal) == (in_chans, 64, 8, True) + assert (config.mode, config.spatial_attention, config.skip_num) == ("swin", "1", 3) + torch.manual_seed(0) + port = build_model("asufm", task="segmentation", in_channels=in_chans) + _assert_same_state(reference, port) + assert _n_params(port) == expected + + torch.manual_seed(1) + x = torch.randn(3, in_chans, 64, 64) + _compare_forward(reference, port, x, seed=2) + assert port(x).shape == (3, 1, 64, 64) + + +def test_asufm_gradient_checkpointing_does_not_change_outputs(): + torch.manual_seed(0) + reference, _ = _asufm_reference("get_asfum_6_configs") # use_checkpoint=True in the config + port = build_model("asufm", task="segmentation", in_channels=6, use_checkpoint=True) + port.load_state_dict(reference.state_dict(), strict=True) + x = torch.randn(2, 6, 64, 64, requires_grad=True) + _compare_forward(reference, port, x, seed=5) + + port.train() + torch.manual_seed(6) + port(x).sum().backward() + assert x.grad is not None and torch.isfinite(x.grad).all() + + +def test_asufm_without_focal_modulation_matches_reference(): + torch.manual_seed(0) + repo = oracle_repo("fire-asufm") + configs = import_from(repo, "configs.asufm") + asufm = import_from(repo, "model.asufm.asufm") + config = configs.get_swin_unet_attention_configs() # the same network with focal=False + reference = asufm.ASUFM(config=config, num_classes=1) + torch.manual_seed(0) + port = build_model("asufm", task="segmentation", in_channels=6, focal=False) + _assert_same_state(reference, port) + x = torch.randn(2, 6, 64, 64) + _compare_forward(reference, port, x, seed=7) diff --git a/tests/oracle/test_swin_unetr_oracle.py b/tests/oracle/test_swin_unetr_oracle.py new file mode 100644 index 00000000..f2c1368e --- /dev/null +++ b/tests/oracle/test_swin_unetr_oracle.py @@ -0,0 +1,159 @@ +"""SwinUNETR checked against MONAI 1.3.2 and TS-SatFire's modified copy. + +References: ``monai.networks.nets.SwinUNETR`` from monai 1.3.2 and ``spatial_models/swinunetr/`` +from zhaoyutim/TS-SatFire (pinned in repos.yaml; no LICENSE, so it is only imported here as an +oracle). Each check builds both models from the same seed, requires identical parameter names and +initial values, then compares outputs in eval and train mode after randomising the weights and +BatchNorm statistics. + +Forward checks use 32x32 (3D) or 64x64 (2D) tiles instead of 256x256 for CPU speed; the merging +plan of TS-SatFire's copy depends only on the time length T, which is kept at the paper's values. +Parameter counts are checked at the full 256x256 size. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.swin_unetr import SwinUNETR, TemporalSwinUNETR +from tssatfire_oracle_helpers import ( + PRED_CHANNELS, + assert_close, + assert_same_names_and_shapes, + assert_same_state, + compare_eval_and_train, + monai_nets, + n_params, + randomise, + ts_satfire_module, +) + + +def _ts_swinunetr(): + return ts_satfire_module("swinunetr.swinunetr").SwinUNETR + + +def _ts_config(in_channels: int, history: int, size: int, feature_size: int = 36, num_heads: int = 3, attn_version: str = "v1"): + # run_spatial_temp_model_pred.py, model "swinunetr3d" (-ed = feature size, -nh = heads). + return dict( + image_size=(history, size, size), + patch_size=(1, 2, 2), + window_size=(history, 4, 4), + in_channels=in_channels, + out_channels=2, + depths=(2, 2, 2, 2), + num_heads=(num_heads,) * 4, + feature_size=feature_size, + norm_name="batch", + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + attn_version=attn_version, + normalize=True, + use_checkpoint=False, + spatial_dims=3, + ) + + +def test_ts_satfire_prediction_model_matches_reference(): + TSSwinUNETR = _ts_swinunetr() + torch.manual_seed(0) + reference = TSSwinUNETR(**_ts_config(PRED_CHANNELS, history=6, size=32)) + torch.manual_seed(0) + port = build_model("swin_unetr", task="segmentation", in_channels=PRED_CHANNELS, history=6, image_size=32) + assert isinstance(port, TemporalSwinUNETR) + assert_same_state(reference, port) + assert port.swinViT.resamples == reference.swinViT.resamples == [[1, 2, 2], [1, 2, 2], [1, 2, 2], [2, 2, 2]] + + randomise(reference, port, seed=1) + torch.manual_seed(2) + x = torch.randn(2, 6, PRED_CHANNELS, 32, 32) # (batch, time, channels, H, W) + x_ref = x.transpose(1, 2).contiguous() + compare_eval_and_train(reference, port, x_ref, x, reduce_time=True) + port.time_reduction = "none" + reference.eval() + port.eval() + with torch.no_grad(): + assert_close(port(x), reference(x_ref)) + + +@pytest.mark.parametrize("history", [2, 3, 4]) +def test_ts_satfire_merging_plans_match_reference(history): + """T = 2 and 4 (Table 5) merge time once and twice; an odd T never merges it.""" + TSSwinUNETR = _ts_swinunetr() + torch.manual_seed(0) + reference = TSSwinUNETR(**_ts_config(7, history=history, size=32, feature_size=12)) + torch.manual_seed(0) + port = build_model("swin_unetr", task="segmentation", in_channels=7, history=history, image_size=32, feature_size=12) + assert_same_state(reference, port) + assert port.swinViT.resamples == reference.swinViT.resamples + randomise(reference, port, seed=3) + x = torch.randn(2, history, 7, 32, 32) + compare_eval_and_train(reference, port, x.transpose(1, 2).contiguous(), x, reduce_time=True) + + +def test_ts_satfire_v2_attention_matches_reference(): + """``attn_version="v2"`` (an option of the AF/BA script): Swin-V2 cosine attention.""" + TSSwinUNETR = _ts_swinunetr() + torch.manual_seed(0) + reference = TSSwinUNETR(**_ts_config(8, history=4, size=32, feature_size=24, num_heads=4, attn_version="v2")) + torch.manual_seed(0) + port = build_model( + "swin_unetr", task="segmentation", in_channels=8, history=4, image_size=32, feature_size=24, num_heads=4, attn_version="v2" + ) + assert_same_state(reference, port) + randomise(reference, port, seed=4) + x = torch.randn(2, 4, 8, 32, 32) + compare_eval_and_train(reference, port, x.transpose(1, 2).contiguous(), x, reduce_time=True) + + +def test_ts_satfire_parameter_counts_at_full_size(): + TSSwinUNETR = _ts_swinunetr() + # The reference calls Tensor.item() while building, so it cannot be built on the meta device. + reference = TSSwinUNETR(**_ts_config(PRED_CHANNELS, history=6, size=256)) + with torch.device("meta"): + port = build_model("swin_unetr", task="segmentation", in_channels=PRED_CHANNELS) + assert_same_names_and_shapes(reference, port) + assert n_params(port) == n_params(reference) == 33_191_942 # Table 3: 33.2M + del reference + + +def test_ts_satfire_2d_config_matches_monai(): + MonaiSwinUNETR = monai_nets().SwinUNETR + # run_spatial_model.py, model "swinunetr2d": stock MONAI, feature size 48, batch norm. + config = dict(in_channels=8, out_channels=2, spatial_dims=2, feature_size=48, norm_name="batch") + torch.manual_seed(0) + reference = MonaiSwinUNETR(img_size=(64, 64), **config) + torch.manual_seed(0) + port = build_model("swin_unetr", task="segmentation", in_channels=8, spatial_dims=2, image_size=64) + assert type(port) is SwinUNETR + assert_same_state(reference, port) + assert n_params(port) == 25_151_996 # Table 3: 25.2M (the 2D model's size does not depend on the tile) + randomise(reference, port, seed=5) + torch.manual_seed(6) + x = torch.randn(2, 8, 64, 64) + compare_eval_and_train(reference, port, x, x) + + +def test_non_default_configs_match_monai(): + """MONAI's "merging" (with its repeated slices), "mergingv2", SwinUNETR-v2 blocks, dropout, + stochastic depth, instance norm, gradient checkpointing and unnormalised features.""" + MonaiSwinUNETR = monai_nets().SwinUNETR + configs = [ + dict(img_size=(32, 32, 32), in_channels=3, out_channels=2, feature_size=12, norm_name="batch", drop_rate=0.1, attn_drop_rate=0.1, dropout_path_rate=0.2), + dict(img_size=(32, 64, 32), in_channels=3, out_channels=2, feature_size=12, num_heads=(1, 2, 2, 4), downsample="mergingv2", use_v2=True), + dict(img_size=(64, 32), in_channels=2, out_channels=3, feature_size=24, spatial_dims=2, normalize=False, use_v2=True, depths=(2, 1, 2, 1)), + dict(img_size=(32, 32), in_channels=2, out_channels=1, feature_size=12, spatial_dims=2, norm_name="batch", downsample="mergingv2", use_checkpoint=True, dropout_path_rate=0.1), + ] + for config in configs: + torch.manual_seed(0) + reference = MonaiSwinUNETR(**config) + torch.manual_seed(0) + port = SwinUNETR(**config) + assert_same_state(reference, port) + randomise(reference, port, seed=7) + torch.manual_seed(8) + x = torch.randn(2, config["in_channels"], *config["img_size"]) + compare_eval_and_train(reference, port, x, x, seed=9) # same dropout / drop-path draws diff --git a/tests/oracle/test_swinlstm_oracle.py b/tests/oracle/test_swinlstm_oracle.py new file mode 100644 index 00000000..dc1e4e74 --- /dev/null +++ b/tests/oracle/test_swinlstm_oracle.py @@ -0,0 +1,215 @@ +"""SwinLSTM checked against the official implementation and its released weights. + +Reference (pinned in repos.yaml): SongTang-x/SwinLSTM (MIT), whose repository also holds the +Moving-MNIST SwinLSTM-D weights ``Pretrained/trained_model_state_dict``. It needs timm 0.4.12 and +einops, so this file runs in the ``swin`` suite of the Oracle workflow (requirements-swin.txt). + +The rollout is the official one: ``functions.model_forward_multi_layer`` (SwinLSTM-D) and +``functions.model_forward_single_layer`` (SwinLSTM-B) are called on the official models. +``functions.py`` imports ``utils.py``, which needs matplotlib and scikit-image only for metrics and +plots; a stub ``utils`` module stands in for it. +""" + +from __future__ import annotations + +import sys +import types +from importlib import metadata +from pathlib import Path + +import pytest +import torch + +from oracle_utils import import_from, missing, oracle_repo +from pyhazards.models import build_model + +REQUIREMENTS = Path(__file__).parent / "requirements-swin.txt" +CHECKPOINT = "Pretrained/trained_model_state_dict" +MNIST_D = dict( + img_size=64, patch_size=2, in_chans=1, embed_dim=128, depths_downsample=[2, 6], depths_upsample=[6, 2], + num_heads=[4, 8], window_size=4, +) +# configs.py defaults with --model SwinLSTM-B (depths [12], heads [4, 8], drop_path_rate 0.1). +MNIST_B = dict( + img_size=64, patch_size=2, in_chans=1, embed_dim=128, depths=[12], num_heads=[4, 8], window_size=4, + drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1, +) + + +@pytest.fixture(autouse=True) +def _reference_stack(): + for line in REQUIREMENTS.read_text().splitlines(): + if "==" not in line or line.lstrip().startswith("#"): + continue + name, version = line.split("#")[0].strip().split("==") + if name not in {"timm", "einops"}: + continue + try: + found = metadata.version(name) + except metadata.PackageNotFoundError: + missing(f"{name} is not installed; pip install -r tests/oracle/requirements-swin.txt") + if found != version: + missing(f"needs {name}=={version}, found {found}") + + +@pytest.fixture() +def reference(monkeypatch): + repo = oracle_repo("SwinLSTM") + # functions.py needs utils.compute_metrics / utils.visualize only in its test loop. + monkeypatch.setitem(sys.modules, "utils", types.SimpleNamespace(compute_metrics=None, visualize=None)) + return types.SimpleNamespace( + repo=repo, + D=import_from(repo, "SwinLSTM_D"), + B=import_from(repo, "SwinLSTM_B"), + functions=import_from(repo, "functions"), + ) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _rollout_d(functions, model, inputs, targets_len): + return torch.stack(functions.model_forward_multi_layer(model, inputs, targets_len, [2, 6]), dim=1) + + +def _rollout_b(functions, model, inputs, targets_len, depths): + return torch.stack(functions.model_forward_single_layer(model, inputs, targets_len, depths), dim=1) + + +def test_swinlstm_d_official_weights_match_reference(reference): + state = torch.load(reference.repo / CHECKPOINT, map_location="cpu", weights_only=True) + official = reference.D.SwinLSTM(**MNIST_D) + official.load_state_dict(state, strict=True) + port = build_model("swinlstm", task="forecasting") + port.load_state_dict(state, strict=True) + assert _n_params(port) == _n_params(official) == 20_191_969 + assert list(port.state_dict()) == list(state) + + torch.manual_seed(0) + frames = torch.rand(2, 10, 1, 64, 64) + official.eval() + port.eval() + with torch.no_grad(): + expected = _rollout_d(reference.functions, official, frames, 10) # 9 warm-up + 10 predicted frames + _assert_close(port(frames, include_warmup=True), expected) + _assert_close(port(frames), expected[:, 9:]) # the official test loop keeps outputs[:, T_in - 1:] + # One reference step (SwinLSTM.forward) with explicit states. + out, down, up = port.step(frames[:, 0]) + ref_out, ref_down, ref_up = official(frames[:, 0], [None, None], [None, None]) + _assert_close(out, ref_out) + _assert_close(port.step(frames[:, 1], down, up)[0], official(frames[:, 1], ref_down, ref_up)[0]) + + +def test_swinlstm_d_initialisation_and_train_mode_match_reference(reference): + torch.manual_seed(0) + official = reference.D.SwinLSTM(**MNIST_D) + torch.manual_seed(0) + port = build_model("swinlstm", task="forecasting") + _assert_same_state(official, port) + + torch.manual_seed(1) + frames = torch.rand(2, 4, 1, 64, 64) + official.train() + port.train() + torch.manual_seed(2) # stochastic depth draws the same random numbers + expected = _rollout_d(reference.functions, official, frames, 3) + torch.manual_seed(2) + _assert_close(port(frames, num_output_frames=3, include_warmup=True), expected) + + +def test_swinlstm_b_matches_reference(reference): + torch.manual_seed(0) + official = reference.B.SwinLSTM(**MNIST_B) + torch.manual_seed(0) + port = build_model("swinlstm", task="forecasting", variant="b", depths=[12]) + _assert_same_state(official, port) + assert _n_params(port) == 2_778_417 + + torch.manual_seed(1) + frames = torch.rand(2, 4, 1, 64, 64) + official.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(frames, num_output_frames=4, include_warmup=True), _rollout_b(reference.functions, official, frames, 4, [12])) + official.train() + port.train() + torch.manual_seed(3) + expected = _rollout_b(reference.functions, official, frames, 2, [12]) + torch.manual_seed(3) + _assert_close(port(frames, num_output_frames=2, include_warmup=True), expected) + + +def test_swinlstm_b_human36m_and_two_cell_configurations(reference): + # Paper Table 1, Human3.6m: SwinLSTM-B with 12 Swin blocks, patch 2, 128x128x3 frames. + torch.manual_seed(0) + official = reference.B.SwinLSTM(**{**MNIST_B, "img_size": 128, "in_chans": 3}) + torch.manual_seed(0) + port = build_model("swinlstm", task="forecasting", variant="b", depths=[12], img_size=128, in_channels=3) + _assert_same_state(official, port) + assert _n_params(port) == _n_params(official) == 2_781_747 + + # Two SwinLSTM-B cells with different head counts, and a small two-level SwinLSTM-D. + small_b = dict(MNIST_B, img_size=32, embed_dim=32, depths=[2, 4], num_heads=[2, 4], drop_path_rate=0.2) + torch.manual_seed(4) + official = reference.B.SwinLSTM(**small_b) + torch.manual_seed(4) + port = build_model( + "swinlstm", task="forecasting", variant="b", img_size=32, embed_dim=32, depths=[2, 4], num_heads=[2, 4], + drop_path_rate=0.2, + ) + _assert_same_state(official, port) + frames = torch.rand(3, 3, 1, 32, 32) + official.train() + port.train() + torch.manual_seed(5) + expected = _rollout_b(reference.functions, official, frames, 2, [2, 4]) + torch.manual_seed(5) + _assert_close(port(frames, num_output_frames=2, include_warmup=True), expected) + + small_d = dict(MNIST_D, img_size=32, in_chans=2, embed_dim=32, depths_downsample=[2, 2], depths_upsample=[4, 2]) + torch.manual_seed(6) + official = reference.D.SwinLSTM(**small_d) + torch.manual_seed(6) + port = build_model( + "swinlstm", task="forecasting", img_size=32, in_channels=2, embed_dim=32, depths_downsample=[2, 2], + depths_upsample=[4, 2], + ) + _assert_same_state(official, port) + frames = torch.rand(2, 3, 2, 32, 32) + official.train() + port.train() + torch.manual_seed(7) + expected = _rollout_d(reference.functions, official, frames, 2) + torch.manual_seed(7) + _assert_close(port(frames, num_output_frames=2, include_warmup=True), expected) + + +def test_swinlstm_segmentation_adaptation_is_the_reference_rollout_without_sigmoid(reference): + # With one input and one output channel the segmentation head is the official model: its + # logits are the official one-frame prediction before the final sigmoid. + state = torch.load(reference.repo / CHECKPOINT, map_location="cpu", weights_only=True) + official = reference.D.SwinLSTM(**MNIST_D) + official.load_state_dict(state, strict=True) + segmenter = build_model("swinlstm", task="segmentation") + segmenter.load_state_dict(state, strict=True) + official.eval() + segmenter.eval() + torch.manual_seed(0) + frames = torch.rand(2, 3, 1, 64, 64) + with torch.no_grad(): + expected = _rollout_d(reference.functions, official, frames, 1)[:, -1] + logits = segmenter(frames) + assert logits.shape == (2, 1, 64, 64) + _assert_close(torch.sigmoid(logits), expected) diff --git a/tests/oracle/test_tcbench_evaluation_oracle.py b/tests/oracle/test_tcbench_evaluation_oracle.py new file mode 100644 index 00000000..7019b909 --- /dev/null +++ b/tests/oracle/test_tcbench_evaluation_oracle.py @@ -0,0 +1,74 @@ +"""TCBench-protocol scoring checked against TCBench's own evaluation code on its released tracks. + +TCBench_Alpha (https://github.com/msgomez06/TCBench_Alpha, MIT; pinned in repos.yaml) computes the +direct position error and intensity errors of each forecast row in ``dev/metrics_test.py`` (``_DPE``, +``_AE``) against IBTrACS read by ``dev/utils/toolbox.read_hist_track_file`` with the column types of +``dev/utils/constants.py`` (``LAT`` / ``LON`` as float16). Those functions are executed from the pinned +files (their modules import plotting and deep-learning packages the functions do not use, so only the +function definitions are loaded) on TCBench's released ``matched_tracks`` files for Pangu-Weather and +FourCastNet v2 with TCBench's own 2023 IBTrACS extract, after the filtering of +``dev/evaluate_tracks.py`` (00/12 UTC initialisations, storms of the year, duplicates dropped) and the +unit conversion of ``dev/track_matcher.py``. :func:`pyhazards.forecasts.forecast_track_errors` with +``protocol="tcbench"`` must give the same value for every row. +""" + +from __future__ import annotations + +import os +import types + +import numpy as np +import pandas as pd +import pytest + +from oracle_utils import import_from, load_definitions, oracle_asset, oracle_repo + +from pyhazards.forecasts import forecast_track_errors, read_tcbench_matched_tracks +from pyhazards.forecasts.scoring import TCBENCH_KT_PER_MS + + +@pytest.fixture(scope="module") +def tcbench(): + import joblib + + dev = oracle_repo("TCBench_Alpha") / "dev" + constants = import_from(dev / "utils", "constants") + toolbox_defs = load_definitions(dev / "utils" / "toolbox.py", ["haversine", "read_hist_track_file"], {"np": np, "pd": pd, "os": os, "constants": constants}) + toolbox = types.SimpleNamespace(**toolbox_defs) + namespace = {"np": np, "pd": pd, "jl": joblib, "toolbox": toolbox} + return load_definitions(dev / "metrics_test.py", ["_DPE", "_AE"], namespace), toolbox + + +@pytest.mark.parametrize("asset, filename", [("tcbench_matched_pangu", "2023_PANGU.csv"), ("tcbench_matched_fcnet", "2023_fcnet.csv")]) +def test_tcbench_protocol_matches_official_evaluation(tcbench, tmp_path, asset, filename): + functions, toolbox = tcbench + ib_dir = tmp_path / "ibtracs" + ib_dir.mkdir() + (ib_dir / "2023_IBTrACS.csv").write_bytes((oracle_asset("tcbench_ibtracs_2023") / "2023_IBTrACS.csv").read_bytes()) + # TCBench's 2023 extract has no units row (the NCEI files do), hence skip_rows=None. + ibtracs = toolbox.read_hist_track_file(tracks_path=str(ib_dir), skip_rows=None) + ibtracs = ibtracs[pd.to_datetime(ibtracs["ISO_TIME"]).dt.year == 2023] + assert ibtracs["LAT"].dtype == np.float16 + + released = pd.read_csv(oracle_asset(asset) / filename) + # dev/track_matcher.py converts to knots and hPa before evaluation. + tracks = released.copy() + tracks["wind max"] = tracks["wind max"] * TCBENCH_KT_PER_MS + tracks["pressure min"] = tracks["pressure min"] / 100 + # dev/evaluate_tracks.py filtering. + tracks["Initial Time"] = pd.to_datetime(tracks["Initial Time"]) + tracks = tracks[tracks["Initial Time"].dt.hour.isin({0, 12})] + tracks = tracks[tracks["SID"].isin(ibtracs["SID"].unique())] + tracks = tracks.drop_duplicates(subset=["Initial Time", "Valid Time", "SID"], keep="first").reset_index(drop=True) + dpe = functions["_DPE"](reference=ibtracs, predictions=tracks) + ae = np.asarray(functions["_AE"](reference=ibtracs, predictions=tracks)) + + reference = pd.read_csv(oracle_asset("tcbench_ibtracs_2023") / "2023_IBTrACS.csv", keep_default_na=False, na_values=[""]) + reference = reference[pd.to_datetime(reference["ISO_TIME"]).dt.year == 2023] + ours = forecast_track_errors(read_tcbench_matched_tracks(oracle_asset(asset) / filename), reference, protocol="tcbench") + assert len(ours) == len(tracks) + assert (ours["SID"].to_numpy() == tracks["SID"].to_numpy()).all() + np.testing.assert_allclose(ours["track_error_km"].to_numpy(), np.asarray(dpe, dtype=float), rtol=0, atol=1e-9, equal_nan=True) + np.testing.assert_allclose(np.abs(ours["wind_error_kt"].to_numpy()), ae[:, 0].astype(float), rtol=0, atol=1e-9, equal_nan=True) + np.testing.assert_allclose(np.abs(ours["pres_error_hpa"].to_numpy()), ae[:, 1].astype(float), rtol=0, atol=1e-9, equal_nan=True) + assert np.isfinite(ours["track_error_km"]).sum() > 1000 diff --git a/tests/oracle/test_tcif_fusion_oracle.py b/tests/oracle/test_tcif_fusion_oracle.py new file mode 100644 index 00000000..86276be3 --- /dev/null +++ b/tests/oracle/test_tcif_fusion_oracle.py @@ -0,0 +1,180 @@ +"""TCIF-fusion checked against the official notebooks (wangchong96/TCIF-fusion, pinned). + +The notebooks have no licence and cannot run as published (Keras 2 / TensorFlow 1 session code, no data +loading); pyhazards/models/tcif_fusion.py is written from the paper and the notebook's layer list. Here: + +* the model summary printed in ``obtain model knowledge.ipynb`` by the authors' own run (Keras 2, + TensorFlow 1.14) gives every layer's parameter count and the total, 299,611,263; +* the notebook's ``F3d``, ``F2d``, ``VGG192d`` and ``TCIF_fusion`` functions are executed unchanged from the + pinned ``TCIF-fusion.ipynb`` with Keras 3 on the PyTorch backend (only the ALL input's channel count is + substituted for the paper's 65-channel variant); the Keras weights are copied into the port and the + outputs compared; +* the training settings of the notebook's ``compile`` / ``fit`` call and the first step of its + model-knowledge example (gradient of the forecast w.r.t. the SST input, averaged over the batch and the + two horizontal axes). +""" + +from __future__ import annotations + +import ast +import json +import os +import re +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.tcif_fusion import TCIF_TRAINING, load_keras_weights, model_knowledge_heatmaps + +os.environ.setdefault("KERAS_BACKEND", "torch") + + +def _cells(repo: Path, name: str): + notebook = json.loads((repo / name).read_text(encoding="utf-8")) + return [cell for cell in notebook["cells"] if cell["cell_type"] == "code"] + + +def _keras(): + keras = oracle_package("keras", "3.12.4", "requirements-tc.txt") + if keras.backend.backend() != "torch": + pytest.skip("set KERAS_BACKEND=torch before keras is imported") + return keras + + +def _official_graph(all_channels: int = 85): + """The notebook's TCIF_fusion() built with Keras 3; returns the model and its weights by Keras-2 name.""" + keras = _keras() + from keras.layers import Concatenate, Dense, Flatten, Input, add + from keras.models import Model + + repo = oracle_repo("TCIF-fusion") + source = "\n".join("".join(cell["source"]) for cell in _cells(repo, "TCIF-fusion.ipynb")) + if all_channels != 85: + assert source.count("shape = (25, 25, 85)") == 1 + source = source.replace("shape = (25, 25, 85)", f"shape = (25, 25, {all_channels})") + tree = ast.parse(source) + nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in {"F3d", "F2d", "VGG192d", "TCIF_fusion"}] + assert len(nodes) == 4 + scope = {"keras": keras, "Concatenate": Concatenate, "Dense": Dense, "Flatten": Flatten, "Input": Input, "Model": Model, "add": add} + exec(compile(ast.Module(body=nodes, type_ignores=[]), "TCIF-fusion.ipynb", "exec"), scope) + keras.backend.clear_session() + keras.utils.set_random_seed(0) + model = scope["TCIF_fusion"]() + # Keras names layers , _1, ... in creation order; the notebook's Keras 2 named them _1, _2, ... + groups = {} + for layer in model.layers: + if layer.weights: + kind, _, suffix = layer.name.partition("_") + index = int(suffix) if suffix.isdigit() else 0 + groups.setdefault(kind, []).append((index, layer)) + weights = {} + for kind, items in groups.items(): + for number, (_, layer) in enumerate(sorted(items, key=lambda item: item[0]), start=1): + weights[f"{kind}_{number}"] = [np.asarray(w) for w in layer.get_weights()] + return model, weights + + +def _inputs(all_channels: int, batch: int = 2, seed: int = 0): + rng = np.random.default_rng(seed) + arrays = [rng.standard_normal((batch, 25, 25, 5, 4)).astype("float32") for _ in range(3)] + arrays += [ + rng.standard_normal((batch, 25, 25, 5, 1)).astype("float32"), + rng.standard_normal((batch, 25, 25, all_channels)).astype("float32"), + rng.standard_normal((batch, 30)).astype("float32"), + rng.random((batch, 224, 224, 5)).astype("float32"), + ] + return arrays # notebook input order: u, v, w, sst, h (ALL), left (history), sat (IR) + + +def test_parameters_match_the_authors_printed_summary(): + repo = oracle_repo("TCIF-fusion") + cell = next(cell for cell in _cells(repo, "obtain model knowledge.ipynb") if "def TCIF_fusion" in "".join(cell["source"])) + text = "".join("".join(output.get("text", [])) for output in cell["outputs"]) + lines = text.splitlines() + header = next(line for line in lines if line.startswith("Layer (type)")) + shape_col, param_col, link_col = header.index("Output Shape"), header.index("Param #"), header.index("Connected to") + printed = {} + for line in lines: + match = re.match(r"^(\w+) \((\w+)\)", line) + if match and line != header and len(line) > param_col: + printed[match.group(1)] = (match.group(2), line[shape_col:param_col].strip(), int(line[param_col:link_col].strip())) + total = int(re.search(r"Total params: ([\d,]+)", text).group(1).replace(",", "")) + assert total == 299_611_263 + port = build_model("tcif_fusion", task="regression", all_channels=85) + assert sum(p.numel() for p in port.parameters()) == total + assert printed["input_5"][1] == "(None, 25, 25, 85)" # the ALL input of the notebook's graph + modules = dict(port.named_modules()) + weighted = {name: entry for name, entry in printed.items() if entry[2] > 0} + assert set(weighted) == set(port.keras_layer_names()) + for keras_name, module_name in port.keras_layer_names().items(): + assert sum(p.numel() for p in modules[module_name].parameters()) == weighted[keras_name][2], keras_name + # The paper's variant: 65 ALL channels (Figure 1), 23,040 fewer weights in the first ALL convolution. + assert sum(p.numel() for p in build_model("tcif_fusion", task="regression").parameters()) == 299_588_223 + + +@pytest.mark.parametrize("all_channels", [85, 65]) +def test_outputs_match_the_notebook_graph(all_channels): + reference, weights = _official_graph(all_channels) + port = build_model("tcif_fusion", task="regression", all_channels=all_channels).eval() + assert reference.count_params() == sum(p.numel() for p in port.parameters()) + load_keras_weights(port, weights) + arrays = _inputs(all_channels) + expected = np.asarray(reference.predict(arrays, verbose=0)) + tensors = [torch.as_tensor(a) for a in arrays] + with torch.no_grad(): + positional = port(*tensors).numpy() + named = port(dict(zip(("u", "v", "w", "sst", "all", "his", "ir"), tensors))).numpy() + np.testing.assert_allclose(positional, expected, rtol=1e-5, atol=1e-6) + np.testing.assert_array_equal(named, positional) + + +def test_initialisation_follows_keras_defaults(): + """Glorot-uniform kernels and zero biases like the Keras layers (the random draws differ).""" + torch.manual_seed(0) + port = build_model("tcif_fusion", task="regression") + modules = dict(port.named_modules()) + for module_name in ("u_block1.conv1", "fusion_block3.conv3", "all_block1.conv1", "ir.conv5_4", "era5_dense1", "res2_dense3"): + layer = modules[module_name] + receptive = layer.weight[0, 0].numel() + limit = np.sqrt(6.0 / (layer.weight.shape[1] * receptive + layer.weight.shape[0] * receptive)) + weight = layer.weight.detach() + assert float(weight.abs().max()) <= limit + 1e-7 + assert float(weight.std()) == pytest.approx(limit / np.sqrt(3.0), rel=0.05) + assert not torch.any(layer.bias) + + +def test_training_settings_are_the_notebooks(): + repo = oracle_repo("TCIF-fusion") + source = "".join(next(cell for cell in _cells(repo, "TCIF-fusion.ipynb") if ".fit(" in "".join(cell["source"]))["source"]) + calls = {} + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Call): + name = node.func.attr if isinstance(node.func, ast.Attribute) else getattr(node.func, "id", None) + calls.setdefault(name, {}).update({kw.arg: kw.value for kw in node.keywords}) + literal = lambda name, key: ast.literal_eval(calls[name][key]) # noqa: E731 + assert literal("Adam", "lr") == TCIF_TRAINING["learning_rate"] + assert literal("compile", "loss") == TCIF_TRAINING["loss"] + assert literal("fit", "batch_size") == TCIF_TRAINING["batch_size"] + assert literal("fit", "epochs") == TCIF_TRAINING["epochs"] + plateau = TCIF_TRAINING["reduce_lr_on_plateau"] + assert (literal("ReduceLROnPlateau", "factor"), literal("ReduceLROnPlateau", "patience"), literal("ReduceLROnPlateau", "min_lr")) == (plateau["factor"], plateau["patience"], plateau["min_lr"]) + + +def test_model_knowledge_gradients_follow_the_notebook(): + """The MK example takes d(forecast)/d(SST input) of one sample and averages it over axes (0, 1, 2).""" + reference, weights = _official_graph(85) + port = build_model("tcif_fusion", task="regression", all_channels=85).eval() + load_keras_weights(port, weights) + arrays = _inputs(85, batch=1, seed=3) + tensors = [torch.as_tensor(a) for a in arrays] + sst = tensors[3].clone().requires_grad_(True) + output = reference([*tensors[:3], sst, *tensors[4:]], training=False) + grads = torch.autograd.grad(output[:, 0].sum(), sst)[0] + pooled = grads.mean(dim=(0, 1, 2)) # K.mean(grads, axis=(0, 1, 2)) of the notebook: (time, channel) + expected = (tensors[3][0] * pooled).mean(dim=-1) # Grad-CAM: weighted channels, averaged + heatmaps = model_knowledge_heatmaps(port, dict(zip(("u", "v", "w", "sst", "all", "his", "ir"), tensors)), names=("sst",)) + torch.testing.assert_close(heatmaps["sst"][0], expected.detach(), rtol=1e-4, atol=1e-9) diff --git a/tests/oracle/test_tcn_oracle.py b/tests/oracle/test_tcn_oracle.py new file mode 100644 index 00000000..312244dc --- /dev/null +++ b/tests/oracle/test_tcn_oracle.py @@ -0,0 +1,173 @@ +"""TCN checked against the official locuslab/TCN code (pinned in repos.yaml). + +The official modules use the deprecated hook-based ``torch.nn.utils.weight_norm`` (``weight_g`` / +``weight_v``); the port uses ``torch.nn.utils.parametrizations.weight_norm``. Parameter names are +compared after :func:`to_official_state_dict`, and official state dicts are loaded into the port +unchanged. Each check builds both models from the same seed and requires identical initial values +and outputs; configurations are the official example scripts' defaults. +""" + +from __future__ import annotations + +import warnings + +import pytest +import torch + +from oracle_utils import import_from, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.tcn import TCN, TemporalConvNet, to_official_state_dict + + +def _official(module: str): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) # torch.nn.utils.weight_norm is deprecated + return import_from(oracle_repo("TCN"), f"TCN.{module}") + + +def _build(factory, *args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + return factory(*args, **kwargs) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), to_official_state_dict(port.state_dict()) + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def test_adding_problem_model_matches_official(): + official = _official("adding_problem.model") + # add_test.py defaults: 2 inputs, 1 output, 8 levels x 30 channels, kernel 7, dropout 0. + torch.manual_seed(0) + reference = _build(official.TCN, 2, 1, [30] * 8, kernel_size=7, dropout=0.0) + torch.manual_seed(0) + port = build_model("tcn", task="regression") + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 96_001 + + torch.manual_seed(1) + x = torch.randn(4, 2, 400) # official layout (batch, channels, length), seq_len 400 + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x.transpose(1, 2)), reference(x)) + + # Official state dicts load unchanged, and port state dicts load into the official code. + restored = build_model("tcn", task="regression") + restored.load_state_dict(reference.state_dict(), strict=True) + exported = _build(official.TCN, 2, 1, [30] * 8, kernel_size=7, dropout=0.0) + exported.load_state_dict(to_official_state_dict(port.state_dict()), strict=True) + restored.eval() + exported.eval() + with torch.no_grad(): + _assert_close(restored(x.transpose(1, 2)), reference(x)) + _assert_close(exported(x), port(x.transpose(1, 2))) + + +def test_official_normal_init_does_not_reach_weight_normed_convs(): + """``init_weights`` writes N(0, 0.01) into the computed weight, which weight norm recomputes.""" + tcn = _official("tcn") + torch.manual_seed(0) + reference = _build(tcn.TemporalConvNet, 3, [16, 16], kernel_size=3, dropout=0.0) + torch.manual_seed(0) + port = TemporalConvNet(3, [16, 16], kernel_size=3, dropout=0.0) + _assert_same_state(reference, port) + block = reference.network[0] + assert block.conv1.weight_v.std() > 0.1 # PyTorch's default Conv1d init, not N(0, 0.01) + assert block.downsample.weight.std() < 0.02 # the plain 1x1 conv does get N(0, 0.01) + with torch.no_grad(): + reference(torch.randn(1, 3, 8)) # the forward pre-hook recomputes conv1.weight from g, v + effective = block.conv1.weight_g * block.conv1.weight_v / block.conv1.weight_v.norm(dim=(1, 2), keepdim=True) + _assert_close(block.conv1.weight, effective) + _assert_close(port.network[0].conv1.weight, effective) + + +def test_sequential_mnist_model_matches_official_in_train_mode(): + official = _official("mnist_pixel.model") + # pmnist_test.py defaults: 1 input, 10 classes, 8 levels x 25 channels, kernel 7, dropout 0.05; + # the head keeps PyTorch's initialisation and the official forward ends with log_softmax. + torch.manual_seed(0) + reference = _build(official.TCN, 1, 10, [25] * 8, kernel_size=7, dropout=0.05) + torch.manual_seed(0) + port = build_model( + "tcn", + task="classification", + input_dim=1, + out_dim=10, + hidden_dim=25, + num_levels=8, + kernel_size=7, + dropout=0.05, + head_init="default", + ) + _assert_same_state(reference, port) + assert _n_params(port) == _n_params(reference) == 66_910 + + torch.manual_seed(1) + x = torch.randn(3, 1, 196) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(torch.log_softmax(port(x.transpose(1, 2)), dim=1), reference(x)) + reference.train() + port.train() + torch.manual_seed(2) + expected = reference(x) + torch.manual_seed(2) + _assert_close(torch.log_softmax(port(x.transpose(1, 2)), dim=1), expected) # same dropout masks + + +@pytest.mark.parametrize("task_dir", ["copy_memory", "poly_music"]) +def test_sequence_heads_match_official(task_dir): + official = _official(f"{task_dir}.model") + if task_dir == "copy_memory": + # copymem_test.py: 1 input, 10 classes, 8 levels x 10 channels, kernel 8; input (N, C, L). + args, kwargs, head_init = (1, 10, [10] * 8), dict(kernel_size=8, dropout=0.0), "normal" + x = torch.randn(2, 1, 30) + else: + # music_test.py: 88 keys in and out, 4 levels x 150 channels, kernel 5, dropout 0.25; + # input (N, L, C), output sigmoid in float64. + args, kwargs, head_init = (88, 88, [150] * 4), dict(kernel_size=5, dropout=0.25), "default" + x = torch.randn(2, 40, 88) + torch.manual_seed(0) + reference = _build(official.TCN, *args, **kwargs) + torch.manual_seed(0) + port = TCN(*args, **kwargs, readout="sequence", head_init=head_init) + _assert_same_state(reference, port) + + reference.eval() + port.eval() + with torch.no_grad(): + if task_dir == "copy_memory": + _assert_close(port(x.transpose(1, 2)), reference(x)) + else: + _assert_close(torch.sigmoid(port(x).double()), reference(x)) + + +def test_official_and_port_are_causal(): + tcn = _official("tcn") + torch.manual_seed(0) + reference = _build(tcn.TemporalConvNet, 2, [8, 8, 8], kernel_size=3, dropout=0.0).eval() + port = TemporalConvNet(2, [8, 8, 8], kernel_size=3, dropout=0.0).eval() + port.load_state_dict(reference.state_dict(), strict=True) + x = torch.randn(1, 2, 40) + t = 25 + perturbed = x.clone() + perturbed[:, :, t + 1 :] += torch.randn_like(perturbed[:, :, t + 1 :]) + with torch.no_grad(): + for model in (reference, port): + base, moved = model(x), model(perturbed) + torch.testing.assert_close(base[:, :, : t + 1], moved[:, :, : t + 1], rtol=0, atol=0) + assert not torch.allclose(base[:, :, t + 1 :], moved[:, :, t + 1 :]) + _assert_close(port(x), reference(x)) diff --git a/tests/oracle/test_tempest_oracle.py b/tests/oracle/test_tempest_oracle.py new file mode 100644 index 00000000..8bb2ac8c --- /dev/null +++ b/tests/oracle/test_tempest_oracle.py @@ -0,0 +1,225 @@ +"""pyhazards.forecasts.tempest checked against the official TempestExtremes binaries and TCBench's tracks. + +TempestExtremes v2.4.2 (https://github.com/ClimateGlobalChange/tempestextremes, BSD-2-Clause per its +LICENSE; pinned in repos.yaml) is built from source with CMake on first use (needs a C++ compiler and +the netCDF C library, e.g. ``apt-get install cmake libnetcdf-dev``) and run as a separate program; +nothing of it is copied into PyHazards. + +1. Synthetic global fields (cyclones in both hemispheres, one crossing the dateline, a cold-core low, + a shallow low, a polar low) written to netCDF: DetectNodes with TCBench's command line must give the + same nodes and printed values as :func:`detect_nodes`, and StitchNodes the same CSV, byte for byte. + Further option sets cover diagonal connectivity, regional grids, ``--maxgap`` and thresholds. +2. Large / network (``PYHAZARDS_ORACLE_LARGE=1``): the TempestExtremes variables of TCBench's + Pangu-Weather forecast initialised 2023-07-16 12 UTC are read from the pinned Hugging Face revision + (about 200 MB of range requests). Both the official binaries and PyHazards must reproduce TCBench's + released ``unmatched_tracks`` file for that forecast byte for byte, and PyHazards' IBTrACS matching + must find TCBench's matched storms. +""" + +from __future__ import annotations + +import dataclasses +import os +import shutil +import subprocess +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from oracle_utils import missing, oracle_asset, oracle_repo + +from pyhazards.forecasts import ( + TCBENCH_DETECT_NODES, + TCBENCH_STITCH_NODES, + ClosedContourCriterion, + DetectNodesConfig, + NodeOutput, + StitchNodesConfig, + StitchThreshold, + detect_nodes, + stitch_nodes, + write_stitchnodes_csv, +) +from pyhazards.forecasts.synthetic import SyntheticVortex, synthetic_cyclone_fields + +TCBENCH_DETECT_ARGS = [ + "--searchbymin", "msl", + "--closedcontourcmd", "msl,200.0,5.5,0;_DIFF(z300,z500),-58.8,6.5,1.0", + "--mergedist", "6.0", + "--outputcmd", "msl,min,0;_VECMAG(u10,v10),max,2", +] +TCBENCH_STITCH_ARGS = [ + "--in_fmt", "lon,lat,slp,wind10", + "--range", "8.0", + "--mintime", "12h", + "--threshold", "wind10,>=,10.0,2;lat,<=,50.0,1;lat,>=,-50.0,1", + "--out_file_format", "csv", +] + + +@pytest.fixture(scope="module") +def tempest_bin() -> Path: + repo = oracle_repo("tempestextremes") + binaries = repo / "build" / "bin" + if not (binaries / "DetectNodes").exists() or not (binaries / "StitchNodes").exists(): + if shutil.which("cmake") is None: + missing("cmake is needed to build TempestExtremes (apt-get install cmake libnetcdf-dev)") + build = repo / "build" + build.mkdir(exist_ok=True) + subprocess.run(["cmake", "-DCMAKE_BUILD_TYPE=Release", "-DENABLE_MPI=OFF", ".."], cwd=build, check=True, capture_output=True) + jobs = str(min(8, os.cpu_count() or 1)) + subprocess.run(["make", f"-j{jobs}", "DetectNodes", "StitchNodes"], cwd=build, check=True, capture_output=True) + return binaries + + +def _write_netcdf(path: Path, fields, lat, lon, times) -> None: + import netCDF4 + + times = pd.to_datetime(list(times)) + with netCDF4.Dataset(path, "w") as ds: + ds.createDimension("time", None) + ds.createDimension("lat", len(lat)) + ds.createDimension("lon", len(lon)) + var = ds.createVariable("time", "f8", ("time",)) + var.units = f"hours since {times[0]:%Y-%m-%d %H:%M:%S}" + var.calendar = "standard" + var[:] = (times - times[0]).total_seconds() / 3600.0 + ds.createVariable("lat", "f8", ("lat",))[:] = lat + ds.createVariable("lon", "f8", ("lon",))[:] = lon + for name, values in fields.items(): + ds.createVariable(name, "f4", ("time", "lat", "lon"))[:] = np.asarray(values, dtype=np.float32) + + +def _parse_nodes(path: Path): + """DetectNodes text output -> list of (time, i, j, lon, lat, values...) string tuples.""" + rows = [] + lines = path.read_text().splitlines() + k = 0 + while k < len(lines): + year, month, day, count, hour = lines[k].split("\t") + stamp = pd.Timestamp(int(year), int(month), int(day), int(hour)) + for line in lines[k + 1 : k + 1 + int(count)]: + rows.append((stamp,) + tuple(line.strip().split("\t"))) + k += 1 + int(count) + return rows + + +def _run_official(tempest_bin: Path, workdir: Path, fields, lat, lon, times, detect_args, stitch_args, extra=()): + nc = workdir / "fields.nc" + _write_netcdf(nc, fields, lat, lon, times) + nodes = workdir / "nodes.txt" + tracks = workdir / "tracks.csv" + subprocess.run([str(tempest_bin / "DetectNodes"), "--in_data", str(nc), "--out", str(nodes), *detect_args, *extra], check=True, capture_output=True) + subprocess.run([str(tempest_bin / "StitchNodes"), "--in", str(nodes), "--out", str(tracks), *stitch_args], check=True, capture_output=True) + return nodes, tracks + + +def _compare(tmp_path, tempest_bin, ds, detect, stitch, detect_args, stitch_args, extra=(), crop=None): + names = ("msl", "u10", "v10", "z300", "z500") + lat, lon = ds["lat"].values, ds["lon"].values + fields = {name: ds[name].values for name in names} + if crop is not None: + rows, cols = crop + lat, lon = lat[rows], lon[cols] + fields = {name: value[:, rows][:, :, cols] for name, value in fields.items()} + times = ds["time"].values + nodes_path, tracks_path = _run_official(tempest_bin, tmp_path, fields, lat, lon, times, detect_args, stitch_args, extra) + ours = detect_nodes(fields, lat, lon, times, detect) + official = _parse_nodes(nodes_path) + columns = ["time", "i", "j", "text_lon", "text_lat"] + [c for c in ours.columns if c.startswith("text_") and c not in ("text_lon", "text_lat")] + mine = [(row[0],) + tuple(str(v) for v in row[1:]) for row in ours[columns].itertuples(index=False)] + assert mine == official + assert len(mine) > 0 + ours.attrs["times"] = list(times) + tracks = stitch_nodes(ours, stitch) + out = tmp_path / "ours.csv" + write_stitchnodes_csv(tracks, out) + assert out.read_text() == tracks_path.read_text() + return tracks + + +@pytest.fixture(scope="module") +def synthetic(): + vortices = [ + SyntheticVortex(15.0, 140.0, u=-5.0, v=2.0), + SyntheticVortex(-15.0, 60.0, u=-4.0, v=-2.0), + SyntheticVortex(-18.0, 179.0, u=6.0, v=-1.0), # crosses the dateline + SyntheticVortex(25.0, 300.0, u=3.0, v=3.0, warm_core=0.0), # cold core: rejected + SyntheticVortex(10.0, 200.0, pressure_drop=100.0), # too shallow: rejected + SyntheticVortex(55.0, 20.0, u=8.0, v=0.0, vmax=20.0), # warm-core low poleward of 50 degrees + ] + return synthetic_cyclone_fields(vortices, list(range(0, 49, 6)), resolution=0.5) + + +def test_tcbench_configuration_matches_official_binaries(tmp_path, tempest_bin, synthetic): + tracks = _compare(tmp_path, tempest_bin, synthetic, TCBENCH_DETECT_NODES, TCBENCH_STITCH_NODES, TCBENCH_DETECT_ARGS, TCBENCH_STITCH_ARGS) + assert tracks["track_id"].nunique() == 3 # the poleward low fails the |lat| <= 50 threshold + + +def test_option_variants_match_official_binaries(tmp_path, tempest_bin, synthetic): + detect = DetectNodesConfig( + search_by_min="msl", + closed_contours=(ClosedContourCriterion("msl", 150.0, 4.0, 0.0), ClosedContourCriterion("_DIFF(z300,z500)", -40.0, 5.0, 1.5)), + merge_dist=4.0, + outputs=(NodeOutput("msl", "min", 0.0, "slp"), NodeOutput("_VECMAG(u10,v10)", "max", 3.0, "wind10"), NodeOutput("z300", "max", 1.0, "zmax")), + diagonal_connectivity=True, + ) + detect_args = [ + "--searchbymin", "msl", + "--closedcontourcmd", "msl,150.0,4.0,0;_DIFF(z300,z500),-40.0,5.0,1.5", + "--mergedist", "4.0", + "--outputcmd", "msl,min,0;_VECMAG(u10,v10),max,3;z300,max,1", + "--diag_connect", + ] + stitch = StitchNodesConfig( + columns=("lon", "lat", "slp", "wind10", "zmax"), + range_deg=6.0, + min_time=3, + max_gap=1, + thresholds=(StitchThreshold("wind10", ">=", 15.0, "all"), StitchThreshold("lat", "|<=", 52.0, "first")), + ) + stitch_args = [ + "--in_fmt", "lon,lat,slp,wind10,zmax", "--range", "6.0", "--mintime", "3", "--maxgap", "1", + "--threshold", "wind10,>=,15.0,all;lat,|<=,52.0,first", "--out_file_format", "csv", + ] + _compare(tmp_path, tempest_bin, synthetic, detect, stitch, detect_args, stitch_args) + + +def test_regional_grid_matches_official_binaries(tmp_path, tempest_bin, synthetic): + lat, lon = synthetic["lat"].values, synthetic["lon"].values + rows = np.flatnonzero((lat <= 40) & (lat >= -40)) + cols = np.flatnonzero((lon >= 30) & (lon <= 200)) + detect = dataclasses.replace(TCBENCH_DETECT_NODES, regional=True) + _compare(tmp_path, tempest_bin, synthetic, detect, TCBENCH_STITCH_NODES, TCBENCH_DETECT_ARGS, TCBENCH_STITCH_ARGS, extra=("--regional",), crop=(rows, cols)) + + +def test_tcbench_released_pangu_tracks_reproduced(tmp_path, tempest_bin): + if os.environ.get("PYHAZARDS_ORACLE_LARGE") != "1": + pytest.skip("reads ~200 MB of TCBench's raw Pangu-Weather output over HTTP; set PYHAZARDS_ORACLE_LARGE=1") + from pyhazards.forecasts import read_tcbench_fields, read_tcbench_matched_tracks, tempest_forecast_tracks + + init = pd.Timestamp("2023-07-16 12:00") + released = oracle_asset("tcbench_pangu_unmatched_20230716_12") / "panguweather_2023.07.16-12h00_maxltd-120_timeres-6.csv" + fields = read_tcbench_fields("pangu", init) + arrays = {name: fields[name].values for name in fields.data_vars} + _, official = _run_official(tempest_bin, tmp_path, arrays, fields["lat"].values, fields["lon"].values, fields["time"].values, TCBENCH_DETECT_ARGS, TCBENCH_STITCH_ARGS) + assert official.read_text() == released.read_text() + + matched = read_tcbench_matched_tracks(oracle_asset("tcbench_matched_pangu") / "2023_PANGU.csv") + matched = matched[matched["init_time"] == init] + # Best tracks for the matching step: TCBench's own 2023 IBTrACS extract (pinned with the dataset). + ibtracs = pd.read_csv(oracle_asset("tcbench_ibtracs_2023") / "2023_IBTrACS.csv", keep_default_na=False, na_values=[""]) + table, tracks = tempest_forecast_tracks(fields, ibtracs, init, return_tracks=True) + ours = tmp_path / "ours.csv" + write_stitchnodes_csv(tracks, ours) + assert ours.read_text() == released.read_text() + assert set(table["SID"]) == set(matched["SID"]) + key = ["SID", "valid_time"] + merged = table.merge(matched, on=key, suffixes=("", "_tcbench")) + assert len(merged) == len(matched) + np.testing.assert_allclose(merged["lat"], merged["lat_tcbench"]) + np.testing.assert_allclose(merged["lon"], merged["lon_tcbench"]) + np.testing.assert_allclose(merged["wind_ms"], merged["wind_ms_tcbench"], rtol=1e-6) + np.testing.assert_allclose(merged["pres_pa"], merged["pres_pa_tcbench"], rtol=1e-6) diff --git a/tests/oracle/test_trajgru_oracle.py b/tests/oracle/test_trajgru_oracle.py new file mode 100644 index 00000000..76cdbc82 --- /dev/null +++ b/tests/oracle/test_trajgru_oracle.py @@ -0,0 +1,340 @@ +"""TrajGRU (and the HKO-7 ConvGRU baseline) checked against the official MXNet implementation. + +Reference (pinned in repos.yaml): sxjscience/HKO-7 (MIT), the MXNet code of Shi et al. (NeurIPS +2017), and its released checkpoints for HKO-7 and MovingMNIST++ (``hko7_hko_weights``, +``hko7_movingmnist_weights``). The authors tested the code on MXNet 0.12; it runs unchanged on +MXNet 1.9.1, the last release of the retired project, which needs numpy < 1.24 +(requirements-trajgru.txt, a suite of its own in the Oracle workflow). + +The reference networks are built exactly as the official training scripts build them: +``nowcasting.config`` merged with an official configuration file, a ``MovingMNISTFactory`` (its +loss is the only part that depends on the dataset, and the frame size is taken from +``cfg.MOVINGMNIST.IMG_SIZE``), ``encoder_forecaster_build_networks`` (which also applies the +official ``MSRAPrelu`` initialisation), ``EncoderForecasterStates`` for the zero initial states, and +the encoder/forecaster forward passes of ``mnist_get_prediction``. +""" + +from __future__ import annotations + +import contextlib +import importlib +import io +import math +import sys +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +import yaml + +from oracle_utils import oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.trajgru import TRAJGRU_CONFIGS, TrajGRU, load_hko7_params, warp + +HKO_DIR = "experiments/hko/configurations" +MNIST_DIR = "experiments/movingmnist/configurations" +HKO_TRAJGRU = f"{HKO_DIR}/trajgru_55_55_33_1_64_1_192_1_192_13_13_9_b4.yml" +HKO_CONVGRU = f"{HKO_DIR}/convgru_55_55_33_1_64_1_192_1_192_b4.yml" +MNIST = {name: f"{MNIST_DIR}/{name}.yml" for name in ( + "trajgru_1_64_1_96_1_96_L5", "trajgru_1_64_1_96_1_96_L9", "trajgru_1_64_1_96_1_96_L13", + "trajgru_1_64_1_96_1_96_L17", "convgru_1_64_1_96_1_96_K3D2", "convgru_1_64_1_96_1_96_K5", + "convgru_1_64_1_96_1_96_K7", +)} +# Released checkpoints: (asset, directory, iteration) for each configuration file. +CHECKPOINTS = { + HKO_TRAJGRU: ("hko7_hko_weights", "TrajGRU", 79999), + HKO_CONVGRU: ("hko7_hko_weights", "ConvGRU", 49999), + MNIST["trajgru_1_64_1_96_1_96_L5"]: ("hko7_movingmnist_weights", "TrajGRU-L5", 199999), + MNIST["trajgru_1_64_1_96_1_96_L9"]: ("hko7_movingmnist_weights", "TrajGRU-L9", 199999), + MNIST["trajgru_1_64_1_96_1_96_L13"]: ("hko7_movingmnist_weights", "TrajGRU-L13", 199999), + MNIST["trajgru_1_64_1_96_1_96_L17"]: ("hko7_movingmnist_weights", "TrajGRU-L17", 199999), + MNIST["convgru_1_64_1_96_1_96_K3D2"]: ("hko7_movingmnist_weights", "ConvGRU-K3D2", 199999), + MNIST["convgru_1_64_1_96_1_96_K5"]: ("hko7_movingmnist_weights", "ConvGRU-K5", 199999), + MNIST["convgru_1_64_1_96_1_96_K7"]: ("hko7_movingmnist_weights", "ConvGRU-K7", 199999), +} +# Parameter counts of the reference code for each configuration file. +PARAMETER_COUNTS = { + HKO_TRAJGRU: 12_150_053, + HKO_CONVGRU: 13_649_081, + MNIST["trajgru_1_64_1_96_1_96_L5"]: 2_842_157, + MNIST["trajgru_1_64_1_96_1_96_L9"]: 3_421_277, + MNIST["trajgru_1_64_1_96_1_96_L13"]: 4_000_397, + MNIST["trajgru_1_64_1_96_1_96_L17"]: 4_579_517, + MNIST["convgru_1_64_1_96_1_96_K3D2"]: 2_604_817, + MNIST["convgru_1_64_1_96_1_96_K5"]: 4_767_505, + MNIST["convgru_1_64_1_96_1_96_K7"]: 8_011_537, +} + + +def _is_hko(config_file: str) -> bool: + return config_file.startswith(HKO_DIR) + + +@contextlib.contextmanager +def hko7(config_file: str, batch: int, in_len: int, out_len: int, rnn_overrides=None, build: bool = True): + """Official encoder/forecaster networks for one configuration file (fresh ``nowcasting`` import).""" + repo = oracle_repo("HKO-7") + mx = oracle_package("mxnet", "1.9.1", "requirements-trajgru.txt") + # nowcasting/config.py refuses to import unless the HKO-7 radar folders exist; the network + # code never reads them. + for folder in ("radarPNG", "radarPNG_mask"): + (repo / "hko_data" / folder).mkdir(parents=True, exist_ok=True) + paths = [str(repo), str(repo / "experiments" / "movingmnist")] + before = set(sys.modules) + sys.path[:0] = paths + try: + config = importlib.import_module("nowcasting.config") + edict = importlib.import_module("nowcasting.helpers.ordered_easydict").OrderedEasyDict + user = edict(yaml.safe_load((repo / config_file).read_text())) + # hko_main.py merges into cfg.MODEL, mnist_rnn_main.py into cfg (cfg_from_file calls yaml.load + # without a Loader, which PyYAML 6 rejects, so its merge step is called directly). + config._merge_two_config(user, config.cfg.MODEL if _is_hko(config_file) else config.cfg) + cfg = config.cfg + if _is_hko(config_file): + cfg.MOVINGMNIST.IMG_SIZE = 480 # HKO-7 radar maps are 480 x 480 + cfg.MODEL.ENCODER_FORECASTER.HAS_MASK = False # only shapes the loss network + for key, value in (rnn_overrides or {}).items(): + cfg.MODEL.ENCODER_FORECASTER.RNN_BLOCKS[key] = value + factory_module = importlib.import_module("mnist_rnn_factory") + ef = importlib.import_module("nowcasting.encoder_forecaster") + encoder = forecaster = None + with contextlib.redirect_stdout(io.StringIO()): + factory = factory_module.MovingMNISTFactory(batch_size=batch, in_seq_len=in_len, out_seq_len=out_len) + if build: + encoder, forecaster, _ = ef.encoder_forecaster_build_networks(factory, [mx.cpu()]) + yield SimpleNamespace(mx=mx, cfg=cfg, ef=ef, factory=factory, encoder=encoder, forecaster=forecaster) + finally: + for path in paths: + sys.path.remove(path) + for name in set(sys.modules) - before: + if name.split(".")[0] in {"nowcasting", "mnist_rnn_factory"}: + del sys.modules[name] + + +def _port_kwargs(cfg) -> dict: + """PyHazards builder arguments for the architecture fields of an HKO-7 configuration.""" + ef, rnn = cfg.MODEL.ENCODER_FORECASTER, cfg.MODEL.ENCODER_FORECASTER.RNN_BLOCKS + tup = lambda rows: tuple(tuple(int(v) for v in row) for row in rows) # noqa: E731 + return dict( + num_filter=tuple(int(v) for v in rnn.NUM_FILTER), + layer_type=tuple(rnn.LAYER_TYPE), + L=tuple(int(v) for v in rnn.L), + h2h_kernel=tup(rnn.H2H_KERNEL), + h2h_dilate=tup(rnn.H2H_DILATE), + i2h_kernel=tup(rnn.I2H_KERNEL), + i2h_pad=tup(rnn.I2H_PAD), + stack_num=tuple(int(v) for v in rnn.STACK_NUM), + first_conv=tuple(int(v) for v in ef.FIRST_CONV), + last_deconv=tuple(int(v) for v in ef.LAST_DECONV), + downsample=tup(ef.DOWNSAMPLE), + upsample=tup(ef.UPSAMPLE), + rnn_act_type=cfg.MODEL.RNN_ACT_TYPE, + cnn_act_type=cfg.MODEL.CNN_ACT_TYPE, + residual_connection=bool(rnn.RES_CONNECTION), + init_grid=bool(cfg.MODEL.TRAJRNN.INIT_GRID), + ) + + +def _port(cfg, num_output_frames: int) -> TrajGRU: + assert cfg.MODEL.OUT_TYPE == "direct" and cfg.MODEL.FRAME_STACK == 1 + return TrajGRU(num_output_frames=num_output_frames, **_port_kwargs(cfg)) + + +def _reference_params(ref) -> dict: + params = {} + for net in (ref.encoder, ref.forecaster): + params.update(net.get_params()[0]) + return params + + +def _predict(ref, data: np.ndarray, states=None): + """``mnist_get_prediction``: data (T, B, 1, H, W) -> prediction (T_out, B, 1, H, W), states.""" + mx = ref.mx + if states is None: + states = ref.ef.EncoderForecasterStates(factory=ref.factory, ctx=mx.cpu()) + states.reset_all() + ref.encoder.forward(is_train=False, data_batch=mx.io.DataBatch(data=[mx.nd.array(data)] + states.get_encoder_states())) + states.update(ref.encoder.get_outputs()) + ref.forecaster.forward(is_train=False, data_batch=mx.io.DataBatch(data=states.get_forecaster_state())) + return ref.forecaster.get_outputs()[0].asnumpy(), states + + +def _port_predict(port: TrajGRU, data: np.ndarray, **kwargs): + with torch.no_grad(): + out = port(torch.from_numpy(data).transpose(0, 1), **kwargs) + if isinstance(out, tuple): + return out[0].transpose(0, 1).numpy(), out[1] + return out.transpose(0, 1).numpy() + + +def _assert_close(actual, expected) -> None: + torch.testing.assert_close(torch.as_tensor(actual), torch.as_tensor(expected), rtol=1e-5, atol=1e-6) + + +@pytest.mark.parametrize("config_file", list(PARAMETER_COUNTS)) +def test_parameter_names_shapes_and_counts_match_reference(config_file): + with hko7(config_file, batch=1, in_len=2, out_len=2) as ref: + params = _reference_params(ref) + port = _port(ref.cfg, 2) + state = {key.replace(".", "_"): tuple(value.shape) for key, value in port.state_dict().items()} + assert state == {name: tuple(value.shape) for name, value in params.items()} + count = sum(p.numel() for p in port.parameters()) + assert count == sum(int(np.prod(value.shape)) for value in params.values()) == PARAMETER_COUNTS[config_file] + + +def test_presets_and_paper_table_1(): + with hko7(HKO_TRAJGRU, batch=1, in_len=1, out_len=1) as ref: + hko = _port_kwargs(ref.cfg) + with hko7(MNIST["trajgru_1_64_1_96_1_96_L13"], batch=1, in_len=1, out_len=1) as ref: + mnist = _port_kwargs(ref.cfg) + for preset, expected in ((TRAJGRU_CONFIGS["hko7"], hko), (TRAJGRU_CONFIGS["movingmnist"], mnist)): + assert expected.pop("layer_type") == ("TrajGRU",) * 3 + for key in ("rnn_act_type", "cnn_act_type"): + assert expected.pop(key) == "leaky" + assert expected.pop("residual_connection") and expected.pop("init_grid") + assert {key: preset[key] for key in expected} == expected + assert TRAJGRU_CONFIGS["hko7"]["num_output_frames"] == 20 and TRAJGRU_CONFIGS["movingmnist"]["num_output_frames"] == 10 + + # Paper Table 1 (MovingMNIST++, millions of parameters). Traj-L9, Traj-L13, Conv-K5-D1 and + # Conv-K7-D1 agree with the code; the code gives Conv-K3-D2 2.60M and Traj-L5 2.84M, the + # paper prints these two values swapped, and Traj-L17 has 4.58M, not the 4.77M of the table. + table = {"trajgru_1_64_1_96_1_96_L9": 3.42, "trajgru_1_64_1_96_1_96_L13": 4.00, + "convgru_1_64_1_96_1_96_K5": 4.77, "convgru_1_64_1_96_1_96_K7": 8.01} + for name, millions in table.items(): + assert round(PARAMETER_COUNTS[MNIST[name]] / 1e6, 2) == millions + assert round(PARAMETER_COUNTS[MNIST["convgru_1_64_1_96_1_96_K3D2"]] / 1e6, 2) == 2.60 + assert round(PARAMETER_COUNTS[MNIST["trajgru_1_64_1_96_1_96_L5"]] / 1e6, 2) == 2.84 + # The builder presets are the official configurations. + assert sum(p.numel() for p in build_model("trajgru", task="forecasting").parameters()) == 12_150_053 + assert sum(p.numel() for p in build_model("trajgru", task="forecasting", config="movingmnist").parameters()) == 4_000_397 + + +@pytest.mark.parametrize("config_file", list(CHECKPOINTS)) +def test_official_weights_match_reference(config_file): + asset, folder, iteration = CHECKPOINTS[config_file] + directory = oracle_asset(asset) / folder + hko = _is_hko(config_file) + batch, in_len, out_len, size = (1, 5, 20, 480) if hko else (2, 10, 10, 64) + with hko7(config_file, batch=batch, in_len=in_len, out_len=out_len) as ref: + with contextlib.redirect_stdout(io.StringIO()): + ref.ef.load_encoder_forecaster_params(str(directory), iteration, ref.encoder, ref.forecaster) + port = _port(ref.cfg, out_len) + load_hko7_params(port, _reference_params(ref)) + port.eval() + data = np.random.RandomState(0).rand(in_len, batch, 1, size, size).astype(np.float32) + expected, _ = _predict(ref, data) + assert expected.shape == (out_len, batch, 1, size, size) + _assert_close(_port_predict(port, data), expected) + + +def _randomise_flow_layers(ref, nets, seed: int) -> None: + """Non-zero flow layers (the official initialisation zeroes them, so every warp starts as identity).""" + params = {} + for net in nets: + params.update(net.get_params()[0]) + rng = np.random.RandomState(seed) + for name in params: + if "_f_out_" in name: + scale = 0.05 if name.endswith("weight") else 2.0 + params[name] = ref.mx.nd.array(rng.normal(0.0, scale, params[name].shape)) + for net in nets: + net.set_params(params, {}, allow_extra=True, force_init=True) + + +def test_random_flows_and_odd_batch_match_reference(): + with hko7(MNIST["trajgru_1_64_1_96_1_96_L5"], batch=3, in_len=4, out_len=3) as ref: + _randomise_flow_layers(ref, (ref.encoder, ref.forecaster), seed=1) + port = _port(ref.cfg, 3) + load_hko7_params(port, _reference_params(ref)) + data = np.random.RandomState(2).rand(4, 3, 1, 64, 64).astype(np.float32) + expected, _ = _predict(ref, data) + _assert_close(_port_predict(port, data), expected) + + +def test_stacked_encoder_blocks_match_reference(): + # Several cells per block (residual connections between them) appear in no released + # configuration. With STACK_NUM > 1 the official forecaster network fails to bind on MXNet + # 1.9.1, so only the encoder (whose final states feed the forecaster) is compared here. + overrides = {"STACK_NUM": [2, 3, 1]} + with hko7(MNIST["trajgru_1_64_1_96_1_96_L5"], batch=2, in_len=3, out_len=1, rnn_overrides=overrides, build=False) as ref: + mx, factory = ref.mx, ref.factory + my_module = importlib.import_module("nowcasting.my_module") + with contextlib.redirect_stdout(io.StringIO()): + encoder = my_module.MyModule( + factory.encoder_sym(), data_names=[d.name for d in factory.encoder_data_desc()], label_names=[], + context=[mx.cpu()], name="encoder_net", + ) + encoder.bind(data_shapes=factory.encoder_data_desc(), label_shapes=None, inputs_need_grad=True) + encoder.init_params(mx.init.MSRAPrelu(slope=0.2)) # as encoder_forecaster_build_networks + _randomise_flow_layers(ref, (encoder,), seed=3) + port = _port(ref.cfg, 1) + assert [len(getattr(port, f"ebrnn{i}")) for i in (1, 2, 3)] == [2, 3, 1] + params = encoder.get_params()[0] + encoder_state = {k: v for k, v in port.state_dict().items() if not k.startswith(("fbrnn", "fup", "fdeconv", "conv_final", "out."))} + port.load_state_dict( + {**port.state_dict(), **{k: torch.from_numpy(params[k.replace(".", "_")].asnumpy()) for k in encoder_state}} + ) + data = np.random.RandomState(4).rand(3, 2, 1, 64, 64).astype(np.float32) + states = ref.ef.EncoderForecasterStates(factory=factory, ctx=mx.cpu()) + states.reset_all() + encoder.forward(is_train=False, data_batch=mx.io.DataBatch(data=[mx.nd.array(data)] + states.get_encoder_states())) + expected = [out.asnumpy() for out in encoder.get_outputs()] # per block, stacked states concatenated + with torch.no_grad(): + actual = port.encode(torch.from_numpy(data).transpose(0, 1)) + assert len(actual) == len(expected) == 3 + for block_states, reference in zip(actual, expected): + _assert_close(torch.cat(block_states, dim=1), reference) + + +def test_carried_over_encoder_states_match_reference(): + # mnist_rnn_main.py resets the encoder states once and then starts every batch from the + # previous batch's final states; ``initial_states`` / ``return_states`` reproduce that. + asset, folder, iteration = CHECKPOINTS[MNIST["trajgru_1_64_1_96_1_96_L13"]] + with hko7(MNIST["trajgru_1_64_1_96_1_96_L13"], batch=2, in_len=10, out_len=10) as ref: + with contextlib.redirect_stdout(io.StringIO()): + ref.ef.load_encoder_forecaster_params(str(oracle_asset(asset) / folder), iteration, ref.encoder, ref.forecaster) + port = _port(ref.cfg, 10) + load_hko7_params(port, _reference_params(ref)) + rng = np.random.RandomState(3) + first, second = (rng.rand(10, 2, 1, 64, 64).astype(np.float32) for _ in range(2)) + _, states = _predict(ref, first) + expected, _ = _predict(ref, second, states) + _, port_states = _port_predict(port, first, return_states=True) + _assert_close(_port_predict(port, second, initial_states=port_states), expected) + + +def test_initialisation_follows_reference_scheme(): + # MXNet and PyTorch draw different random numbers, so the scheme is compared, not the values: + # zero tensors must be zero in both, and every other tensor must have the MSRAPrelu(0.2) std. + with hko7(HKO_TRAJGRU, batch=1, in_len=1, out_len=1) as ref: + params = {name: value.asnumpy() for name, value in _reference_params(ref).items()} + torch.manual_seed(0) + port = _port(ref.cfg, 1) + for key, tensor in port.state_dict().items(): + name = key.replace(".", "_") + reference = params[name] + if not reference.any(): + assert not tensor.any(), name + continue + receptive = int(np.prod(reference.shape[2:])) + expected_std = math.sqrt(2.0 / (1.0 + 0.2 ** 2) / ((reference.shape[0] + reference.shape[1]) * receptive / 2.0)) + if reference.size >= 5000: + assert abs(reference.std() / expected_std - 1) < 0.1, name + assert abs(tensor.std().item() / expected_std - 1) < 0.1, name + assert not port.ebrnn1[0].f_out.weight.any() and not port.fbrnn3[0].f_out.bias.any() + + +def test_warp_matches_mxnet_grid_generator_and_bilinear_sampler(): + mx = oracle_package("mxnet", "1.9.1", "requirements-trajgru.txt") + rng = np.random.RandomState(4) + data = rng.normal(size=(2, 3, 9, 11)).astype(np.float32) + flows = rng.normal(0.0, 3.0, size=(2, 2 * 4, 9, 11)).astype(np.float32) # 4 links, many out of range + expected = [] + for link in range(4): + grid = mx.nd.GridGenerator(data=-mx.nd.array(flows[:, 2 * link : 2 * link + 2]), transform_type="warp") + expected.append(mx.nd.BilinearSampler(data=mx.nd.array(data), grid=grid).asnumpy()) + actual = warp(torch.from_numpy(data), torch.from_numpy(flows)) + _assert_close(actual, np.concatenate(expected, axis=1)) + diff --git a/tests/oracle/test_tropicalcyclone_mlp_oracle.py b/tests/oracle/test_tropicalcyclone_mlp_oracle.py new file mode 100644 index 00000000..70f66598 --- /dev/null +++ b/tests/oracle/test_tropicalcyclone_mlp_oracle.py @@ -0,0 +1,104 @@ +"""tropicalcyclone_mlp checked against the official Keras model (wenweixu/tropicalcyclone_MLP, pinned). + +The official ``models.mlp`` is executed from the pinned ``models.py`` with Keras 3 on the PyTorch +backend (the original Keras 2.2.4 / TensorFlow 1.12 stack no longer installs); only its ``Adam(lr=...)`` +argument is mapped to Keras 3's ``learning_rate``. Keras ``Dense`` computes ``x @ kernel + bias`` +in every version, so the official weights are copied into the port and the outputs compared. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import load_definitions, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.tropicalcyclone_mlp import SHIPS_PREDICTORS, load_keras_weights + +os.environ.setdefault("KERAS_BACKEND", "torch") + +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures" / "ships_xu2021" / "train_global_fill_REA_na_wo_img_scaled.fixture.csv" + + +def _official(): + keras = oracle_package("keras", "3.12.4", "requirements-tc.txt") + if keras.backend.backend() != "torch": + pytest.skip("set KERAS_BACKEND=torch before keras is imported") + from keras.layers import Dense, Input + from keras.models import Model + from keras.optimizers import Adam + + def adam(lr=None, **kwargs): # Keras 2 spelling used by the official code + return Adam(learning_rate=lr, **kwargs) + + repo = oracle_repo("tropicalcyclone_MLP") + scope = {"Dense": Dense, "Input": Input, "Model": Model, "Adam": adam} + official = load_definitions(repo / "models.py", ["mlp"], scope)["mlp"] + return keras, official, repo + + +def _hand_features(repo: Path): + """The official predictor list ``utils.hand_features`` (utils.py imports h5py, scipy, ...).""" + source = (repo / "utils.py").read_text(encoding="utf-8") + start = source.index("hand_features = [") + end = source.index("]", start) + scope: dict = {} + exec(source[start : end + 1], scope) + return scope["hand_features"] + + +def test_architecture_and_parameter_count_match_official(): + keras, official, repo = _official() + reference = official(input_shape=(121,)) + port = build_model("tropicalcyclone_mlp", task="regression") + n_port = sum(p.numel() for p in port.parameters()) + assert reference.count_params() == n_port == 4_448_257 + dense = [layer for layer in reference.layers if layer.weights] + assert [layer.name for layer in dense] == port.layer_names == ["dense", "dense_1", "dense_2"] + assert [layer.activation.__name__ for layer in dense] == ["sigmoid", "relu", "linear"] + assert list(port.activation_names) == ["sigmoid", "relu"] + # Official training configuration (models.mlp compile): MAE loss, Adam with learning rate 1e-4. + assert reference.loss == "mae" + assert float(reference.optimizer.learning_rate) == pytest.approx(1e-4) + # The predictor list is the official one, in order. + assert tuple(_hand_features(repo)) == SHIPS_PREDICTORS + + +def test_official_weights_give_identical_outputs(): + keras, official, _ = _official() + keras.utils.set_random_seed(0) + reference = official(input_shape=(121,)) + port = build_model("tropicalcyclone_mlp", task="regression").eval() + load_keras_weights(port, reference.get_weights()) + + torch.manual_seed(1) + x = torch.randn(32, 121) + import pandas as pd + + real = torch.as_tensor(pd.read_csv(FIXTURE, usecols=list(SHIPS_PREDICTORS))[list(SHIPS_PREDICTORS)].to_numpy(np.float32)) + for inputs in (x, real): + expected = np.asarray(reference.predict(inputs.numpy(), verbose=0)) + with torch.no_grad(): + actual = port(inputs).numpy() + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6) + + +def test_initialisation_follows_keras_defaults(): + """Glorot-uniform kernels and zero biases, like Keras Dense; draws differ between frameworks.""" + keras, official, _ = _official() + keras.utils.set_random_seed(0) + reference = official(input_shape=(121,)) + torch.manual_seed(0) + port = build_model("tropicalcyclone_mlp", task="regression") + for name, (kernel, bias) in zip(port.layer_names, zip(reference.get_weights()[::2], reference.get_weights()[1::2])): + layer = getattr(port, name) + fan_in, fan_out = kernel.shape + limit = np.sqrt(6.0 / (fan_in + fan_out)) + for weights in (np.asarray(kernel), layer.weight.detach().numpy()): + assert np.abs(weights).max() <= limit + 1e-7 + assert weights.std() == pytest.approx(limit / np.sqrt(3.0), rel=0.05) + assert not np.any(bias) and not torch.any(layer.bias) diff --git a/tests/oracle/test_tropicyclonenet_oracle.py b/tests/oracle/test_tropicyclonenet_oracle.py new file mode 100644 index 00000000..3b7b7923 --- /dev/null +++ b/tests/oracle/test_tropicyclonenet_oracle.py @@ -0,0 +1,327 @@ +"""TropiCycloneNet checked against the official generator, discriminator, checkpoint and evaluation code. + +The official code (xiaochengfuhuo/TropiCycloneNet, pinned) is imported from the checkout and run on the +CPU: its ``.cuda()`` calls are redirected to CPU copies while it runs (``_cpu_cuda``). The released +checkpoint (Zenodo 10.5281/zenodo.15024028, CC BY 4.0) is a pinned asset. +""" + +from __future__ import annotations + +import contextlib +import warnings +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, load_definitions, oracle_asset, oracle_repo +from pyhazards.benchmarks.tc import track_intensity_metrics +from pyhazards.models import build_model +from pyhazards.models import tropicyclonenet as port_module +from pyhazards.models.tropicyclonenet import ENV_FEATURES, TrajectoryDiscriminator, load_tropicyclonenet_checkpoint + +# Generator / discriminator arguments stored in the released checkpoint (its ``args``). +OFFICIAL_G_ARGS = dict( + obs_len=8, pred_len=4, embedding_dim=32, encoder_h_dim=64, decoder_h_dim=64, mlp_dim=128, num_layers=1, + noise_dim=(16,), noise_type="gaussian", noise_mix_type="ped", pooling_type=None, pool_every_timestep=False, + dropout=0, bottleneck_dim=16, neighborhood_size=2.0, grid_size=8, batch_norm=0, +) +OFFICIAL_D_ARGS = dict(obs_len=8, pred_len=4, embedding_dim=32, h_dim=128, mlp_dim=128, num_layers=1, dropout=0, batch_norm=0, d_type="local") + + +@contextlib.contextmanager +def _cpu_cuda(): + """Run official code written for CUDA on the CPU: ``tensor.cuda()`` returns a CPU copy.""" + original = torch.Tensor.cuda + torch.Tensor.cuda = lambda self, *args, **kwargs: self.to("cpu", copy=True) + try: + yield + finally: + torch.Tensor.cuda = original + + +def _official(module: str = "TCNM.models_prior_unet"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) # nn.TransformerEncoder nested-tensor notice + return import_from(oracle_repo("TropiCycloneNet"), module) + + +def _build(factory, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + return factory(**kwargs) + + +def _checkpoint(): + path = oracle_asset("tropicyclonenet_checkpoint") / "checkpoint_with_model_16000.pt" + return path, torch.load(path, map_location="cpu", weights_only=False) + + +def _batch(batch: int = 4, seed: int = 3): + g = torch.Generator().manual_seed(seed) + obs = 0.3 * torch.randn(8, batch, 4, generator=g) + rel = torch.zeros_like(obs) + rel[1:] = obs[1:] - obs[:-1] + image = torch.rand(batch, 1, 8, 64, 64, generator=g) + env = {} + for key, width in ENV_FEATURES: + if width == 1: + env[key] = torch.rand(batch, 8, 1, generator=g) + else: + env[key] = torch.nn.functional.one_hot(torch.randint(0, width, (batch, 8), generator=g), width).float() + seq_start_end = torch.stack([torch.arange(batch), torch.arange(batch) + 1], dim=1) + return obs, rel, seq_start_end, image, env + + +def _assert_same_state(reference, port): + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def test_parameter_counts_and_seeded_initialisation_match_official(): + official = _official() + torch.manual_seed(0) + reference = _build(official.TrajectoryGenerator, **OFFICIAL_G_ARGS) + torch.manual_seed(0) + port = build_model("tropicyclonenet", task="regression") + assert sum(p.numel() for p in reference.parameters()) == sum(p.numel() for p in port.parameters()) == 4_767_195 + _assert_same_state(reference, port) + + torch.manual_seed(0) + reference_d = official.TrajectoryDiscriminator(**OFFICIAL_D_ARGS) + torch.manual_seed(0) + port_d = TrajectoryDiscriminator() + assert sum(p.numel() for p in reference_d.parameters()) == sum(p.numel() for p in port_d.parameters()) == 231_009 + _assert_same_state(reference_d, port_d) + + +def test_released_checkpoint_loads_and_all_generators_match_official(): + official = _official() + path, checkpoint = _checkpoint() + assert checkpoint["args"]["best_k"] == 6 and checkpoint["args"]["noise_dim"] == (16,) + reference = _build(official.TrajectoryGenerator, **OFFICIAL_G_ARGS) + reference.load_state_dict(checkpoint["g_state"], strict=True) + port = load_tropicyclonenet_checkpoint(path) # sha256-checked, strict + reference.eval() + port.eval() + obs, rel, sse, image, env = _batch() + with torch.no_grad(), _cpu_cuda(): + torch.manual_seed(11) + expected = reference(obs, rel, sse, image, env, num_samples=6, all_g_out=True) + with torch.no_grad(): + torch.manual_seed(11) + actual = port(obs, rel, sse, image, env, num_samples=6, all_g_out=True) + for name, a, e in zip(("relative steps", "GPH frames", "chooser logits"), actual[:3], expected[:3]): + torch.testing.assert_close(a, e, rtol=1e-5, atol=1e-6, msg=name) + assert torch.equal(actual[3], torch.as_tensor(expected[3])) # same RNG stream -> same sampled decoders + assert actual[0].shape == (4, 6, 4, 4) + + # The released discriminator, on real-shaped inputs. + reference_d = official.TrajectoryDiscriminator(**OFFICIAL_D_ARGS) + reference_d.load_state_dict(checkpoint["d_state"], strict=True) + port_d = load_tropicyclonenet_checkpoint(path, state="d_state") + traj_rel = torch.cat([rel, actual[0][:, 0]], dim=0) + traj = torch.cat([obs, obs[-1:] + torch.cumsum(actual[0][:, 0], dim=0)], dim=0) + with torch.no_grad(), _cpu_cuda(): + expected_d = reference_d(traj, traj_rel, sse, actual[1]) + with torch.no_grad(): + actual_d = port_d(traj, traj_rel, sse, actual[1]) + torch.testing.assert_close(actual_d[0], expected_d[0], rtol=1e-5, atol=1e-6) + torch.testing.assert_close(actual_d[1], expected_d[1], rtol=1e-5, atol=1e-6) + + +def test_sampled_forward_matches_official_loop_exactly(): + """``official_sample_loop=True`` reproduces the released evaluation path bit for bit (same seed).""" + official = _official() + _, checkpoint = _checkpoint() + reference = _build(official.TrajectoryGenerator, **OFFICIAL_G_ARGS) + reference.load_state_dict(checkpoint["g_state"]) + port = build_model("tropicyclonenet", task="regression", official_sample_loop=True) + port.load_state_dict(checkpoint["g_state"], strict=True) + reference.eval() + port.eval() + obs, rel, sse, image, env = _batch(batch=7, seed=5) + for seed in (0, 1, 2): + with torch.no_grad(), _cpu_cuda(): + torch.manual_seed(seed) + expected = reference(obs, rel, sse, image, env, num_samples=6, all_g_out=False) + with torch.no_grad(): + torch.manual_seed(seed) + actual = port(obs, rel, sse, image, env, num_samples=6, all_g_out=False) + torch.testing.assert_close(actual[0], expected[0], rtol=1e-5, atol=1e-6) + assert torch.equal(actual[3], torch.as_tensor(expected[3])) + + +def test_default_sample_loop_uses_every_sampled_decoder(monkeypatch): + """With zero noise, each sample must equal the output of the decoder that was sampled for it. + + The official loop visits decoder indices ``0 .. n_distinct - 1`` instead of the distinct sampled + indices, so storms whose sampled index is not visited keep the placeholder value 1; PyHazards' + default loop does not. + """ + official = _official() + _, checkpoint = _checkpoint() + zeros = lambda shape, noise_type, **kwargs: torch.zeros(*shape) # noqa: E731 + monkeypatch.setattr(port_module, "get_noise", zeros) + port = build_model("tropicyclonenet", task="regression") + port.load_state_dict(checkpoint["g_state"], strict=True) + port.eval() + obs, rel, sse, image, env = _batch(batch=9, seed=7) + with torch.no_grad(): + every = port(obs, rel, sse, image, env, all_g_out=True, user_noise=torch.zeros(9, 16))[0] # (L, 6, B, 4) + torch.manual_seed(4) + sampled, _, _, index = port(obs, rel, sse, image, env, num_samples=6) + for b in range(9): + for s in range(6): + torch.testing.assert_close(sampled[:, s, b], every[:, int(index[b, s]), b], rtol=1e-5, atol=1e-6) + + official_module = _official() + reference = _build(official_module.TrajectoryGenerator, **OFFICIAL_G_ARGS) + reference.load_state_dict(checkpoint["g_state"]) + reference.eval() + monkeypatch.setattr(official_module, "get_noise", lambda shape, noise_type: torch.zeros(*shape)) + with torch.no_grad(), _cpu_cuda(): + torch.manual_seed(4) + expected, _, _, official_index = reference(obs, rel, sse, image, env, num_samples=6) + official_index = torch.as_tensor(official_index) + assert torch.equal(official_index, index) + for s in range(6): + visited = set(range(len(torch.unique(official_index[:, s])))) + for b in range(9): + if int(official_index[b, s]) in visited: + torch.testing.assert_close(expected[:, s, b], sampled[:, s, b], rtol=1e-5, atol=1e-6) + else: + assert torch.all(expected[:, s, b] == 1.0) + + +def test_train_mode_matches_official(): + official = _official() + _, checkpoint = _checkpoint() + reference = _build(official.TrajectoryGenerator, **OFFICIAL_G_ARGS) + reference.load_state_dict(checkpoint["g_state"]) + port = build_model("tropicyclonenet", task="regression") + port.load_state_dict(checkpoint["g_state"]) + reference.train() + port.train() + obs, rel, sse, image, env = _batch(batch=5, seed=9) + with _cpu_cuda(): + torch.manual_seed(21) + expected = reference(obs, rel, sse, image, env, num_samples=6, all_g_out=True) + torch.manual_seed(21) + actual = port(obs, rel, sse, image, env, num_samples=6, all_g_out=True) + for a, e in zip(actual[:3], expected[:3]): + torch.testing.assert_close(a, e, rtol=1e-5, atol=1e-6) + _assert_same_state(reference, port) # BatchNorm running statistics updated identically + + +def test_forecast_matches_official_postprocessing(): + """Absolute positions / intensities equal the official relative_to_abs + toNE conversion.""" + utils = _official("TCNM.utils") + losses = _official("TCNM.losses") + path, _ = _checkpoint() + port = load_tropicyclonenet_checkpoint(path).eval() + obs, rel, sse, image, env = _batch(batch=3, seed=13) + batch = {"obs_traj": obs, "obs_traj_rel": rel, "image_obs": image, "env_data": env, "seq_start_end": sse} + with torch.no_grad(): + torch.manual_seed(0) + forecast = port.forecast(batch, num_samples=6) + torch.manual_seed(0) + rel_pred = port(batch, num_samples=6)[0] + track = utils.relative_to_abs(rel_pred[..., :2], obs[-1, :, :2]) + intensity = utils.relative_to_abs(rel_pred[..., 2:], obs[-1, :, 2:]) + for sample in range(6): + tenths, me = losses.toNE(track[:, sample].clone(), intensity[:, sample].clone()) + torch.testing.assert_close(forecast["lon"][:, sample], (tenths[..., 0] / 10).T, rtol=1e-5, atol=1e-4) + torch.testing.assert_close(forecast["lat"][:, sample], (tenths[..., 1] / 10).T, rtol=1e-5, atol=1e-4) + torch.testing.assert_close(forecast["pres"][:, sample], me[..., 0].T, rtol=1e-5, atol=1e-3) + torch.testing.assert_close(forecast["wind"][:, sample], me[..., 1].T, rtol=1e-5, atol=1e-3) + + +def test_best_of_k_metrics_match_official_evaluation(): + """PyHazards' best-of-k errors with the TCN distance equal evaluate_model_Me.py's per-lead errors.""" + repo = oracle_repo("TropiCycloneNet") + losses = _official("TCNM.losses") + helpers = load_definitions(repo / "scripts" / "evaluate_model_Me.py", ["evaluate_helper", "ve_evaluate_helper"], {"torch": torch}) + g = torch.Generator().manual_seed(0) + storms, samples, lead = 10, 6, 4 + # Physical values in the official units: track in tenths of a degree, pressure hPa, wind m/s. + true_track = torch.stack([1300 + 50 * torch.rand(lead, storms, generator=g), 150 + 50 * torch.rand(lead, storms, generator=g)], -1) + true_me = torch.stack([980 + 20 * torch.rand(lead, storms, generator=g), 30 + 10 * torch.rand(lead, storms, generator=g)], -1) + fake_track = true_track.unsqueeze(1) + 10 * torch.randn(lead, samples, storms, 2, generator=g) + fake_me = true_me.unsqueeze(1) + 3 * torch.randn(lead, samples, storms, 2, generator=g) + tde = [losses.trajectory_displacement_error(fake_track[:, s], true_track, mode="raw") for s in range(samples)] + ve = [losses.value_error(fake_me[:, s], true_me, mode="raw") for s in range(samples)] + sse = torch.stack([torch.arange(storms), torch.arange(storms) + 1], dim=1) + official_track = torch.stack([helpers["evaluate_helper"]([x[:, i] for x in tde], sse) for i in range(lead)]) / storms + official_me = torch.tensor([[float(v) for v in helpers["ve_evaluate_helper"]([x[:, i] for x in ve], sse)] for i in range(lead)]) / storms + + forecast = { + "lon": fake_track[..., 0].permute(2, 1, 0) / 10, + "lat": fake_track[..., 1].permute(2, 1, 0) / 10, + "pres": fake_me[..., 0].permute(2, 1, 0), + "wind": fake_me[..., 1].permute(2, 1, 0), + } + target = { + "lon": true_track[..., 0].T / 10, + "lat": true_track[..., 1].T / 10, + "pres": true_me[..., 0].T, + "wind": true_me[..., 1].T, + } + metrics = track_intensity_metrics( + {k: v.double() for k, v in forecast.items()}, {k: v.double() for k, v in target.items()}, [6, 12, 18, 24], "tcn_equirectangular" + ) + for i, hours in enumerate((6, 12, 18, 24)): + assert metrics[f"best_of_k_track_error_km_{hours}h"] == pytest.approx(float(official_track[i]), rel=1e-5) + assert metrics[f"best_of_k_pressure_mae_{hours}h"] == pytest.approx(float(official_me[i, 0]), rel=1e-5) + assert metrics[f"best_of_k_intensity_mae_{hours}h"] == pytest.approx(float(official_me[i, 1]), rel=1e-5) + # Great-circle distance differs from the official equirectangular approximation by well under 1 %. + great_circle = track_intensity_metrics( + {k: v.double() for k, v in forecast.items()}, {k: v.double() for k, v in target.items()}, [6, 12, 18, 24] + ) + assert great_circle["best_of_k_track_error_km"] == pytest.approx(metrics["best_of_k_track_error_km"], rel=1e-2) + + +def test_tcnd_reader_matches_official_loader(tmp_path): + """``tropicyclonenet_dataset`` equals the official TrajectoryDataset + seq_collate on a real storm. + + Data1d and Env-Data are the real files of tests/fixtures/tcnd (EP 2018 Carlotta); the GPH crops + are random values in the official file layout (100 x 100 float64), since the real ones are too + large to vendor. + """ + import shutil + + from oracle_utils import oracle_package + from pyhazards.datasets import load_dataset + from pyhazards.datasets.tc import read_tcnd_track + + oracle_package("cv2", "5.0.0", "requirements-tc.txt", distribution="opencv-python-headless") + fixture = Path(__file__).resolve().parents[1] / "fixtures" / "tcnd" + root = tmp_path / "tcnd" + shutil.copytree(fixture / "BST_data", root / "BST_data") + shutil.copytree(fixture / "Env_data", root / "Env_data") + _, dates, _ = read_tcnd_track(fixture / "BST_data" / "EP" / "test" / "EP2018BSTCARLOTTA.txt") + storm = root / "ERA5_gph500" / "EP" / "2018" / "CARLOTTA" + storm.mkdir(parents=True) + rng = np.random.default_rng(0) + for date in dates: + np.save(storm / f"{date}.npy", rng.uniform(55000.0, 59500.0, size=(100, 100))) + + loader = _official("TCNM.data.trajectoriesWithMe_unet") + dataset = loader.TrajectoryDataset({"root": str(root), "type": "test"}, obs_len=8, pred_len=4, skip=1, delim="\t", areas=["EP"]) + batch = loader.seq_collate([dataset[i] for i in range(len(dataset))]) + obs_traj, pred_traj, obs_rel, _, _, _, _, obs_me, pred_me, obs_rel_me = batch[:10] + image_obs, env = batch[13], batch[15] + + port = load_dataset("tropicyclonenet_dataset", root=str(root), areas=["EP"], splits=["test"]).load().splits["test"] + assert len(dataset) == len(port.targets) == 7 + torch.testing.assert_close(port.inputs["obs_traj"], torch.cat([obs_traj, obs_me], dim=2)) + torch.testing.assert_close(port.inputs["obs_traj_rel"], torch.cat([obs_rel, obs_rel_me], dim=2)) + torch.testing.assert_close(port.inputs["image_obs"], image_obs, rtol=1e-5, atol=1e-6) + for key, _ in ENV_FEATURES: + torch.testing.assert_close(port.inputs["env_data"][key], env[key], msg=key) + tenths, me = _official("TCNM.losses").toNE(pred_traj.clone(), pred_me.clone()) + expected = torch.stack([tenths[..., 1] / 10, tenths[..., 0] / 10, me[..., 0], me[..., 1]], dim=-1).permute(1, 0, 2) + torch.testing.assert_close(port.targets, expected, rtol=1e-5, atol=1e-4) diff --git a/tests/oracle/test_ts_satfire_oracle.py b/tests/oracle/test_ts_satfire_oracle.py new file mode 100644 index 00000000..ff770c81 --- /dev/null +++ b/tests/oracle/test_ts_satfire_oracle.py @@ -0,0 +1,106 @@ +"""The ts_satfire preset checked against TS-SatFire's prediction-script models. + +Each baseline is built the way ``run_spatial_temp_model_pred.py`` (zhaoyutim/TS-SatFire, pinned in +repos.yaml; no LICENSE, test oracle only) builds it -- 43 input channels, T input days, 256x256 +tiles, two classes, logits averaged over time -- and compared with ``build_model("ts_satfire", +baseline=...)``: parameter counts at the full size, then names, seeded initial values and eval / +train-mode outputs on 32x32 tiles with T = 2 (CPU speed; U-Nets are fully convolutional and +UNETR / SwinUNETR are built for the smaller size on both sides). +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from tssatfire_oracle_helpers import ( + PRED_CHANNELS, + TS_SATFIRE_CHANNELS, + assert_same_names_and_shapes, + assert_same_state, + compare_eval_and_train, + n_params, + randomise, + ts_satfire_module, +) + +EXPECTED_PARAMETERS = { + "unet3d": 31_712_970, # Table 3: 31.7M + "attention_unet3d": 94_555_506, # Table 3: 94.5M + "unetr3d": 28_816_866, # Table 3 lists 34.8M, the AF/BA configuration (see test_unetr_oracle.py) + "swinunetr3d": 33_191_942, # Table 3: 33.2M +} + + +def _reference(baseline: str, history: int, size: int) -> torch.nn.Module: + """The model of run_spatial_temp_model_pred.py (n_channel=43, -ed 36 and -nh 3 for SwinUNETR).""" + n_channel, num_classes = PRED_CHANNELS, 2 + if baseline == "unet3d": + UNet = ts_satfire_module("unet").UNet + return UNet(spatial_dims=3, in_channels=n_channel, out_channels=num_classes, channels=TS_SATFIRE_CHANNELS, strides=(1, 2, 2)) + if baseline == "attention_unet3d": + AttentionUnet = ts_satfire_module("attentionunet").AttentionUnet + return AttentionUnet( + spatial_dims=3, in_channels=n_channel, out_channels=num_classes, channels=TS_SATFIRE_CHANNELS, strides=(1, 2, 2) + ) + image_size = (history, size, size) + if baseline == "unetr3d": + UNETR = ts_satfire_module("unetr.unetr").UNETR + # The script's kernel_size_up_down=(1, 2, 2) is hard-coded in the released file. + return UNETR( + in_channels=n_channel, + out_channels=num_classes, + img_size=image_size, + spatial_dims=3, + norm_name="batch", + feature_size=16, + patch_size=(1, 16, 16), + hidden_size=384, + mlp_dim=1536, + ) + SwinUNETR = ts_satfire_module("swinunetr.swinunetr").SwinUNETR + return SwinUNETR( + image_size=image_size, + patch_size=(1, 2, 2), + window_size=(history, 4, 4), + in_channels=n_channel, + out_channels=2, + depths=(2, 2, 2, 2), + num_heads=(3, 3, 3, 3), + feature_size=36, + norm_name="batch", + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + attn_version="v1", + normalize=True, + use_checkpoint=False, + spatial_dims=3, + ) + + +@pytest.mark.parametrize("baseline", sorted(EXPECTED_PARAMETERS)) +def test_parameter_counts_at_full_size(baseline): + if baseline == "swinunetr3d": + reference = _reference(baseline, history=6, size=256) # calls Tensor.item(): not on meta + else: + with torch.device("meta"): + reference = _reference(baseline, history=6, size=256) + with torch.device("meta"): + port = build_model("ts_satfire", task="segmentation", baseline=baseline) + assert_same_names_and_shapes(reference, port) + assert n_params(port) == n_params(reference) == EXPECTED_PARAMETERS[baseline] + + +@pytest.mark.parametrize("baseline", sorted(EXPECTED_PARAMETERS)) +def test_baselines_match_reference(baseline): + torch.manual_seed(0) + reference = _reference(baseline, history=2, size=32) + torch.manual_seed(0) + port = build_model("ts_satfire", task="segmentation", baseline=baseline, history=2, image_size=32) + assert_same_state(reference, port) + randomise(reference, port, seed=1) + torch.manual_seed(2) + x = torch.randn(2, 2, PRED_CHANNELS, 32, 32) # (batch, days, channels, H, W) + compare_eval_and_train(reference, port, x.transpose(1, 2).contiguous(), x, reduce_time=True) diff --git a/tests/oracle/test_unet3d_oracle.py b/tests/oracle/test_unet3d_oracle.py new file mode 100644 index 00000000..baa46fec --- /dev/null +++ b/tests/oracle/test_unet3d_oracle.py @@ -0,0 +1,149 @@ +"""MONAI U-Net checked against MONAI 1.3.2 and TS-SatFire's modified copy. + +References: ``monai.networks.nets.UNet`` from monai 1.3.2 and ``spatial_models/unet.py`` from +zhaoyutim/TS-SatFire (pinned in repos.yaml; no LICENSE, so it is only imported here as an +oracle). Each check builds both models from the same seed, requires identical parameter names and +initial values, then compares outputs in eval and train mode after randomising the weights. + +Spatial sizes are reduced for CPU speed (the network is fully convolutional; TS-SatFire uses +256x256 tiles): 32x32 with T = 2 for the full-width 3D prediction model, 64x64 for the 2D model. +""" + +from __future__ import annotations + +import torch + +from pyhazards.models import build_model +from pyhazards.models.unet3d import TemporalUNet, UNet +from tssatfire_oracle_helpers import ( + PRED_CHANNELS, + TS_SATFIRE_CHANNELS, + assert_close, + assert_same_state, + compare_eval_and_train, + monai_nets, + n_params, + randomise, + ts_satfire_module, +) + +SMALL_CHANNELS = (8, 16, 32, 64, 128) + + +def test_ts_satfire_prediction_model_matches_reference(): + TSUNet = ts_satfire_module("unet").UNet + # run_spatial_temp_model_pred.py, model "unet3d": 43 input channels, 2 classes. + torch.manual_seed(0) + reference = TSUNet( + spatial_dims=3, in_channels=PRED_CHANNELS, out_channels=2, channels=TS_SATFIRE_CHANNELS, strides=(1, 2, 2) + ) + torch.manual_seed(0) + port = build_model("unet3d", task="segmentation", in_channels=PRED_CHANNELS) + assert isinstance(port, TemporalUNet) + assert_same_state(reference, port) + assert n_params(port) == n_params(reference) == 31_712_970 # Table 3: 31.7M + + randomise(reference, port, seed=1) + torch.manual_seed(2) + x = torch.randn(2, 2, PRED_CHANNELS, 32, 32) # (batch, time, channels, H, W) + x_ref = x.transpose(1, 2).contiguous() # TS-SatFire feeds (batch, channels, time, H, W) + compare_eval_and_train(reference, port, x_ref, x, reduce_time=True) + port.time_reduction = "none" + reference.eval() + port.eval() + with torch.no_grad(): + assert_close(port(x), reference(x_ref)) + + +def test_ts_satfire_shared_strides_equal_monai_per_level_strides(): + TSUNet = ts_satfire_module("unet").UNet + MonaiUNet = monai_nets().UNet + config = dict(spatial_dims=3, in_channels=5, out_channels=2, channels=SMALL_CHANNELS) + torch.manual_seed(0) + ts_model = TSUNet(**config, strides=(1, 2, 2)) + torch.manual_seed(0) + monai_model = MonaiUNet(**config, strides=((1, 2, 2),) * 4) + torch.manual_seed(0) + port_shared = UNet(**config, strides=(1, 2, 2), stride_mode="shared") + torch.manual_seed(0) + port_per_level = UNet(**config, strides=((1, 2, 2),) * 4) + for model in (monai_model, port_shared, port_per_level): + assert_same_state(ts_model, model) + + torch.manual_seed(1) + x = torch.randn(2, 5, 3, 32, 32) + for model in (ts_model, monai_model, port_shared, port_per_level): + model.eval() + with torch.no_grad(): + expected = ts_model(x) + assert expected.shape == (2, 2, 3, 32, 32) # time is never down-sampled + for model in (monai_model, port_shared, port_per_level): + assert_close(model(x), expected) + + +def test_ts_satfire_2d_config_matches_monai(): + MonaiUNet = monai_nets().UNet + # run_spatial_model.py, model "unet": stock MONAI, 2D, strides (2, 2, 2, 2); 8 VIIRS bands. + torch.manual_seed(0) + reference = MonaiUNet(spatial_dims=2, in_channels=8, out_channels=2, channels=TS_SATFIRE_CHANNELS, strides=(2, 2, 2, 2)) + torch.manual_seed(0) + port = build_model("unet3d", task="segmentation", in_channels=8, spatial_dims=2) + assert type(port) is UNet + assert_same_state(reference, port) + assert n_params(port) == 10_552_458 # Table 3: 10.6M + + randomise(reference, port, seed=3) + torch.manual_seed(4) + x = torch.randn(2, 8, 64, 64) + compare_eval_and_train(reference, port, x, x) + + +def test_non_default_configs_match_monai(): + """Residual units, batch norm / ReLU, dropout, larger kernels and non-uniform strides in 1D-3D.""" + MonaiUNet = monai_nets().UNet + configs = [ + dict(spatial_dims=1, in_channels=3, out_channels=1, channels=(4, 8, 16), strides=(2, 2), kernel_size=5), + dict( + spatial_dims=2, + in_channels=3, + out_channels=3, + channels=(4, 8, 16, 32), + strides=((2, 1), 2, (1, 2)), + num_res_units=2, + dropout=0.2, + ), + dict( + spatial_dims=2, + in_channels=3, + out_channels=2, + channels=(4, 8, 16), + strides=(2, 2), + num_res_units=1, + act="relu", + norm="batch", + kernel_size=(3, 5), + up_kernel_size=5, + bias=False, + ), + dict( + spatial_dims=3, + in_channels=2, + out_channels=1, + channels=(4, 8, 16), + strides=((1, 2, 2), 2), + num_res_units=2, + norm="batch", + dropout=0.1, + adn_ordering="ADN", + ), + ] + inputs = [(2, 3, 16), (2, 3, 16, 16), (2, 3, 16, 16), (2, 2, 4, 16, 16)] + for config, shape in zip(configs, inputs): + torch.manual_seed(0) + reference = MonaiUNet(**config) + torch.manual_seed(0) + port = UNet(**config) + assert_same_state(reference, port) + randomise(reference, port, seed=5) + x = torch.randn(*shape) + compare_eval_and_train(reference, port, x, x, seed=6) # same dropout masks: same module order diff --git a/tests/oracle/test_unet_oracle.py b/tests/oracle/test_unet_oracle.py new file mode 100644 index 00000000..1315293e --- /dev/null +++ b/tests/oracle/test_unet_oracle.py @@ -0,0 +1,301 @@ +"""U-Net checked against the authors' released Caffe network (u-net-release-2015-10-02). + +The release (no license; fetched at test time only, never vendored) contains the network +definition ``phseg_v5-train.prototxt`` and the trained ``phseg_v5.caffemodel`` of the ISBI 2015 +cell-tracking submission. Caffe itself is not needed: the weights are read with a small protobuf +reader, and the reference forward pass runs in OpenCV's Caffe importer (Apache-2.0), an +independent implementation of Caffe's layers. The released network is the ``phseg_v5`` variant +of the PyHazards U-Net; the paper's Fig. 1 network differs from it only where the tests say so. +""" + +from __future__ import annotations + +import re +import tarfile +from functools import lru_cache + +import numpy as np +import torch + +from oracle_utils import oracle_asset, oracle_package +from pyhazards.models import build_model +from pyhazards.models.unet import unet_output_size + +RELEASE = "u-net-release-2015-10-02.tar.gz" +PHSEG_V5_PARAMETERS = 31_100_354 + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@lru_cache(maxsize=None) +def _release_member(name: str) -> bytes: + with tarfile.open(oracle_asset("unet_release") / RELEASE) as archive: + return archive.extractfile(f"u-net-release/{name}").read() + + +def _prototxt_layers() -> list[dict]: + """Layers of ``phseg_v5-train.prototxt`` (one V1 layer per line) as dictionaries.""" + layers = [] + for line in _release_member("phseg_v5-train.prototxt").decode().splitlines(): + if not line.startswith("layers"): + continue + layer = { + "name": re.search(r"name: '([^']+)'", line).group(1), + "type": re.search(r"type: (\w+)", line).group(1), + "bottom": re.findall(r"bottom: '([^']+)'", line), + "top": re.findall(r"top: '([^']+)'", line), + "train_only": "phase: TRAIN" in line, + } + for key in ("num_output", "kernel_size", "stride", "pad"): + match = re.search(rf"{key}: (\d+)", line) + layer[key] = int(match.group(1)) if match else None + match = re.search(r"dropout_ratio: ([\d.]+)", line) + layer["dropout_ratio"] = float(match.group(1)) if match else None + match = re.search(r"weight_filler \{ type: '(\w+)'", line) + layer["filler"] = match.group(1) if match else None + layers.append(layer) + return layers + + +# --- minimal protobuf reader for Caffe's V1 NetParameter (layers = 2; name = 4, blobs = 6; +# BlobProto num/channels/height/width = 1-4, packed float data = 5) --------------------------- +def _varint(buf: memoryview, pos: int) -> tuple[int, int]: + result = shift = 0 + while True: + byte = buf[pos] + pos += 1 + result |= (byte & 0x7F) << shift + if byte < 0x80: + return result, pos + shift += 7 + + +def _fields(buf: memoryview): + pos = 0 + while pos < len(buf): + key, pos = _varint(buf, pos) + field, wire = key >> 3, key & 7 + if wire == 0: + value, pos = _varint(buf, pos) + elif wire == 2: + size, pos = _varint(buf, pos) + value, pos = buf[pos : pos + size], pos + size + elif wire == 5: + value, pos = buf[pos : pos + 4], pos + 4 + elif wire == 1: + value, pos = buf[pos : pos + 8], pos + 8 + else: + raise ValueError(f"unsupported protobuf wire type {wire}") + yield field, wire, value + + +def _caffemodel_blobs(data: bytes) -> dict[str, list[np.ndarray]]: + layers: dict[str, list[np.ndarray]] = {} + for field, _, layer in _fields(memoryview(data)): + if field != 2: + continue + name, blobs = None, [] + for layer_field, _, value in _fields(layer): + if layer_field == 4: + name = bytes(value).decode() + elif layer_field == 6: + dims, chunks = [0, 0, 0, 0], [] + for blob_field, wire, blob_value in _fields(value): + if blob_field in (1, 2, 3, 4): + dims[blob_field - 1] = blob_value + elif blob_field == 5: + chunks.append(np.frombuffer(blob_value, dtype=" dict[str, torch.Tensor]: + """The caffemodel as a state dict: Caffe layer ``conv_d0a-b`` -> module ``conv_d0a_b``.""" + state = {} + for name, (weight, bias) in _caffemodel_blobs(_release_member("phseg_v5.caffemodel")).items(): + key = name.replace("-", "_") + state[f"{key}.weight"] = torch.from_numpy(weight.copy()) + state[f"{key}.bias"] = torch.from_numpy(bias.reshape(-1).copy()) + return state + + +def _deploy_prototxt(height: int, width: int) -> str: + """Rewrite the release prototxt for OpenCV (current layer syntax, test phase, fixed input size). + + The release's CROP layer aligns its two inputs through the layers' coordinate maps; OpenCV's + Crop needs explicit offsets, so they are derived here the same way: each blob carries the + affine map from its coordinates to input coordinates, and the offset is the shift that + aligns the skip feature with the up-sampled map. + """ + lines = ['name: "phseg_v5"', 'input: "data"'] + [f"input_dim: {d}" for d in (1, 1, height, width)] + size = {"data": np.array([height, width])} + coord = {"data": (1.0, 0.0)} # input coordinate = scale * blob coordinate + shift + for layer in _prototxt_layers(): + if layer["train_only"]: + continue + name, kind, bottom, top = layer["name"], layer["type"], layer["bottom"], layer["top"][0] + scale, shift = coord[bottom[0]] + if kind == "CONVOLUTION": + k = layer["kernel_size"] + lines.append( + f'layer {{ name: "{name}" type: "Convolution" bottom: "{bottom[0]}" top: "{top}" ' + f"convolution_param {{ num_output: {layer['num_output']} pad: 0 kernel_size: {k} }} }}" + ) + size[top], coord[top] = size[bottom[0]] - (k - 1), (scale, shift + scale * (k - 1) / 2) + elif kind == "POOLING": + lines.append( + f'layer {{ name: "{name}" type: "Pooling" bottom: "{bottom[0]}" top: "{top}" ' + "pooling_param { pool: MAX kernel_size: 2 stride: 2 } }" + ) + size[top], coord[top] = size[bottom[0]] // 2, (2 * scale, shift + 0.5 * scale) + elif kind == "DECONVOLUTION": + lines.append( + f'layer {{ name: "{name}" type: "Deconvolution" bottom: "{bottom[0]}" top: "{top}" ' + f"convolution_param {{ num_output: {layer['num_output']} pad: 0 kernel_size: 2 stride: 2 }} }}" + ) + size[top], coord[top] = size[bottom[0]] * 2, (scale / 2, shift - 0.25 * scale) + elif kind == "RELU": + lines.append(f'layer {{ name: "{name}" type: "ReLU" bottom: "{bottom[0]}" top: "{top}" }}') + elif kind == "CROP": + (skip_scale, skip_shift), (up_scale, up_shift) = coord[bottom[0]], coord[bottom[1]] + assert skip_scale == up_scale + offset = (up_shift - skip_shift) / skip_scale + assert offset == int(offset) and offset >= 0 + assert np.all(size[bottom[0]] - size[bottom[1]] == 2 * offset) # the crop is centred + lines.append( + f'layer {{ name: "{name}" type: "Crop" bottom: "{bottom[0]}" bottom: "{bottom[1]}" top: "{top}" ' + f"crop_param {{ axis: 2 offset: {int(offset)} offset: {int(offset)} }} }}" + ) + size[top], coord[top] = size[bottom[1]], coord[bottom[1]] + elif kind == "CONCAT": + lines.append( + f'layer {{ name: "{name}" type: "Concat" bottom: "{bottom[0]}" bottom: "{bottom[1]}" top: "{top}" }}' + ) + size[top], coord[top] = size[bottom[0]], coord[bottom[0]] + else: + raise AssertionError(f"unexpected layer type {kind}") + assert tuple(size["score"]) == (unet_output_size(height), unet_output_size(width)) + return "\n".join(lines) + "\n" + + +def _opencv_forward(x: np.ndarray) -> np.ndarray: + cv2 = oracle_package("cv2", "4.10.0", requirements="requirements-unet.txt") + net = cv2.dnn.readNetFromCaffe( + np.frombuffer(_deploy_prototxt(*x.shape[-2:]).encode(), dtype=np.uint8), + np.frombuffer(_release_member("phseg_v5.caffemodel"), dtype=np.uint8), + ) + net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) + net.enableWinograd(False) + net.setInput(x) + return net.forward() + + +def _assert_close_to_opencv(actual: torch.Tensor, expected: np.ndarray) -> None: + # OpenCV and PyTorch use different float32 convolution kernels (summation order) through 23 + # layers; the outputs reach about 10 in magnitude and differ by about 1e-5, so the absolute + # tolerance is 1e-4 instead of 1e-6. + torch.testing.assert_close(actual, torch.from_numpy(expected), rtol=1e-5, atol=1e-4) + + +def test_phseg_v5_variant_has_the_released_layers(): + model = build_model("unet", task="segmentation", variant="phseg_v5") + modules = dict(model.named_modules()) + layers = _prototxt_layers() + convs = [layer for layer in layers if layer["type"] in ("CONVOLUTION", "DECONVOLUTION")] + assert len(convs) == 23 # "In total the network has 23 convolutional layers" (paper Sec. 2) + for layer in convs: + module = modules[layer["name"].replace("-", "_")] + transposed = layer["type"] == "DECONVOLUTION" + assert isinstance(module, torch.nn.ConvTranspose2d if transposed else torch.nn.Conv2d), layer["name"] + assert module.out_channels == layer["num_output"], layer["name"] + assert module.kernel_size == (layer["kernel_size"],) * 2, layer["name"] + assert module.stride == ((layer["stride"] or 1),) * 2 and module.padding == (layer["pad"],) * 2 + assert layer["filler"] == "xavier" # Olaf's filler: N(0, 2 / fan_in), see the next test + # Up-sampled map first in every concatenation, then the centre-cropped skip feature. + concats = [layer for layer in layers if layer["type"] == "CONCAT"] + assert [layer["bottom"] for layer in concats] == [["u3a", "d3cc"], ["u2a", "d2cc"], ["u1a", "d1cc"], ["u0a", "d0cc"]] + # A ReLU follows every up-convolution in the release (not in the paper's Fig. 1). + relus = {layer["top"][0] for layer in layers if layer["type"] == "RELU"} + assert {"u3a", "u2a", "u1a", "u0a"} <= relus + # Two in-place dropout layers (ratio 0.5, training only) on the 512- and 1024-channel levels; + # d3c is dropped out before it feeds both the pooling and the crop for the skip connection. + dropouts = [layer for layer in layers if layer["type"] == "DROPOUT"] + assert [(d["name"], d["bottom"], d["top"], d["dropout_ratio"], d["train_only"]) for d in dropouts] == [ + ("dropout_d3c", ["d3c"], ["d3c"], 0.5, True), + ("dropout_d4c", ["d4c"], ["d4c"], 0.5, True), + ] + assert model.dropout_d3c.p == model.dropout_d4c.p == 0.5 + names = [layer["name"] for layer in layers] + assert names.index("dropout_d3c") < names.index("pool_d3c-4a") < names.index("crop_d3c-d3cc") + + paper = build_model("unet", task="segmentation") + assert _n_params(paper) == 31_030_658 + assert _n_params(model) == PHSEG_V5_PARAMETERS + # The paper's last up-convolution halves the channels to 64; the release keeps 128. + assert paper.upconv_u1d_u0a.out_channels == 64 and model.upconv_u1d_u0a.out_channels == 128 + + +def test_initialisation_follows_the_release_filler(): + # The release patches Caffe's "xavier" filler into a Gaussian with std sqrt(2 / fan_in), where + # fan_in = count / num of the weight blob (the paper's "sqrt(2/N)", Sec. 3). + filler = _release_member("caffe-unet-src/include/caffe/filler.hpp").decode() + assert "Dtype scale = sqrt(Dtype(2) / fan_in);" in filler + assert "int fan_in = blob->count() / blob->num();" in filler + torch.manual_seed(0) + model = build_model("unet", task="segmentation", variant="phseg_v5") + for name, param in model.named_parameters(): + if name.endswith(".bias"): + assert torch.count_nonzero(param) == 0, name + continue + # Caffe blobs: (out, in, k, k) for convolutions, (in, out, k, k) for deconvolutions, which are + # also PyTorch's Conv2d / ConvTranspose2d layouts, so fan_in = numel / size(0) for both. + expected = (2.0 / (param.numel() / param.size(0))) ** 0.5 + if param.numel() >= 100_000: + assert abs(param.std().item() / expected - 1) < 0.02, name + assert abs(param.mean().item()) < 0.02 * expected, name + + +def test_released_weights_load_strict_and_match_opencv_caffe(): + model = build_model("unet", task="segmentation", variant="phseg_v5").eval() + state = _release_state_dict() + assert list(state) == list(model.state_dict()) + model.load_state_dict(state, strict=True) + assert _n_params(model) == PHSEG_V5_PARAMETERS + + rng = np.random.RandomState(0) + x = rng.rand(1, 1, 572, 572).astype(np.float32) # the paper's Fig. 1 tile + with torch.no_grad(): + out = model(torch.from_numpy(x)) + assert out.shape == (1, 2, 388, 388) + _assert_close_to_opencv(out, _opencv_forward(x)) + + +def test_released_weights_on_sample_image_tile_match_opencv_caffe(): + cv2 = oracle_package("cv2", "4.10.0", requirements="requirements-unet.txt") + image = cv2.imdecode( + np.frombuffer(_release_member("PhC-C2DH-U373/01/t000.tif"), dtype=np.uint8), cv2.IMREAD_UNCHANGED + ) + assert image.shape == (520, 696) and image.dtype == np.uint8 + # First of the two tiles that the release's segmentAndTrack script feeds the network for these + # images (tmp-test.prototxt: 444 x 892): im2double, mirror padding of (input - output) / 2, + # zero fill beyond the padded image. + height, width = 444, 892 + border = (height - unet_output_size(height)) // 2 + padded = np.pad(image.astype(np.float32) / 255.0, border, mode="reflect") + tile = np.zeros((1, 1, height, width), dtype=np.float32) + rows, cols = min(height, padded.shape[0]), min(width, padded.shape[1]) + tile[0, 0, :rows, :cols] = padded[:rows, :cols] + + model = build_model("unet", task="segmentation", variant="phseg_v5").eval() + model.load_state_dict(_release_state_dict(), strict=True) + with torch.no_grad(): + out = model(torch.from_numpy(tile)) + assert out.shape == (1, 2, 260, 708) + reference = _opencv_forward(tile) + _assert_close_to_opencv(out, reference) + # Same foreground/background decision for every pixel of the tile. + assert torch.equal(out.argmax(1), torch.from_numpy(reference).argmax(1)) diff --git a/tests/oracle/test_unetr_oracle.py b/tests/oracle/test_unetr_oracle.py new file mode 100644 index 00000000..283e3ab9 --- /dev/null +++ b/tests/oracle/test_unetr_oracle.py @@ -0,0 +1,147 @@ +"""UNETR checked against MONAI 1.3.2 and TS-SatFire's modified copy. + +References: ``monai.networks.nets.UNETR`` from monai 1.3.2 and ``spatial_models/unetr/unetr.py`` +from zhaoyutim/TS-SatFire (pinned in repos.yaml; no LICENSE, so it is only imported here as an +oracle). Each check builds both models from the same seed, requires identical parameter names and +initial values, then compares outputs in eval and train mode after randomising the weights and +BatchNorm statistics. + +UNETR's position embedding fixes the input size, so the forward checks build both models for a +small input -- (T, H, W) = (2, 32, 32) for the 3D prediction model, 64x64 for the 2D model -- +while parameter counts are checked at TS-SatFire's 256x256 on the meta device. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.unetr import UNETR, TemporalUNETR +from tssatfire_oracle_helpers import ( + PRED_CHANNELS, + assert_close, + assert_same_names_and_shapes, + assert_same_state, + compare_eval_and_train, + monai_nets, + n_params, + randomise, + ts_satfire_module, +) + + +def _ts_unetr(): + return ts_satfire_module("unetr.unetr").UNETR + + +def _ts_prediction_config(in_channels: int, img_size, feature_size: int = 16, hidden_size: int = 384, mlp_dim: int = 1536): + # run_spatial_temp_model_pred.py, model "unetr3d" (default branch: hidden 384, MLP 1536). The + # script also passes kernel_size_up_down=(1, 2, 2), an argument the released unetr.py does not + # have; that file hard-codes (1, 2, 2) for every transposed convolution instead. + return dict( + in_channels=in_channels, + out_channels=2, + img_size=img_size, + spatial_dims=3, + norm_name="batch", + feature_size=feature_size, + patch_size=(1, 16, 16), + hidden_size=hidden_size, + mlp_dim=mlp_dim, + ) + + +def test_released_file_has_no_kernel_size_up_down_argument(): + """The prediction script's UNETR call does not run against the released unetr.py.""" + TSUNETR = _ts_unetr() + with pytest.raises(TypeError): + with torch.device("meta"): + TSUNETR(**_ts_prediction_config(PRED_CHANNELS, (2, 32, 32)), kernel_size_up_down=(1, 2, 2)) + + +def test_ts_satfire_prediction_model_matches_reference(): + TSUNETR = _ts_unetr() + torch.manual_seed(0) + reference = TSUNETR(**_ts_prediction_config(PRED_CHANNELS, (2, 32, 32))) + torch.manual_seed(0) + port = build_model("unetr", task="segmentation", in_channels=PRED_CHANNELS, history=2, image_size=32) + assert isinstance(port, TemporalUNETR) + assert_same_state(reference, port) + + randomise(reference, port, seed=1) + torch.manual_seed(2) + x = torch.randn(2, 2, PRED_CHANNELS, 32, 32) # (batch, time, channels, H, W) + x_ref = x.transpose(1, 2).contiguous() + compare_eval_and_train(reference, port, x_ref, x, reduce_time=True) + port.time_reduction = "none" + reference.eval() + port.eval() + with torch.no_grad(): + assert_close(port(x), reference(x_ref)) + + +def test_ts_satfire_parameter_counts_at_full_size(): + TSUNETR = _ts_unetr() + with torch.device("meta"): + # Prediction script configuration, 6 days of 43 channels at 256x256. + reference = TSUNETR(**_ts_prediction_config(PRED_CHANNELS, (6, 256, 256))) + port = build_model("unetr", task="segmentation", in_channels=PRED_CHANNELS) + assert_same_names_and_shapes(reference, port) + assert n_params(port) == n_params(reference) == 28_816_866 + # The 34.8M of Table 3 is the AF/BA configuration: 8 channels, feature size 36 (paper text). + reference = TSUNETR(**_ts_prediction_config(8, (6, 256, 256), feature_size=36)) + port = build_model("unetr", task="segmentation", in_channels=8, feature_size=36) + assert_same_names_and_shapes(reference, port) + assert n_params(port) == n_params(reference) == 34_806_506 + # The prediction script's alternative "v0" widths. + reference = TSUNETR(**_ts_prediction_config(PRED_CHANNELS, (6, 256, 256), hidden_size=768, mlp_dim=3072)) + port = build_model("ts_satfire", task="segmentation", baseline="unetr3d", unetr_version="v0") + assert_same_names_and_shapes(reference, port) + assert n_params(port) == n_params(reference) == 97_922_658 + + +def test_ts_satfire_2d_config_matches_monai(): + MonaiUNETR = monai_nets().UNETR + # run_spatial_model.py, model "unetr2d_half": stock MONAI, hidden 384, MLP 1536, batch norm. + config = dict(in_channels=8, out_channels=2, spatial_dims=2, norm_name="batch", feature_size=16, hidden_size=384, mlp_dim=1536) + with torch.device("meta"): + reference = MonaiUNETR(img_size=(256, 256), **config) + port = build_model("unetr", task="segmentation", in_channels=8, spatial_dims=2) + assert type(port) is UNETR + assert_same_names_and_shapes(reference, port) + assert n_params(port) == 23_521_186 # Table 3: 23.52M + + torch.manual_seed(0) + reference = MonaiUNETR(img_size=(64, 64), **config) + torch.manual_seed(0) + port = build_model("unetr", task="segmentation", in_channels=8, spatial_dims=2, image_size=64) + assert_same_state(reference, port) + randomise(reference, port, seed=3) + torch.manual_seed(4) + x = torch.randn(2, 8, 64, 64) + compare_eval_and_train(reference, port, x, x) + + +def test_non_default_configs_match_monai(): + """Instance norm, dropout, qkv bias, perceptron patches and plain (non-residual) blocks.""" + MonaiUNETR = monai_nets().UNETR + configs = [ + dict(in_channels=3, out_channels=2, img_size=(32, 32, 32), feature_size=8, hidden_size=48, mlp_dim=96, num_heads=4, dropout_rate=0.1, qkv_bias=True), + dict(in_channels=3, out_channels=3, img_size=(32, 48), spatial_dims=2, feature_size=8, hidden_size=48, mlp_dim=0, num_heads=3, proj_type="perceptron", norm_name="batch"), + dict(in_channels=2, out_channels=1, img_size=(32, 32), spatial_dims=2, feature_size=12, hidden_size=48, mlp_dim=64, num_heads=4, conv_block=False, res_block=False, save_attn=True), + dict(in_channels=2, out_channels=1, img_size=(16, 32, 16), feature_size=8, hidden_size=32, mlp_dim=64, num_heads=2, res_block=False, norm_name=("batch", {"momentum": 0.3})), + ] + for config in configs: + torch.manual_seed(0) + reference = MonaiUNETR(**config) + torch.manual_seed(0) + port = UNETR(**config) + assert_same_state(reference, port) + randomise(reference, port, seed=5) + torch.manual_seed(6) + x = torch.randn(2, config["in_channels"], *config["img_size"]) + compare_eval_and_train(reference, port, x, x, seed=7) # same dropout masks: same module order + if config.get("save_attn"): + for ref_block, port_block in zip(reference.vit.blocks, port.vit.blocks): + assert_close(port_block.attn.att_mat, ref_block.attn.att_mat) diff --git a/tests/oracle/test_urbanfloodcast_oracle.py b/tests/oracle/test_urbanfloodcast_oracle.py new file mode 100644 index 00000000..b7314a22 --- /dev/null +++ b/tests/oracle/test_urbanfloodcast_oracle.py @@ -0,0 +1,187 @@ +"""UrbanFloodCast DNO checked against the official code (HydroPML/UrbanFloodCast, pinned in repos.yaml). + +The official repository has no licence: PyHazards' DNO is written from the paper and from U-NO (BSD-2) / +FNO (MIT) building blocks, and the official ``DNO/models/DNO.py`` (DNO-3, the default of ``DNO_main.py``), +the one-shot data pipeline ``flood_data`` and the metrics of ``DNO/utils25.py`` are imported here from the +pinned checkout only as test oracles. ``DNO_main.py`` cannot be imported as released (``models/FNO.py`` +does ``from utils import grid`` and the repository has no ``utils.py``), so its ``get_eval_pred`` is +executed from the file's own source and its test-loop metric lines are reproduced below. +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, load_definitions, oracle_repo +from pyhazards.benchmarks.flood import evaluate_inundation +from pyhazards.datasets import load_dataset +from pyhazards.datasets.base import DataBundle, DataSplit, FeatureSpec, LabelSpec +from pyhazards.datasets.flood.urbanfloodcast import prepare_urbanfloodcast_event, synthetic_urbanfloodcast_event +from pyhazards.metrics.inundation import inundation_metrics +from pyhazards.models import build_model +from pyhazards.models.urbanfloodcast import UrbanFloodCast + + +def _dno_dir() -> Path: + return oracle_repo("UrbanFloodCast") / "DNO" + + +def _official_dno(): + return import_from(_dno_dir(), "models.DNO").DNO + + +def _utils25(): + return import_from(_dno_dir(), "utils25") + + +def _assert_same_state(reference, port) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert value.shape == port_state[key].shape and value.dtype == port_state[key].dtype, key + assert torch.equal(value, port_state[key]), key + + +@pytest.mark.parametrize("seed", [0, 1]) +def test_parameters_names_and_seeded_initialisation_match_official(seed): + DNO = _official_dno() + # DNO_main.py builds DNO(num_channels=5, width=10, initial_step=1, pad=args.time_pad (False), factor=1) + # after torch.manual_seed(args.seed) (default 1); models/DNO.py seeds 0 at import time. + torch.manual_seed(seed) + reference = DNO(num_channels=5, width=10, initial_step=1, pad=False, factor=1) + torch.manual_seed(seed) + port = build_model("urbanfloodcast", task="regression") + assert sum(p.numel() for p in reference.parameters()) == sum(p.numel() for p in port.parameters()) == 4_470_437 + assert sum(p.numel() * (1 + p.is_complex()) for p in port.parameters()) == 8_937_637 + _assert_same_state(reference, port) + + +@pytest.mark.parametrize("shape", [(2, 32, 32, 24, 1, 5), (1, 28, 36, 16, 1, 5)], ids=["32x32x24", "28x36x16"]) +def test_outputs_and_gradients_match_official(shape): + DNO = _official_dno() + torch.manual_seed(1) + reference = DNO(num_channels=5, width=10, initial_step=1, pad=False, factor=1) + port = UrbanFloodCast() + port.load_state_dict(reference.state_dict(), strict=True) + x = torch.randn(*shape, generator=torch.Generator().manual_seed(2)) + for train in (False, True): # InstanceNorm3d without running statistics: same in both modes + reference.train(train) + port.train(train) + with torch.no_grad(): + expected = reference(x) + torch.testing.assert_close(port(x), expected, rtol=1e-5, atol=1e-6) + torch.testing.assert_close(port(x.reshape(*shape[:4], -1)), expected, rtol=1e-5, atol=1e-6) + reference.zero_grad() + port.zero_grad() + reference(x).square().sum().backward() + port(x).square().sum().backward() + for (name, ref_param), port_param in zip(reference.named_parameters(), port.parameters()): + torch.testing.assert_close(port_param.grad, ref_param.grad, rtol=1e-4, atol=1e-6, msg=name) + + +def _events(directory: Path, count: int = 3, seed: int = 0, missing_terrain: bool = False): + generator = torch.Generator().manual_seed(seed) + events = [] + for i in range(count): + event = synthetic_urbanfloodcast_event(30, 34, 25, generator) + if missing_terrain and i == 0: + # A missing terrain cell: the reference's nan_to_num(nan=z.max() + 30) cannot fill it because + # torch.max propagates NaN, so the whole terrain channel becomes NaN (reproduced). + event[3, 5, 7:, 4] = float("nan") + torch.save(event, directory / f"{i}.pt") + events.append(event) + return events + + +def test_one_shot_samples_match_flood_data(tmp_path): + flood_data = _utils25().flood_data + events = _events(tmp_path, missing_terrain=True) + for train in (True, False): + official = flood_data(path_root=str(tmp_path), T_in=1, T_out=24, train=train, strategy="oneshot") + assert len(official) == len(events) + for idx in range(len(official)): + x, y, mask = official[idx] + event = events[int(Path(official.data[idx]).stem)] + before = event.clone() + ours = prepare_urbanfloodcast_event(event, T_in=1, T_out=24) + assert torch.equal(event.nan_to_num(-1.0), before.nan_to_num(-1.0)) # the event is not modified + for actual, expected in zip(ours, (x, y, mask)): + assert actual.shape == expected.shape and actual.dtype == expected.dtype + assert torch.equal(actual.nan_to_num(-7.0), expected.nan_to_num(-7.0)) + + +def test_inundation_metrics_match_dno_main_test_loop(tmp_path): + """Relative L2, NSE, Pearson r and CSI as DNO_main.py computes them in its test loop (batch size 1).""" + utils25 = _utils25() + get_eval_pred = load_definitions(_dno_dir() / "DNO_main.py", ["get_eval_pred"], {"torch": torch})["get_eval_pred"] + DNO = _official_dno() + torch.manual_seed(1) + model = DNO(num_channels=5, width=10, initial_step=1, pad=False, factor=1).eval() + _events(tmp_path) + test_data = utils25.flood_data(path_root=str(tmp_path), T_in=1, T_out=24, train=False, strategy="oneshot") + loader = torch.utils.data.DataLoader(test_data, batch_size=1, shuffle=False) + lploss = utils25.LpLoss(size_average=False) + Sy, Sx, T, num_channels_y = 30, 34, 24, 3 # noqa: N806 (DNO_main names) + totals = dict.fromkeys(["relative_l2", "nse", "pearson_r", "csi_1cm", "csi_10cm", "csi_50cm"], 0.0) + xs, ys, masks = [], [], [] + with torch.no_grad(): + for xx, yy, mask in loader: + xs.append(xx[0]) + ys.append(yy[0].clone()) + masks.append(mask[0]) + yy = yy * mask + pred = get_eval_pred(model=model, x=xx, strategy="oneshot", T=T, times=[]).view(len(xx), Sy, Sx, T, num_channels_y) + pred = pred * mask + totals["relative_l2"] += lploss(pred.reshape(len(pred), -1, num_channels_y), yy.reshape(len(yy), -1, num_channels_y)).item() + totals["nse"] += utils25.nse(pred.reshape(len(pred), -1, num_channels_y), yy.reshape(len(yy), -1, num_channels_y)).item() + totals["pearson_r"] += utils25.corr(pred.reshape(len(pred), -1, num_channels_y), yy.reshape(len(yy), -1, num_channels_y)).item() + for name, threshold in (("csi_1cm", 0.01), ("csi_10cm", 0.1), ("csi_50cm", 0.5)): + totals[name] += utils25.critical_success_index( + pred[..., 0:1].reshape(len(pred), -1, 1), yy[..., 0:1].reshape(len(yy), -1, 1), threshold + ).item() + expected = {name: value / len(test_data) for name, value in totals.items()} + + port = UrbanFloodCast() + port.load_state_dict(model.state_dict(), strict=True) + port.eval() + x, y, m = torch.stack(xs), torch.stack(ys), torch.stack(masks) + bundle = DataBundle( + splits={"test": DataSplit(x, y, metadata={"mask": m})}, + feature_spec=FeatureSpec(channels=5), + label_spec=LabelSpec(num_targets=3), + metadata={"depth_channel": 0, "inundation_layout": "channels_last"}, + ) + metrics, _ = evaluate_inundation(port, bundle, "test", batch_size=1) + for name, value in expected.items(): + assert metrics[name] == pytest.approx(value, rel=1e-5, abs=1e-7), name + with torch.no_grad(): + direct = inundation_metrics(port(x), y, mask=m, depth_index=0) + for name, value in expected.items(): + assert direct[name] == pytest.approx(value, rel=1e-5, abs=1e-7), name + + +def test_metric_functions_match_utils25(): + utils25 = _utils25() + from pyhazards.metrics import inundation + + generator = torch.Generator().manual_seed(0) + pred, target = torch.rand(2, 500, 3, generator=generator), torch.rand(2, 500, 3, generator=generator) + torch.testing.assert_close(inundation.relative_l2(pred, target).sum(), utils25.LpLoss(size_average=False)(pred, target)) + torch.testing.assert_close(inundation.nash_sutcliffe(pred, target), utils25.nse(pred, target)) + torch.testing.assert_close(inundation.pearson_correlation(pred, target), utils25.corr(pred, target)) + for threshold in (0.01, 0.1, 0.5): + torch.testing.assert_close( + inundation.critical_success_index(pred[..., :1], target[..., :1], threshold), + utils25.critical_success_index(pred[..., :1], target[..., :1], threshold), + ) + + +def test_synthetic_dataset_uses_the_official_layout(): + bundle = load_dataset("urbanfloodcast_synthetic", micro=True).load() + x = bundle.get_split("train").inputs + assert tuple(x.shape[1:]) == (32, 32, 24, 1, 5) + assert np.isfinite(x.numpy()).all() diff --git a/tests/oracle/test_wavecastnet_oracle.py b/tests/oracle/test_wavecastnet_oracle.py new file mode 100644 index 00000000..70d96574 --- /dev/null +++ b/tests/oracle/test_wavecastnet_oracle.py @@ -0,0 +1,286 @@ +"""WaveCastNet checked against the official PyTorch code and its released checkpoints. + +Reference (pinned in repos.yaml): dwlyu/WaveCastNet at c859e04 (MIT). ``AEConvLEM_dense`` and +``AEConvLEM_sparse`` are imported from ``src/models_earthquake`` with the README / notebook arguments +(``dt=1, num_channels=3, num_kernels=144, kernel_size=(3, 3), padding=(1, 1), activation="tanh", +frame_size=(43, 28)``; sparse: ``mask_mode=1, mask_ratio=1 - 101/564``). ``Encoder1d`` reads the station +list from a hard-coded NERSC path, so ``numpy.load`` is redirected to the repository's +``filtered_coord.npy`` (or to a list of the checkpoint's size) while the official modules run. + +Checks: parameter counts (10,093,242 dense, 16,535,430 sparse), parameter names and shapes, identical +seeded initialisation, identical outputs in evaluation and training mode (same global seed for the +decoder noise and the station mask, and the port's generator hook), batch-norm statistics, gradients, +the rolling validation forecast of ``earthquake_train.py``, the released ``best_lem_dense_.pt`` (strict +load, same outputs) and ``best_lem_irr_mask_shakealert_.pt`` (strict load with 558 stations, same +outputs), the training ``Huber`` loss and the ``Validation_pixel`` metrics. +""" + +from __future__ import annotations + +import hashlib + +import numpy as np +import pytest +import torch +import torch.nn as nn + +from oracle_utils import import_from, load_definitions, oracle_asset, oracle_repo +from pyhazards.metrics.wavefield import wavefield_acc, wavefield_metrics, wavefield_rfne, wavefield_rmse +from pyhazards.models import build_model +from pyhazards.models.wavecastnet import ( + DEFAULT_MASK_RATIO, + WAVECASTNET_STATIONS, + WAVECASTNET_WEIGHTS, + ConvLEMCell, + WaveCastNet, + WaveCastNetLoss, + WaveCastNetSparse, + load_wavecastnet_checkpoint, +) + +OFFICIAL = dict( + dt=1, num_channels=3, num_kernels=144, kernel_size=(3, 3), padding=(1, 1), activation="tanh", frame_size=(43, 28) +) +EXACT = dict(rtol=0, atol=0) +# The checkpoint comparisons run the same float32 operations in the same order; allow summation noise. +TOLERANCE = dict(rtol=1e-5, atol=1e-6) +NERSC = "/global/homes/d/dwlyu/earthquake/" + + +@pytest.fixture(scope="module") +def source(): + return oracle_repo("WaveCastNet") / "src" / "models_earthquake" + + +@pytest.fixture(scope="module") +def official(source): + """The official model classes (``ConvLEMCell`` module objects included).""" + modules = {name: import_from(source, name) for name in ("ConvLEMCell", "AEConvLEM_dense", "AEConvLEM_sparse")} + return modules + + +@pytest.fixture +def stations(source, monkeypatch): + """Redirect the official ``np.load`` of the NERSC station list to ``coords`` (default: the repo file).""" + original = np.load + state = {"coords": original(source / "filtered_coord.npy")} + + def load(path, *args, **kwargs): + if isinstance(path, str) and path.startswith(NERSC): + return state["coords"] + return original(path, *args, **kwargs) + + monkeypatch.setattr(np, "load", load) + return state + + +def _count(model: nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: nn.Module, port: nn.Module) -> None: + ref, ours = reference.state_dict(), port.state_dict() + assert list(ref) == list(ours) + for key in ref: + assert ref[key].shape == ours[key].shape, key + torch.testing.assert_close(ours[key], ref[key], **EXACT, msg=key) + + +def _load_official_state(path, model: nn.Module) -> None: + state = torch.load(str(path), map_location="cpu", weights_only=True) + model.load_state_dict({k.replace("module.", ""): v for k, v in state.items()}, strict=True) + + +def test_parameter_counts_names_and_seeded_initialisation(official, stations): + torch.manual_seed(0) + dense_ref = official["AEConvLEM_dense"].AEConvLEM_dense(**OFFICIAL) + torch.manual_seed(0) + dense = WaveCastNet() + assert _count(dense_ref) == _count(dense) == 10_093_242 + _assert_same_state(dense_ref, dense) + assert dense.encoder_1_convlem.W_z4.shape == (144, 43, 28) + + torch.manual_seed(3) + sparse_ref = official["AEConvLEM_sparse"].AEConvLEM_sparse(mask_mode=1, mask_ratio=DEFAULT_MASK_RATIO, **OFFICIAL) + torch.manual_seed(3) + sparse = WaveCastNetSparse(station_coords=stations["coords"]) + assert _count(sparse_ref) == _count(sparse) == 16_535_430 + _assert_same_state(sparse_ref, sparse) + + # Both cell variants of ConvLEMCell.py (ConvLEMCell: no reset gate, xavier-normal). + for name, reset_gate in (("ConvLEMCell", False), ("ConvLEMCell_1", True)): + torch.manual_seed(5) + cell_ref = getattr(official["ConvLEMCell"], name)( + dt=0.5, in_channels=6, out_channels=8, kernel_size=(3, 3), padding=(1, 1), activation="relu", frame_size=(5, 4) + ) + torch.manual_seed(5) + cell = ConvLEMCell(6, 8, (5, 4), kernel_size=3, padding=1, dt=0.5, activation="relu", reset_gate=reset_gate) + _assert_same_state(cell_ref, cell) + x, h, c = torch.randn(2, 6, 5, 4), torch.randn(2, 8, 5, 4), torch.randn(2, 8, 5, 4) + for ours, ref in zip(cell(x, h, c), cell_ref(x, h, c)): + torch.testing.assert_close(ours, ref, **EXACT) + + +@pytest.mark.parametrize("future_seq", [1, 3]) +def test_dense_outputs_match_in_eval_and_train_mode(official, future_seq): + torch.manual_seed(11) + reference = official["AEConvLEM_dense"].AEConvLEM_dense(**OFFICIAL) + port = WaveCastNet() + port.load_state_dict(reference.state_dict()) + x = torch.randn(2, 3, 3, 344, 224) + + reference.eval(), port.eval() + with torch.no_grad(): + torch.manual_seed(1) + expected = reference(x, future_seq=future_seq) + torch.manual_seed(1) + torch.testing.assert_close(port(x, future_seq), expected, **EXACT) + # Generator hook: the same draws as the official global generator. + torch.manual_seed(99) + torch.testing.assert_close(port(x, future_seq, generator=torch.Generator().manual_seed(1)), expected, **EXACT) + # decoder_noise hook: the official uniform noise drawn explicitly. + torch.manual_seed(1) + noise = torch.rand(2, 144, 43, 28) + torch.testing.assert_close(port(x, future_seq, decoder_noise=noise), expected, **EXACT) + # The decoder starts from noise also in eval mode, so outputs depend on the seed. + torch.manual_seed(2) + assert not torch.equal(reference(x, future_seq=future_seq), expected) + + reference.train(), port.train() + torch.manual_seed(4) + expected = reference(x, future_seq=future_seq) + torch.manual_seed(4) + actual = port(x, future_seq) + torch.testing.assert_close(actual, expected, **EXACT) + _assert_same_state(reference, port) # batch-norm running statistics + grad_out = torch.randn_like(expected) + expected.backward(grad_out) + actual.backward(grad_out) + for (name, p_ref), p_port in zip(reference.named_parameters(), port.parameters()): + torch.testing.assert_close(p_port.grad, p_ref.grad, rtol=1e-5, atol=1e-7, msg=name) + + +def test_sparse_outputs_match(official, stations): + torch.manual_seed(12) + reference = official["AEConvLEM_sparse"].AEConvLEM_sparse(mask_mode=1, mask_ratio=DEFAULT_MASK_RATIO, **OFFICIAL) + port = WaveCastNetSparse(station_coords=stations["coords"]) + port.load_state_dict(reference.state_dict()) + x = torch.randn(2, 3, 3, 344, 224) + + reference.eval(), port.eval() + with torch.no_grad(): + torch.manual_seed(6) + expected = reference(x, future_seq=2) + torch.manual_seed(6) + torch.testing.assert_close(port(x, 2), expected, **EXACT) + torch.testing.assert_close(port(x, 2, generator=torch.Generator().manual_seed(6)), expected, **EXACT) + # Official draw order: the station mask (one uniform per sample and station, masked if < ratio), + # then the decoder noise; the station_mask and decoder_noise hooks take them explicitly. + torch.manual_seed(6) + draw, noise = torch.rand(2, 564), torch.rand(2, 144, 43, 28) + kept = port(x, 2, station_mask=draw >= DEFAULT_MASK_RATIO, decoder_noise=noise) + torch.testing.assert_close(kept, expected, **EXACT) + + reference.train(), port.train() + torch.manual_seed(7) + expected = reference(x, future_seq=2) + torch.manual_seed(7) + torch.testing.assert_close(port(x, 2), expected, **EXACT) + _assert_same_state(reference, port) # batch-norm running statistics + + +def test_rolling_validation_forecast_matches_earthquake_train(official): + """``earthquake_train.py`` validation: six calls of ``step`` frames and one of ``step // 2``, each on the + previous output; here with step 2 (13 frames) instead of 30 (195 frames) to keep the test fast.""" + torch.manual_seed(13) + reference = official["AEConvLEM_dense"].AEConvLEM_dense(**OFFICIAL).eval() + port = WaveCastNet(future_seq=2).eval() + port.load_state_dict(reference.state_dict()) + x, step = torch.randn(1, 3, 2, 344, 224), 2 + with torch.no_grad(): + torch.manual_seed(8) + output, current = [], x + for i in range(7): + current = reference(current, future_seq=step if i < 6 else step // 2).detach() + output.append(current) + expected = torch.concat(output, dim=2) + torch.manual_seed(8) + actual = port.rollout(x, 13) + assert actual.shape == (1, 3, 13, 344, 224) + torch.testing.assert_close(actual, expected, **EXACT) + + +def test_released_dense_checkpoint(official): + path = oracle_asset("wavecastnet_dense_checkpoint") / WAVECASTNET_WEIGHTS["dense"]["filename"] + reference = official["AEConvLEM_dense"].AEConvLEM_dense(**OFFICIAL) + _load_official_state(path, reference) + port = load_wavecastnet_checkpoint(WaveCastNet(), path) + built = build_model("wavecastnet", task="forecasting", pretrained=str(path)) + _assert_same_state(reference, port) + _assert_same_state(reference, built) + reference.eval(), port.eval() + x = torch.randn(1, 3, 4, 344, 224) + with torch.no_grad(): + torch.manual_seed(21) + expected = reference(x, future_seq=3) + torch.manual_seed(21) + actual = port(x, 3) + torch.testing.assert_close(actual, expected, **TOLERANCE) + assert torch.isfinite(actual).all() and actual.abs().max() > 0 + + +def test_released_sparse_checkpoint(official, stations, source): + path = oracle_asset("wavecastnet_sparse_checkpoint") / "best_lem_irr_mask_shakealert_.pt" + state = torch.load(str(path), map_location="cpu", weights_only=True) + assert state["module.encoder.FC1.0.weight"].shape == (1204, 558) + # The released station list has 564 entries: the checkpoint's 558-station list was not published. + with pytest.raises(RuntimeError, match="size mismatch"): + load_wavecastnet_checkpoint(WaveCastNetSparse(station_coords=stations["coords"]), path) + coords = stations["coords"][:558] # any 558 grid points: names, shapes and arithmetic are what is checked + stations["coords"] = coords + reference = official["AEConvLEM_sparse"].AEConvLEM_sparse(mask_mode=1, mask_ratio=DEFAULT_MASK_RATIO, **OFFICIAL) + _load_official_state(path, reference) + port = load_wavecastnet_checkpoint(WaveCastNetSparse(station_coords=coords), path) + _assert_same_state(reference, port) + reference.eval(), port.eval() + x = torch.randn(1, 3, 3, 344, 224) + with torch.no_grad(): + torch.manual_seed(22) + expected = reference(x, future_seq=2) + torch.manual_seed(22) + actual = port(x, 2) + torch.testing.assert_close(actual, expected, **TOLERANCE) + + +def test_station_files_match_the_pinned_hashes(source): + for spec in WAVECASTNET_STATIONS.values(): + assert hashlib.sha256((source / spec["filename"]).read_bytes()).hexdigest() == spec["sha256"] + assert len(np.load(source / "filtered_coord.npy")) == 564 + assert len(np.load(source / "shakealert_coords.npy")) == 101 + + +def test_loss_and_metrics_match_the_official_functions(source): + train_script = source.parent.parent / "earthquake_train.py" + huber = load_definitions(train_script, ["Huber"], {"torch": torch, "nn": nn})["Huber"](reduction="mean") + validation = import_from(source, "Validation_pixel") + torch.manual_seed(0) + pred, target = torch.randn(3, 3, 5, 16, 8), torch.randn(3, 3, 5, 16, 8) * 0.3 + loss = WaveCastNetLoss() + torch.testing.assert_close(loss(pred, target), huber(pred.flatten(), target.flatten()), **EXACT) + torch.testing.assert_close( + WaveCastNetLoss(delta=0.7)(pred, target), huber(pred.flatten(), target.flatten(), delta=0.7), **EXACT + ) + expected = { + "acc": validation.validation_acc(pred, target), + "rfne": validation.validation_rfne(pred, target), + "rmse": validation.validation_rmse(pred, target), + } + metrics = wavefield_metrics(pred, target) + for key, value in expected.items(): + assert metrics[key] == pytest.approx(value, rel=1e-6) + for fn, official_fn in ((wavefield_acc, validation.validation_acc), (wavefield_rfne, validation.validation_rfne), + (wavefield_rmse, validation.validation_rmse)): + for channel in range(3): + assert float(fn(pred, target)[:, channel].mean()) == pytest.approx( + official_fn(pred[:, channel : channel + 1], target[:, channel : channel + 1]), rel=1e-6 + ) diff --git a/tests/oracle/test_wildfire_forecasting_oracle.py b/tests/oracle/test_wildfire_forecasting_oracle.py new file mode 100644 index 00000000..ab3b0bde --- /dev/null +++ b/tests/oracle/test_wildfire_forecasting_oracle.py @@ -0,0 +1,182 @@ +"""Kondylatos et al. (2022) LSTM / ConvLSTM checked against the official wildfire_forecasting code. + +Reference (pinned in repos.yaml): Orion-AI-Lab/wildfire_forecasting, +``wildfire_forecasting/models/modules/fire_modules.py`` and ``convlstm.py``. That module imports +fastai (``unet``) and torchvision (``resnet18``) without using either; both are replaced by empty +stand-in modules for the import when they are not installed. Lightning, Hydra and torchmetrics are +only imported by the LightningModule wrappers (``greece_fire_models.py``), which are not needed. +The paper configurations come from ``configs/experiment/{lstm_temporal_cls,clstm_spatiotemporal_cls}.yaml``. +""" + +from __future__ import annotations + +import importlib.util +import sys +from types import ModuleType + +import numpy as np +import pytest +import torch + +from oracle_utils import import_from, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.convlstm import ConvLSTM + +DYNAMIC_FEATURES = [ + "1 km 16 days NDVI", + "LST_Day_1km", + "LST_Night_1km", + "era5_max_d2m", + "era5_max_t2m", + "era5_max_sp", + "era5_max_tp", + "sminx", + "era5_max_wind_speed", + "era5_min_rh", +] +STATIC_FEATURES = ["dem_mean", "slope_mean", "roads_distance", "waterway_distance", "population_density"] +PAPER_HPARAMS = { + "lstm": {"hidden_size": 64, "lstm_layers": 1, "dropout": 0.5}, + "convlstm": {"hidden_size": 32, "lstm_layers": 1, "dropout": 0.5}, +} +EXPECTED_PARAMS = {"lstm": 29_652, "convlstm": 372_212} + + +def _hparams(variant: str, **overrides) -> dict: + return { + "dynamic_features": DYNAMIC_FEATURES, + "static_features": STATIC_FEATURES, + "clc": "vec", + **PAPER_HPARAMS[variant], + **overrides, + } + + +def _stub(name: str, **attrs) -> ModuleType: + module = ModuleType(name) + module.__dict__.update(attrs) + return module + + +@pytest.fixture(scope="module") +def reference(): + root = oracle_repo("wildfire_forecasting") + stubs = { + "fastai": _stub("fastai"), + "fastai.vision": _stub("fastai.vision"), + "fastai.vision.models": _stub("fastai.vision.models", unet=None), + } + if importlib.util.find_spec("torchvision") is None: + stubs.update( + { + "torchvision": _stub("torchvision"), + "torchvision.models": _stub("torchvision.models"), + "torchvision.models.resnet": _stub("torchvision.models.resnet", resnet18=None), + } + ) + patch = pytest.MonkeyPatch() # restores sys.modules after the import + for name, module in stubs.items(): + patch.setitem(sys.modules, name, module) + numpy_errors = np.geterr() # fire_modules calls np.seterr(divide="ignore", invalid="ignore") + try: + fire_modules = import_from(root, "wildfire_forecasting.models.modules.fire_modules") + convlstm = import_from(root, "wildfire_forecasting.models.modules.convlstm") + finally: + np.seterr(**numpy_errors) + patch.undo() + return fire_modules, convlstm + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _seeded_pair(reference_cls, variant: str, seed: int = 0, **overrides): + torch.manual_seed(seed) + ref = reference_cls(_hparams(variant, **overrides)) + torch.manual_seed(seed) + port_kwargs = {"hidden_size": overrides.get("hidden_size", PAPER_HPARAMS[variant]["hidden_size"])} + if "lstm_layers" in overrides: + port_kwargs["lstm_layers"] = overrides["lstm_layers"] + port = build_model("wildfire_forecasting", task="classification", variant=variant, **port_kwargs) + return ref, port + + +def _compare_forward(ref: torch.nn.Module, port: torch.nn.Module, x: torch.Tensor) -> None: + ref.eval() + port.eval() + with torch.no_grad(): + expected = ref(x) + _assert_close(port(x), expected) + assert torch.allclose(expected.exp().sum(dim=1), torch.ones(x.size(0))) # log-probabilities + + ref.train() + port.train() + torch.manual_seed(5) + expected = ref(x) + torch.manual_seed(5) + _assert_close(port(x), expected) + + +def test_lstm_matches_reference(reference): + fire_modules, _ = reference + ref, port = _seeded_pair(fire_modules.SimpleLSTM, "lstm") + assert _n_params(ref) == _n_params(port) == EXPECTED_PARAMS["lstm"] + _assert_same_state(ref, port) + port.load_state_dict(ref.state_dict(), strict=True) + + torch.manual_seed(1) + _compare_forward(ref, port, torch.randn(8, 10, 25)) + + +def test_convlstm_matches_reference(reference): + fire_modules, _ = reference + ref, port = _seeded_pair(fire_modules.SimpleConvLSTM, "convlstm") + assert _n_params(ref) == _n_params(port) == EXPECTED_PARAMS["convlstm"] + _assert_same_state(ref, port) + port.load_state_dict(ref.state_dict(), strict=True) + + torch.manual_seed(1) + _compare_forward(ref, port, torch.randn(4, 10, 25, 25, 25)) + + +@pytest.mark.parametrize("variant", ["lstm", "convlstm"]) +def test_other_hyperparameters_match_reference(reference, variant): + fire_modules, _ = reference + reference_cls = fire_modules.SimpleLSTM if variant == "lstm" else fire_modules.SimpleConvLSTM + # The hidden size of the reference default model configs (configs/model/greecefire_*_model.yaml), + # and a two-layer stack. + ref, port = _seeded_pair(reference_cls, variant, seed=3, hidden_size=16, lstm_layers=2) + _assert_same_state(ref, port) + torch.manual_seed(4) + shape = (3, 6, 25) if variant == "lstm" else (3, 6, 25, 25, 25) + _compare_forward(ref, port, torch.randn(*shape)) + + +def test_reference_convlstm_equals_pyhazards_convlstm(reference): + _, convlstm = reference + torch.manual_seed(0) + ref = convlstm.ConvLSTM(25, 32, (3, 3), 2, True, True, False, dilation=1) + torch.manual_seed(0) + port = ConvLSTM(25, 32, kernel_size=(3, 3), num_layers=2) + _assert_same_state(ref, port) + + torch.manual_seed(1) + x = torch.randn(2, 5, 25, 25, 25) + with torch.no_grad(): + ref_outputs, ref_states = ref(x) + outputs, states = port(x) + _assert_close(outputs, ref_outputs[-1]) + _assert_close(states[-1][0], ref_states[-1][0]) + _assert_close(states[-1][1], ref_states[-1][1]) diff --git a/tests/oracle/test_wildfirespreadts_oracle.py b/tests/oracle/test_wildfirespreadts_oracle.py new file mode 100644 index 00000000..733518d7 --- /dev/null +++ b/tests/oracle/test_wildfirespreadts_oracle.py @@ -0,0 +1,223 @@ +"""WildfireSpreadTS baselines checked against their reference implementations. + +References (pinned in repos.yaml): VSainteuf/utae-paps for U-TAE and ConvLSTM (vendored unchanged +by WildfireSpreadTS), segmentation_models_pytorch 0.3.2 for the ResNet-18 U-Net, and the +WildfireSpreadTS sources for the logistic-regression baseline. Each check builds both models from +the same seed, requires identical parameter names and initial values, and compares outputs. +""" + +from __future__ import annotations + +import re +import sys +import types +import typing + +import torch + +from oracle_utils import import_from, oracle_asset, oracle_package, oracle_repo +from pyhazards.models import build_model +from pyhazards.models.utae import UTAE + +WSTS_UTAE_CONFIG = dict( + encoder_widths=[64, 64, 64, 128], + decoder_widths=[32, 32, 64, 128], + out_conv=[32, 1], + str_conv_k=4, + str_conv_s=2, + str_conv_p=1, + agg_mode="att_group", + encoder_norm="group", + n_head=16, + d_model=256, + d_k=4, + encoder=False, + return_maps=False, + pad_value=0, + padding_mode="reflect", +) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def _assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def _utae_paps(module: str): + return import_from(oracle_repo("utae-paps"), f"src.backbones.{module}") + + +def _strip_imports(text: str) -> list[str]: + return [line.rstrip() for line in text.splitlines() if line.strip() and not re.match(r"\s*(from|import) ", line)] + + +def test_wildfirespreadts_vendors_utae_paps_unchanged(): + wsts = oracle_repo("WildfireSpreadTS") / "src" / "models" / "utae_paps_models" + paps = oracle_repo("utae-paps") / "src" / "backbones" + for name in ["utae.py", "ltae.py", "convlstm.py", "positional_encoding.py"]: + assert _strip_imports((wsts / name).read_text()) == _strip_imports((paps / name).read_text()), name + + +def test_logistic_regression_matches_wildfirespreadts_definition(): + source = (oracle_repo("WildfireSpreadTS") / "src" / "models" / "LogisticRegression.py").read_text() + assert re.search( + r"nn\.Conv2d\(\s*in_channels=n_channels,\s*out_channels=1,\s*kernel_size=3,\s*padding=1\s*\)", source + ) + port = build_model("wildfirespreadts", task="segmentation", baseline="logistic_regression", in_channels=40, history=1) + torch.manual_seed(0) + reference = torch.nn.Conv2d(in_channels=40, out_channels=1, kernel_size=3, padding=1) + port.conv.load_state_dict(reference.state_dict()) + assert _n_params(port) == 361 + x = torch.randn(2, 1, 40, 24, 24) + _assert_close(port(x), reference(x[:, 0])) + + +def test_convlstm_matches_reference(): + convlstm = _utae_paps("convlstm") + torch.manual_seed(0) + reference = convlstm.ConvLSTM_Seg(num_classes=1, input_size=(32, 32), input_dim=40, hidden_dim=64, kernel_size=(3, 3)) + torch.manual_seed(0) + port = build_model("wildfirespreadts", task="segmentation", baseline="convlstm", in_channels=40) + _assert_same_state(reference, port) + assert _n_params(port) == 240_449 + + x = torch.randn(2, 5, 40, 32, 32) + x[1, 0] = 0 # an all-zero frame takes the reference pad-mask branch + with torch.no_grad(): + _assert_close(port(x), reference(x)) + + +def test_utae_wildfirespreadts_config_matches_reference(): + utae = _utae_paps("utae") + torch.manual_seed(0) + reference = utae.UTAE(input_dim=40, **WSTS_UTAE_CONFIG) + torch.manual_seed(0) + port = build_model("wildfirespreadts", task="segmentation", baseline="utae", in_channels=40) + _assert_same_state(reference, port) + assert _n_params(port) == 1_099_011 + + torch.manual_seed(1) + x = torch.randn(2, 5, 40, 32, 32) + doy = torch.tensor([[150.0, 151, 152, 153, 154], [200, 201, 202, 203, 204]]) + reference.eval() + port.eval() + with torch.no_grad(): + ref_out, ref_att = reference(x, batch_positions=doy, return_att=True) + out, att = port(x, batch_positions=doy, return_att=True) + _assert_close(out, ref_out) + _assert_close(att, ref_att) + + padded = x.clone() + padded[1, :2] = 0 # two leading padded dates in the second sample + _assert_close(port(padded, batch_positions=doy), reference(padded, batch_positions=doy)) + + reference.train() + port.train() + torch.manual_seed(2) + ref_out = reference(x, batch_positions=doy) + torch.manual_seed(2) + out = port(x, batch_positions=doy) + _assert_close(out, ref_out) + + +def test_utae_loads_official_pastis_weights(): + utae = _utae_paps("utae") + checkpoint = oracle_asset("utae_pastis_weights") / "UATE_zenodo" / "Fold_1" / "model.pth.tar" + state = torch.load(checkpoint, map_location="cpu", weights_only=True)["state_dict"] + # PASTIS semantic segmentation configuration from the released conf.json (N_params 1,087,260). + port = UTAE(input_dim=10, out_conv=[32, 20]) + port.load_state_dict(state, strict=True) + reference = utae.UTAE(input_dim=10, out_conv=[32, 20]) + reference.load_state_dict(state, strict=True) + assert _n_params(port) == 1_087_260 + + torch.manual_seed(3) + x = torch.randn(2, 6, 10, 64, 64) + days = torch.tensor([[10.0, 25, 40, 70, 100, 130], [5, 20, 50, 80, 110, 160]]) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x, batch_positions=days), reference(x, batch_positions=days)) + + +def _smp(): + return oracle_package("segmentation_models_pytorch", "0.3.2") + + +def test_resnet18_unet_matches_smp(): + smp = _smp() + torch.manual_seed(0) + reference = smp.Unet(encoder_name="resnet18", encoder_weights=None, in_channels=40, classes=1) + torch.manual_seed(0) + port = build_model("wildfirespreadts", task="segmentation", baseline="resnet18_unet", in_channels=40, history=1) + _assert_same_state(reference, port) + assert _n_params(port) == 14_444_241 + + torch.manual_seed(1) + x = torch.randn(2, 40, 64, 64) + reference.eval() + port.eval() + with torch.no_grad(): + _assert_close(port(x), reference(x)) + _assert_close(port(x[:, None]), reference(x)) + reference.train() + port.train() + _assert_close(port(x), reference(x)) + + +def test_resnet18_unet_multiday_flattening_matches_smp(): + smp = _smp() + reference = smp.Unet(encoder_name="resnet18", encoder_weights=None, in_channels=200, classes=1).eval() + port = build_model( + "wildfirespreadts", + task="segmentation", + baseline="resnet18_unet", + in_channels=40, + history=5, + remove_duplicate_features=False, + ).eval() + port.load_state_dict(reference.state_dict(), strict=True) + x = torch.randn(1, 5, 40, 32, 32) + with torch.no_grad(): + _assert_close(port(x), reference(x.flatten(1, 2))) + + +def test_resnet18_unet_removes_duplicate_static_features_like_wildfirespreadts(): + smp = _smp() + # Shims needed only to import the module: rasterio is used for reading GeoTIFFs, and T_co was + # removed from torch.utils.data.dataset in recent torch releases. + sys.modules.setdefault("rasterio", types.ModuleType("rasterio")) + import torch.utils.data.dataset as torch_dataset + + if not hasattr(torch_dataset, "T_co"): + torch_dataset.T_co = typing.TypeVar("T_co", covariant=True) + dataset = import_from(oracle_repo("WildfireSpreadTS"), "src.dataloader.FireSpreadDataset").FireSpreadDataset + assert dataset.get_n_features(5, None, True) == 120 + reference = smp.Unet(encoder_name="resnet18", encoder_weights=None, in_channels=120, classes=1).eval() + port = build_model("wildfirespreadts", task="segmentation", baseline="resnet18_unet", in_channels=40, history=5).eval() + port.load_state_dict(reference.state_dict(), strict=True) + x = torch.randn(2, 5, 40, 32, 32) + holder = types.SimpleNamespace(features_to_keep=None, get_static_and_dynamic_features_to_keep=dataset.get_static_and_dynamic_features_to_keep) + flattened = torch.stack([dataset.flatten_and_remove_duplicate_features_(holder, sample) for sample in x]) + with torch.no_grad(): + _assert_close(port(x), reference(flattened)) + + +def test_resnet18_unet_imagenet_stem_matches_smp(): + smp = _smp() + reference = smp.Unet(encoder_name="resnet18", encoder_weights="imagenet", in_channels=40, classes=1) + port = build_model("resnet18_unet", task="segmentation", in_channels=40, encoder_weights="imagenet") + ref_encoder, port_encoder = reference.encoder.state_dict(), port.encoder.state_dict() + assert list(ref_encoder) == list(port_encoder) + for key, value in ref_encoder.items(): + assert torch.equal(value, port_encoder[key]), key diff --git a/tests/oracle/tssatfire_oracle_helpers.py b/tests/oracle/tssatfire_oracle_helpers.py new file mode 100644 index 00000000..d6336427 --- /dev/null +++ b/tests/oracle/tssatfire_oracle_helpers.py @@ -0,0 +1,102 @@ +"""Shared helpers for the MONAI / TS-SatFire oracle tests (unet3d, unetr, swin_unetr, ts_satfire). + +References: ``monai==1.3.2`` (the version in TS-SatFire's environment.yml; requirements in +``requirements-tssatfire.txt``) and TS-SatFire's ``spatial_models`` at the commit pinned in +repos.yaml (no LICENSE, so it is only imported here as an oracle). +""" + +from __future__ import annotations + +import warnings +from types import ModuleType + +import torch + +from oracle_utils import import_from, oracle_package, oracle_repo + +REQUIREMENTS = "requirements-tssatfire.txt" +TS_SATFIRE_CHANNELS = (64, 128, 256, 512, 1024) +# 27 TS-SatFire bands with the 17-class land cover one-hot encoded (FireDataset.preprocess). +PRED_CHANNELS = 43 + + +def monai_nets() -> ModuleType: + oracle_package("monai", "1.3.2", REQUIREMENTS) + oracle_package("einops", "0.8.0", REQUIREMENTS) + from monai.networks import nets + + return nets + + +def ts_satfire_module(module: str) -> ModuleType: + """Import ``spatial_models.`` from the pinned TS-SatFire checkout.""" + monai_nets() # TS-SatFire's files import MONAI blocks + if module.startswith("swinunetr"): + oracle_package("torchinfo", "1.8.0", REQUIREMENTS) # imported by swinunetr.py + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return import_from(oracle_repo("TS-SatFire"), f"spatial_models.{module}") + + +def n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def assert_same_state(reference: torch.nn.Module, port: torch.nn.Module) -> None: + """Identical parameter/buffer names in the same order, and identical values.""" + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert torch.equal(value, port_state[key]), key + + +def assert_same_names_and_shapes(reference: torch.nn.Module, port: torch.nn.Module) -> None: + ref_state, port_state = reference.state_dict(), port.state_dict() + assert list(ref_state) == list(port_state) + for key, value in ref_state.items(): + assert value.shape == port_state[key].shape, key + + +def assert_close(actual: torch.Tensor, expected: torch.Tensor) -> None: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + + +def randomise(reference: torch.nn.Module, port: torch.nn.Module, seed: int) -> None: + """Give both models the same non-trivial weights, BatchNorm statistics and PReLU slopes.""" + generator = torch.Generator().manual_seed(seed) + state = reference.state_dict() + for key, value in state.items(): + if not value.is_floating_point(): + continue + if key.endswith("running_var"): + value.copy_(torch.rand(value.shape, generator=generator) + 0.5) + elif key.endswith("running_mean"): + value.copy_(0.1 * torch.randn(value.shape, generator=generator)) + else: + value.add_(0.05 * torch.randn(value.shape, generator=generator)) + reference.load_state_dict(state, strict=True) + port.load_state_dict(state, strict=True) + + +def compare_eval_and_train(reference, port, x_ref, x_port, reduce_time: bool = False, seed: int = 0) -> None: + """Outputs equal in eval mode and in train mode (same seed before each call), then equal states. + + With ``reduce_time`` the port takes PyHazards' ``(B, T, C, H, W)`` layout and averages over + time, as TS-SatFire's prediction script does with ``outputs.mean(2)``. + """ + + def ref_out(): + out = reference(x_ref) + return out.mean(2) if reduce_time else out + + reference.eval() + port.eval() + with torch.no_grad(): + assert_close(port(x_port), ref_out()) + reference.train() + port.train() + torch.manual_seed(seed) + expected = ref_out() + torch.manual_seed(seed) + assert_close(port(x_port), expected) + assert_same_state(reference, port) # BatchNorm running statistics were updated identically diff --git a/tests/test_adapter_datasets.py b/tests/test_adapter_datasets.py index 55f18c62..e7ce9e1c 100644 --- a/tests/test_adapter_datasets.py +++ b/tests/test_adapter_datasets.py @@ -3,17 +3,18 @@ def test_named_adapter_datasets_are_registered_and_loadable(): expected = { - "seisbench_waveforms", - "pick_benchmark_waveforms", - "aefa_forecast", - "caravan_streamflow", - "waterbench_streamflow", - "hydrobench_streamflow", - "floodcastbench_inundation", - "ibtracs_tracks", - "tcbench_alpha", - "tropicyclonenet_dataset", + "earthquake_waveforms_synthetic", + "earthquake_wavefield_synthetic", + "flood_streamflow_synthetic", + "flood_mesh_synthetic", + "flood_inundation_synthetic", + "urbanfloodcast_synthetic", + "tc_tracks_synthetic", + "ships_xu2021_synthetic", + "safnet_cma_era_interim_synthetic", + "tropicyclonenet_dataset_synthetic", "wildfire_spread_temporal_synthetic", + "wildfire_danger_synthetic", } assert expected.issubset(set(available_datasets())) @@ -21,3 +22,18 @@ def test_named_adapter_datasets_are_registered_and_loadable(): bundle = load_dataset(name, micro=True).load() assert bundle.splits["test"].inputs is not None assert bundle.metadata.get("source_dataset", name) == name or bundle.metadata.get("dataset") == name + + +def test_former_wavefield_name_is_a_deprecated_alias(): + bundle = load_dataset("earthquake_forecast_synthetic", micro=True).load() + assert bundle.metadata["dataset"] == "earthquake_wavefield_synthetic" and bundle.metadata["synthetic"] + + +def test_real_earthquake_reader_is_registered_but_needs_data(): + import pytest + + assert "seisbench_waveforms" in available_datasets() + for removed in ("pick_benchmark_waveforms", "aefa_forecast", "earthquake_waveforms"): + assert removed not in available_datasets() + with pytest.raises(ValueError, match="path="): + load_dataset("seisbench_waveforms", micro=True).load() diff --git a/tests/test_appendix_a_catalog.py b/tests/test_appendix_a_catalog.py index 197372cd..05f9523c 100644 --- a/tests/test_appendix_a_catalog.py +++ b/tests/test_appendix_a_catalog.py @@ -1,6 +1,8 @@ from pathlib import Path from pyhazards.appendix_a_catalog import ( + APPENDIX_A_ENTRIES, + AppendixAEntry, appendix_a_alignment_issues, render_appendix_a_page, ) @@ -19,14 +21,73 @@ def test_appendix_a_page_lists_missing_and_non_core_entries() -> None: assert "`wildfire_forecasting `_" in page assert "``Implemented``" in page assert "``Experimental``" in page - assert "GraphCast / GenCast" in page - assert ":doc:`ForeFire Adapter `" in page - assert ":doc:`WRF-SFIRE Adapter `" in page + assert "`GraphCast `_" in page + assert "GraphCast / GenCast" not in page + assert "models_forefire" not in page + assert "models_wrf_sfire" not in page assert ":doc:`FireCastNet `" in page - assert ":doc:`WaveCastNet `" in page + # EQNet is rebuilt from its paper (variant); WaveCastNet is core and not an Appendix A item. + assert ":doc:`EQNet `" in page + assert "``Variant only``" in page and " - Variant only" in page + assert "models_wavecastnet" not in page def test_appendix_a_page_is_linked_from_docs_index() -> None: repo_root = Path(__file__).resolve().parents[1] index_text = (repo_root / "docs" / "source" / "index.rst").read_text(encoding="utf-8") assert "appendix_a_coverage" in index_text + + +def test_external_simulators_are_listed_without_model_cards() -> None: + cards = load_model_cards() + page = render_appendix_a_page(cards) + entries = {entry.source_name: entry for entry in APPENDIX_A_ENTRIES} + for name in ("ForeFire", "WRF-SFIRE"): + assert entries[name].status == "external" + assert not entries[name].mapped_models + assert "``External simulator``" in page + assert " - External" in page + assert ":doc:`Simulators `" in page + assert ":doc:`WRF-SFIRE Outputs `" in page + assert not {"forefire", "wrf_sfire"} & {card.model_name for card in cards} + + +def test_external_status_rules_are_enforced() -> None: + cards = load_model_cards() + bad = [ + AppendixAEntry("Wildfire", "Sim A", "Simulator Adapter", "https://example.org", "external", ("firecastnet",), + mapped_docs=(("Simulators", "pyhazards_simulators"),)), + AppendixAEntry("Wildfire", "Sim B", "Simulator Adapter", "https://example.org", "external"), + AppendixAEntry("Wildfire", "Sim C", "Simulator Adapter", "https://example.org", "external", + mapped_docs=(("Nowhere", "no_such_page"), ("No data", "datasets/no_such_dataset"))), + AppendixAEntry("Wildfire", "Sim D", "Simulator Adapter", "https://example.org", "unknown"), + ] + issues = appendix_a_alignment_issues(cards, entries=bad) + assert any("Sim A" in issue and "must not map to model cards" in issue for issue in issues) + assert any("Sim B" in issue and "links no documentation" in issue for issue in issues) + assert any("no_such_page" in issue for issue in issues) + assert any("no_such_dataset" in issue for issue in issues) + assert any("Sim D" in issue and "unknown status" in issue for issue in issues) + + +def test_foundation_model_pipelines_are_listed_without_model_cards() -> None: + cards = load_model_cards() + page = render_appendix_a_page(cards) + entries = {entry.source_name: entry for entry in APPENDIX_A_ENTRIES} + for name in ("GraphCast", "Pangu-Weather", "FourCastNet"): + assert entries[name].status == "pipeline" + assert not entries[name].mapped_models + assert ("Foundation Weather Models", "pyhazards_forecasts") in entries[name].mapped_docs + assert "``Foundation model pipeline``" in page + assert " - Pipeline" in page + assert ":doc:`Foundation Weather Models `" in page + assert not {"graphcast_tc", "pangu_tc", "fourcastnet_tc"} & {card.model_name for card in cards} + assert entries["TCBench Alpha"].status == "core" + bad = [ + AppendixAEntry("Hurricane / Tropical Cyclone", "Model A", "Foundation Model Pipeline", "https://example.org", "pipeline", ("hurricast",), + mapped_docs=(("Foundation Weather Models", "pyhazards_forecasts"),)), + AppendixAEntry("Hurricane / Tropical Cyclone", "Model B", "Foundation Model Pipeline", "https://example.org", "pipeline"), + ] + issues = appendix_a_alignment_issues(cards, entries=bad) + assert any("Model A" in issue and "foundation model pipeline and must not map" in issue for issue in issues) + assert any("Model B" in issue and "links no documentation" in issue for issue in issues) diff --git a/tests/test_asufm.py b/tests/test_asufm.py new file mode 100644 index 00000000..90aaa4a2 --- /dev/null +++ b/tests/test_asufm.py @@ -0,0 +1,57 @@ +"""ASUFM: configurations, shapes and input validation. + +Numerical equivalence with the official fire-asufm code lives in tests/oracle/test_swin_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize("in_channels, expected", [(6, 35_047_840), (12, 35_057_056)]) +def test_asufm_parameter_counts(in_channels, expected): + # get_asfum_6_configs / get_asufm_12_configs of the official code + assert _n_params(build_model("asufm", task="segmentation", in_channels=in_channels)) == expected + + +def test_asufm_forward_shape(): + model = build_model("asufm", task="segmentation", in_channels=12).eval() + x = torch.randn(2, 12, 64, 64) + with torch.no_grad(): + out = model(x) + torch.testing.assert_close(model(x[:, None]), out) # a length-one time axis is accepted + assert out.shape == (2, 1, 64, 64) + + +def test_asufm_decoder_modulation_is_unused(): + model = build_model("asufm", task="segmentation").eval() + x = torch.randn(1, 6, 64, 64) + with torch.no_grad(): + before = model(x) + for name, param in model.named_parameters(): + if name.startswith("decoder.") and ".modulation." in name: + param.add_(1.0) + if name.startswith(("patch_embed.", "decoder.norm.")): + param.add_(1.0) + torch.testing.assert_close(model(x), before) + model.encoder.layers[0].blocks[0].modulation.proj.weight.add_(0.1) + assert not torch.allclose(model(x), before) + + +@pytest.mark.parametrize("shape", [(2, 12, 64, 64), (2, 6, 32, 32), (6, 64, 64), (2, 2, 6, 64, 64)]) +def test_asufm_bad_input_shapes_raise(shape): + model = build_model("asufm", task="segmentation", in_channels=6) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +def test_asufm_rejects_other_tasks(): + with pytest.raises(ValueError): + build_model("asufm", task="forecasting") diff --git a/tests/test_attention_unet.py b/tests/test_attention_unet.py new file mode 100644 index 00000000..f792550d --- /dev/null +++ b/tests/test_attention_unet.py @@ -0,0 +1,125 @@ +"""Attention U-Net: configurations, shapes and input validation. + +Numerical equivalence with MONAI and TS-SatFire lives in tests/oracle/test_attention_unet_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.attention_unet import AttentionUnet, TemporalAttentionUnet + +SMALL = dict(channels=(8, 16, 32)) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_ts_satfire_parameter_counts(): + with torch.device("meta"): + # Prediction model (3D, 43 channels) and the 2D detection model (8 channels). + assert _n_params(build_model("attention_unet", task="segmentation", in_channels=43)) == 94_555_506 + assert _n_params(build_model("attention_unet", task="segmentation", in_channels=8, spatial_dims=2)) == 31_743_282 + + +def test_default_strides_keep_time_and_halve_space(): + model = build_model("attention_unet", task="segmentation", in_channels=43) + assert isinstance(model, TemporalAttentionUnet) + assert model.level_strides == [(1, 2, 2)] * 4 + assert model.size_multiple() == (1, 16, 16) + model_2d = build_model("attention_unet", task="segmentation", in_channels=8, spatial_dims=2) + assert type(model_2d) is AttentionUnet + assert model_2d.level_strides == [(2, 2)] * 4 + + +def test_forward_shapes(): + model = build_model("attention_unet", task="segmentation", in_channels=4, out_channels=1, **SMALL).eval() + x = torch.randn(2, 3, 4, 16, 16) + with torch.no_grad(): + assert model(x).shape == (2, 1, 16, 16) + model.time_reduction = "none" + assert model(x).shape == (2, 1, 3, 16, 16) + model_2d = build_model("attention_unet", task="segmentation", in_channels=4, spatial_dims=2, **SMALL).eval() + with torch.no_grad(): + assert model_2d(torch.randn(2, 4, 12, 20)).shape == (2, 2, 12, 20) + + +def test_temporal_wrapper_is_the_3d_network_averaged_over_time(): + torch.manual_seed(0) + temporal = TemporalAttentionUnet(spatial_dims=3, in_channels=3, out_channels=2, strides=(1, 2, 2), stride_mode="shared", **SMALL) + plain = AttentionUnet(spatial_dims=3, in_channels=3, out_channels=2, strides=[(1, 2, 2)] * 2, **SMALL) + plain.load_state_dict(temporal.state_dict(), strict=True) + temporal.eval() + plain.eval() + x = torch.randn(2, 4, 3, 8, 8) + with torch.no_grad(): + torch.testing.assert_close(temporal(x), plain(x.transpose(1, 2)).mean(2)) + + +def test_shared_strides_equal_repeated_per_level_strides(): + torch.manual_seed(0) + shared = AttentionUnet(spatial_dims=2, in_channels=3, out_channels=1, strides=(1, 2), stride_mode="shared", **SMALL) + torch.manual_seed(0) + per_level = AttentionUnet(spatial_dims=2, in_channels=3, out_channels=1, strides=[(1, 2), (1, 2)], **SMALL) + for key, value in shared.state_dict().items(): + assert torch.equal(value, per_level.state_dict()[key]), key + x = torch.randn(2, 3, 5, 8) + shared.eval() + per_level.eval() + with torch.no_grad(): + torch.testing.assert_close(shared(x), per_level(x)) + + +def test_monai_parameter_names(): + model = AttentionUnet(spatial_dims=2, in_channels=3, out_channels=1, strides=(2, 2), **SMALL) + names = list(model.state_dict()) + assert names[:3] == ["model.0.conv.0.conv.weight", "model.0.conv.0.conv.bias", "model.0.conv.0.adn.N.weight"] + assert "model.1.attention.W_g.0.conv.weight" in names + assert "model.1.upconv.up.conv.weight" in names + assert "model.1.merge.adn.A.weight" in names # PReLU of the merge convolution + assert "model.1.submodule.1.submodule.conv.1.conv.weight" in names + assert names[-2:] == ["model.2.conv.weight", "model.2.conv.bias"] + + +@pytest.mark.parametrize( + "spatial_dims, shape", + [ + (3, (2, 4, 16, 16)), # missing time axis + (3, (2, 3, 5, 16, 16)), # wrong channel count + (3, (2, 3, 4, 14, 16)), # height not divisible by 4 + (2, (2, 4, 16)), + (2, (2, 4, 18, 16)), + ], +) +def test_bad_input_shapes_raise(spatial_dims, shape): + model = build_model("attention_unet", task="segmentation", in_channels=4, spatial_dims=spatial_dims, **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(strides=(2,)), # one stride per level is needed + dict(strides=2), # an int needs stride_mode="shared" + dict(strides=(2, 2), stride_mode="mixed"), + dict(strides=[(2, 2, 2), 2]), # stride with the wrong number of dimensions + dict(strides=(2, 2), kernel_size=4), # "same" padding needs odd kernels + dict(strides=(2, 2), channels=(8,)), + ], +) +def test_bad_configurations_raise(kwargs): + config = dict(spatial_dims=2, in_channels=3, out_channels=1, channels=(8, 16, 32)) + config.update(kwargs) + with pytest.raises(ValueError): + AttentionUnet(**config) + + +def test_builder_validates_task_and_dims(): + with pytest.raises(ValueError): + build_model("attention_unet", task="classification", in_channels=4) + with pytest.raises(ValueError): + build_model("attention_unet", task="segmentation", in_channels=4, spatial_dims=1) diff --git a/tests/test_benchmark_catalog.py b/tests/test_benchmark_catalog.py index a9907aed..08151bb0 100644 --- a/tests/test_benchmark_catalog.py +++ b/tests/test_benchmark_catalog.py @@ -37,24 +37,28 @@ def test_benchmark_page_lists_family_and_ecosystem_tables() -> None: ".. grid-item-card:: WildfireSpreadTS", ".. grid-item-card:: SeisBench", ".. grid-item-card:: pick-benchmark", - ".. grid-item-card:: pyCSEP", - ".. grid-item-card:: AEFA", ".. grid-item-card:: Caravan", - ".. grid-item-card:: WaterBench", - ".. grid-item-card:: FloodCastBench", - ".. grid-item-card:: HydroBench", - ".. grid-item-card:: TCBench Alpha", + ".. grid-item-card:: CAMELS-US", + ".. grid-item-card:: HydroGraphNet White River", + ".. grid-item-card:: SHIPS Predictors (Xu et al. 2021)", ".. grid-item-card:: IBTrACS", - ".. grid-item-card:: TropiCycloneNet-Dataset", + ".. grid-item-card:: TropiCycloneNet Dataset", ] for card in ecosystem_cards: assert page.count(card) == 1 + # TCBench is read and scored by pyhazards.forecasts (the old synthetic tcbench_alpha dataset was removed). + assert page.count(".. grid-item-card:: TCBench Alpha") == 1 + for removed in ("WaterBench", "FloodCastBench", "HydroBench"): # synthetic adapters removed + assert f".. grid-item-card:: {removed}" not in page assert "WildfireSpreadTS: A Dataset of Multi-Modal Time Series for Wildfire Spread Prediction" in page - assert "8 smoke configs | 8 models | 1 ecosystem" in page + assert "7 smoke configs | 29 models | 1 ecosystem" in page + assert "5 smoke configs | 5 models | 2 ecosystems" in page + # AEFA (earthquake-occurrence data) and pyCSEP (rate-forecast tests) are not implemented. + assert ".. grid-item-card:: pyCSEP" not in page and ".. grid-item-card:: AEFA" not in page + assert "6 smoke configs | 6 models | 3 ecosystems" in page + # FourCastNet / GraphCast / Pangu-Weather are pipelines, not models: 5 TC configs and models. assert "5 smoke configs | 5 models | 4 ecosystems" in page - assert "6 smoke configs | 6 models | 4 ecosystems" in page - assert "8 smoke configs | 8 models | 3 ecosystems" in page def test_rendered_docs_include_detail_pages_with_absolute_cross_links() -> None: diff --git a/tests/test_benchmark_runner.py b/tests/test_benchmark_runner.py index 841af664..b2737b7d 100644 --- a/tests/test_benchmark_runner.py +++ b/tests/test_benchmark_runner.py @@ -96,3 +96,21 @@ def test_experiment_config_roundtrip(tmp_path): assert loaded.model.params["out_dim"] == 5 assert loaded.report.formats == ["json", "csv"] assert loaded.seed == 7 + + +def test_benchmark_scores_in_eval_mode_and_restores_training(monkeypatch, tmp_path): + monkeypatch.setattr("pyhazards.benchmarks.registry._BENCHMARK_REGISTRY", {}) + register_benchmark("dummy_regression", DummyRegressionBenchmark) + experiment = ExperimentConfig( + benchmark=BenchmarkConfig(name="dummy_regression", hazard_task="flood.streamflow", eval_split="test"), + dataset=DatasetRef(name="unused"), + model=ModelRef(name="mlp", task="regression"), + report=ReportConfig(output_dir=str(tmp_path), formats=["json"]), + ) + model = nn.Sequential(nn.Linear(4, 32), nn.Dropout(0.9), nn.Linear(32, 1)) + model.train() + bundle = _dummy_bundle() + first = BenchmarkRunner().run(experiment, model=model, data=bundle, output_dir=str(tmp_path)) + second = BenchmarkRunner().run(experiment, model=model, data=bundle, output_dir=str(tmp_path)) + assert first.metrics["mae"] == second.metrics["mae"] + assert model.training diff --git a/tests/test_classical.py b/tests/test_classical.py new file mode 100644 index 00000000..ac9452db --- /dev/null +++ b/tests/test_classical.py @@ -0,0 +1,200 @@ +"""random_forest / xgboost: instance features, the estimator-module contract, Trainer guard, persistence. + +Equality with the official Kondylatos et al. (2022) random-forest notebook (and with xgboost's +XGBClassifier defaults) lives in tests/oracle/test_classical_oracle.py. Tests that need xgboost skip +when it is not installed (it is an optional extra). +""" + +from __future__ import annotations + +import importlib.util +import sys + +import numpy as np +import pytest +import torch +from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor +from sklearn.exceptions import NotFittedError + +from pyhazards.datasets import load_dataset +from pyhazards.engine import Trainer +from pyhazards.models import EstimatorModule, build_model, kondylatos_instance_features +from pyhazards.models.classical import KONDYLATOS_DAILY_LAYOUT, KONDYLATOS_RF_PARAMS + +needs_xgboost = pytest.mark.skipif(importlib.util.find_spec("xgboost") is None, reason="xgboost is not installed") + + +@pytest.fixture(scope="module") +def danger(): + return load_dataset("wildfire_danger_synthetic", samples=150).load() + + +@pytest.fixture(scope="module") +def fitted_forest(danger): + train = danger.get_split("train") + return build_model("random_forest", task="classification").fit(train.inputs, train.targets) + + +def test_instance_features_follow_the_notebook_order(): + daily = torch.arange(2 * 3 * 25, dtype=torch.float32).reshape(2, 3, 25) + daily[0, 0, 1] = float("nan") + features = kondylatos_instance_features(daily) + values = daily.double().numpy() + assert features.shape == (2, 35) and features.dtype == np.float64 + np.testing.assert_array_equal(features[1, :10], values[1, :, :10].mean(axis=0)) # ten-day means + assert features[0, 1] == values[0, 1:, 1].mean() # the missing day is skipped (np.nanmean) + np.testing.assert_array_equal(features[:, 10:], values[:, -1, :]) # t-1 dynamic, static, land cover + assert kondylatos_instance_features(torch.randn(4, 7, 8), n_dynamic=3, n_static=2, n_land_cover=3).shape == (4, 11) + + +def test_instance_features_validate_shape(): + with pytest.raises(ValueError, match="shape"): + kondylatos_instance_features(torch.randn(2, 10, 24)) + with pytest.raises(ValueError, match="shape"): + kondylatos_instance_features(torch.randn(2, 25)) + with pytest.raises(ValueError, match="daily_layout"): + kondylatos_instance_features(torch.randn(2, 10, 25), n_dynamic=0) + + +def test_random_forest_defaults_are_the_notebook_configuration(): + model = build_model("random_forest", task="classification") + assert isinstance(model, EstimatorModule) and isinstance(model.estimator, RandomForestClassifier) + params = model.estimator.get_params() + assert {key: params[key] for key in KONDYLATOS_RF_PARAMS} == KONDYLATOS_RF_PARAMS + assert model.daily_layout == KONDYLATOS_DAILY_LAYOUT + assert list(model.parameters()) == [] and model.state_dict() == {} + assert not model.is_fitted + + +def test_unfitted_model_raises(): + model = build_model("random_forest", task="classification") + for call in (model, model.predict_proba, model.predict): + with pytest.raises(NotFittedError, match="fit"): + call(torch.randn(2, 10, 25)) + + +def test_fit_and_forward_on_daily_tensors(danger, fitted_forest): + test = danger.get_split("test") + assert fitted_forest.is_fitted + log_probs = fitted_forest(test.inputs) + assert log_probs.shape == (len(test.targets), 2) + assert log_probs.dtype == torch.float32 and not log_probs.requires_grad + probabilities = fitted_forest.predict_proba(test.inputs) + torch.testing.assert_close(log_probs.exp(), torch.from_numpy(probabilities).float()) + np.testing.assert_array_equal(fitted_forest.predict(test.inputs), fitted_forest.estimator.classes_[probabilities.argmax(1)]) + assert fitted_forest(test.inputs.double()).dtype == torch.float64 + assert fitted_forest(test.inputs.numpy()).dtype == torch.get_default_dtype() + accuracy = (log_probs.argmax(dim=1) == test.targets).float().mean() + assert accuracy > 0.6 # the synthetic danger data carry a learnable signal + + +def test_two_dimensional_features_are_accepted(danger, fitted_forest): + test = danger.get_split("test") + features = kondylatos_instance_features(test.inputs) + np.testing.assert_array_equal(fitted_forest.predict_proba(features), fitted_forest.predict_proba(test.inputs)) + with pytest.raises(ValueError, match="35 features"): + fitted_forest(torch.randn(3, 30)) + with pytest.raises(ValueError, match="shape"): + fitted_forest(torch.randn(3, 10, 25, 1)) + no_layout = build_model("random_forest", task="classification", daily_layout=None) + with pytest.raises(ValueError, match="shape"): + no_layout.fit(torch.randn(6, 10, 25), torch.tensor([0, 1] * 3)) + + +def test_target_validation(): + model = build_model("random_forest", task="classification") + with pytest.raises(ValueError, match="shape"): + model.fit(torch.randn(6, 10, 25), torch.zeros(6, 2, dtype=torch.long)) + with pytest.raises(ValueError, match="rows"): + model.fit(torch.randn(6, 10, 25), torch.zeros(5, dtype=torch.long)) + model.fit(torch.randn(6, 10, 25), torch.tensor([[0], [1]] * 3)) # (n, 1) labels are flattened + assert model(torch.randn(2, 10, 25)).shape == (2, 2) + + +def test_regression_forest(): + model = build_model("random_forest", task="regression") + assert isinstance(model.estimator, RandomForestRegressor) + assert model.estimator.max_depth == 10 + x = torch.randn(30, 10, 25) + model.fit(x, torch.randn(30)) + assert model(x[:4]).shape == (4, 1) + model.fit(x, torch.randn(30, 2)) + assert model(x[:4]).shape == (4, 2) + with pytest.raises(ValueError, match="predict_proba"): + model.predict_proba(x[:4]) + + +def test_builder_arguments(): + with pytest.raises(ValueError, match="task"): + build_model("random_forest", task="segmentation") + model = build_model("random_forest", task="classification", n_estimators=7, n_jobs=2, class_weight="balanced") + assert (model.estimator.n_estimators, model.estimator.n_jobs, model.estimator.class_weight) == (7, 2, "balanced") + with pytest.raises(TypeError): + build_model("random_forest", task="classification", not_an_option=1) + + +def test_save_and_load_round_trip(tmp_path, danger, fitted_forest): + path = tmp_path / "forest.joblib" + fitted_forest.save(path) + loaded = EstimatorModule.load(path) + assert (loaded.name, loaded.task, loaded.daily_layout) == ("random_forest", "classification", KONDYLATOS_DAILY_LAYOUT) + test = danger.get_split("test") + np.testing.assert_array_equal(loaded.predict_proba(test.inputs), fitted_forest.predict_proba(test.inputs)) + + import joblib + + joblib.dump({"something": "else"}, tmp_path / "other.joblib") + with pytest.raises(ValueError, match="EstimatorModule.save"): + EstimatorModule.load(tmp_path / "other.joblib") + + +def test_trainer_refuses_fit_and_evaluates_fitted_model(danger, fitted_forest): + model = build_model("random_forest", task="classification") + with pytest.raises(TypeError, match=r"model\.fit\(inputs, targets\)"): + Trainer(model, device="cpu").fit(danger, optimizer=None, loss_fn=torch.nn.NLLLoss()) + trainer = Trainer(fitted_forest, device="cpu") + metrics = trainer.evaluate(danger, split="test") + assert metrics and all(np.isfinite(list(metrics.values()))) + predictions = trainer.predict(danger, split="test") + assert torch.cat(predictions).shape == (len(danger.get_split("test").targets), 2) + + +def test_estimator_module_validation(): + with pytest.raises(ValueError, match="task"): + EstimatorModule(RandomForestClassifier(), task="segmentation") + with pytest.raises(ValueError, match="predict_proba"): + EstimatorModule(RandomForestRegressor(), task="classification") + + +def test_missing_xgboost_gives_install_hint(monkeypatch): + monkeypatch.setitem(sys.modules, "xgboost", None) # makes "import xgboost" fail + with pytest.raises(ImportError, match=r"pyhazards\[xgboost\]"): + build_model("xgboost", task="classification") + + +@needs_xgboost +def test_xgboost_uses_library_defaults(danger): + import xgboost + + model = build_model("xgboost", task="classification", n_jobs=2) + assert isinstance(model.estimator, xgboost.XGBClassifier) + assert repr(build_model("xgboost", task="classification").estimator.get_params()) == repr( + xgboost.XGBClassifier().get_params() + ) + train, test = danger.get_split("train"), danger.get_split("test") + model.fit(train.inputs, train.targets) + log_probs = model(test.inputs) + assert log_probs.shape == (len(test.targets), 2) + torch.testing.assert_close(log_probs.exp().sum(dim=1), torch.ones(len(test.targets))) + with pytest.raises(TypeError, match="model.fit"): + Trainer(model, device="cpu").fit(danger) + + +@needs_xgboost +def test_xgboost_regression(): + import xgboost + + model = build_model("xgboost", task="regression", n_estimators=5, n_jobs=1) + assert isinstance(model.estimator, xgboost.XGBRegressor) + x = torch.randn(20, 10, 25) + assert model.fit(x, torch.randn(20))(x[:3]).shape == (3, 1) diff --git a/tests/test_cnn_aspp.py b/tests/test_cnn_aspp.py new file mode 100644 index 00000000..6cf0e49e --- /dev/null +++ b/tests/test_cnn_aspp.py @@ -0,0 +1,37 @@ +"""CNN-ASPP (Marjani et al., IEEE GRSL 2024), rebuilt from the paper description.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.wildfire_aspp import TverskyLoss + + +def test_cnn_aspp_matches_paper_architecture(): + model = build_model("wildfire_aspp", task="segmentation", in_channels=12) + convs = [m for m in model.modules() if isinstance(m, torch.nn.Conv2d)] + assert [c.out_channels for c in convs] == [64, 128, 32, 32, 32, 32, 32, 32, 1] + assert [c.dilation[0] for c in model.aspp.modules() if isinstance(c, torch.nn.Conv2d)] == [1, 3, 6, 12] + assert sum(p.numel() for p in model.parameters()) == 274_657 + + +def test_cnn_aspp_keeps_resolution_and_alias(): + model = build_model("wildfire_cnn_aspp", task="segmentation", in_channels=12).eval() + with torch.no_grad(): + assert model(torch.randn(2, 12, 64, 64)).shape == (2, 1, 64, 64) + with pytest.raises(ValueError): + model(torch.randn(2, 11, 64, 64)) + + +def test_tversky_weights_false_positives_with_alpha(): + targets = torch.zeros(1, 1, 2, 2) + targets[0, 0, 0, 0] = 1 + logits = torch.full((1, 1, 2, 2), -50.0) + logits[0, 0, 0, 1] = 50.0 # one false positive, one false negative, no true positive + fp_heavy = TverskyLoss(alpha=0.9, beta=0.1, smooth=0.0) + assert torch.isclose(fp_heavy(logits, targets), torch.tensor(1.0)) + logits[0, 0, 0, 0] = 50.0 # now one TP and one FP + loss = TverskyLoss(alpha=0.3, beta=0.7, smooth=0.0)(logits, targets) + assert torch.isclose(loss, torch.tensor(1 - 1 / (1 + 0.3)), atol=1e-6) diff --git a/tests/test_convgru.py b/tests/test_convgru.py new file mode 100644 index 00000000..1ea22fe2 --- /dev/null +++ b/tests/test_convgru.py @@ -0,0 +1,77 @@ +"""ConvGRU (FireCastNet's Conv-GRU baseline) without the reference code. + +The comparison with FireCastNet's ``ConvGRUSeg`` is in tests/oracle/test_convgru_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.convgru import ConvGRU, ConvGRUCell + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "kwargs, expected", + [ + ({}, 1_337_985), # configs/conv-gru-config.yaml: 11 inputs, one layer of 128, 5x5 + (dict(hidden_dim=64), 361_793), # the paper's "single hidden layer with 64 hidden units" + ], +) +def test_parameter_counts(kwargs, expected): + assert _n_params(build_model("convgru", task="segmentation", **kwargs)) == expected + + +def test_state_dict_layout(): + model = build_model("convgru", task="segmentation") + assert list(model.state_dict()) == [ + "convgru_encoder.cell_list.0.in_conv.weight", + "convgru_encoder.cell_list.0.in_conv.bias", + "convgru_encoder.cell_list.0.out_conv.weight", + "convgru_encoder.cell_list.0.out_conv.bias", + "classification_layer.weight", + "classification_layer.bias", + ] + + +def test_forward_shape_and_gradients(): + model = build_model("convgru", task="segmentation", in_channels=4, hidden_dim=8, kernel_size=3, num_layers=2) + logits = model(torch.randn(2, 5, 4, 16, 12)) + assert logits.shape == (2, 1, 16, 12) + logits.mean().backward() + assert all(p.grad is not None for p in model.parameters()) + + +def test_cell_follows_ballas_equations(): + torch.manual_seed(0) + cell = ConvGRUCell(input_dim=3, hidden_dim=4, kernel_size=3) + x, h = torch.randn(2, 3, 6, 6), torch.randn(2, 4, 6, 6) + gates = torch.sigmoid(cell.in_conv(torch.cat([x, h], 1))) + update, reset = gates[:, :4], gates[:, 4:] + candidate = torch.tanh(cell.out_conv(torch.cat([x, reset * h], 1))) + torch.testing.assert_close(cell(x, h), (1 - update) * h + update * candidate) + + +def test_encoder_returns_sequence_and_final_states(): + encoder = ConvGRU(input_dim=3, hidden_dim=[4, 5], kernel_size=[(3, 3), (1, 1)], num_layers=2) + outputs, states = encoder(torch.randn(2, 6, 3, 8, 8)) + assert outputs.shape == (2, 6, 5, 8, 8) + assert [s.shape for s in states] == [(2, 4, 8, 8), (2, 5, 8, 8)] + torch.testing.assert_close(outputs[:, -1], states[-1]) + + +def test_input_validation(): + model = build_model("convgru", task="segmentation", in_channels=3, hidden_dim=4) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(2, 3, 8, 8)) + with pytest.raises(ValueError, match="channels"): + model(torch.randn(2, 4, 5, 8, 8)) + with pytest.raises(ValueError, match="trajgru"): + build_model("convgru", task="forecasting") + with pytest.raises(ValueError, match="num_layers"): + build_model("convgru", task="segmentation", num_layers=0) diff --git a/tests/test_dataset_catalog.py b/tests/test_dataset_catalog.py index 5b39474a..8e3f16cb 100644 --- a/tests/test_dataset_catalog.py +++ b/tests/test_dataset_catalog.py @@ -40,7 +40,9 @@ def test_dataset_page_lists_curated_hazard_tabs() -> None: assert ":doc:`ERA5 `" in page assert ":doc:`WFIGS `" in page assert ":doc:`Caravan `" in page - assert ":doc:`SeisBench `" in page + assert ":doc:`SeisBench-format Waveforms `" in page + assert ":doc:`Synthetic Phase-Picking Waveforms `" in page + assert "datasets/aefa_forecast" not in page and "datasets/pick_benchmark_waveforms" not in page assert ":doc:`IBTrACS `" in page assert "Registry-loadable Datasets" in page assert "Inspection Entry Points" in page diff --git a/tests/test_deep_ensemble.py b/tests/test_deep_ensemble.py new file mode 100644 index 00000000..744abb28 --- /dev/null +++ b/tests/test_deep_ensemble.py @@ -0,0 +1,295 @@ +"""deep_ensemble: member seeding, mixture outputs per task, uncertainty terms, training helpers. + +The comparison with the reference deep ensemble of Kondylatos et al. (2025), including its ten +released members, lives in tests/oracle/test_deep_ensemble_oracle.py. The Gaussian regression path and +the FGSM helpers follow Lakshminarayanan et al. (2017), which released no code; they are checked here +against the paper's formulas. +""" + +from __future__ import annotations + +import copy + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +from pyhazards.datasets import load_dataset +from pyhazards.engine import Trainer +from pyhazards.models import DeepEnsemble, build_model +from pyhazards.models.deep_ensemble import ( + classification_uncertainties, + fgsm_example, + gaussian_nll_loss, + input_range_epsilon, + split_gaussian_output, +) + +EPS = 1e-6 + + +def _lstm_ensemble(**kwargs) -> DeepEnsemble: + return build_model("deep_ensemble", task="classification", base_model="wildfire_forecasting", **kwargs) + + +def _mlp_ensemble(task: str, out_dim: int, **kwargs) -> DeepEnsemble: + return build_model("deep_ensemble", task=task, base_model="mlp", base_kwargs={"in_dim": 3, "out_dim": out_dim, "hidden_dim": 16}, **kwargs) + + +def _close(actual, expected, **kwargs): + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6, **kwargs) + + +def test_members_equal_single_models_built_with_their_seed(): + ensemble = _lstm_ensemble(num_members=3, seeds=[5, 6, 7]) + assert ensemble.num_members == 3 and ensemble.seeds == [5, 6, 7] + for seed, member in zip(ensemble.seeds, ensemble.members): + torch.manual_seed(seed) + single = build_model("wildfire_forecasting", task="classification") + for (key, value), (other_key, other) in zip(member.state_dict().items(), single.state_dict().items()): + assert key == other_key and torch.equal(value, other) + assert not torch.equal(ensemble.members[0].fc1.weight, ensemble.members[1].fc1.weight) + default = _lstm_ensemble() + assert default.num_members == 5 and default.seeds == [0, 1, 2, 3, 4] + + +def test_builder_leaves_the_global_random_state_alone(): + torch.manual_seed(123) + expected = torch.rand(3) + torch.manual_seed(123) + _lstm_ensemble(num_members=2) + torch.testing.assert_close(torch.rand(3), expected) + + +def test_classification_mixture_and_uncertainty_terms(): + ensemble = _lstm_ensemble(num_members=4).eval() + x = torch.randn(5, 10, 25) + with torch.no_grad(): + member_probs = torch.stack([member(x).exp() for member in ensemble.members]) + log_probs = ensemble(x) + terms = ensemble.predict_uncertainty(x) + mean = member_probs.mean(dim=0) + assert log_probs.shape == (5, 2) + _close(log_probs.exp(), mean) + _close(terms["probs"], mean) + _close(terms["member_probs"], member_probs) + _close(terms["epistemic"], ((member_probs - mean) ** 2).mean(dim=0)) + _close(terms["aleatoric"], (member_probs * (1 - member_probs)).mean(dim=0)) + entropy = -(mean * torch.log(mean + EPS)).sum(dim=1) + member_entropy = -(member_probs * torch.log(member_probs + EPS)).sum(dim=2).mean(dim=0) + _close(terms["entropy"], entropy) + _close(terms["mutual_information"], entropy - member_entropy) + assert terms["entropy"].shape == terms["mutual_information"].shape == (5,) + assert (terms["mutual_information"] > -1e-5).all() + + +def test_one_member_ensemble_is_the_member(): + ensemble = _lstm_ensemble(num_members=1, seeds=[3]).eval() + torch.manual_seed(3) + single = build_model("wildfire_forecasting", task="classification").eval() + x = torch.randn(4, 10, 25) + with torch.no_grad(): + _close(ensemble(x), single(x)) + terms = ensemble.predict_uncertainty(x) + assert torch.count_nonzero(terms["epistemic"]) == 0 + _close(terms["mutual_information"], torch.zeros(4)) + + +def test_binary_segmentation_members_use_a_sigmoid(): + ensemble = build_model( + "deep_ensemble", task="segmentation", base_model="logistic_regression", base_kwargs={"in_channels": 4}, num_members=3 + ) + x = torch.randn(2, 4, 8, 8) + with torch.no_grad(): + member_probs = torch.stack([torch.sigmoid(member(x)) for member in ensemble.members]) + logits = ensemble(x) + terms = ensemble.predict_uncertainty(x) + mean = member_probs.mean(dim=0) + assert logits.shape == (2, 1, 8, 8) + _close(torch.sigmoid(logits), mean) + _close(terms["probs"], mean) + _close(terms["epistemic"], member_probs.var(dim=0, unbiased=False)) + _close(terms["aleatoric"], (member_probs * (1 - member_probs)).mean(dim=0)) + entropy = -(mean * torch.log(mean + EPS) + (1 - mean) * torch.log(1 - mean + EPS)).squeeze(1) + _close(terms["entropy"], entropy) + assert terms["mutual_information"].shape == (2, 8, 8) + + +def test_member_arguments_are_passed_through(): + ensemble = build_model("deep_ensemble", task="segmentation", base_model="utae", base_kwargs={"in_channels": 3}, num_members=2).eval() + x = torch.randn(1, 3, 3, 32, 32) + positions = torch.tensor([[10.0, 11.0, 12.0]]) + with torch.no_grad(): + out = ensemble(x, batch_positions=positions) + expected = torch.stack([torch.sigmoid(m(x, batch_positions=positions)) for m in ensemble.members]).mean(dim=0) + assert out.shape == (1, 1, 32, 32) + _close(torch.sigmoid(out), expected) + + +def test_gaussian_regression_is_the_moment_matched_mixture(): + ensemble = _mlp_ensemble("regression", out_dim=4, num_members=3) + x = torch.randn(6, 3) + with torch.no_grad(): + raw = torch.stack([member(x) for member in ensemble.members]) + mean, variance = ensemble(x) + terms = ensemble.predict_uncertainty(x) + mu, var = raw[:, :, :2], F.softplus(raw[:, :, 2:]) + 1e-6 + _close(mean, mu.mean(dim=0)) + _close(variance, (var + mu**2).mean(dim=0) - mu.mean(dim=0) ** 2) # the paper's formula + _close(terms["aleatoric"], var.mean(dim=0)) + _close(terms["epistemic"], mu.var(dim=0, unbiased=False)) + _close(terms["member_variances"], var) + assert mean.shape == variance.shape == (6, 2) + odd = _mlp_ensemble("regression", out_dim=3, num_members=2) + with pytest.raises(ValueError, match="even number"): + odd(x) + + +def test_point_regression_uses_the_member_spread(): + ensemble = _mlp_ensemble("regression", out_dim=1, num_members=3, regression_output="point") + x = torch.randn(6, 3) + with torch.no_grad(): + raw = torch.stack([member(x) for member in ensemble.members]) + mean, variance = ensemble(x) + terms = ensemble.predict_uncertainty(x) + _close(mean, raw.mean(dim=0)) + _close(variance, raw.var(dim=0, unbiased=False)) + assert "aleatoric" not in terms + + +def test_gaussian_nll_is_equation_1(): + output, target = torch.randn(8, 4), torch.randn(8, 2) + mean, variance = split_gaussian_output(output) + expected = (0.5 * torch.log(variance) + (target - mean) ** 2 / (2 * variance)).mean() + _close(gaussian_nll_loss(output, target), expected) + _close(gaussian_nll_loss(output, target), nn.GaussianNLLLoss()(mean, target, variance)) + with pytest.raises(ValueError, match="target shape"): + gaussian_nll_loss(output, torch.randn(8, 3)) + + +def test_input_range_epsilon_is_one_percent_of_each_dimension(): + x = torch.stack([torch.linspace(0, 255, 10), torch.linspace(-1, 1, 10)], dim=1) + x[3, 1] = float("nan") + epsilon = input_range_epsilon(x) + assert epsilon.shape == (1, 2) + _close(epsilon, torch.tensor([[2.55, 0.02]])) # the paper's example: 2.55 for inputs in [0, 255] + sequence = torch.randn(5, 4, 3) + per_feature = input_range_epsilon(sequence, dims=(0, 1)) + assert per_feature.shape == (1, 1, 3) + _close(per_feature.flatten(), 0.01 * (sequence.amax(dim=(0, 1)) - sequence.amin(dim=(0, 1)))) + + +def test_fgsm_example_steps_along_the_gradient_sign(): + model = nn.Linear(3, 2) + x, y = torch.randn(4, 3), torch.tensor([0, 1, 1, 0]) + loss_fn = nn.CrossEntropyLoss() + epsilon = torch.tensor([0.1, 0.2, 0.3]) + adversarial = fgsm_example(model, x, y, loss_fn, epsilon) + assert model.weight.grad is None and not adversarial.requires_grad # only the input gradient + probe = x.clone().requires_grad_(True) + loss_fn(model(probe), y).backward() + _close(adversarial, x + epsilon * probe.grad.sign()) + + +def _toy_classification(): + generator = torch.Generator().manual_seed(0) + x = torch.randn(60, 3, generator=generator) + return x, (x[:, 0] > 0).long() + + +def _fit(ensemble, x, y, **kwargs): + return ensemble.fit( + x, + y, + loss_fn=nn.CrossEntropyLoss(), + optimizer_factory=lambda params: torch.optim.SGD(params, lr=0.3), + epochs=15, + batch_size=10, + **kwargs, + ) + + +def test_fit_trains_each_member_independently(): + x, y = _toy_classification() + ensemble = _mlp_ensemble("classification", out_dim=2, num_members=2, seeds=[4, 9]) + first_member = copy.deepcopy(ensemble.members[0]) + _fit(ensemble, x, y) + with torch.no_grad(): + accuracy = (ensemble(x).argmax(dim=1) == y).float().mean() + assert accuracy > 0.9 + # Member 0 trained alone, with its own seed, ends up the same: members do not interact. + alone = _fit(DeepEnsemble([first_member], task="classification", seeds=[4]), x, y) + for value, other in zip(ensemble.members[0].state_dict().values(), alone.members[0].state_dict().values()): + assert torch.equal(value, other) + + +def test_fit_with_adversarial_examples(): + x, y = _toy_classification() + plain = _fit(_mlp_ensemble("classification", out_dim=2, num_members=2), x, y) + adversarial = _fit(_mlp_ensemble("classification", out_dim=2, num_members=2), x, y, adversarial_epsilon=input_range_epsilon(x)) + plain_state, adversarial_state = plain.members[0].state_dict(), adversarial.members[0].state_dict() + assert any(not torch.equal(plain_state[key], adversarial_state[key]) for key in plain_state) + with torch.no_grad(): + assert (adversarial(x).argmax(dim=1) == y).float().mean() > 0.9 + with pytest.raises(ValueError, match="length"): + _fit(_mlp_ensemble("classification", out_dim=2, num_members=1), x, y[:-1]) + + +def test_mc_dropout_passes_pool_stochastic_samples(): + ensemble = _lstm_ensemble(num_members=2, mc_dropout_passes=4).eval() + x = torch.randn(3, 10, 25) + with torch.no_grad(): + terms = ensemble.predict_uncertainty(x) + assert terms["member_probs"].shape == (8, 3, 2) + assert not torch.equal(terms["member_probs"][0], terms["member_probs"][1]) + assert not any(module.training for module in ensemble.modules()) + deterministic = _lstm_ensemble(num_members=2).eval() + with torch.no_grad(): + torch.testing.assert_close(deterministic(x), deterministic(x), rtol=0, atol=0) + + +def test_trainer_refuses_fit_and_evaluates_the_ensemble(): + bundle = load_dataset("wildfire_danger_synthetic", micro=True).load() + ensemble = _lstm_ensemble(num_members=2) + with pytest.raises(TypeError, match="independently"): + Trainer(ensemble, device="cpu").fit( + bundle, optimizer=torch.optim.Adam(ensemble.parameters()), loss_fn=nn.NLLLoss() + ) + assert Trainer(ensemble, device="cpu").evaluate(bundle, split="test") + + +def test_invalid_arguments(): + with pytest.raises(ValueError, match="base_model"): + build_model("deep_ensemble", task="classification") + with pytest.raises(ValueError, match="itself"): + build_model("deep_ensemble", task="classification", base_model="deep_ensemble") + with pytest.raises(KeyError): + build_model("deep_ensemble", task="classification", base_model="no_such_model") + with pytest.raises(ValueError, match="distinct"): + _lstm_ensemble(num_members=2, seeds=[1, 1]) + with pytest.raises(ValueError, match="distinct"): + _lstm_ensemble(num_members=3, seeds=[1, 2]) + with pytest.raises(ValueError, match="num_members"): + _lstm_ensemble(num_members=0) + with pytest.raises(TypeError, match="base_kwargs"): + _lstm_ensemble(hidden_size=128) + with pytest.raises(ValueError, match="regression_output"): + _lstm_ensemble(regression_output="quantile") + with pytest.raises(ValueError, match="mc_dropout_passes"): + _lstm_ensemble(mc_dropout_passes=-1) + with pytest.raises(ValueError, match="task"): + DeepEnsemble([nn.Linear(2, 2)], task="detection") + + +def test_members_must_return_one_tensor_with_channels(): + class Pair(nn.Module): + def forward(self, x): + return x, x + + with pytest.raises(ValueError, match="one tensor"): + DeepEnsemble([Pair()])(torch.randn(2, 3)) + with pytest.raises(ValueError, match="shape"): + DeepEnsemble([nn.Identity()])(torch.randn(4)) + with pytest.raises(ValueError, match="shape"): + classification_uncertainties(torch.rand(3, 4)) diff --git a/tests/test_deeplabv3.py b/tests/test_deeplabv3.py new file mode 100644 index 00000000..3bf1265b --- /dev/null +++ b/tests/test_deeplabv3.py @@ -0,0 +1,56 @@ +"""DeepLabV3 (smp port) in Shadrin et al.'s configuration; the oracle test compares it with smp.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.deeplabv3 import DeepLabV3 + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_deeplabv3_shadrin_defaults(): + model = build_model("deeplabv3", task="segmentation") + assert model.in_channels == 58 + assert _n_params(model) == 13_220_609 + assert model.encoder.output_stride == 8 + model.eval() + with torch.no_grad(): + assert model(torch.randn(2, 58, 32, 32)).shape == (2, 1, 32, 32) + aspp_rates = [m.dilation[0] for m in model.decoder[0].convs.modules() if isinstance(m, torch.nn.Conv2d) and m.kernel_size == (3, 3)] + assert aspp_rates == [12, 24, 36] + + +def test_deeplabv3_dilates_last_stages_like_smp(): + model = DeepLabV3(in_channels=3) + assert _n_params(model) == 26_007_105 # smp.DeepLabV3() defaults: ResNet-34, five stages + for layer, rate in ((model.encoder.layer3, 2), (model.encoder.layer4, 4)): + for conv in (m for m in layer.modules() if isinstance(m, torch.nn.Conv2d)): + assert conv.stride == (1, 1) and conv.dilation == (rate, rate) + assert conv.padding == ((conv.kernel_size[0] // 2) * rate,) * 2 + assert model.encoder.layer2[0].conv1.stride == (2, 2) + model.eval() + with torch.no_grad(): + assert model(torch.randn(1, 3, 64, 48)).shape == (1, 1, 64, 48) + + +def test_deeplabv3_validation(): + model = build_model("deeplabv3", task="segmentation", in_channels=4) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(2, 1, 4, 32, 32)) + with pytest.raises(ValueError, match="channels"): + model(torch.randn(2, 5, 32, 32)) + with pytest.raises(ValueError, match="divisible"): + model(torch.randn(2, 4, 36, 32)) + with pytest.raises(ValueError): + DeepLabV3(encoder_depth=2) + with pytest.raises(ValueError): + DeepLabV3(encoder_name="resnet50") + with pytest.raises(ValueError): + DeepLabV3(encoder_weights="ssl") + with pytest.raises(ValueError): + build_model("deeplabv3", task="classification") diff --git a/tests/test_earthfarseer.py b/tests/test_earthfarseer.py new file mode 100644 index 00000000..9f9a07a4 --- /dev/null +++ b/tests/test_earthfarseer.py @@ -0,0 +1,111 @@ +"""Earthfarseer: parameter counts, shapes, the segmentation adaptation and input validation. + +Numerical equivalence with the official code lives in tests/oracle/test_earthfarseer_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.earthfarseer import Earthfarseer + +# Small enough for CPU tests (the fixed-size SimVP skip branch still has 13.9M parameters). +SMALL = dict(history=3, img_size=32, hid_S=8, hid_T=16, N_S=4, N_T=2, gf_embed_dim=32, gf_depth=1) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_earthfarseer_default_parameter_count(): + with torch.device("meta"): + model = build_model("earthfarseer", task="forecasting") + assert model.shape_in == (10, 1, 64, 64) + assert _n_params(model) == 157_518_863 # official Earthfarseer_model(shape_in=(10, 1, 64, 64)) + parts = {name: _n_params(child) for name, child in model.named_children()} + assert parts == { + "fotf_encoder": 78_246_509, + "skip_conneciton": 13_866_401, + "latent_projection": 7_088_640, + "enc": 7_088_640, + "TeDev_block": 39_425_536, + "dec": 11_803_137, + } + + +def test_earthfarseer_forecasting_shapes(): + model = build_model("earthfarseer", task="forecasting", in_channels=2, **SMALL).eval() + x = torch.randn(2, 3, 2, 32, 32) + with torch.no_grad(): + assert model(x).shape == (2, 3, 2, 32, 32) + + +def test_earthfarseer_segmentation_adaptation_keeps_reference_names(): + torch.manual_seed(0) + core = build_model("earthfarseer", task="forecasting", in_channels=2, **SMALL) + torch.manual_seed(0) + seg = build_model("earthfarseer", task="segmentation", in_channels=2, **SMALL) + core_state, seg_state = core.state_dict(), seg.state_dict() + assert list(seg_state) == list(core_state) + ["segmentation_head.weight", "segmentation_head.bias"] + for key, value in core_state.items(): + assert torch.equal(value, seg_state[key]), key + + core.eval() + seg.eval() + x = torch.randn(2, 3, 2, 32, 32) + with torch.no_grad(): + logits = seg(x) + torch.testing.assert_close(logits, seg.segmentation_head(core(x)[:, 0])) + assert logits.shape == (2, 1, 32, 32) + + +def test_earthfarseer_unused_reference_modules_get_no_gradient(): + model = build_model("earthfarseer", task="forecasting", **SMALL) + model(torch.randn(1, 3, 1, 32, 32)).sum().backward() + assert all(p.grad is None for p in model.enc.parameters()) # second encoder, never called + assert model.fotf_encoder.gf_block.blocks[0].mlp.fc2.weight.grad is None # replaced by avg pool + assert model.fotf_encoder.gf_block.blocks[0].mlp.fc1.weight.grad is not None + + +def test_earthfarseer_runs_where_the_reference_token_grid_formula_fails(): + # The reference sizes the TeDev grid as int(H / 4) + 1 when H % 3 == 0 (48 -> 13, latent 12) + # and only supports square inputs; the port uses the true latent size. + model = build_model("earthfarseer", task="forecasting", **{**SMALL, "img_size": 48}).eval() + assert (model.H1, model.W1) == (12, 12) + rect = build_model("earthfarseer", task="forecasting", **{**SMALL, "img_size": (32, 48)}).eval() + with torch.no_grad(): + assert model(torch.randn(1, 3, 1, 48, 48)).shape == (1, 3, 1, 48, 48) + assert rect(torch.randn(1, 3, 1, 32, 48)).shape == (1, 3, 1, 32, 48) + + +@pytest.mark.parametrize("shape", [(1, 3, 1, 32, 48), (1, 4, 1, 32, 32), (1, 3, 2, 32, 32), (3, 1, 32, 32)]) +def test_earthfarseer_bad_input_shapes_raise(shape): + model = build_model("earthfarseer", task="forecasting", **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "overrides", [dict(img_size=40), dict(img_size=(32, 24)), dict(N_T=1), dict(N_S=0), dict(history=0)] +) +def test_earthfarseer_rejects_unsupported_configurations(overrides): + with pytest.raises(ValueError): + build_model("earthfarseer", task="forecasting", **{**SMALL, **overrides}) + + +def test_earthfarseer_rejects_unknown_task(): + with pytest.raises(ValueError): + build_model("earthfarseer", task="classification", **SMALL) + + +def test_earthfarseer_class_defaults_are_the_official_defaults(): + with torch.device("meta"): + model = Earthfarseer() + assert model.shape_in == (10, 1, 64, 64) + assert len(model.TeDev_block.enc) == len(model.TeDev_block.dec) == 8 + assert len(model.TeDev_block.blocks) == 12 + assert len(model.fotf_encoder.gf_block.blocks) == 12 + assert model.fotf_encoder.gf_block.embed_dim == 768 + assert model.fotf_encoder.num_interactions == 3 diff --git a/tests/test_earthformer.py b/tests/test_earthformer.py new file mode 100644 index 00000000..6b227ba2 --- /dev/null +++ b/tests/test_earthformer.py @@ -0,0 +1,173 @@ +"""Earthformer: presets, parameter counts, shapes, layouts and input validation. + +Numerical equivalence with the official code and checkpoints lives in +tests/oracle/test_earthformer_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.earthformer import ( + EARTHFORMER_CONFIGS, + CuboidTransformerModel, + Earthformer, + EarthformerSegmenter, + earthformer_config, +) + +SMALL = dict(history=4, in_channels=3, img_size=24) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _count(config: str, **overrides) -> int: + with torch.device("meta"): + return _n_params(build_model("earthformer", task="forecasting", config=config, **overrides)) + + +@pytest.mark.parametrize( + "config, expected", + [("sevir", 8_659_677), ("sevir_lr", 1_505_069), ("moving_mnist", 6_702_109), ("nbody", 6_702_109), ("enso", 1_394_325)], +) +def test_official_config_parameter_counts(config, expected): + assert _count(config) == expected + + +PAPER_GLOBAL = dict( + num_global_vectors=8, + use_dec_self_global=False, + use_dec_cross_global=False, + use_global_vector_ffn=False, + use_global_self_attn=False, + separate_global_qkv=False, +) + + +def test_paper_parameter_counts(): + # Earthformer paper Tables 4-7: 15.1M / 13.1M (SEVIR), 7.61M / 6.61M (Moving-MNIST), 7.6M / 6.6M (ENSO). + assert _count("sevir", enc_depth=[2, 2], dec_depth=[2, 2], **PAPER_GLOBAL) == 15_082_069 + assert _count("sevir", enc_depth=[2, 2], dec_depth=[2, 2], num_global_vectors=0) == 13_075_029 + assert _count("moving_mnist", pos_embed_type="t+h+w", **PAPER_GLOBAL) == 7_610_781 + assert _count("moving_mnist", pos_embed_type="t+h+w") == 6_611_997 + assert _count("enso", enc_depth=[4, 4], dec_depth=[4, 4], **PAPER_GLOBAL) == 7_600_077 + assert _count("enso", enc_depth=[4, 4], dec_depth=[4, 4]) == 6_601_293 + + +def test_default_build_is_the_released_sevir_model(): + with torch.device("meta"): + model = build_model("earthformer", task="forecasting") + assert isinstance(model, Earthformer) + assert model.input_shape == (13, 384, 384, 1) + assert model.target_shape == (12, 384, 384, 1) + assert model.input_shape_after_initial_downsample == (13, 32, 32, 128) + assert model.encoder.get_mem_shapes() == [(13, 32, 32, 128), (13, 16, 16, 256)] + assert _n_params(model) == 8_659_677 + + +def test_config_expands_patterns_like_the_training_scripts(): + kwargs = earthformer_config("sevir") + assert kwargs["enc_attn_patterns"] == ["axial", "axial"] + assert kwargs["dec_self_attn_patterns"] == ["axial", "axial"] + assert kwargs["dec_cross_attn_patterns"] == ["cross_1x1", "cross_1x1"] + assert "self_pattern" not in kwargs + kwargs = earthformer_config("moving_mnist", self_pattern="video_swin_2x8", enc_attn_patterns=["full", "axial"]) + assert kwargs["enc_attn_patterns"] == ["full", "axial"] + assert kwargs["dec_self_attn_patterns"] == ["axial", "axial"] + assert EARTHFORMER_CONFIGS["nbody"] == EARTHFORMER_CONFIGS["moving_mnist"] + + +def test_forecasting_shapes(): + model = build_model("earthformer", task="forecasting", horizon=2, out_channels=2, **SMALL).eval() + with torch.no_grad(): + assert model(torch.randn(2, 4, 3, 24, 24)).shape == (2, 2, 2, 24, 24) + # Sizes that the 12x initial down-sampling does not divide are padded inside the patch merging. + model = build_model("earthformer", task="forecasting", history=3, img_size=(26, 31)).eval() + with torch.no_grad(): + assert model(torch.randn(1, 3, 1, 26, 31)).shape == (1, 12, 1, 26, 31) + model = build_model("earthformer", task="forecasting", config="moving_mnist", img_size=16, history=3, horizon=2).eval() + with torch.no_grad(): + assert model(torch.randn(2, 3, 1, 16, 16)).shape == (2, 2, 1, 16, 16) + + +def test_segmentation_returns_one_mask_logit_map(): + model = build_model("earthformer", task="segmentation", **SMALL) + assert isinstance(model, EarthformerSegmenter) + assert model.target_shape == (1, 24, 24, 1) + model.eval() + with torch.no_grad(): + assert model(torch.randn(2, 4, 3, 24, 24)).shape == (2, 1, 24, 24) + model.train() + loss = model(torch.randn(2, 4, 3, 24, 24)).square().mean() + loss.backward() + assert model.encoder.blocks[0][0].attn_l[0].qkv.weight.grad is not None + + +def test_wrappers_keep_core_parameter_names_and_layout(): + torch.manual_seed(0) + kwargs = earthformer_config("sevir", input_shape=[4, 24, 24, 3], target_shape=[2, 24, 24, 2]) + core = CuboidTransformerModel(**kwargs) + torch.manual_seed(0) + wrapped = Earthformer(**kwargs) + assert list(core.state_dict()) == list(wrapped.state_dict()) + for key, value in core.state_dict().items(): + assert torch.equal(value, wrapped.state_dict()[key]), key + core.eval() + wrapped.eval() + x = torch.randn(2, 4, 3, 24, 24) + with torch.no_grad(): + expected = core(x.permute(0, 1, 3, 4, 2)).permute(0, 1, 4, 2, 3) + torch.testing.assert_close(wrapped(x), expected) + + segmenter = build_model("earthformer", task="segmentation", **SMALL) + reference = CuboidTransformerModel(**earthformer_config("sevir", input_shape=[4, 24, 24, 3], target_shape=[1, 24, 24, 1])) + assert list(segmenter.state_dict()) == list(reference.state_dict()) + + +def test_local_state_dict_loads_strictly(tmp_path): + torch.manual_seed(0) + source = build_model("earthformer", task="forecasting", **SMALL) + path = tmp_path / "earthformer.pt" + torch.save(source.state_dict(), path) + torch.manual_seed(1) + loaded = build_model("earthformer", task="forecasting", pretrained=path, **SMALL) + for key, value in source.state_dict().items(): + assert torch.equal(value, loaded.state_dict()[key]), key + + +def test_input_validation(): + model = build_model("earthformer", task="forecasting", **SMALL) + with pytest.raises(ValueError, match=r"\(batch, time, channels, height, width\)"): + model(torch.randn(2, 4, 24, 24, 3)) # channels-last input + with pytest.raises(ValueError, match="shape"): + model(torch.randn(4, 3, 24, 24)) + with pytest.raises(ValueError, match="shape"): + CuboidTransformerModel.forward(model, torch.randn(2, 4, 3, 24, 24)) # the core takes (B, T, H, W, C) + + +def test_builder_validation(): + with pytest.raises(ValueError, match="task"): + build_model("earthformer", task="classification") + with pytest.raises(ValueError, match="config"): + build_model("earthformer", task="forecasting", config="sevir_v2") + with pytest.raises(ValueError, match="Unknown Earthformer arguments"): + build_model("earthformer", task="forecasting", base_unit=64) + with pytest.raises(ValueError, match="input_shape"): + build_model("earthformer", task="forecasting", input_shape=[13, 384, 384, 1]) + with pytest.raises(ValueError, match="one frame"): + build_model("earthformer", task="segmentation", horizon=2) + with pytest.raises(ValueError, match="positive"): + build_model("earthformer", task="forecasting", history=0) + with pytest.raises(ValueError, match="pattern"): + build_model("earthformer", task="forecasting", self_pattern="diagonal", **SMALL) + # Official checkpoints only fit their own configuration (checked before any download). + with pytest.raises(ValueError, match="checkpoint"): + build_model("earthformer", task="forecasting", pretrained="sevir", **SMALL) + with pytest.raises(ValueError, match="checkpoint"): + build_model("earthformer", task="segmentation", pretrained="sevir") + with pytest.raises(ValueError, match="checkpoint"): + build_model("earthformer", task="forecasting", config="moving_mnist", pretrained="icarenso2021") diff --git a/tests/test_earthquake_benchmarks.py b/tests/test_earthquake_benchmarks.py index ca4abca1..08f54233 100644 --- a/tests/test_earthquake_benchmarks.py +++ b/tests/test_earthquake_benchmarks.py @@ -1,5 +1,15 @@ +import math + +import pytest +import torch +import torch.nn as nn + +from pyhazards.benchmarks import run_benchmark from pyhazards.configs import load_experiment_config +from pyhazards.datasets import load_dataset +from pyhazards.datasets.base import DataBundle, DataSplit, FeatureSpec, LabelSpec from pyhazards.engine.runner import BenchmarkRunner +from pyhazards.models import build_model def test_earthquake_vertical_slice(tmp_path): @@ -8,13 +18,173 @@ def test_earthquake_vertical_slice(tmp_path): assert summary.benchmark_name == "earthquake" assert summary.hazard_task == "earthquake.picking" - assert "p_pick_mae" in summary.metrics - assert "json" in summary.report_paths + for key in ("p_precision", "p_recall", "p_f1", "s_f1", "p_pick_mae", "p_residual_mean", "s_residual_std"): + assert key in summary.metrics + assert "json" in summary.report_paths and "pick_counts" in summary.report_paths + assert summary.metadata["protocol"] == "phasenet" -def test_earthquake_forecasting_exports_pycsep_style_report(tmp_path): +def test_earthquake_forecasting_reports_the_wavecastnet_metrics(tmp_path): config = load_experiment_config("pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml") summary = BenchmarkRunner().run(config, output_dir=str(tmp_path)) assert summary.hazard_task == "earthquake.forecasting" - assert "pycsep" in summary.report_paths + expected = {"acc", "rfne", "rmse", "mae", "mse"} | {f"{m}_{c}" for m in ("acc", "rfne") for c in "xyz"} + assert set(summary.metrics) == expected + assert "pycsep" not in summary.report_paths # the mislabelled "pyCSEP-style" export was removed + # WaveCastNet's decoder starts from noise; the benchmark draws it from a generator seeded by `seed`. + model = build_model(config.model.name, task=config.model.task, **config.model.params) + first = BenchmarkRunner().run(config, model=model, output_dir=str(tmp_path)) + assert BenchmarkRunner().run(config, model=model, output_dir=str(tmp_path)).metrics == first.metrics + config.benchmark.params = {**config.benchmark.params, "seed": 1} + assert BenchmarkRunner().run(config, model=model, output_dir=str(tmp_path)).metrics != first.metrics + + +class _Persistence(nn.Module): + """Repeats the last input frame (a forecast without ``rollout``).""" + + def __init__(self, steps): + super().__init__() + self.steps = steps + + def forward(self, x): + return x[:, :, -1:].expand(-1, -1, self.steps, -1, -1) + + +def _wavefield_bundle(targets, inputs=None): + inputs = targets[:, :, :1] if inputs is None else inputs + split = DataSplit(inputs, targets) + return DataBundle( + splits={"train": split, "val": split, "test": split}, + feature_spec=FeatureSpec(channels=targets.shape[1]), + label_spec=LabelSpec(num_targets=1, task_type="regression"), + metadata={"dataset": "fixture", "channel_names": ["e", "n"]}, + ) + + +def test_forecasting_metrics_follow_the_official_definitions(tmp_path): + config = load_experiment_config("pyhazards/configs/earthquake/wavecastnet_benchmark_smoke.yaml") + targets = torch.randn(3, 2, 4, 4, 4) + perfect = _wavefield_bundle(targets, inputs=targets[:, :, -1:].clone()) + constant = targets[:, :, -1:].expand(-1, -1, 4, -1, -1).clone() + summary = run_benchmark("earthquake", _Persistence(4), _wavefield_bundle(constant, constant[:, :, :1]), config, output_dir=str(tmp_path)) + assert summary.metrics["acc"] == pytest.approx(1.0) and summary.metrics["rfne"] == pytest.approx(0.0, abs=1e-6) + assert {"acc_e", "rfne_n"} <= set(summary.metrics) + flipped = _wavefield_bundle(-constant, constant[:, :, :1]) + summary = run_benchmark("earthquake", _Persistence(4), flipped, config, output_dir=str(tmp_path)) + assert summary.metrics["acc"] == pytest.approx(-1.0) and summary.metrics["rfne"] == pytest.approx(2.0) + with pytest.raises(ValueError, match="forecast has shape"): + run_benchmark("earthquake", _Persistence(2), perfect, config, output_dir=str(tmp_path)) + + +class _OraclePicker(nn.Module): + """Returns Gaussian probability peaks at the true arrivals shifted by ``shift`` samples.""" + + sampling_rate = 100.0 + component_order = "ENZ" + phase_channels = {"P": 1, "S": 2} + + def __init__(self, targets, shift=0.0, with_detection=False): + super().__init__() + self.targets = targets + self.shift = shift + self.seen = [] + if with_detection: + self.extract_detections = self._detections + + def forward(self, x): + self.seen.append(x) + n, _, length = x.shape + index = torch.arange(length, dtype=torch.float32) + rows = self.targets[len(torch.cat(self.seen)) - n : len(torch.cat(self.seen))] + out = torch.zeros(n, 3, length) + for i, (p, s) in enumerate(rows.tolist()): + for channel, arrival in ((1, p), (2, s)): + if not math.isnan(arrival): + out[i, channel] = 0.9 * torch.exp(-0.5 * ((index - arrival - self.shift) / 5.0) ** 2) + return out + + def _detections(self, annotations, **kwargs): + return [[(0, 10, 0.9)] if bool(trace[1:].max() > 0.5) else [] for trace in annotations] + + +def _bundle(targets, length=3000, order="ZNE", rate=100.0): + x = torch.arange(3.0).view(1, 3, 1).expand(len(targets), 3, length).clone() + split = DataSplit(x, targets) + return DataBundle( + splits={"train": split, "val": split, "test": split}, + feature_spec=FeatureSpec(channels=3), + label_spec=LabelSpec(num_targets=2, task_type="picking"), + metadata={"dataset": "fixture", "sampling_rate": rate, "component_order": order}, + ) + + +def _run(model, data, tmp_path, **params): + config = load_experiment_config("pyhazards/configs/earthquake/phasenet_smoke.yaml") + config.benchmark.params = params + return run_benchmark("earthquake", model, data, config, output_dir=str(tmp_path)) + + +TARGETS = torch.tensor([[500.0, 1500.0], [800.0, 1200.0], [float("nan"), float("nan")], [700.0, float("nan")]]) + + +def test_perfect_picks_score_one_and_channels_are_reordered(tmp_path): + model = _OraclePicker(TARGETS) + summary = _run(model, _bundle(TARGETS), tmp_path, batch_size=3) + assert summary.metrics["p_precision"] == summary.metrics["p_recall"] == summary.metrics["p_f1"] == 1.0 + assert summary.metrics["s_f1"] == 1.0 + assert summary.metrics["p_pick_mae"] == 0.0 and summary.metrics["p_residual_std"] == 0.0 + assert summary.metadata["pick_counts"]["S"] == {"manual": 2, "predicted": 2, "true_positive": 2} + seen = torch.cat(model.seen) + assert seen[0, :, 0].tolist() == [2.0, 1.0, 0.0] # dataset Z, N, E -> model E, N, Z + assert "detection_f1" not in summary.metrics + + +def test_tolerance_windows_follow_the_protocols(tmp_path): + late = _OraclePicker(TARGETS, shift=20.0) # 0.2 s late + strict = _run(late, _bundle(TARGETS), tmp_path, protocol="phasenet") + assert strict.metrics["p_precision"] == 0.0 and strict.metrics["p_recall"] == 0.0 + assert strict.metrics["p_residual_mean"] == pytest.approx(0.2) # residuals within 0.5 s are kept + late.seen.clear() + loose = _run(late, _bundle(TARGETS), tmp_path, protocol="eqtransformer") + assert loose.metrics["p_f1"] == 1.0 and loose.metrics["p_pick_mae"] == pytest.approx(0.2) + late.seen.clear() + custom = _run(late, _bundle(TARGETS), tmp_path, tolerance_s=0.25, residual_window_s=0.1) + assert custom.metrics["p_f1"] == 1.0 and math.isnan(custom.metrics["p_pick_mae"]) + + +def test_detection_metrics_and_regression_outputs(tmp_path): + model = _OraclePicker(TARGETS, with_detection=True) + summary = _run(model, _bundle(TARGETS), tmp_path) + assert summary.metrics["detection_precision"] == summary.metrics["detection_recall"] == 1.0 + + class Regressor(nn.Module): + def forward(self, x): + return TARGETS[: len(x)].nan_to_num(0.0) + 3.0 + + summary = _run(Regressor(), _bundle(TARGETS), tmp_path) + assert summary.metadata["pick_counts"]["P"] == {"manual": 3, "predicted": 4, "true_positive": 3} + assert summary.metrics["p_precision"] == pytest.approx(0.75) and summary.metrics["p_recall"] == 1.0 + + +def test_picking_input_checks(tmp_path): + with pytest.raises(ValueError, match="Hz"): + _run(_OraclePicker(TARGETS), _bundle(TARGETS, rate=50.0), tmp_path) + with pytest.raises(ValueError, match="protocol"): + _run(_OraclePicker(TARGETS), _bundle(TARGETS), tmp_path, protocol="unknown") + + class Bad(nn.Module): + def forward(self, x): + return x.mean(dim=(1, 2)) + + with pytest.raises(ValueError, match="probabilities"): + _run(Bad(), _bundle(TARGETS), tmp_path) + + +def test_synthetic_dataset_runs_through_the_picking_benchmark(tmp_path): + data = load_dataset("earthquake_waveforms_synthetic", micro=True).load() + test = data.get_split("test") + model = _OraclePicker(test.targets) + model.component_order = "ZNE" + summary = _run(model, data, tmp_path) + assert summary.metrics["p_f1"] == 1.0 diff --git a/tests/test_earthquake_breadth.py b/tests/test_earthquake_breadth.py index 96487397..26348234 100644 --- a/tests/test_earthquake_breadth.py +++ b/tests/test_earthquake_breadth.py @@ -5,12 +5,16 @@ from pyhazards.models import build_model -def test_additional_earthquake_picking_models_forward(): - x = torch.randn(3, 3, 256) - for name in ["eqtransformer", "gpd", "eqnet"]: - model = build_model(name=name, task="regression", in_channels=3) - preds = model(x) - assert preds.shape == (3, 2) +def test_earthquake_models_follow_their_original_contracts(): + with torch.no_grad(): + assert build_model("phasenet", task="picking").eval()(torch.randn(2, 3, 3001)).shape == (2, 3, 3001) + assert build_model("eqtransformer", task="picking").eval()(torch.randn(1, 3, 6000)).shape == (1, 3, 6000) + assert build_model("gpd", task="classification").eval()(torch.randn(2, 3, 400)).shape == (2, 3) + eqnet = build_model("eqnet", task="picking").eval() + assert eqnet(torch.randn(2, 4, 3, 3072))["phase"].shape == (2, 4, 2, 1536) + assert eqnet.annotate(torch.randn(3, 3, 3072)).shape == (3, 2, 1536) + wavecastnet = build_model("wavecastnet", task="forecasting", height=16, width=16, future_seq=3).eval() + assert wavecastnet(torch.randn(1, 3, 4, 16, 16)).shape == (1, 3, 3, 16, 16) def test_earthquake_breadth_configs(tmp_path): @@ -24,7 +28,8 @@ def test_earthquake_breadth_configs(tmp_path): output_dir=str(tmp_path), ) assert summary.hazard_task == "earthquake.picking" - assert "f1" in summary.metrics + assert "p_f1" in summary.metrics and "s_pick_mae" in summary.metrics + assert summary.metadata["protocol"] == "eqtransformer" def test_wavecastnet_forecasting_benchmark(tmp_path): @@ -33,5 +38,6 @@ def test_wavecastnet_forecasting_benchmark(tmp_path): assert summary.benchmark_name == "earthquake" assert summary.hazard_task == "earthquake.forecasting" - assert "mae" in summary.metrics - assert "mse" in summary.metrics + for key in ("acc", "rfne", "rmse", "acc_x", "rfne_z", "mae", "mse"): + assert key in summary.metrics + assert summary.metadata["synthetic_data"] and summary.metadata["forecast_steps"] == 6 diff --git a/tests/test_eqnet.py b/tests/test_eqnet.py new file mode 100644 index 00000000..09398490 --- /dev/null +++ b/tests/test_eqnet.py @@ -0,0 +1,160 @@ +import math + +import pytest +import torch +import torch.nn.functional as F + +from pyhazards.models import build_model +from pyhazards.models.eqnet import ( + EQNet, + EQNetLoss, + eqnet_candidate_grid, + eqnet_travel_times, + geometric_median, + shift_and_stack, +) + +RATE = 100.0 / 32 # feature samples per second at 100 Hz + + +def _count(module): + return sum(p.numel() for p in module.parameters()) + + +def test_parameter_counts_follow_figure_3(): + model = EQNet() + assert _count(model) == 1_043_619 + assert {name: _count(m) for name, m in model.named_children()} == { + "backbone": 996_960, + "p_picker": 7_825, + "s_picker": 7_825, + "event_detector": 31_009, + } + assert model.backbone.conv1.weight.shape == (32, 3, 7) + assert model.backbone.conv2.weight.shape == (128, 256, 1) + assert model.p_picker.conv1.weight.shape == (32, 64, 3) and model.p_picker.conv_out.bias is not None + assert model.event_detector.conv1.weight.shape == (64, 128, 3) + + +def test_multi_station_contract_and_single_station_annotation(): + torch.manual_seed(0) + model = build_model("eqnet", task="detection").eval() + waveforms = torch.randn(2, 4, 3, 1024) + travel_times = torch.rand(2, 4, 7, 2) * 5 + with torch.no_grad(): + out = model(waveforms, travel_times) + assert out["phase"].shape == (2, 4, 2, 512) and out["event"].shape == (2, 7, 32) + assert 0 <= float(out["phase"].min()) and float(out["phase"].max()) <= 1 + logits = model(waveforms, travel_times, logits=True) + torch.testing.assert_close(torch.sigmoid(logits["event"]), out["event"]) + assert set(model(waveforms)) == {"phase"} + # Candidates are chunked in evaluation mode; the result does not depend on the chunk size. + model.candidate_chunk = 2 + torch.testing.assert_close(model(waveforms, travel_times)["event"], out["event"]) + # Single stations (the picking benchmark): (n, 3, samples) -> (n, 2, samples // 2). + assert model.annotate(torch.randn(3, 3, 6000)).shape == (3, 2, 3000) + assert model.annotate(torch.randn(1, 2, 3, 3000)).shape == (1, 2, 2, 1500) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(2, 3, 1024)) + with pytest.raises(ValueError, match="shape"): + model(waveforms, torch.rand(2, 3, 7, 2)) + with pytest.raises(ValueError, match="shape"): + model(waveforms, travel_times, station_mask=torch.ones(2, 3, dtype=torch.bool)) + + +def test_shift_and_stack_finds_the_true_hypocentre_and_origin_time(): + stations = torch.tensor([[0.0, 0.0, 0.0], [40.0, 0.0, 0.0], [0.0, 40.0, 0.0], [40.0, 40.0, 0.0], [20.0, -5.0, 0.0], [-5.0, 20.0, 0.0]]) + candidates = eqnet_candidate_grid((0.0, 40.0), (0.0, 40.0), spacing=4.0, depth=8.0) + assert candidates.shape == (121, 3) + true_index, origin = 47, 20.0 # feature samples + travel_times = eqnet_travel_times(stations, candidates) # (1, 6, 121, 2), 6 and 3.4 km/s + assert travel_times.shape == (1, 6, 121, 2) + distance = torch.linalg.vector_norm(stations[2] - candidates[5]) + torch.testing.assert_close(travel_times[0, 2, 5], torch.stack([distance / 6.0, distance / 3.4])) + + time = torch.arange(96.0) + features = torch.zeros(1, 6, 128, 96) + for s in range(6): + p_arrival = origin + travel_times[0, s, true_index, 0] * RATE + s_arrival = origin + travel_times[0, s, true_index, 1] * RATE + features[0, s, :64] = torch.exp(-0.5 * ((time - p_arrival) / 0.7) ** 2) + features[0, s, 64:] = torch.exp(-0.5 * ((time - s_arrival) / 0.7) ** 2) + stacked = shift_and_stack(features, travel_times, RATE) + assert stacked.shape == (1, 121, 128, 96) + score = stacked.sum(dim=2)[0] + best = int(score.argmax()) + assert divmod(best, 96) == (true_index, int(origin)) + + # The detector path runs on the same geometry, chunked or not. + model = EQNet().eval() + with torch.no_grad(): + event = model.detect(features, travel_times) + assert event.shape == (1, 121, 96) + + +def test_shift_and_stack_interpolates_masks_and_backpropagates(): + features = torch.randn(1, 2, 4, 10, requires_grad=True) + half = torch.full((1, 2, 1, 2), 0.5 / RATE) # half a feature sample for P and S + shifted = shift_and_stack(features, half, RATE) + expected = 0.5 * (features[..., :-1] + features[..., 1:]).mean(dim=1) + torch.testing.assert_close(shifted[0, 0, :, :-1], expected[0]) + torch.testing.assert_close(shifted[0, 0, :, -1], 0.5 * features[0, :, :, -1].mean(dim=0)) # zero beyond the end + shifted.sum().backward() + assert features.grad is not None and float(features.grad.abs().sum()) > 0 + + garbage = features.detach().clone() + garbage[0, 1] = 1e6 + mask = torch.tensor([[True, False]]) + zero = torch.zeros(1, 2, 3, 2) + torch.testing.assert_close(shift_and_stack(garbage, zero, RATE, station_mask=mask)[0, 0], garbage[0, 0]) + + +def test_pick_and_event_extraction(): + model = EQNet() + annotations = torch.zeros(1, 2, 200) + annotations[0, 0, 30] = 0.9 + annotations[0, 1, 60] = 0.7 + annotations[0, 1, 62] = 0.6 # within 0.5 s of the stronger peak: dropped + annotations[0, 1, 150] = 0.4 # below the threshold + picks = model.extract_picks(annotations) + assert picks == [{"P": [(60.0, pytest.approx(0.9))], "S": [(120.0, pytest.approx(0.7))]}] + + candidates = eqnet_candidate_grid((0.0, 40.0), (0.0, 40.0), spacing=4.0) + centre = candidates[60] + activation = torch.zeros(1, 121, 96) + distance = torch.linalg.vector_norm(candidates - centre, dim=1) + activation[0, :, 40] = 0.95 * torch.exp(-((distance / 6.0) ** 2)) + events = model.extract_events(activation, candidates, top_k=9) + assert len(events[0]) == 1 + event = events[0][0] + assert event["time"] == pytest.approx(40 / RATE) and event["sample"] == 40 * 32 + assert event["probability"] == pytest.approx(0.95) + assert event["location"] == pytest.approx(centre.tolist(), abs=1e-6) + + square = torch.tensor([[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0], [1.0, 1.0]]) + assert geometric_median(square).tolist() == pytest.approx([1.0, 1.0], abs=1e-6) + + +def test_loss_is_the_sum_of_three_binary_cross_entropies(): + torch.manual_seed(1) + outputs = {"phase": torch.randn(2, 3, 2, 16), "event": torch.randn(2, 5, 8)} + phase_targets = torch.rand(2, 3, 2, 16) + event_targets = torch.rand(2, 5, 8) + expected = sum( + F.binary_cross_entropy_with_logits(outputs["phase"][:, :, i], phase_targets[:, :, i], reduction="sum") / 6 + for i in range(2) + ) + F.binary_cross_entropy_with_logits(outputs["event"], event_targets, reduction="sum") / 10 + torch.testing.assert_close(EQNetLoss()(outputs, phase_targets, event_targets), expected) + weighted = EQNetLoss(weights=(1.0, 0.0, 0.0))(outputs, phase_targets, event_targets) + torch.testing.assert_close(weighted, F.binary_cross_entropy_with_logits(outputs["phase"][:, :, 0], phase_targets[:, :, 0], reduction="sum") / 6) + with pytest.raises(ValueError, match="shape"): + EQNetLoss()(outputs, phase_targets[..., :8]) + + +def test_builder_contract(): + assert isinstance(build_model("eqnet", task="picking"), EQNet) + with pytest.raises(ValueError, match="picking"): + build_model("eqnet", task="regression") + with pytest.raises(TypeError, match="no longer"): + build_model("eqnet", task="picking", hidden_dim=48) + assert math.isclose(EQNet().feature_rate, RATE) diff --git a/tests/test_eqtransformer.py b/tests/test_eqtransformer.py new file mode 100644 index 00000000..6b590547 --- /dev/null +++ b/tests/test_eqtransformer.py @@ -0,0 +1,196 @@ +"""EQTransformer port: shapes, parameter counts, building blocks and pick extraction (CPU, offline). + +The comparison with the official Keras models lives in tests/oracle/test_eqtransformer_oracle.py. +""" + +from __future__ import annotations + +import h5py +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.eqtransformer import ( + EQTransformer, + KerasBatchNorm1d, + KerasLSTM, + SeqSelfAttention, + eqtransformer_builder, + keras_weight_map, + load_eqtransformer_keras_weights, +) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +@pytest.mark.parametrize("variant, expected", [("original", 371_639), ("conservative", 376_423)]) +def test_parameter_counts_match_the_released_keras_models(variant, expected): + model = build_model("eqtransformer", task="picking", variant=variant) + assert _n_params(model) == expected + assert model.lstm_blocks == (2 if variant == "original" else 3) + + +def test_forward_returns_detection_p_and_s_probabilities(): + torch.manual_seed(0) + model = build_model("eqtransformer", task="picking").eval() + x = torch.randn(2, 3, 6000) + with torch.no_grad(): + probabilities = model(x) + logits = model(x, logits=True) + annotated = model.annotate(x * 1e4 + 3.0) + assert probabilities.shape == (2, 3, 6000) + assert torch.all((probabilities >= 0) & (probabilities <= 1)) + torch.testing.assert_close(torch.sigmoid(logits), probabilities) + # annotate() normalises each channel (demean, divide by its standard deviation) first. + normalised = (x - x.mean(-1, keepdim=True)) / x.std(-1, unbiased=False, keepdim=True) + with torch.no_grad(): + torch.testing.assert_close(annotated, model(normalised), rtol=1e-4, atol=1e-5) + assert model.output_names == ("detection", "P", "S") + assert model.component_order == "ENZ" and model.sampling_rate == 100.0 + + +@pytest.mark.parametrize("shape", [(2, 3, 3000), (2, 2, 6000), (3, 6000), (1, 3, 6001)]) +def test_invalid_input_shapes_raise(shape): + model = build_model("eqtransformer", task="picking") + with pytest.raises(ValueError, match="shape"): + model(torch.randn(*shape)) + + +def test_builder_validation(): + with pytest.raises(ValueError, match="picking"): + build_model("eqtransformer", task="regression") + with pytest.raises(TypeError, match="hidden_dim"): + build_model("eqtransformer", task="picking", hidden_dim=48) + with pytest.raises(ValueError, match="variant"): + build_model("eqtransformer", task="picking", variant="large") + with pytest.raises(ValueError, match="variant"): + eqtransformer_builder("picking", variant="original", pretrained="conservative") + with pytest.raises(ValueError, match="in_channels=3"): + eqtransformer_builder("picking", in_channels=4, pretrained=True) + + +def test_eval_is_deterministic_unless_mc_dropout(): + torch.manual_seed(0) + model = build_model("eqtransformer", task="picking").eval() + x = torch.randn(1, 3, 6000) + with torch.no_grad(): + assert torch.equal(model(x), model(x)) + model.mc_dropout = True + assert not torch.equal(model(x), model(x)) + model.mc_dropout = False + averaged = model.annotate(x, mc_samples=3) + assert averaged.shape == (1, 3, 6000) and model.mc_dropout is False + + +def test_keras_lstm_equals_torch_lstm_with_one_bias(): + torch.manual_seed(0) + lstm = KerasLSTM(5, 4) + reference = torch.nn.LSTM(5, 4, batch_first=True) + with torch.no_grad(): # PyTorch's gate order (i, f, g, o) is Keras' (i, f, c, o) + reference.weight_ih_l0.copy_(lstm.kernel.T) + reference.weight_hh_l0.copy_(lstm.recurrent_kernel.T) + reference.bias_ih_l0.copy_(lstm.bias) + reference.bias_hh_l0.zero_() + x = torch.randn(3, 7, 5) + torch.testing.assert_close(lstm(x), reference(x)[0]) + torch.testing.assert_close(lstm(x, reverse=True), reference(x.flip(1))[0].flip(1)) + assert torch.equal(lstm.bias[4:8], torch.ones(4)) # unit forget bias + hard = KerasLSTM(5, 4, recurrent_activation="hard_sigmoid") + hard.load_state_dict(lstm.state_dict()) + assert not torch.allclose(hard(x), lstm(x)) + + +def test_local_attention_only_sees_neighbours(): + torch.manual_seed(0) + attention = SeqSelfAttention(4, 8, attention_width=3) + x = torch.randn(1, 10, 4) + moved = x.clone() + moved[:, 7:] += 5.0 + out, weights = attention(x, return_attention=True) + torch.testing.assert_close(attention(moved)[:, :6], out[:, :6]) + assert torch.all(weights[0].triu(2) == 0) and torch.all(weights[0].tril(-2) == 0) + + +@pytest.mark.parametrize("zero_debias", [False, True]) +def test_keras_batch_norm_running_statistics(zero_debias): + torch.manual_seed(0) + bn = KerasBatchNorm1d(3, zero_debias=zero_debias) + batches = [torch.randn(4, 3, 10) * (i + 1) + i for i in range(3)] + mean, var = np.zeros(3), np.ones(3) + biased_mean, biased_var = np.zeros(3), np.zeros(3) + bn.train() + for step, x in enumerate(batches, start=1): + out = bn(x) + values = x.double().numpy() + n = values.shape[0] * values.shape[2] + batch_mean = values.mean(axis=(0, 2)) + batch_var = values.var(axis=(0, 2)) * n / (n - (1 + 1e-3)) + if zero_debias: # TensorFlow assign_moving_average(..., zero_debias=True) + biased_mean = 0.99 * biased_mean + 0.01 * batch_mean + biased_var = 0.99 * biased_var + 0.01 * batch_var + mean, var = biased_mean / (1 - 0.99**step), biased_var / (1 - 0.99**step) + else: # Keras 2.3 K.moving_average_update + mean, var = mean - (mean - batch_mean) * 0.01, var - (var - batch_var) * 0.01 + expected = (values - values.mean(axis=(0, 2), keepdims=True)) / np.sqrt(values.var(axis=(0, 2), keepdims=True) + 1e-3) + np.testing.assert_allclose(out.detach().numpy(), expected, rtol=1e-4, atol=1e-5) + np.testing.assert_allclose(bn.running_mean.numpy(), mean, rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(bn.running_var.numpy(), var, rtol=1e-5, atol=1e-6) + + +@pytest.mark.parametrize("variant", ["original", "conservative"]) +def test_keras_h5_round_trip(tmp_path, variant): + """Write a model's tensors in the released files' Keras layout and load them back strictly.""" + torch.manual_seed(1) + source = EQTransformer(variant=variant) + with torch.no_grad(): + for buffer in source.buffers(): + if buffer.dtype.is_floating_point: + buffer.uniform_(0.5, 1.5) + state = source.state_dict() + path = tmp_path / "model.h5" + layers = {} + for key, (layer, name) in keras_weight_map(source.lstm_blocks).items(): + value = state[key].numpy() + if name == "kernel" and value.ndim == 3: + value = value.transpose(2, 1, 0) + layers.setdefault(layer, []).append((f"{layer}/{name}:0", value)) + with h5py.File(path, "w") as handle: + group = handle.create_group("model_weights") + group.attrs["layer_names"] = [name.encode() for name in layers] + for layer, weights in layers.items(): + sub = group.create_group(layer) + sub.attrs["weight_names"] = [name.encode() for name, _ in weights] + for name, value in weights: + sub.create_dataset(name, data=value) + target = load_eqtransformer_keras_weights(EQTransformer(variant=variant), path) + for key, value in target.state_dict().items(): + if not key.endswith("num_batches_tracked"): + assert torch.equal(value, state[key]), key + other = "conservative" if variant == "original" else "original" + with pytest.raises((KeyError, ValueError)): + load_eqtransformer_keras_weights(EQTransformer(variant=other), path) + + +def test_extract_picks_follows_the_official_picker(): + model = EQTransformer() + annotations = torch.zeros(2, 3, 6000) + # Trace 0: one event 1000-2000 with P peaks at 990 (0.4) and 1100 (0.8), S peaks at 1500 and 1700. + annotations[0, 0, 1000:2001] = 0.9 + for sample, value in ((990, 0.4), (1100, 0.8), (1600, 0.95)): + annotations[0, 1, sample] = value + for sample, value in ((1500, 0.3), (1700, 0.9)): + annotations[0, 2, sample] = value + # Trace 1: a detection of only 5 samples (ignored) and a P peak without a detection. + annotations[1, 0, 3000:3005] = 0.9 + annotations[1, 1, 3002] = 0.9 + picks = model.extract_picks(annotations) + # The earliest S inside the window, then the most probable P between on - 100 and S - 10. + assert picks[0] == {"P": [(1100.0, 0.8)], "S": [(1500.0, 0.3)]} + assert picks[1] == {"P": [], "S": []} + detections = model.extract_detections(annotations) + assert detections[0] == [(1000, 2000, 0.9)] and detections[1] == [] + stricter = model.extract_picks(annotations, p_threshold=0.85, s_threshold=0.5) + assert stricter[0] == {"P": [(1600.0, 0.95)], "S": [(1700.0, 0.9)]} diff --git a/tests/test_figlib_smokebench.py b/tests/test_figlib_smokebench.py new file mode 100644 index 00000000..d2cc8c45 --- /dev/null +++ b/tests/test_figlib_smokebench.py @@ -0,0 +1,173 @@ +"""Tests of the FIgLib SmokeBench dataset adapter on small synthetic fixtures (no network).""" + +from __future__ import annotations + +import hashlib +import io +import pickle +import tarfile +from pathlib import Path + +import numpy as np +import pytest + +import pyhazards.datasets.figlib_smokebench as figlib +from pyhazards.datasets.figlib_smokebench import FIgLibSmokeBench, SmokeSample, load_smokeynet_boxes + +SEQ_A = "20160722_FIRE_mw-e-mobo-c" +SEQ_B = "20170520_FIRE_lp-s-iqeye" + + +def _write_metadata(root: Path, monkeypatch) -> Path: + """A metadata.pkl shaped like SmokeyNet's (numpy int32 boxes) and its checksum pinned.""" + metadata = { + "bbox_labels": { + f"{SEQ_A}/1469223181_+00060": [[np.int32(1821), np.int32(1027), np.int32(1922), np.int32(1074)]], + f"{SEQ_A}/1469223241_+00120": [np.array([1807, 1031, 1926, 1074], dtype=np.int32)], + f"{SEQ_B}/1495300000_+00000": [[10, 20, 30, 40]], + }, + "night_fires": np.array(["x"]), + } + path = root / figlib.METADATA_FILENAME + path.write_bytes(pickle.dumps(metadata)) + monkeypatch.setattr(figlib, "SMOKEYNET_METADATA_SHA256", hashlib.sha256(path.read_bytes()).hexdigest()) + return path + + +def _touch_frames(root: Path, names): + for name in names: + path = root / f"{name}.jpg" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"") + + +def _fixture(tmp_path, monkeypatch): + _write_metadata(tmp_path, monkeypatch) + _touch_frames( + tmp_path, + [ + f"{SEQ_A}/1469223181_+00060", + f"{SEQ_A}/1469223241_+00120", + f"{SEQ_A}/1469223301_+00180", # unannotated smoke frame: never used + f"{SEQ_A}/1469220001_-01200", + f"{SEQ_A}/1469220061_-01140", + f"{SEQ_A}/1469220121_-01080", + f"{SEQ_B}/1495300000_+00000", + f"{SEQ_B}/1495299940_-00060", + ], + ) + (tmp_path / SEQ_A / "notes.txt").write_text("ignored") + return tmp_path + + +def test_boxes_load_as_plain_ints(tmp_path, monkeypatch): + path = _write_metadata(tmp_path, monkeypatch) + boxes = load_smokeynet_boxes(path) + assert boxes[f"{SEQ_A}/1469223181_+00060"] == [[1821, 1027, 1922, 1074]] + assert boxes[f"{SEQ_A}/1469223241_+00120"] == [[1807, 1031, 1926, 1074]] + assert all(type(v) is int for box in boxes[f"{SEQ_A}/1469223181_+00060"] for v in box) + monkeypatch.setattr(figlib, "SMOKEYNET_METADATA_SHA256", "0" * 64) + with pytest.raises(ValueError, match="sha256"): + load_smokeynet_boxes(path) + assert len(load_smokeynet_boxes(path, verify=False)) == 3 + + +def test_metadata_unpickler_refuses_code(tmp_path): + class Exploit: + def __reduce__(self): + return (print, ("pwned",)) + + path = tmp_path / "evil.pkl" + path.write_bytes(pickle.dumps({"bbox_labels": Exploit()})) + with pytest.raises(pickle.UnpicklingError, match="refusing"): + load_smokeynet_boxes(path, verify=False) + + +def test_dataset_lists_smoke_and_sampled_smoke_free_frames(tmp_path, monkeypatch): + root = _fixture(tmp_path, monkeypatch) + data = FIgLibSmokeBench(root, negatives=2, negative_seed=0) + assert [s.image_id for s in data.positives] == [ + f"{SEQ_A}/1469223181_+00060", + f"{SEQ_A}/1469223241_+00120", + f"{SEQ_B}/1495300000_+00000", + ] + assert data.positives[0].boxes == ((1821, 1027, 1922, 1074),) + assert len(data.negatives) == 2 and data.negative_pool_size == 4 + assert all(not s.label and s.boxes == () and s.offset_seconds < 0 for s in data.negatives) + assert [s.image_id for s in FIgLibSmokeBench(root, negatives=2, negative_seed=0).negatives] == [s.image_id for s in data.negatives] + assert len(data) == 5 and data[0] is data.positives[0] + assert data.positives[2].offset_seconds == 0 and data.positives[1].offset_seconds == 120 + everything = FIgLibSmokeBench(root, negatives=100) + assert len(everything.negatives) == 4 # capped at the pool + only_b = FIgLibSmokeBench(root, sequences=[SEQ_B]) + assert [s.image_id for s in only_b] == [f"{SEQ_B}/1495300000_+00000", f"{SEQ_B}/1495299940_-00060"] + assert FIgLibSmokeBench(root, negatives=0).negatives == [] + info = data.describe() + assert info["smoke_images"] == 3 and info["smoke_free_images"] == 2 and info["sequences"] == 2 + + +def test_dataset_errors(tmp_path, monkeypatch): + with pytest.raises(FileNotFoundError, match="download_smokebench"): + FIgLibSmokeBench(tmp_path) + root = _fixture(tmp_path, monkeypatch) + with pytest.raises(ValueError, match="without SmokeyNet boxes"): + FIgLibSmokeBench(root, sequences=["20990101_FIRE_none"]) + with pytest.raises(ValueError, match="negatives"): + FIgLibSmokeBench(root, negatives=-1) + (root / SEQ_B / "1495300000_+00000.jpg").unlink() + with pytest.raises(FileNotFoundError, match="1 annotated frames are missing"): + FIgLibSmokeBench(root) + + +def _archive(path: Path, sequence: str) -> None: + with tarfile.open(path, "w:gz") as tar: + def add(name: str, data: bytes) -> None: + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + + add(f"{sequence}/1469223181_+00060.jpg", b"jpeg-1") + add(f"{sequence}/1469220001_-01200.jpg", b"jpeg-2") + add(f"{sequence}/{sequence}.mp4", b"video") + add(f"{sequence}/sub/1469223181_+00060.jpg", b"nested") + add("../1469223181_+00060.jpg", b"escape") + add("other_sequence/1469223181_+00060.jpg", b"other") + + +def test_download_streams_only_frames(tmp_path, monkeypatch): + server = tmp_path / "server" + server.mkdir() + _archive(server / f"{SEQ_A}.tgz", SEQ_A) + monkeypatch.setattr(figlib, "FIGLIB_ARCHIVE_URL", server.as_uri() + "/{sequence}.tgz") + root = tmp_path / "data" + assert figlib.download_sequence(root, SEQ_A) == 2 + files = sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()) + assert files == [f"{SEQ_A}/.complete", f"{SEQ_A}/1469220001_-01200.jpg", f"{SEQ_A}/1469223181_+00060.jpg"] + assert (root / SEQ_A / "1469223181_+00060.jpg").read_bytes() == b"jpeg-1" + (server / f"{SEQ_A}.tgz").unlink() + assert figlib.download_sequence(root, SEQ_A) == 2 # marker: no second download + with pytest.raises(ValueError, match="invalid"): + figlib.download_sequence(root, "../etc") + + +def test_download_metadata_checks_the_pin(tmp_path, monkeypatch): + server = tmp_path / "server" + server.mkdir() + (server / "metadata.pkl").write_bytes(pickle.dumps({"bbox_labels": {}})) + monkeypatch.setattr(figlib, "SMOKEYNET_METADATA_URL", (server / "metadata.pkl").as_uri()) + monkeypatch.setattr(figlib, "SMOKEYNET_METADATA_SHA256", hashlib.sha256((server / "metadata.pkl").read_bytes()).hexdigest()) + path = figlib.download_metadata(tmp_path / "data") + assert path.name == figlib.METADATA_FILENAME and load_smokeynet_boxes(path) == {} + monkeypatch.setattr(figlib, "SMOKEYNET_METADATA_SHA256", "1" * 64) + with pytest.raises(ValueError, match="sha256"): + figlib.download_metadata(tmp_path / "other") + + +def test_sample_offsets_and_image_loading(tmp_path): + sample = SmokeSample("seq/1469220001_-01200", tmp_path / "x.jpg", False) + assert sample.sequence == "seq" and sample.offset_seconds == -1200 + pil = pytest.importorskip("PIL.Image") + array = (np.arange(6 * 8 * 3) % 256).reshape(6, 8, 3).astype(np.uint8) + pil.fromarray(array).save(tmp_path / "x.png") + loaded = FIgLibSmokeBench.load_image(SmokeSample("seq/1_+00000", tmp_path / "x.png", True, ((0, 0, 1, 1),))) + assert loaded.dtype == np.uint8 and np.array_equal(loaded, array) diff --git a/tests/test_firecastnet.py b/tests/test_firecastnet.py new file mode 100644 index 00000000..7b57fcbc --- /dev/null +++ b/tests/test_firecastnet.py @@ -0,0 +1,145 @@ +"""FireCastNet without the reference code: sizes, shapes, validation and checkpoint loading. + +The comparison with the official implementation is in tests/oracle/test_firecastnet_oracle.py. +""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.firecastnet import FireCastNet, lightning_state_dict_to_firecastnet, load_official_checkpoint +from pyhazards.models.firecastnet_graph import build_graph, icosphere, icospheres, latlon_grid + +# A 10-degree graph grid (input 2.5 degrees, 72 x 144) on icosphere levels 0-2. +TINY_GLOBAL = dict(sp_res=2.5, max_lat=88.75, min_lat=-88.75, max_lon=178.75, min_lon=-178.75) +TINY = dict(in_channels=3, timeseries_len=2, mesh_levels=(0, 1, 2), hidden_dim=16, embed_cube_dim=16, processor_layers=3, **TINY_GLOBAL) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_released_global_configuration(): + model = build_model(name="firecastnet", task="segmentation") + assert _n_params(model) == 9_087_568 + assert _n_params(model._downsample.layer_norm) == 8_294_400 # LayerNorm over the whole 64x1x180x360 cube + assert (model.lat_dim, model.lon_dim, model.graph_lat_dim, model.graph_lon_dim) == (720, 1440, 180, 360) + net = model._net + assert (net.num_grid_nodes, net.num_mesh_nodes) == (64_800, 40_962) + assert (net.mesh_src.numel(), net.g2m_src.numel(), net.m2g_src.numel()) == (327_660, 100_160, 64_800) + assert len(model.state_dict()) == 212 + assert all(not name.startswith(("static_data", "_net.mesh_", "_net.g2m_", "_net.m2g_")) for name in model.state_dict()) + assert len(net.processor.processor_layers) == 10 + + +@pytest.mark.parametrize("level", [0, 1, 2, 3]) +def test_icosphere_sizes_and_nesting(level): + vertices, faces = icosphere(level) + assert vertices.shape == (10 * 4**level + 2, 3) + assert faces.shape == (20 * 4**level, 3) + np.testing.assert_allclose(np.linalg.norm(vertices, axis=1), 1.0, rtol=0, atol=1e-15) + edges = {tuple(sorted(edge)) for face in faces.tolist() for edge in ((face[0], face[1]), (face[1], face[2]), (face[2], face[0]))} + assert len(vertices) - len(edges) + len(faces) == 2 # Euler characteristic of a sphere + if level: + coarse, _ = icosphere(level - 1) + assert np.array_equal(vertices[: len(coarse)], coarse) + meshes = icospheres(range(level + 1)) + assert np.array_equal(meshes[f"order_{level}_vertices"], vertices) + + +def test_graph_on_tiny_global_grid(): + latitudes, longitudes = latlon_grid(10.0, 85.0, -85.0, 175.0, -175.0) + graph = build_graph(latitudes, longitudes, icospheres((0, 1, 2))) + assert graph.num_grid_nodes == 18 * 36 and graph.num_mesh_nodes == 162 + # the multimesh of levels 0-2 has 30 + 120 + 480 undirected edges + assert graph.mesh_src.numel() == 2 * (30 + 120 + 480) + assert torch.all(graph.mesh_src != graph.mesh_dst) + assert graph.g2m_edata.shape == (graph.g2m_src.numel(), 4) and graph.m2g_edata.shape == (648, 4) + assert torch.equal(graph.m2g_dst, torch.arange(648)) + assert float(graph.mesh_edata[:, 3].max()) == pytest.approx(1.0) # normalised by the longest edge + + +def test_forward_shape_and_batching(): + torch.manual_seed(0) + model = build_model(name="firecastnet", task="segmentation", **TINY).eval() + x = torch.randn(2, 2, 3, 72, 144) + with torch.no_grad(): + out = model(x) + assert out.shape == (2, 1, 72, 144) + torch.testing.assert_close(out[1:], model(x[1:]), rtol=1e-5, atol=1e-6) + + +def test_two_output_channels_and_options(): + model = FireCastNet(output_dim_grid_nodes=32, lat_lon_static_data=False, aggregation="mean", hidden_layers=2, embed_cube_layer_norm=False, **TINY) + assert model._downsample.layer_norm is None + assert model(torch.randn(1, 2, 3, 72, 144)).shape == (1, 2, 72, 144) + + +def test_regional_window(): + # 16 x 16 cells of 0.25 degree; the reference code needs global grids, the port does not. + model = FireCastNet( + in_channels=6, timeseries_len=4, mesh_levels=(0, 1, 2, 3, 4), sp_res=0.25, + max_lat=41.875, min_lat=38.125, max_lon=-120.125, min_lon=-123.875, hidden_dim=16, embed_cube_dim=16, + ) + assert (model.graph_lat_dim, model.graph_lon_dim) == (4, 4) + assert model(torch.randn(2, 4, 6, 16, 16)).shape == (2, 1, 16, 16) + + +def test_input_and_config_validation(): + model = FireCastNet(**TINY) + for bad in (torch.randn(2, 3, 72, 144), torch.randn(1, 2, 4, 72, 144), torch.randn(1, 3, 3, 72, 144), torch.randn(1, 2, 3, 72, 140)): + with pytest.raises(ValueError, match="shape"): + model(bad) + with pytest.raises(ValueError, match="embed_cube_time"): + FireCastNet(embed_cube_time=1, **TINY) + with pytest.raises(ValueError, match="at least 3 processor layers"): + FireCastNet(**{**TINY, "processor_layers": 2}) + with pytest.raises(ValueError, match="norm_type"): + FireCastNet(norm_type="BatchNorm", **TINY) + with pytest.raises(ValueError, match="equal"): + FireCastNet(embed_cube_width=4, embed_cube_height=2, **TINY) + with pytest.raises(ValueError, match="graph grid"): + FireCastNet(embed_cube_max_lat=80.0, **TINY) + with pytest.raises(ValueError, match="task"): + build_model(name="firecastnet", task="classification", **TINY) + with pytest.raises(TypeError): + build_model(name="firecastnet", task="segmentation", dropout=0.1, **TINY) + + +def test_official_checkpoint_layout_round_trip(tmp_path): + torch.manual_seed(0) + model = FireCastNet(**TINY).eval() + state = {"_net." + key: value for key, value in model.state_dict().items()} + state["_lsm_mask"] = torch.zeros(1, 72, 144, dtype=torch.bool) # LightningModule buffer, not a weight + hparams = dict( + icospheres_graph_path="icospheres/icospheres_0_1_2.json.gz", + input_dim_grid_nodes=3, + timeseries_len=2, + embed_cube=True, + embed_cube_time=2, + embed_cube_dim=16, + embed_cube_sp_res=10.0, + embed_cube_max_lat=85.0, + embed_cube_min_lat=-85.0, + embed_cube_max_lon=175.0, + embed_cube_min_lon=-175.0, + output_dim_grid_nodes=16, + hidden_dim=16, + processor_layers=3, + **TINY_GLOBAL, + ) + path = tmp_path / "firecastnet.ckpt" + torch.save({"state_dict": state, "hyper_parameters": hparams}, path) + assert list(lightning_state_dict_to_firecastnet(state)) == list(model.state_dict()) + + loaded = build_model(name="firecastnet", task="segmentation", checkpoint=str(path)).eval() + x = torch.randn(1, 2, 3, 72, 144) + with torch.no_grad(): + torch.testing.assert_close(loaded(x), model(x), rtol=0, atol=0) + + torch.save({"state_dict": state, "hyper_parameters": {**hparams, "icospheres_graph_path": "lam.json.gz"}}, path) + with pytest.raises(ValueError, match="icospheres_graph_path"): + load_official_checkpoint(path) diff --git a/tests/test_flood_benchmarks.py b/tests/test_flood_benchmarks.py index 5167e1ae..a044a12b 100644 --- a/tests/test_flood_benchmarks.py +++ b/tests/test_flood_benchmarks.py @@ -3,12 +3,22 @@ def test_flood_streamflow_vertical_slice(tmp_path): - config = load_experiment_config("pyhazards/configs/flood/hydrographnet_smoke.yaml") + config = load_experiment_config("pyhazards/configs/flood/neuralhydrology_lstm_smoke.yaml") summary = BenchmarkRunner().run(config, output_dir=str(tmp_path)) assert summary.benchmark_name == "flood" assert summary.hazard_task == "flood.streamflow" - assert "mae" in summary.metrics - assert "rmse" in summary.metrics - assert "nse" in summary.metrics - assert "kge" in summary.metrics + # NeuralHydrology's metrics per basin, summarised by the median (and mean) over basins. + for metric in ("nse", "kge", "alpha_nse", "beta_nse", "fhv", "fms", "flv", "peak_timing", "nse_mean"): + assert metric in summary.metrics + assert summary.metrics["n_basins"] == len(summary.metadata["per_basin"]) + + +def test_flood_mesh_vertical_slice(tmp_path): + config = load_experiment_config("pyhazards/configs/flood/hydrographnet_smoke.yaml") + summary = BenchmarkRunner().run(config, output_dir=str(tmp_path)) + + assert summary.hazard_task == "flood.inundation" + # HydroGraphNet rollouts on synthetic mesh hydrographs, scored in metres. + assert {"rollout_rmse", "pixel_mae", "rmse", "iou", "f1", "csi_10cm"} <= set(summary.metrics) + assert summary.metadata["rollout_rmse_per_step_m"] diff --git a/tests/test_flood_breadth.py b/tests/test_flood_breadth.py index f93ddc4b..d1ab0576 100644 --- a/tests/test_flood_breadth.py +++ b/tests/test_flood_breadth.py @@ -5,20 +5,24 @@ from pyhazards.models import build_model -def test_neuralhydrology_baselines_forward(): - batch = {"x": torch.randn(2, 4, 6, 2)} - for name in ["neuralhydrology_lstm", "neuralhydrology_ealstm", "google_flood_forecasting"]: - model = build_model(name=name, task="regression", input_dim=2, out_dim=1) - preds = model(batch) - assert preds.shape == (2, 6, 1) - - -def test_inundation_baselines_forward(): - x = torch.randn(2, 4, 3, 16, 16) - for name in ["floodcast", "urbanfloodcast"]: - model = build_model(name=name, task="regression", in_channels=3, history=4) - preds = model(x) - assert preds.shape == (2, 1, 16, 16) +def test_streamflow_models_forward(): + batch = {"x_d": torch.randn(2, 30, 5), "x_s": torch.randn(2, 27)} + for name in ["neuralhydrology_lstm", "neuralhydrology_ealstm"]: + out = build_model(name=name, task="regression", hidden_size=16)(batch) + assert out["y_hat"].shape == (2, 30, 1) + google = build_model("google_flood_forecasting", task="regression", config="streamflow", seq_length=30, hidden_size=16) + assert google.point_prediction(google(batch)).shape == (2, 30, 1) + + +def test_inundation_models_forward(): + floodcast = build_model(name="floodcast", task="regression", in_channels=3, history=4) + assert floodcast(torch.randn(2, 4, 3, 16, 16)).shape == (2, 1, 16, 16) + # UrbanFloodCast: (batch, Sy, Sx, T, T_in, 5) -> depth and discharges at all T steps. + urbanfloodcast = build_model(name="urbanfloodcast", task="regression") + assert urbanfloodcast(torch.randn(1, 28, 28, 14, 1, 5)).shape == (1, 28, 28, 14, 3) + hydrographnet = build_model(name="hydrographnet", task="regression") + edge_index = torch.stack([torch.arange(8), (torch.arange(8) + 1) % 8]) + assert hydrographnet(torch.randn(8, 16), torch.randn(8, 3), edge_index).shape == (8, 2) def test_flood_streamflow_breadth_configs(tmp_path): @@ -32,19 +36,22 @@ def test_flood_streamflow_breadth_configs(tmp_path): output_dir=str(tmp_path), ) assert summary.hazard_task == "flood.streamflow" - assert "rmse" in summary.metrics - assert "nse" in summary.metrics + for metric in ("nse", "nse_mean", "kge", "alpha_nse", "fhv", "n_basins"): + assert metric in summary.metrics + assert summary.metrics["n_basins"] == 3 + assert set(summary.metadata["per_basin"]) == {"synthetic_000", "synthetic_001", "synthetic_002"} def test_flood_inundation_breadth_configs(tmp_path): for config_name in [ "pyhazards/configs/flood/floodcast_smoke.yaml", "pyhazards/configs/flood/urbanfloodcast_smoke.yaml", + "pyhazards/configs/flood/hydrographnet_smoke.yaml", ]: summary = BenchmarkRunner().run( load_experiment_config(config_name), output_dir=str(tmp_path), ) assert summary.hazard_task == "flood.inundation" - assert "iou" in summary.metrics - assert "pixel_mae" in summary.metrics + for metric in ("iou", "pixel_mae", "rmse", "csi_10cm", "relative_l2", "nse"): + assert metric in summary.metrics diff --git a/tests/test_flood_streamflow.py b/tests/test_flood_streamflow.py new file mode 100644 index 00000000..dbe99e7e --- /dev/null +++ b/tests/test_flood_streamflow.py @@ -0,0 +1,245 @@ +"""Streamflow task: hydrological metrics, CAMELS-US / Caravan readers on files in the real layout, evaluator.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import torch +import torch.nn as nn + +from pyhazards.benchmarks.flood import evaluate_streamflow +from pyhazards.datasets import available_datasets, load_dataset +from pyhazards.datasets.flood import ( + CamelsUSStreamflowDataset, + CaravanStreamflowDataset, + build_streamflow_bundle, + load_camels_us_basin, +) +from pyhazards.metrics import hydrology + + +# -- metrics ----------------------------------------------------------------------------------------- + +def test_metric_definitions_on_known_series(): + obs = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) + assert hydrology.nse(obs, obs) == 1.0 + assert hydrology.kge(obs, obs) == pytest.approx(1.0) + assert hydrology.nse(obs, np.full(5, obs.mean())) == pytest.approx(0.0) + assert hydrology.alpha_nse(obs, 2 * obs) == pytest.approx(2.0) + assert hydrology.beta_kge(obs, obs + 3.0) == pytest.approx(2.0) + assert hydrology.beta_nse(obs, obs + np.std(obs)) == pytest.approx(1.0) # population std + assert hydrology.rmse(obs, obs + 2.0) == pytest.approx(2.0) + # KGE = 1 - sqrt((r-1)^2 + (alpha-1)^2 + (beta-1)^2): doubling the flows gives alpha = beta = 2. + assert hydrology.kge(obs, 2 * obs) == pytest.approx(1 - np.sqrt(2.0)) + + +def test_metrics_skip_missing_values(): + obs = np.array([1.0, np.nan, 3.0, 4.0, 2.0]) + sim = np.array([1.0, 5.0, 3.0, np.nan, 2.0]) + assert hydrology.nse(obs, sim) == 1.0 + values = hydrology.calculate_metrics(np.full(4, np.nan), np.arange(4.0)) + assert set(values) == set(hydrology.STREAMFLOW_METRICS) and all(np.isnan(v) for v in values.values()) + with pytest.raises(ValueError, match="1-D"): + hydrology.nse(np.ones((2, 2)), np.ones((2, 2))) + with pytest.raises(ValueError, match="Shapes"): + hydrology.nse(np.ones(3), np.ones(4)) + + +def test_peak_timing_uses_dates(): + n = 400 + dates = pd.date_range("2000-01-01", periods=n, freq="1D").values + obs = np.ones(n) + obs[200] = 50.0 + sim = np.ones(n) + sim[202] = 40.0 # peak two days late + assert hydrology.mean_peak_timing(obs, sim, dates=dates) == 2.0 + assert hydrology.missed_peaks(obs, sim, dates=dates) == 1.0 # outside the 1-day window + sim_gap = sim.copy() + sim_gap[199] = np.nan # a gap inside the window: the peak is skipped + assert np.isnan(hydrology.mean_peak_timing(obs, sim_gap, dates=dates)) + + +def test_aggregation_median_mean_and_counts(): + summary = hydrology.aggregate_basin_metrics( + {"a": {"nse": 0.8}, "b": {"nse": -0.2}, "c": {"nse": 0.5}, "d": {"nse": float("nan")}} + ) + assert summary["nse"] == pytest.approx(0.5) + assert summary["nse_mean"] == pytest.approx(1.1 / 3) + assert summary["n_basins"] == 4 + assert summary["n_basins_nse_le_0"] == 1 + assert set(hydrology.streamflow_metric_names()) >= {"nse", "nse_mean", "kge", "fhv_mean", "n_basins"} + + +# -- CAMELS-US reader -------------------------------------------------------------------------------- + +BASINS = ["01022500", "01031500"] +DYN = ["prcp(mm/day)", "srad(W/m2)", "tmax(C)", "tmin(C)", "vp(Pa)"] + + +def _write_camels(root: Path, days: int = 120, start: str = "2000-01-01") -> Path: + """Two basins in the CAMELS-US layout (header, whitespace tables, HUC folders, ';' attribute files).""" + rng = np.random.default_rng(0) + dates = pd.date_range(start, periods=days, freq="1D") + for i, basin in enumerate(BASINS): + forcing_dir = root / "basin_mean_forcing" / "maurer_extended" / "01" + flow_dir = root / "usgs_streamflow" / "01" + forcing_dir.mkdir(parents=True, exist_ok=True) + flow_dir.mkdir(parents=True, exist_ok=True) + area = 573_623_053 + i * 1_000_000 + lines = ["44.82", "133.00", str(area), "Year\tMnth\tDay\tHr\tdayl(s)\tprcp(mm/day)\tsrad(W/m2)\tswe(mm)\ttmax(C)\ttmin(C)\tvp(Pa)"] + for d in dates: + row = [d.year, d.month, d.day, 12, 31185.94, *np.round(rng.gamma(1, 3, 1), 2), *np.round(rng.uniform(100, 300, 1), 2), + 0.0, *np.round(rng.uniform(0, 20, 1), 2), *np.round(rng.uniform(-10, 0, 1), 2), *np.round(rng.uniform(100, 900, 1), 2)] + lines.append("\t".join(str(v) for v in row)) + (forcing_dir / f"{basin}_lump_maurer_forcing_leap.txt").write_text("\n".join(lines) + "\n") + flows = [] + for j, d in enumerate(dates): + q = -999.0 if j == 40 else float(np.round(rng.uniform(50, 500), 2)) + flows.append(f"{basin} {d.year} {d.month:02d} {d.day:02d} {q:8.2f} A") + (flow_dir / f"{basin}_streamflow_qc.txt").write_text("\n".join(flows) + "\n") + attributes = root / "camels_attributes_v2.0" + attributes.mkdir(parents=True) + (attributes / "camels_clim.txt").write_text( + "gauge_id;p_mean;aridity;high_prec_timing\n01022500;3.6;0.58;son\n01031500;3.5;0.62;son\n" + ) + (attributes / "camels_topo.txt").write_text( + "gauge_id;huc_02;elev_mean;area_gages2\n01022500;1;92.68;573.6\n01031500;1;443.25;298.4\n" + ) + return root + + +def test_camels_us_reader_reads_the_official_layout(tmp_path): + root = _write_camels(tmp_path / "CAMELS_US") + frame = load_camels_us_basin(root, "01022500", ["maurer_extended"]) + raw = pd.read_csv(root / "usgs_streamflow" / "01" / "01022500_streamflow_qc.txt", sep=r"\s+", header=None) + expected = 28316846.592 * raw.iloc[0, 4] * 86400 / (573_623_053 * 10**6) # cfs -> mm/day + assert frame["QObs(mm/d)"].iloc[0] == pytest.approx(expected) + assert np.isnan(frame["QObs(mm/d)"].iloc[40]) # -999 flag (2000-02-10) + assert set(DYN) <= set(frame.columns) + + bundle = CamelsUSStreamflowDataset( + data_dir=root, basins=BASINS, static_attributes=["elev_mean", "p_mean", "aridity"], seq_length=20, + periods={"train": ("2000-01-21", "2000-03-15"), "test": ("2000-03-16", "2000-04-29")}, + ).load() + assert bundle.metadata["static_attributes"] == ["aridity", "elev_mean", "p_mean"] # alphabetical, as NH + test = bundle.get_split("test").inputs + assert len(test) == 2 * 45 # one sample per basin and test day, warm-up taken from before the period + assert pd.Timestamp(test.sample_date.min()) == pd.Timestamp("2000-03-16") + inputs, y = test[0] + assert inputs["x_d"].shape == (20, 5) and inputs["x_s"].shape == (3,) and y.shape == (20, 1) + assert torch.isnan(y[:-1]).all() # targets inside the warm-up are masked + train = bundle.get_split("train").inputs + assert len(train) == 2 * 55 - 2 # training drops the sample whose (only) target is missing + with pytest.raises(ValueError, match="data_dir"): + CamelsUSStreamflowDataset(basins=BASINS) + with pytest.raises(ValueError, match="missing"): + CamelsUSStreamflowDataset(data_dir=root, basins=BASINS, static_attributes=["no_such_attribute"], + periods={"train": ("2000-01-21", "2000-03-15")}, seq_length=20).load() + + +# -- Caravan reader ---------------------------------------------------------------------------------- + +def _write_caravan(root: Path, days: int = 200) -> list: + import xarray as xr + + rng = np.random.default_rng(1) + dates = pd.date_range("1990-01-01", periods=days, freq="1D") + basins = ["camelsgb_28015", "lamah_215"] + variables = ["total_precipitation_sum", "temperature_2m_mean", "potential_evaporation_sum", "streamflow"] + for basin in basins: + source = basin.split("_")[0] + values = {v: rng.gamma(1.0, 2.0, days).astype(np.float32) for v in variables} + nc_dir = root / "timeseries" / "netcdf" / source + csv_dir = root / "timeseries" / "csv" / source + nc_dir.mkdir(parents=True, exist_ok=True) + csv_dir.mkdir(parents=True, exist_ok=True) + xr.Dataset({v: (["date"], a) for v, a in values.items()}, coords={"date": dates}).to_netcdf(nc_dir / f"{basin}.nc") + pd.DataFrame({"date": dates, **values}).to_csv(csv_dir / f"{basin}.csv", index=False) + attr_dir = root / "attributes" / source + attr_dir.mkdir(parents=True, exist_ok=True) + pd.DataFrame({"gauge_id": [basin], "p_mean": [rng.uniform(1, 4)], "aridity": [rng.uniform(0.3, 2)]}).to_csv( + attr_dir / f"attributes_caravan_{source}.csv", index=False) + pd.DataFrame({"gauge_id": [basin], "ele_mt_sav": [rng.uniform(10, 900)]}).to_csv( + attr_dir / f"attributes_hydroatlas_{source}.csv", index=False) + pd.DataFrame({"gauge_id": [basin], "gauge_name": ["x"], "area": [rng.uniform(10, 900)]}).to_csv( + attr_dir / f"attributes_other_{source}.csv", index=False) + return basins + + +def test_caravan_reader_reads_netcdf_and_csv(tmp_path): + basins = _write_caravan(tmp_path / "Caravan") + kwargs = dict( + data_dir=tmp_path / "Caravan", basins=basins, seq_length=30, + dynamic_inputs=["total_precipitation_sum", "temperature_2m_mean", "potential_evaporation_sum"], + static_attributes=["p_mean", "ele_mt_sav", "area"], + periods={"train": ("1990-02-01", "1990-05-31"), "test": ("1990-06-01", "1990-07-19")}, + ) + from_nc = CaravanStreamflowDataset(**kwargs).load() + from_csv = CaravanStreamflowDataset(filetype="csv", **kwargs).load() + assert from_nc.metadata["static_attributes"] == ["area", "ele_mt_sav", "p_mean"] + assert len(from_nc.get_split("test").inputs) == 2 * 49 + a, b = from_nc.get_split("test").inputs[3], from_csv.get_split("test").inputs[3] + torch.testing.assert_close(a[0]["x_d"], b[0]["x_d"]) + torch.testing.assert_close(a[0]["x_s"], b[0]["x_s"]) + with pytest.raises(ValueError, match="dynamic_inputs"): + CaravanStreamflowDataset(data_dir=tmp_path, basins=basins, periods=kwargs["periods"]) + with pytest.raises(ValueError, match="periods"): + CaravanStreamflowDataset(data_dir=tmp_path, basins=basins, dynamic_inputs=["streamflow"]) + with pytest.raises(FileNotFoundError): + CaravanStreamflowDataset(**{**kwargs, "basins": ["camelsgb_00000"]}).load() + + +# -- synthetic data, evaluator ------------------------------------------------------------------------ + +def test_registry_names_are_honest(): + names = set(available_datasets()) + assert {"camels_us_streamflow", "caravan_streamflow", "flood_streamflow_synthetic", "flood_mesh_synthetic"} <= names + assert {"hydrographnet_white_river", "urbanfloodcast_synthetic"} <= names + assert not {"waterbench_streamflow", "hydrobench_streamflow", "floodcastbench_inundation"} & names + with pytest.raises(ValueError, match="data_dir"): + load_dataset("caravan_streamflow") + + +class _Persistence(nn.Module): + """Predicts the target scaler's centre plus the window's first forcing (a deterministic test model).""" + + def __init__(self): + super().__init__() + self.scale = nn.Parameter(torch.tensor(1.0)) + + def forward(self, batch): + return {"y_hat": batch["x_d"][..., :1] * self.scale} + + +def test_evaluator_rescales_clips_and_scores_per_basin(): + bundle = load_dataset("flood_streamflow_synthetic", micro=True).load() + model = _Persistence().eval() + summary, per_basin = evaluate_streamflow(model, bundle, "test", clip_negative=True) + windows = bundle.get_split("test").inputs + center = np.array(bundle.metadata["scaler"]["target_center"]) + scale = np.array(bundle.metadata["scaler"]["target_scale"]) + expected = {} + for b, basin in enumerate(windows.basins): + rows = np.flatnonzero(windows.sample_basin == b) + sim = np.array([windows[i][0]["x_d"][-1, 0].item() for i in rows]) * scale[0] + center[0] + obs = np.array([windows[i][1][-1, 0].item() for i in rows]) * scale[0] + center[0] + expected[basin] = hydrology.nse(obs, np.maximum(sim, 0.0)) + assert set(per_basin) == set(windows.basins) + for basin, value in expected.items(): + assert per_basin[basin]["nse"] == pytest.approx(value, rel=1e-5) + assert summary["nse"] == pytest.approx(float(np.median(list(expected.values()))), rel=1e-5) + assert summary["n_basins"] == len(windows.basins) + + +def test_bundle_rejects_bad_periods_and_inputs(): + frame = pd.DataFrame({"p": np.arange(50.0), "q": np.arange(50.0)}, + index=pd.date_range("2000-01-01", periods=50, freq="1D")) + with pytest.raises(ValueError, match="train"): + build_streamflow_bundle({"a": frame}, None, ["p"], [], ["q"], {"test": ("2000-01-10", "2000-02-01")}, 5) + with pytest.raises(ValueError, match="not available"): + build_streamflow_bundle({"a": frame}, None, ["x"], [], ["q"], {"train": ("2000-01-10", "2000-02-01")}, 5) + with pytest.raises(ValueError, match="before it starts"): + build_streamflow_bundle({"a": frame}, None, ["p"], [], ["q"], {"train": ("2000-02-10", "2000-02-01")}, 5) diff --git a/tests/test_forecasts_pipeline.py b/tests/test_forecasts_pipeline.py new file mode 100644 index 00000000..45af87a7 --- /dev/null +++ b/tests/test_forecasts_pipeline.py @@ -0,0 +1,59 @@ +"""End-to-end forecast pipeline on synthetic fields: track -> match to best tracks -> score.""" + +import ast +import math + +import pandas as pd +import pytest + +from pyhazards.forecasts import ( + ECMWF_TRACKER, + GRAPHCAST_TRACKER, + PANGU_TRACKER, + follow_forecast_tracks, + score_forecast_tracks, + tempest_forecast_tracks, +) +from pyhazards.forecasts.synthetic import SyntheticVortex, synthetic_cyclone_fields + +HOURS = list(range(0, 49, 6)) +HALF_DIAGONAL_KM = 0.5 * math.hypot(0.5, 0.5) * math.pi * 6371.0 / 180.0 + + +@pytest.fixture(scope="module") +def case(): + vortices = [SyntheticVortex(15.0, 140.0, u=-5.0, v=2.0), SyntheticVortex(-15.0, 60.0, u=-4.0, v=-2.0)] + fields = synthetic_cyclone_fields(vortices, HOURS, init_time="2021-08-01T00") + truth = ast.literal_eval(fields.attrs["tracks"]) + times = pd.to_datetime(fields["time"].values) + rows = [] + for sid, track in zip(["2021213N15140", "2021213S15060"], truth): + # Best-track rows: the true centres, plus one 6 h before the forecast starts. + before = (track[0][0] - (track[1][0] - track[0][0]), track[0][1] - (track[1][1] - track[0][1])) + rows.append((sid, times[0] - pd.Timedelta(hours=6), *before, 60.0, 980.0)) + rows += [(sid, time, lat, lon, 60.0, 980.0) for time, (lat, lon) in zip(times, track)] + ibtracs = pd.DataFrame(rows, columns=["SID", "ISO_TIME", "LAT", "LON", "USA_WIND", "USA_PRES"]) + return fields, ibtracs, times[0] + + +def test_tempest_route(case): + fields, ibtracs, init = case + table = tempest_forecast_tracks(fields, ibtracs, init) + assert sorted(table["SID"].unique()) == ["2021213N15140", "2021213S15060"] + result = score_forecast_tracks(table, ibtracs, lead_hours=[6, 24, 48]) + for hours in (6, 24, 48): + assert result.metrics[f"track_error_km_{hours}h"] <= HALF_DIAGONAL_KM + assert result.metrics[f"count_{hours}h"] == 2 + assert "intensity_mae_24h" in result.metrics and "pressure_mae_24h" in result.metrics + + +@pytest.mark.parametrize("config", [PANGU_TRACKER, ECMWF_TRACKER, GRAPHCAST_TRACKER], ids=lambda c: c.name) +def test_following_route(case, config): + fields, ibtracs, init = case + table = follow_forecast_tracks(fields, ibtracs, init, config) + assert table.groupby("SID").size().to_dict() == {"2021213N15140": len(HOURS) - 1, "2021213S15060": len(HOURS) - 1} + assert (table["lead_hours"] > 0).all() + result = score_forecast_tracks(table, ibtracs, lead_hours=[6, 24, 48], protocol="pyhazards") + assert result.metrics["track_error_km"] <= HALF_DIAGONAL_KM + only = follow_forecast_tracks(fields, ibtracs, init, config, sids=["2021213S15060"], max_lead_hours=24) + assert set(only["SID"]) == {"2021213S15060"} and only["lead_hours"].max() == 24 diff --git a/tests/test_forecasts_scoring.py b/tests/test_forecasts_scoring.py new file mode 100644 index 00000000..3fd03d7b --- /dev/null +++ b/tests/test_forecasts_scoring.py @@ -0,0 +1,176 @@ +"""IBTrACS matching and track scoring of pyhazards.forecasts, including TCBench's evaluation quirks.""" + +import math + +import numpy as np +import pandas as pd +import pytest + +from pyhazards.forecasts import ( + KT_PER_MS, + TCBENCH_KT_PER_MS, + forecast_track_errors, + great_circle_km, + match_tracks, + matched_forecast_tracks, + score_forecast_tracks, + storms_at, + tcbench_position_error_km, +) + +# Rows printed by TCBench's official notebook (TCBench_Alpha dev/Getting_Started.ipynb, cell 8, +# Pangu-Weather 2023): forecast position, wind (kt) and pressure (hPa) from the released +# matched_tracks/2023_PANGU.csv (m/s and Pa there), IBTrACS v04r01 position / USA_WIND / USA_PRES, and +# the published DPE_GCD (km), AE_wind (kt) and AE_pressure (hPa). Cheneso's IBTrACS longitude is the +# value in TCBench's own 2023_IBTrACS.csv (55.8); NCEI has since revised it to 55.9. +PUBLISHED = [ + # SID, init, valid, wind m/s, pres Pa, lat, lon, ib lat, ib lon, USA_WIND, USA_PRES, DPE, AE wind, AE pres + ("2023013S08081", "2023-01-15 12:00", "2023-01-18 00:00", 15.55148, 100156.1, -14.5, 57.75, -14.0, 55.8, 35, 995, 216.013123, 4.770411, 6.5610), + ("2023290N12256", "2023-10-19 12:00", "2023-10-20 00:00", 21.7195, 98798.56, 17.75, 251.75, 17.9, -108.2, 105, 948, 18.454374, 62.780767, 39.9856), + ("2023129N08091", "2023-05-07 00:00", "2023-05-12 00:00", 20.2564, 99153.78, 12.75, 84.25, 13.3, 88.1, 65, 982, 424.145817, 25.624799, 9.5378), + ("2023193N37305", "2023-07-16 12:00", "2023-07-20 00:00", 12.21571, 101048.8, 32.0, 317.0, 33.8, -40.6, 45, 1001, 302.565885, 21.254614, 9.4880), +] + + +def _published_tables(): + tracks = pd.DataFrame( + { + "SID": [r[0] for r in PUBLISHED] + ["2023251N16334"], + "init_time": pd.to_datetime([r[1] for r in PUBLISHED] + ["2023-09-17 00:00"]), + "valid_time": pd.to_datetime([r[2] for r in PUBLISHED] + ["2023-09-19 06:00"]), + "wind_ms": [r[3] for r in PUBLISHED] + [12.74171], + "pres_pa": [r[4] for r in PUBLISHED] + [101188.7], + "lat": [r[5] for r in PUBLISHED] + [38.75], + "lon": [r[6] for r in PUBLISHED] + [319.5], + } + ) + ibtracs = pd.DataFrame( + { + "SID": [r[0] for r in PUBLISHED] + ["2023251N16334"], + "ISO_TIME": pd.to_datetime([r[2] for r in PUBLISHED] + ["2023-09-19 03:00"]), # Lee: no 06 UTC record + "LAT": [r[7] for r in PUBLISHED] + [38.0], + "LON": [r[8] for r in PUBLISHED] + [-66.0], + "USA_WIND": [r[9] for r in PUBLISHED] + [70], + "USA_PRES": [r[10] for r in PUBLISHED] + [960], + } + ) + return tracks, ibtracs + + +def test_tcbench_protocol_reproduces_the_published_rows(): + tracks, ibtracs = _published_tables() + errors = forecast_track_errors(tracks, ibtracs, protocol="tcbench") + for row, published in zip(errors.itertuples(), PUBLISHED): + assert row.track_error_km == pytest.approx(published[11], abs=5e-7) + assert abs(row.wind_error_kt) == pytest.approx(published[12], abs=5e-7) + assert abs(row.pres_error_hpa) == pytest.approx(published[13], abs=5e-5) + assert math.isnan(errors["track_error_km"].iloc[-1]) # TCBench prints NaN for Lee at 2023-09-19 06 UTC + # The float16 quirk matters: double-precision positions give different numbers. + exact = forecast_track_errors(tracks, ibtracs, protocol="pyhazards") + assert abs(exact["track_error_km"].iloc[3] - 302.565885) > 1.0 + assert exact["track_error_km"].iloc[3] == pytest.approx(float(great_circle_km(33.8, -40.6, 32.0, 317.0))) + assert exact["wind_kt"].iloc[0] == pytest.approx(15.55148 * KT_PER_MS) + assert errors["wind_kt"].iloc[0] == pytest.approx(15.55148 * TCBENCH_KT_PER_MS) + + +def test_tcbench_position_error_emulates_half_precision_latitudes(): + # TCBench evaluates np.radians / np.cos on the float16 latitude column. + value = tcbench_position_error_km([33.8], [-40.6], [32.0], [317.0])[0] + assert value == pytest.approx(302.565885, abs=5e-7) + lat16 = float(np.float16(33.8)) + assert lat16 != 33.8 and abs(value - float(great_circle_km(lat16, float(np.float16(-40.6)) + 360, 32.0, 317.0))) > 1e-3 + + +def test_tcbench_protocol_filters_and_deduplicates(): + tracks, ibtracs = _published_tables() + extra = tracks.iloc[[3]].copy() + extra["init_time"] = pd.Timestamp("2023-07-16 06:00") # 06 UTC initialisations are not evaluated by TCBench + duplicate = tracks.iloc[[3]].copy() + duplicate["lat"] = 0.0 # duplicates of (SID, init, valid) keep the first row + unknown = tracks.iloc[[3]].copy() + unknown["SID"] = "2099001N00000" + table = pd.concat([tracks, extra, duplicate, unknown], ignore_index=True) + errors = forecast_track_errors(table, ibtracs, protocol="tcbench") + assert len(errors) == len(tracks) + assert errors["track_error_km"].iloc[3] == pytest.approx(302.565885, abs=5e-7) + assert len(forecast_track_errors(table, ibtracs, protocol="pyhazards")) == len(tracks) + 1 # keeps 06 UTC + + +def test_score_forecast_tracks_per_lead_metrics(): + ibtracs = pd.DataFrame( + { + "SID": ["A"] * 3 + ["B"] * 3, + "ISO_TIME": pd.to_datetime(["2020-01-01 00:00", "2020-01-02 00:00", "2020-01-03 00:00"] * 2), + "LAT": [10.0, 11.0, 12.0, -10.0, -11.0, -12.0], + "LON": [130.0, 129.0, 128.0, 179.5, -179.5, -178.5], + "USA_WIND": [50, 60, 70, 40, 45, 50], + "USA_PRES": [990, 985, 980, 995, 993, 990], + } + ) + one_degree = 2 * math.pi * 6371.0 / 360 + tracks = pd.DataFrame( + { + "SID": ["A", "A", "B", "B"], + "init_time": pd.to_datetime(["2020-01-01"] * 4), + "valid_time": pd.to_datetime(["2020-01-02", "2020-01-03", "2020-01-02", "2020-01-03"]), + "lat": [12.0, 12.0, -11.0, -12.0], + "lon": [129.0, 128.0, 179.5, 181.5], # B crosses the dateline in the other convention + "wind_ms": [60 / KT_PER_MS, 70 / KT_PER_MS, 55 / KT_PER_MS, 50 / KT_PER_MS], + "pres_pa": [98000.0, 98000.0, 99300.0, 99000.0], + } + ) + result = score_forecast_tracks(tracks, ibtracs, lead_hours=[24, 48], source="unit test") + m = result.metrics + assert result.benchmark_name == "tc" and result.hazard_task == "tc.track_intensity" + assert m["track_error_km_24h"] == pytest.approx((one_degree + one_degree * math.cos(math.radians(11.0))) / 2, rel=1e-3) + assert m["track_error_km_48h"] == pytest.approx(0.0, abs=1e-6) + assert m["intensity_mae_24h"] == pytest.approx(5.0) + assert m["pressure_mae_24h"] == pytest.approx(2.5) + assert m["count_24h"] == 2 and m["count_48h"] == 2 + assert result.metadata["units"] == {"track_error_km": "km", "intensity_mae": "kt", "pressure_mae": "hPa"} + assert result.metadata["num_storms"] == 2 + with pytest.raises(ValueError, match="no forecast rows"): + score_forecast_tracks(tracks.assign(SID="C"), ibtracs) + + +def test_match_tracks_follows_huracanpy_rule(): + reference = pd.DataFrame( + { + "SID": ["S1", "S1", "S2"], + "ISO_TIME": pd.to_datetime(["2020-01-01 00:00", "2020-01-01 06:00", "2020-01-01 06:00"]), + "LAT": [10.0, 10.5, 20.0], + "LON": [130.0, 129.5, 330.0], + } + ) + km_per_deg = math.pi * 6371.0088 / 180 + tracks = pd.DataFrame( + { + "track_id": [0, 0, 1, 2], + "time": pd.to_datetime(["2020-01-01 00:00", "2020-01-01 06:00", "2020-01-01 06:00", "2020-01-01 06:00"]), + "lat": [10.0 + 299.0 / km_per_deg, 10.5, 20.0, 20.0 + 301.0 / km_per_deg], + "lon": [130.0, 129.5, -30.0, -30.0], + "wind10": [20.0, 25.0, 15.0, 15.0], + "slp": [99000.0, 98900.0, 100000.0, 100000.0], + } + ) + pairs = match_tracks(tracks, reference) + assert pairs[["SID", "track_id", "overlap"]].values.tolist() == [["S1", 0, 2], ["S2", 1, 1]] + assert pairs["mean_dist_km"].iloc[0] == pytest.approx(149.5, rel=1e-6) + assert match_tracks(tracks, reference, min_overlap=2)["SID"].tolist() == ["S1"] + table = matched_forecast_tracks(tracks, reference, "2019-12-31 18:00") + assert table.groupby("SID").size().to_dict() == {"S1": 2, "S2": 1} + assert table["lead_hours"].tolist() == [6.0, 12.0, 12.0] + assert table["wind_ms"].tolist() == [20.0, 25.0, 15.0] + + +def test_storms_at_skips_spurs(): + ibtracs = pd.DataFrame( + { + "SID": ["A", "B", "B"], + "ISO_TIME": pd.to_datetime(["2020-01-01"] * 3), + "LAT": [10.0, 11.0, 11.5], + "LON": [130.0, 140.0, 141.0], + "TRACK_TYPE": ["main", "main", "spur-main"], + } + ) + assert storms_at(ibtracs, "2020-01-01")[["SID", "LAT"]].values.tolist() == [["A", 10.0], ["B", 11.0]] diff --git a/tests/test_forecasts_sources.py b/tests/test_forecasts_sources.py new file mode 100644 index 00000000..82ad5eaf --- /dev/null +++ b/tests/test_forecasts_sources.py @@ -0,0 +1,187 @@ +"""Forecast sources of pyhazards.forecasts (TCBench files, WeatherBench 2, earth2studio) on local fixtures.""" + +import importlib.util + +import numpy as np +import pandas as pd +import pytest +import xarray as xr + +from pyhazards.forecasts import ( + FOUNDATION_MODELS, + TCBENCH_MODELS, + WEATHERBENCH2_FORECASTS, + read_tcbench_fields, + read_tcbench_matched_tracks, + run_earth2studio_forecast, + standardize_fields, + tcbench_path, +) +from pyhazards.forecasts.tcbench import download_tcbench_file, tcbench_url +from pyhazards.forecasts.weatherbench2 import weatherbench2_url + + +def test_tcbench_paths_follow_the_released_layout(): + init = "2023-07-16 12:00" + assert tcbench_path("pangu", "fields", init) == ( + "neural_weather_models/panguweather/panguweather_2023.07.16-12h00_maxltd-120_timeres-6.nc" + ) + assert tcbench_path("fourcastnet_v2", "unmatched", init) == ( + "unmatched_tracks/2023_fcnet/fcnet_2023.07.16-12h00m_maxltd-120_timeres-6.csv" + ) + assert tcbench_path("aifs", "unmatched", "2023-01-01") == "unmatched_tracks/2023_aifs/AIFS_init-2023.01.01-00h00_max-lead-120.csv" + assert tcbench_path("pangu", "matched") == "matched_tracks/2023_PANGU.csv" + assert "0124d14d7f1f468096f46aec1e79696ab9c880c1" in tcbench_url("2023_IBTrACS.csv") + with pytest.raises(ValueError, match="unknown TCBench model"): + tcbench_path("graphcast", "matched") + with pytest.raises(ValueError, match="3 GB"): + download_tcbench_file(tcbench_path("pangu", "fields", init), "/nonexistent") + assert set(TCBENCH_MODELS) == {"pangu", "fourcastnet_v2", "aifs"} + + +def test_read_tcbench_matched_tracks_units(tmp_path): + path = tmp_path / "2023_PANGU.csv" + path.write_text( + "SID,Initial Time,Valid Time,wind max,pressure min,lat,lon\n" + "2023005S18142,2023-01-09 12:00:00,2023-01-10 12:00:00,13.39205,98565.07,-36.75,176.5\n" + "2023005S18142,2023-01-09 12:00:00,2023-01-10 18:00:00,13.1802,98512.62,-37.5,176.25\n" + ) + table = read_tcbench_matched_tracks(path) + assert table.columns.tolist() == ["SID", "init_time", "valid_time", "lead_hours", "lat", "lon", "wind_ms", "pres_pa"] + assert table["lead_hours"].tolist() == [24.0, 30.0] + assert table["wind_ms"].iloc[0] == pytest.approx(13.39205) + converted = tmp_path / "converted.csv" + converted.write_text( # TCBench's track_matcher.py output: knots (x 1.94384) and hPa + "SID,Initial Time,Valid Time,wind max,pressure min,lat,lon\n" + f"2023005S18142,2023-01-09 12:00:00,2023-01-10 12:00:00,{13.39205 * 1.94384!r},985.6507,-36.75,176.5\n" + ) + back = read_tcbench_matched_tracks(converted, units="kt_hpa") + assert back["wind_ms"].iloc[0] == pytest.approx(13.39205, rel=1e-12) + assert back["pres_pa"].iloc[0] == pytest.approx(98565.07) + bad = tmp_path / "bad.csv" + bad.write_text("SID,lat\nX,1\n") + with pytest.raises(ValueError, match="matched-tracks"): + read_tcbench_matched_tracks(bad) + + +def _write_tcbench_like_file(path): + """A small netCDF4 file with the layout of TCBench's raw ai-models outputs (int16, scale/offset).""" + import netCDF4 + + rng = np.random.default_rng(0) + lat = np.array([20.0, 10.0, 0.0, -10.0, -20.0]) + lon = np.arange(0.0, 360.0, 45.0) + levels = np.array([1000, 850, 500, 300]) + with netCDF4.Dataset(path, "w") as ds: + ds.createDimension("time", 1) + ds.createDimension("leadtime_hours", 3) + ds.createDimension("latitude", lat.size) + ds.createDimension("longitude", lon.size) + ds.createDimension("level", levels.size) + ds.createVariable("time", "i8", ("time",))[:] = [0] + ds.createVariable("leadtime_hours", "i8", ("leadtime_hours",))[:] = [6, 12, 18] + ds.createVariable("latitude", "f8", ("latitude",))[:] = lat + ds.createVariable("longitude", "f8", ("longitude",))[:] = lon + ds.createVariable("level", "i8", ("level",))[:] = levels + packed = {} + for name, dims, scale, offset in ( + ("msl", ("time", "leadtime_hours", "latitude", "longitude"), 1.1892572, 100941.74), + ("z", ("time", "leadtime_hours", "level", "latitude", "longitude"), 59.82942969, 78446.516), + ): + var = ds.createVariable(name, "i2", dims, fill_value=np.int16(-32767)) + var.set_auto_maskandscale(False) + var.scale_factor = np.float64(scale) + var.add_offset = np.float32(offset) + shape = tuple(ds.dimensions[d].size for d in dims) + values = rng.integers(-30000, 30000, size=shape, dtype=np.int16) + values.flat[0] = -32767 + var[:] = values + packed[name] = (values, np.float64(scale), float(np.float32(offset))) + return lat, lon, levels, packed + + +def test_read_tcbench_fields_unpacks_selected_levels(tmp_path): + path = tmp_path / "panguweather_2023.07.16-12h00_maxltd-120_timeres-6.nc" + lat, lon, levels, packed = _write_tcbench_like_file(path) + ds = read_tcbench_fields("pangu", "2023-07-16 12:00", variables=("msl", "z500"), path=path) + assert list(ds.data_vars) == ["msl", "z500"] and ds["msl"].dtype == np.float32 + assert ds["time"].values[0] == np.datetime64("2023-07-16T18:00") + np.testing.assert_array_equal(ds["lat"].values, lat) + raw, scale, offset = packed["z"] + expected = (raw[0, :, list(levels).index(500)].astype(np.float64) * scale + offset).astype(np.float32) + np.testing.assert_array_equal(ds["z500"].values, expected) + raw, scale, offset = packed["msl"] + assert np.isnan(ds["msl"].values[0, 0, 0]) # the fill value + np.testing.assert_array_equal(ds["msl"].values[0, 0, 1:], (raw[0, 0, 0, 1:].astype(np.float64) * scale + offset).astype(np.float32)) + with pytest.raises(KeyError, match="level 200"): + read_tcbench_fields("pangu", "2023-07-16 12:00", variables=("z200",), path=path) + with pytest.raises(ValueError, match="cannot map"): + read_tcbench_fields("pangu", "2023-07-16 12:00", variables=("vorticity",), path=path) + + +def test_standardize_fields_accepts_common_layouts(): + time = pd.date_range("2020-01-01", periods=2, freq="6h") + lat, lon = np.array([10.0, 0.0]), np.array([0.0, 90.0, 180.0, 270.0]) + wb2 = xr.Dataset( + { + "mean_sea_level_pressure": (("time", "latitude", "longitude"), np.ones((2, 2, 4))), + "u_component_of_wind": (("time", "level", "latitude", "longitude"), np.ones((2, 2, 2, 4))), + }, + coords={"time": time, "latitude": lat, "longitude": lon, "level": [500, 850]}, + ) + out = standardize_fields(wb2) + assert sorted(out.data_vars) == ["msl", "u500", "u850"] and out["msl"].dims == ("time", "lat", "lon") + e2s = xr.Dataset({"u10m": (("valid_time", "lat", "lon"), np.ones((2, 2, 4)))}, coords={"valid_time": time, "lat": lat, "lon": lon}) + assert list(standardize_fields(e2s, variables=["u10"]).data_vars) == ["u10"] + with pytest.raises(KeyError, match="lacks"): + standardize_fields(e2s, variables=["msl"]) + + +def test_weatherbench2_store_lookup(): + assert weatherbench2_url("graphcast", "2018-09-30T00").endswith("graphcast/2018/date_range_2017-11-16_2019-02-01_12_hours.zarr") + assert weatherbench2_url("graphcast", "2019-01-15T00").endswith("graphcast/2018/date_range_2017-11-16_2019-02-01_12_hours.zarr") + assert weatherbench2_url("pangu", "2021-08-01").endswith("pangu/2018-2022_0012_0p25.zarr") + assert weatherbench2_url("pangu_hres_init", "2021-08-01").endswith("pangu_hres_init/2021_0012_0p25.zarr") + with pytest.raises(ValueError, match="no WeatherBench 2 graphcast store"): + weatherbench2_url("graphcast", "2022-06-01") + assert "fourcastnet" not in WEATHERBENCH2_FORECASTS + + +@pytest.mark.skipif(importlib.util.find_spec("zarr") is None, reason="zarr is an optional dependency (pyhazards[weather])") +def test_weatherbench2_reader_on_a_local_store(tmp_path): + from pyhazards.forecasts import read_weatherbench2_forecast + + init = pd.Timestamp("2018-09-30T00") + lat, lon = np.linspace(90, -90, 7), np.arange(0, 360, 60.0) + store = xr.Dataset( + { + "mean_sea_level_pressure": (("time", "prediction_timedelta", "latitude", "longitude"), np.arange(2 * 3 * 7 * 6, dtype=np.float32).reshape(2, 3, 7, 6)), + "geopotential": (("time", "prediction_timedelta", "level", "latitude", "longitude"), np.ones((2, 3, 2, 7, 6), dtype=np.float32)), + }, + coords={"time": [init, init + pd.Timedelta(hours=12)], "prediction_timedelta": np.array([6, 12, 18]), "level": [300, 500], "latitude": lat, "longitude": lon}, + ) + store["prediction_timedelta"].attrs["units"] = "hours" + path = tmp_path / "pangu.zarr" + store.to_zarr(path, consolidated=True) + ds = read_weatherbench2_forecast("pangu", init, variables=("msl", "z300"), lead_hours=[6, 18], url=str(path), lon_bounds=(300, 60)) + assert ds.sizes == {"time": 2, "lat": 7, "lon": 3} + assert ds["lon"].values.tolist() == [0.0, 60.0, 300.0] + np.testing.assert_array_equal(ds["msl"].values[1], store["mean_sea_level_pressure"].values[0, 2][:, [0, 1, 5]]) + with pytest.raises(KeyError, match="lead times"): + read_weatherbench2_forecast("pangu", init, variables=("msl",), lead_hours=[24], url=str(path)) + + +def test_earth2studio_runner_reports_missing_dependency(): + if importlib.util.find_spec("earth2studio") is not None: + pytest.skip("earth2studio is installed; covered by tests/oracle/test_forecasts_weather_oracle.py") + with pytest.raises(ImportError, match="earth2studio"): + run_earth2studio_forecast(object(), object(), "2020-01-01") + + +def test_foundation_model_catalog_states_licences(): + assert set(FOUNDATION_MODELS) == {"fourcastnet", "graphcast", "pangu_weather"} + pangu = FOUNDATION_MODELS["pangu_weather"] + assert "NC" in pangu.weights_license and "commercial" in pangu.weights_license + assert "120.29" in pangu.paper_tc_evaluation + assert FOUNDATION_MODELS["graphcast"].code_license == "Apache-2.0" + assert "BSD-3" in FOUNDATION_MODELS["fourcastnet"].code_license diff --git a/tests/test_forecasts_tracking.py b/tests/test_forecasts_tracking.py new file mode 100644 index 00000000..463dd38a --- /dev/null +++ b/tests/test_forecasts_tracking.py @@ -0,0 +1,251 @@ +"""Cyclone trackers of pyhazards.forecasts on synthetic vortices with known tracks.""" + +import ast +import math + +import numpy as np +import pandas as pd +import pytest + +from pyhazards.forecasts import ( + ECMWF_TRACKER, + GRAPHCAST_TRACKER, + PANGU_TRACKER, + TCBENCH_DETECT_NODES, + TCBENCH_STITCH_NODES, + ClosedContourCriterion, + DetectNodesConfig, + StitchNodesConfig, + StitchThreshold, + detect_nodes, + follow_cyclone, + great_circle_km, + read_stitchnodes_csv, + relative_vorticity, + required_variables, + stitch_nodes, + tempest_tracks, + write_stitchnodes_csv, +) +from pyhazards.forecasts.following import with_overrides +from pyhazards.forecasts.synthetic import SyntheticVortex, synthetic_cyclone_fields + +HOURS = list(range(0, 73, 6)) +# Grid points are 0.5 degrees apart: a centre is never more than half a cell diagonal from the truth. +HALF_DIAGONAL_KM = 0.5 * math.hypot(0.5, 0.5) * math.pi * 6371.0 / 180.0 + + +def _errors(track, truth, hours=HOURS, times=None): + out = [] + for lat, lon, lead in zip(track["lat"], track["lon"], track["lead_hours"]): + true_lat, true_lon = truth[hours.index(int(lead))] + out.append(float(great_circle_km(lat, lon, true_lat, true_lon))) + return out + + +@pytest.fixture(scope="module") +def storms(): + vortices = [ + SyntheticVortex(15.0, 140.0, u=-5.0, v=2.0), # NH cyclone moving west-north-west + SyntheticVortex(-15.0, 60.0, u=-4.0, v=-2.0), # SH cyclone (clockwise) + SyntheticVortex(25.0, 300.0, u=3.0, v=3.0, warm_core=0.0), # cold-core low + SyntheticVortex(10.0, 200.0, pressure_drop=100.0), # too shallow for a 200 Pa closed contour + ] + ds = synthetic_cyclone_fields(vortices, HOURS) + return vortices, ds, ast.literal_eval(ds.attrs["tracks"]) + + +def _tempest_inputs(ds): + return {name: ds[name].values for name in ("msl", "u10", "v10", "z300", "z500")}, ds["lat"].values, ds["lon"].values, ds["time"].values + + +def test_tempest_tracks_follow_warm_core_cyclones_only(storms): + _, ds, truth = storms + tracks = tempest_tracks(*_tempest_inputs(ds)) + assert sorted(tracks["track_id"].unique()) == [0, 1] + # Paths are ordered by their first node's grid index: with latitudes stored north to south, the + # Northern Hemisphere storm comes first. + for track_id, expected in ((0, truth[0]), (1, truth[1])): + points = tracks[tracks["track_id"] == track_id] + leads = ((pd.to_datetime(points["time"]) - pd.Timestamp(ds["time"].values[0])).dt.total_seconds() / 3600).astype(int) + assert len(points) == len(HOURS) + for lat, lon, lead in zip(points["lat"], points["lon"], leads): + true_lat, true_lon = expected[HOURS.index(lead)] + assert great_circle_km(lat, lon, true_lat, true_lon) <= HALF_DIAGONAL_KM + assert points["wind10"].max() > 25.0 + assert (points["slp"] < 101325 - 1500).all() + + +def test_tempest_nodes_columns_and_formatting(storms): + _, ds, _ = storms + nodes = detect_nodes(*_tempest_inputs(ds)) + assert list(nodes.columns[:7]) == ["time", "i", "j", "text_lon", "text_lat", "text_slp", "text_wind10"] + first = nodes.iloc[0] + assert first["text_lon"] == "%3.6f" % first["lon"] and "e+0" in first["text_slp"] + # Nodes of one time are in DetectNodes' order (ascending flat grid index). + one = nodes[nodes["time"] == nodes["time"].iloc[0]] + flat = one["j"] * ds.sizes["lon"] + one["i"] + assert list(flat) == sorted(flat) + + +def test_tempest_csv_round_trip(storms, tmp_path): + _, ds, _ = storms + tracks = tempest_tracks(*_tempest_inputs(ds)) + path = tmp_path / "tracks.csv" + write_stitchnodes_csv(tracks, path) + lines = path.read_text().splitlines() + assert lines[0] == "track_id, year, month, day, hour, i, j, lon, lat, slp, wind10" + back = read_stitchnodes_csv(path) + assert (back["text_lat"].to_numpy() == tracks["text_lat"].to_numpy()).all() + pd.testing.assert_series_equal(back["time"], tracks["time"], check_names=False) + write_stitchnodes_csv(back, tmp_path / "again.csv") + assert (tmp_path / "again.csv").read_text() == path.read_text() + + +def _nodes(rows): + frame = pd.DataFrame(rows, columns=["time", "i", "j", "lon", "lat", "wind"]) + frame["time"] = pd.to_datetime(frame["time"]) + return frame + + +def test_stitch_first_come_first_served_and_filters(): + t = ["2020-01-01T00", "2020-01-01T06", "2020-01-01T12", "2020-01-01T18"] + rows = [ + (t[0], 0, 0, 100.0, 10.0, 20.0), + (t[0], 1, 0, 101.0, 10.0, 20.0), # also nearest to the same node at t1: shares it, path ends there + (t[1], 0, 0, 100.5, 10.0, 20.0), + (t[2], 0, 0, 101.0, 10.0, 5.0), + (t[3], 0, 0, 130.0, 10.0, 20.0), # beyond 8 degrees: not linked + ] + config = StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time=1) + tracks = stitch_nodes(_nodes(rows), config) + assert tracks.groupby("track_id").size().tolist() == [3, 2] + assert tracks[tracks["track_id"] == 0]["lon"].tolist() == [100.0, 100.5, 101.0] + assert tracks[tracks["track_id"] == 1]["lon"].tolist() == [101.0, 100.5] + # min_time as a duration; thresholds with counts. + longer = stitch_nodes(_nodes(rows), StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time="12h")) + assert longer["track_id"].nunique() == 1 + strict = StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time=1, thresholds=(StitchThreshold("wind", ">=", 10.0, "all"),)) + assert stitch_nodes(_nodes(rows), strict)["track_id"].nunique() == 1 # the 3-point path has a weak point + last = StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time=1, thresholds=(StitchThreshold("wind", "<", 10.0, "last"),)) + assert stitch_nodes(_nodes(rows), last)["lon"].tolist() == [100.0, 100.5, 101.0] + + +def test_stitch_max_gap_bridges_missing_steps(): + t = ["2020-01-01T00", "2020-01-01T06", "2020-01-01T12"] + rows = [(t[0], 0, 0, 100.0, 10.0, 20.0), (t[1], 0, 0, 150.0, -40.0, 20.0), (t[2], 0, 0, 101.0, 10.0, 20.0)] + nodes = _nodes(rows) + no_gap = stitch_nodes(nodes, StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time=2)) + assert no_gap.empty + gap = stitch_nodes(nodes, StitchNodesConfig(columns=("lon", "lat", "wind"), range_deg=8.0, min_time=2, max_gap=1)) + assert gap["lon"].tolist() == [100.0, 101.0] + + +def test_tempest_configuration_validation(): + with pytest.raises(ValueError, match="non-zero"): + ClosedContourCriterion("msl", 0.0, 5.5) + with pytest.raises(NotImplementedError): + from pyhazards.forecasts import NodeOutput + + NodeOutput("msl", "avg", 1.0) + with pytest.raises(ValueError, match="threshold column"): + StitchNodesConfig(columns=("lon", "lat"), thresholds=(StitchThreshold("wind", ">=", 1.0, 1),)) + with pytest.raises(NotImplementedError, match="_LAT"): + detect_nodes( + {"msl": np.random.rand(1, 5, 8)}, + np.linspace(-60, 60, 5), + np.arange(0, 360, 45.0), + ["2020-01-01"], + DetectNodesConfig(closed_contours=(ClosedContourCriterion("_LAT(msl,1)", 1.0, 5.0),)), + ) + with pytest.raises(ValueError, match="shaped"): + detect_nodes({"msl": np.zeros((2, 5, 8))}, np.linspace(-60, 60, 5), np.arange(0, 360, 45.0), ["2020-01-01"]) + assert TCBENCH_DETECT_NODES.merge_dist == 6.0 and TCBENCH_STITCH_NODES.range_deg == 8.0 + + +@pytest.mark.parametrize("config", [PANGU_TRACKER, ECMWF_TRACKER, GRAPHCAST_TRACKER], ids=lambda c: c.name) +def test_following_tracker_presets_follow_both_hemispheres(storms, config): + vortices, ds, truth = storms + for k in (0, 1): + track = follow_cyclone(ds, vortices[k].lat, vortices[k].lon, ds["time"].values[0], config) + expected_points = len(HOURS) - (0 if config.relocate_start else 1) + assert len(track) == expected_points, track.attrs["stop_reason"] + assert max(_errors(track, truth[k])) <= HALF_DIAGONAL_KM + assert track.attrs["stop_reason"] == "end of forecast" + assert (track["msl"] < 101325 - 1500).all() and track["wind_max"].min() > 20.0 + + +def test_graphcast_preset_uses_the_selected_hyperparameters(): + assert GRAPHCAST_TRACKER.search_radius_km == pytest.approx(222.5) + assert GRAPHCAST_TRACKER.check_radius_km == pytest.approx(208.5) + assert GRAPHCAST_TRACKER.steering_weight == 0.5 and GRAPHCAST_TRACKER.max_turn_deg == 90.0 + assert GRAPHCAST_TRACKER.max_first_guess_km is None + assert ECMWF_TRACKER.search_radius_km == 445.0 and ECMWF_TRACKER.check_radius_km == 278.0 + assert not PANGU_TRACKER.use_first_guess and not PANGU_TRACKER.relocate_start + assert set(required_variables(GRAPHCAST_TRACKER)) >= {"msl", "u850", "v850", "u200", "v700"} + assert "z200" in required_variables(with_overrides(PANGU_TRACKER, extratropical_latitude=30.0)) + + +def test_vorticity_check_rejects_lows_without_circulation(): + hours = [0, 6] + storm = SyntheticVortex(15.0, 140.0, u=-15.0, v=0.0) + decoy = SyntheticVortex(15.0, 141.5, u=0.0, v=0.0, vmax=0.0) # a pressure low with no cyclonic winds + ds = synthetic_cyclone_fields([storm, decoy], hours) + truth = ast.literal_eval(ds.attrs["tracks"]) + start = ds["time"].values[0] + # Searching around the start (Pangu rules), the decoy is the closer minimum but fails the vorticity check. + assert great_circle_km(15.0, 140.0, *truth[1][1]) < great_circle_km(15.0, 140.0, *truth[0][1]) < PANGU_TRACKER.search_radius_km + track = follow_cyclone(ds, 15.0, 140.0, start, PANGU_TRACKER) + assert len(track) == 1 + assert great_circle_km(track["lat"].iloc[0], track["lon"].iloc[0], *truth[0][1]) <= HALF_DIAGONAL_KM + vort = relative_vorticity(ds["u850"].values[1], ds["v850"].values[1], ds["lat"].values, ds["lon"].values) + from pyhazards.forecasts.following import _disk + + rows, cols, _ = _disk(ds["lat"].values, ds["lon"].values, 15.0, 141.5, PANGU_TRACKER.check_radius_km) + assert np.nanmax(vort[rows, cols]) < PANGU_TRACKER.vorticity_threshold # what the check sees around the decoy + + +def test_graphcast_turn_limit_and_land_and_thickness_checks(): + # The storm sits still while its previous motion was eastward: any move west turns by > 90 degrees. + ds = synthetic_cyclone_fields([SyntheticVortex(15.0, 140.0, u=-6.0, v=0.0)], [0, 6]) + previous = (15.0, 139.0) # 6 h earlier the storm was west of its start: it was moving east + ecmwf = follow_cyclone(ds, 15.0, 140.0, ds["time"].values[0], with_overrides(ECMWF_TRACKER, steering_weight=0.0), previous_position=previous) + graphcast = follow_cyclone(ds, 15.0, 140.0, ds["time"].values[0], with_overrides(GRAPHCAST_TRACKER, steering_weight=0.0, search_radius_km=445.0), previous_position=previous) + assert len(ecmwf) == 2 and len(graphcast) == 1 # GraphCast keeps lead 0 and stops at 6 h + assert "no qualifying minimum" in graphcast.attrs["stop_reason"] + + # A weak storm over land (lsm = 1) fails the 8 m/s wind check. + weak = SyntheticVortex(30.0, 260.0, u=0.0, v=0.0, vmax=6.0) + land = synthetic_cyclone_fields([weak], [0, 6], land_mask=True) + assert float(land["lsm"].sel(lat=30.0, lon=260.0)) == 1.0 + assert len(follow_cyclone(land, 30.0, 260.0, land["time"].values[0], PANGU_TRACKER)) == 0 + sea = land.drop_vars("lsm") + assert len(follow_cyclone(sea, 30.0, 260.0, sea["time"].values[0], PANGU_TRACKER)) == 1 + + # Extratropical (poleward of the configured latitude) cold-core lows fail the thickness check. + cold = synthetic_cyclone_fields([SyntheticVortex(40.0, 170.0, u=0.0, v=0.0, warm_core=0.0)], [0, 6]) + warm = synthetic_cyclone_fields([SyntheticVortex(40.0, 170.0, u=0.0, v=0.0)], [0, 6]) + config = with_overrides(PANGU_TRACKER, extratropical_latitude=35.0) + assert len(follow_cyclone(cold, 40.0, 170.0, cold["time"].values[0], config)) == 0 + assert len(follow_cyclone(warm, 40.0, 170.0, warm["time"].values[0], config)) == 1 + assert len(follow_cyclone(cold, 40.0, 170.0, cold["time"].values[0], PANGU_TRACKER)) == 1 + + +def test_following_tracker_input_validation(storms): + _, ds, _ = storms + with pytest.raises(KeyError, match="u850"): + follow_cyclone(ds.drop_vars("u850"), 15.0, 140.0, ds["time"].values[0], PANGU_TRACKER) + with pytest.raises(ValueError, match="steering_weight"): + with_overrides(ECMWF_TRACKER, steering_weight=1.5) + + +def test_relative_vorticity_of_solid_body_rotation(): + lat = np.linspace(-60, 60, 121) + lon = np.arange(0, 360, 1.0) + omega = 1e-5 + a = 6371e3 + # Zonal flow u = omega * a * cos(lat) (solid-body rotation about the polar axis) has zeta = 2 omega sin(lat). + u = omega * a * np.cos(np.deg2rad(lat))[:, None] * np.ones((1, lon.size)) + zeta = relative_vorticity(u, np.zeros_like(u), lat, lon) + expected = 2 * omega * np.sin(np.deg2rad(lat))[:, None] + np.testing.assert_allclose(zeta[1:-1], np.broadcast_to(expected, zeta.shape)[1:-1], atol=2e-9) diff --git a/tests/test_forefire_simulator.py b/tests/test_forefire_simulator.py new file mode 100644 index 00000000..e1b80e5c --- /dev/null +++ b/tests/test_forefire_simulator.py @@ -0,0 +1,160 @@ +"""ForeFireSimulator without ForeFire: input conversion, validation and result helpers. + +The comparison with the official ForeFire engine lives in tests/oracle/test_forefire_oracle.py. +""" + +import subprocess +import sys + +import numpy as np +import pytest + +from pyhazards.simulators import ForeFireNotInstalledError, ForeFireResult, ForeFireSimulator +from pyhazards.simulators.forefire import _reduce_min + +TABLE = "Index;vv_coeff;Kcurv;beta\n1;1.0;1.0;1.0\n2;1.0;1.0;1.0" + + +def _job(**kwargs): + sim = ForeFireSimulator("WindDriven", fuels_table=TABLE) + args = dict( + fuel=np.ones((4, 6), dtype=np.int32), + cell_size=10.0, + duration=60.0, + ignition_mask=None, + ignition_points=[(30.0, 20.0)], + wind=None, + wind_u=None, + wind_v=None, + wind_triggers=None, + altitude=None, + output_shape=None, + origin="upper", + ) + args.update(kwargs) + return sim._build_job(**args) + + +def test_importing_the_adapter_does_not_need_forefire(): + code = ( + "import sys, pyhazards.simulators, pyhazards.datasets.wrf_sfire;" + "assert 'pyforefire' not in sys.modules" + ) + subprocess.run([sys.executable, "-c", code], check=True) + + +def test_missing_forefire_raises_with_install_hint(monkeypatch): + monkeypatch.setitem(sys.modules, "pyforefire", None) # makes `import pyforefire` fail + fuel = np.ones((4, 4), dtype=np.int32) + for isolate in (True, False): + sim = ForeFireSimulator("Iso", isolate=isolate) + with pytest.raises(ForeFireNotInstalledError, match="pip install forefire"): + sim.run(fuel, 10.0, 30.0, ignition_points=[(20.0, 20.0)]) + + +def test_domain_and_layers_follow_forefire_conventions(): + fuel = np.arange(24, dtype=np.int32).reshape(4, 6) % 2 + 1 + job = _job(fuel=fuel, cell_size=(5.0, 10.0), ignition_points=[(30.0, 10.0)]) + assert (job["width"], job["height"]) == (60.0, 20.0) + assert (job["atmo_nx"], job["atmo_ny"]) == (6, 4) + # (t, z, y, x) with y growing northward: row 0 of a north-up raster becomes the last y index. + assert job["fuel"].shape == (1, 1, 4, 6) and job["fuel"].dtype == np.int32 + np.testing.assert_array_equal(job["fuel"][0, 0], fuel[::-1]) + lower = _job(fuel=fuel, origin="lower") + np.testing.assert_array_equal(lower["fuel"][0, 0], fuel) + + +def test_ignition_mask_cells_become_cell_centres(): + mask = np.zeros((4, 6), dtype=bool) + mask[0, 1] = True # north-west area, top row + mask[3, 5] = True # bottom-right + job = _job(ignition_mask=mask, ignition_points=None) + assert sorted(job["ignitions"]) == [(15.0, 35.0), (55.0, 5.0)] + lower = _job(ignition_mask=mask, ignition_points=None, origin="lower") + assert sorted(lower["ignitions"]) == [(15.0, 5.0), (55.0, 35.0)] + + +def test_wind_modes(): + constant = _job(wind=(3.0, -1.0)) + assert constant["wind_mode"] == "coefficients" and constant["wind_triggers"] == [(0.0, 3.0, -1.0)] + # Unit direction fields, as in the official idealized examples. + np.testing.assert_array_equal(constant["wind_u"][0, 0], np.ones((4, 6))) + np.testing.assert_array_equal(constant["wind_u"][0, 1], np.zeros((4, 6))) + np.testing.assert_array_equal(constant["wind_v"][0, 1], np.ones((4, 6))) + + field = _job(wind_u=np.full((2, 3), 2.0), wind_v=np.zeros((2, 3))) + assert field["wind_mode"] == "field" and field["wind_u"].shape == (1, 1, 2, 3) + + coeff = _job(wind_u=np.ones((2, 2, 3)), wind_v=np.zeros((2, 2, 3)), wind_triggers=[(30.0, 1.0, 0.0), (0.0, 0.0, 1.0)]) + assert coeff["wind_mode"] == "coefficients" and coeff["wind_u"].shape == (1, 2, 2, 3) + assert coeff["wind_triggers"] == [(0.0, 0.0, 1.0), (30.0, 1.0, 0.0)] + assert _job()["wind_mode"] == "none" + + +@pytest.mark.parametrize( + "kwargs, message", + [ + ({"fuel": np.ones((4,))}, "2-D raster"), + ({"fuel": np.full((4, 4), 1.5)}, "integer fuel codes"), + ({"fuel": np.full((4, 4), 3)}, "not in the Index column"), + ({"fuel": np.full((4, 4), 2000)}, r"\[0, 1023\]"), + ({"cell_size": -1.0}, "cell_size"), + ({"duration": 0.0}, "duration"), + ({"ignition_points": None}, "ignition"), + ({"ignition_points": [(500.0, 5.0)]}, "outside the domain"), + ({"ignition_points": [(5.0, 5.0, 1.0)]}, r"\(x, y\)"), + ({"wind": (1.0, 0.0), "wind_triggers": [(0.0, 1.0, 0.0)]}, "not both"), + ({"wind_triggers": [(60.0, 1.0, 0.0)]}, "0 <= t < duration"), + ({"wind_u": np.ones((2, 2))}, "together"), + ({"wind_u": np.ones((2, 2)), "wind_v": np.ones((2, 2)), "wind": (1.0, 0.0)}, "direction-coefficient"), + ({"wind_u": np.ones((3, 2, 2)), "wind_v": np.ones((3, 2, 2))}, r"\(2, h, w\)"), + ({"altitude": np.ones((2, 2, 2))}, "altitude"), + ({"output_shape": (0, 3)}, "output_shape"), + ({"origin": "north"}, "origin"), + ], +) +def test_invalid_inputs_raise(kwargs, message): + with pytest.raises(ValueError, match=message): + _job(**kwargs) + + +def test_trigger_mode_and_parameters_are_checked(): + with pytest.raises(ValueError, match="trigger_mode"): + _job(trigger_mode="later") + for reserved in ("atmoNX", "propagationModel", "fuelsTable"): + with pytest.raises(ValueError, match="managed by the adapter"): + ForeFireSimulator("Iso", parameters={reserved: 1}) + with pytest.raises(ValueError, match="int, float or str"): + ForeFireSimulator("Iso", parameters={"relax": [0.5]}) + sim = ForeFireSimulator("Iso", parameters={"noInitialScan": True, "relax": 0.5}) + assert sim.parameters == {"noInitialScan": 1, "relax": 0.5} + # Unknown fuel codes can be passed through on request (ForeFire then uses zero properties). + loose = ForeFireSimulator("WindDriven", fuels_table=TABLE, allow_unknown_fuels=True) + loose._check_fuel_codes(np.full((2, 2), 7.0)) + + +def test_reduce_min_takes_earliest_arrival_per_output_cell(): + native = np.arange(36, dtype=float).reshape(6, 6) + native[0, 0] = np.inf + out = _reduce_min(native, (2, 3)) + assert out.shape == (2, 3) + assert out[0, 0] == 1.0 # min over rows 0-2, cols 0-1, skipping the inf + assert out[1, 2] == native[3:6, 4:6].min() + np.testing.assert_array_equal(_reduce_min(native, (6, 6)), native) + + +def test_result_masks_and_area(): + arrival = np.array([[0.0, 10.0], [np.inf, 30.0]]) + result = ForeFireResult( + arrival_time=arrival, + arrival_time_native=arrival, + duration=30.0, + cell_size=(5.0, 5.0), + native_cell_size=(5.0, 5.0), + origin="upper", + ) + np.testing.assert_array_equal(result.burned_mask(), [[True, True], [False, True]]) + np.testing.assert_array_equal(result.burned_mask(10.0), [[True, True], [False, False]]) + stack = result.burned_masks([0.0, 30.0]) + assert stack.shape == (2, 2, 2) and stack.dtype == np.float32 + assert result.burned_area() == 75.0 diff --git a/tests/test_fpa_fod_models.py b/tests/test_fpa_fod_models.py index 410967cd..7a5a4303 100644 --- a/tests/test_fpa_fod_models.py +++ b/tests/test_fpa_fod_models.py @@ -59,37 +59,32 @@ def test_wildfire_fpa_autoencoder_forward(): def test_added_wildfire_public_methods_forward(): - weekly_x = torch.randn(2, 12, 7) - spread_x = torch.randn(2, 12, 16, 16) + daily_x = torch.randn(2, 10, 25) temporal_spread_x = torch.randn(2, 4, 6, 16, 16) - forecasting = build_model( - name="wildfire_forecasting", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) - asufm = build_model( - name="asufm", - task="forecasting", - input_dim=7, - output_dim=5, - lookback=12, - ) + danger = build_model(name="wildfire_forecasting", task="classification") spread_ts = build_model( name="wildfirespreadts", task="segmentation", history=4, in_channels=6, ) - forefire = build_model(name="forefire", task="segmentation", in_channels=12) - wrf_sfire = build_model(name="wrf_sfire", task="segmentation", in_channels=12) - firecastnet = build_model(name="firecastnet", task="segmentation", in_channels=12) + # FireCastNet on a 16 x 16 window of 0.25-degree cells (4 x 4 one-degree graph nodes). + firecastnet = build_model( + name="firecastnet", + task="segmentation", + in_channels=6, + timeseries_len=4, + mesh_levels=(0, 1, 2, 3, 4), + sp_res=0.25, + max_lat=41.875, + min_lat=38.125, + max_lon=-120.125, + min_lon=-123.875, + hidden_dim=16, + embed_cube_dim=16, + ) - assert forecasting(weekly_x).shape == (2, 5) - assert asufm(weekly_x).shape == (2, 5) + assert danger(daily_x).shape == (2, 2) assert spread_ts(temporal_spread_x).shape == (2, 1, 16, 16) - assert forefire(spread_x).shape == (2, 1, 16, 16) - assert wrf_sfire(spread_x).shape == (2, 1, 16, 16) - assert firecastnet(spread_x).shape == (2, 1, 16, 16) + assert firecastnet(temporal_spread_x).shape == (2, 1, 16, 16) diff --git a/tests/test_google_flood_forecasting.py b/tests/test_google_flood_forecasting.py new file mode 100644 index 00000000..1e9b266a --- /dev/null +++ b/tests/test_google_flood_forecasting.py @@ -0,0 +1,87 @@ +"""google_flood_forecasting without the reference code: configuration, NaN handling, layouts, validation.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.google_flood_forecasting import FLOODHUB_CONFIG, FLOODHUB_WEIGHTS + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_floodhub_configuration(): + model = build_model("google_flood_forecasting", task="regression") + assert _n_params(model) == 3_402_832 # the released model + sizes = {name: _n_params(module) for name, module in model.named_children()} + assert sizes == { + "static_embedding_fc": 20_620, + "hindcast_embeddings_fc": 8_440, + "forecast_embeddings_fc": 0, + "shared_embeddings_fc": 3_500, + "hindcast_lstm": 1_134_592, + "forecast_lstm": 2_183_168, + "dropout": 0, + "head": 52_512, + } + assert list(model.hindcast_embeddings_fc) == ["imerg", "cpc"] and list(model.shared_embeddings_fc) == ["hres", "graphcast"] + assert torch.all(model.hindcast_lstm.bias_hh_l0[512:1024] == 3.0) + assert len(FLOODHUB_WEIGHTS["sha256"]) == 64 + + +def _floodhub_inputs(batch=2): + torch.manual_seed(0) + total = FLOODHUB_CONFIG["seq_length"] + FLOODHUB_CONFIG["lead_time"] + return { + "x_s": torch.randn(batch, 84), + "x_d_hindcast": torch.randn(batch, FLOODHUB_CONFIG["seq_length"], 9), + "x_d_forecast": torch.randn(batch, total, 7), + } + + +def test_outputs_and_missing_inputs(): + model = build_model("google_flood_forecasting", task="regression").eval() + data = _floodhub_inputs() + with torch.no_grad(): + out = model(data) + assert set(out) == {"mu", "b", "tau", "pi"} + assert all(v.shape == (2, 372, 3) for v in out.values()) + assert torch.allclose(out["pi"].sum(-1), torch.ones(2, 372), atol=1e-4) + assert model.point_prediction(out).shape == (2, 372, 1) + + # A missing product (imerg = hindcast column 7) is skipped by the masked mean: outputs stay finite. + data["x_d_hindcast"][0, :, 7] = float("nan") + assert torch.isfinite(model(data)["mu"][0]).all() + # All forecast products missing on one day: NaN from that day on. + data["x_d_forecast"][1, 200] = float("nan") + mu = model(data)["mu"][1] + assert torch.isfinite(mu[:200]).all() and torch.isnan(mu[200:]).all() + + +def test_streamflow_layout(): + model = build_model("google_flood_forecasting", task="regression", config="streamflow", seq_length=30, hidden_size=16) + out = model({"x_d": torch.randn(3, 30, 5), "x_s": torch.randn(3, 27)}) + assert out["mu"].shape == (3, 30, 3) + floodhub = build_model("google_flood_forecasting", task="regression") + with pytest.raises(ValueError, match="lead_time=0"): + floodhub({"x_d": torch.randn(2, 372, 9), "x_s": torch.randn(2, 84)}) + + +def test_bad_inputs_raise(): + model = build_model("google_flood_forecasting", task="regression") + data = _floodhub_inputs() + with pytest.raises(ValueError, match="shape"): + model({**data, "x_d_forecast": torch.randn(2, 365, 7)}) + with pytest.raises(ValueError, match="shape"): + model({**data, "x_d_hindcast": torch.randn(2, 365, 8)}) + with pytest.raises(ValueError, match="x_s"): + model({**data, "x_s": torch.randn(2, 80)}) + with pytest.raises(ValueError, match="missing features"): + model({**data, "x_d_hindcast": {"hres_temperature_2m": torch.randn(2, 365, 1)}}) + with pytest.raises(ValueError): + build_model("google_flood_forecasting", task="regression", config="transformer") + with pytest.raises(ValueError): + build_model("google_flood_forecasting", task="regression", history=4) diff --git a/tests/test_gpd.py b/tests/test_gpd.py new file mode 100644 index 00000000..f03cb7b9 --- /dev/null +++ b/tests/test_gpd.py @@ -0,0 +1,140 @@ +"""GPD (Ross et al. 2018): shapes, parameter count, picking logic and the Keras weight loader (offline).""" + +from __future__ import annotations + +import h5py +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.gpd import GPD, KerasBatchNorm1d, load_gpd_keras_weights + + +def _keras_file(model: GPD, path) -> None: + """Write ``model``'s weights in the layout of the released ``model_pol_best.hdf5``.""" + with h5py.File(path, "w") as handle: + group = handle.create_group("model_weights").create_group("sequential_1") + for name, module in model.named_children(): + layer = group.create_group(f"{name}_1") + if isinstance(module, torch.nn.Conv1d): + layer["kernel:0"] = module.weight.detach().permute(2, 1, 0).numpy() + layer["bias:0"] = module.bias.detach().numpy() + elif isinstance(module, torch.nn.Linear): + layer["kernel:0"] = module.weight.detach().t().numpy() + layer["bias:0"] = module.bias.detach().numpy() + else: + layer["gamma:0"] = module.weight.detach().numpy() + layer["beta:0"] = module.bias.detach().numpy() + layer["moving_mean:0"] = module.running_mean.numpy() + layer["moving_variance:0"] = module.running_var.numpy() + + +def test_parameter_count_and_output_shape(): + model = build_model("gpd", task="classification").eval() + assert sum(p.numel() for p in model.parameters()) == 1_741_003 + probabilities = model(torch.randn(2, 3, 400)) + assert probabilities.shape == (2, 3) + torch.testing.assert_close(probabilities.sum(dim=1), torch.ones(2)) + logits = model(torch.randn(2, 3, 400), logits=True) + assert logits.shape == (2, 3) + assert model.output_names == ("P", "S", "noise") + assert model.component_order == "NEZ" + + +def test_shape_validation_and_builder_arguments(): + model = GPD().eval() + for shape in [(2, 3, 300), (2, 2, 400), (3, 400)]: + with pytest.raises(ValueError, match="shape"): + model(torch.randn(*shape)) + with pytest.raises(ValueError): + build_model("gpd", task="regression") + with pytest.raises(TypeError): + build_model("gpd", task="classification", hidden_dim=32) + with pytest.raises(ValueError): + build_model("gpd", task="picking", in_channels=2, pretrained="original") + assert isinstance(build_model("gpd", task="picking"), GPD) + + +def test_keras_initialisation_bounds(): + torch.manual_seed(0) + model = GPD() + for module in model.modules(): + if isinstance(module, (torch.nn.Conv1d, torch.nn.Linear)): + weight = module.weight + receptive = weight[0, 0].numel() if weight.ndim == 3 else 1 + limit = (6.0 / ((weight.shape[0] + weight.shape[1]) * receptive)) ** 0.5 + assert weight.abs().max() <= limit + assert torch.count_nonzero(module.bias) == 0 + + +def test_annotate_windows_and_zero_windows(): + model = GPD().eval() + waveforms = torch.randn(2, 3, 1000) + waveforms[1, :, :500] = 0.0 # the first windows of trace 1 are all zero + with torch.no_grad(): + annotations = model.annotate(waveforms, stride=10) + assert annotations.shape == (2, 3, 61) # (1000 - 400) / 10 + 1 windows + assert torch.isfinite(annotations).all() + windows = model.sliding_windows(waveforms, stride=10) + assert windows.shape == (2, 61, 3, 400) + torch.testing.assert_close(windows[0, 3], waveforms[0, :, 30:430] / waveforms[0, :, 30:430].abs().max()) + with pytest.raises(ValueError): + model.annotate(torch.randn(1, 3, 399)) + + +def test_extract_picks_follows_gpd_predict(): + model = GPD() + n = 50 + annotations = np.zeros((1, 3, n), dtype=np.float32) + annotations[0, 2] = 1.0 + # P: a trigger over windows 10..13 (peak at 12) and a one-window trigger at 30 (skipped). + annotations[0, 0, 10:14] = [0.96, 0.97, 0.99, 0.5] + annotations[0, 0, 14] = 0.05 + annotations[0, 0, 30] = 0.99 + # S: the peak is the last window of the run, which the official slice prob[on:off] excludes. + annotations[0, 1, 20:23] = [0.96, 0.97, 0.99] + picks = model.extract_picks(torch.from_numpy(annotations), stride=10) + assert picks == [{"P": [(12 * 10 + 200.0, pytest.approx(0.99))], "S": [(21 * 10 + 200.0, pytest.approx(0.97))]}] + # A stricter threshold (the paper's 0.98) keeps only the higher peaks. + strict = model.extract_picks(torch.from_numpy(annotations), min_proba=0.98, stride=10) + assert [s for s, _ in strict[0]["P"]] == [12 * 10 + 200.0] + assert strict[0]["S"] == [] + + +def test_keras_weight_file_round_trip(tmp_path): + torch.manual_seed(0) + source = GPD() + for module in source.modules(): + if isinstance(module, KerasBatchNorm1d): + module.running_mean.uniform_(-1, 1) + module.running_var.uniform_(0.5, 2) + module.weight.data.uniform_(0.5, 2) + module.bias.data.uniform_(-1, 1) + path = tmp_path / "gpd.hdf5" + _keras_file(source, path) + target = build_model("gpd", task="classification", pretrained=str(path)).eval() + source.eval() + x = torch.randn(4, 3, 400) + with torch.no_grad(): + torch.testing.assert_close(target(x), source(x), rtol=0, atol=0) + + with h5py.File(path, "a") as handle: + del handle["model_weights/sequential_1/dense_3_1/bias:0"] + with pytest.raises(ValueError, match="lacks"): + load_gpd_keras_weights(GPD(), path) + + +def test_keras_batchnorm_updates_are_zero_debiased(): + norm = KerasBatchNorm1d(4, zero_debias=True) + norm.train() + x1, x2 = torch.randn(16, 4) * 2 + 1, torch.randn(16, 4) - 3 + norm(x1) + factor = 16 / (16 - 1.001) + # The first update replaces the statistics by the batch's (zero-debiased moving average). + torch.testing.assert_close(norm.running_mean, x1.mean(0)) + torch.testing.assert_close(norm.running_var, x1.var(0, unbiased=False) * factor) + norm(x2) + biased = 0.99 * 0.01 * x1.mean(0) + 0.01 * x2.mean(0) + torch.testing.assert_close(norm.running_mean, biased / (1 - 0.99**2)) + assert int(norm.num_batches_tracked) == 2 diff --git a/tests/test_hurricast.py b/tests/test_hurricast.py new file mode 100644 index 00000000..d380255d --- /dev/null +++ b/tests/test_hurricast.py @@ -0,0 +1,147 @@ +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.hurricast import ( + DECODER_CONFIGS, + HURRICAST_STAT_FEATURES, + Hurricast, + hurricast_network, + hurricast_training_loss, + hurricast_xgboost_columns, + hurricast_xgboost_features, +) + + +def _n_params(model): + return sum(p.numel() for p in model.parameters()) + + +def _inputs(n=6, seed=0): + g = torch.Generator().manual_seed(seed) + return { + "x_stat": torch.randn(n, 8, 30, generator=g), + "x_viz": torch.randn(n, 8, 9, 25, 25, generator=g), + "position": torch.randn(n, 2, generator=g) * 10 + 20, + } + + +def test_paper_configuration_parameter_counts(): + intensity = build_model("hurricast", task="regression", predictor="network") + track = build_model("hurricast", task="regression", target="displacement", predictor="network") + assert _n_params(intensity) == 2_969_771 and _n_params(track) == 2_969_914 + assert _n_params(intensity.network.encoder) == 2_732_800 + assert _n_params(intensity.network.decoder) == 236_828 + assert intensity.network.embedding_dim == 142 and intensity.network.n_stat == 14 + # Official key layout under ``network.``. + keys = list(intensity.state_dict()) + assert keys[:3] == ["target_mean", "target_std", "network.encoder.layers.0.weight"] and "network.decoder.pe.pe" in keys + assert _n_params(hurricast_network("displacement", "lstm_config_best_dis")) == 3_864_194 + + +def test_network_shapes_and_validation(): + model = build_model("hurricast", task="regression", target="displacement", predictor="network").eval() + x = _inputs() + with torch.no_grad(): + out = model(x) + forecast = model.forecast(x) + assert out.shape == (6, 2) + torch.testing.assert_close(forecast["lat"][:, 0], x["position"][:, 0] + out[:, 0]) + with pytest.raises(ValueError, match="x_viz must be shaped"): + model({**x, "x_viz": torch.randn(6, 8, 3, 25, 25)}) + with pytest.raises(ValueError, match="x_stat"): + model({"x_stat": torch.randn(6, 30), "x_viz": x["x_viz"]}) + with pytest.raises(ValueError, match="position"): + model.forecast({"x_stat": x["x_stat"], "x_viz": x["x_viz"]}) + with pytest.raises(ValueError, match="regression"): + build_model("hurricast", task="classification") + with pytest.raises(ValueError, match="decoder_config"): + build_model("hurricast", task="regression", decoder_config="gru_paper") + # Statistics only (official transformer_config_noviz, no encoder): 10 features per step. + noviz = hurricast_network("intensity", "transformer_config_noviz", None).eval() + assert noviz(torch.randn(2, 8, 10)).shape == (2, 1) + for name in DECODER_CONFIGS: + if name != "transformer_config_noviz": + net = hurricast_network("intensity", name, "split_encoder_config").eval() + assert net.get_embeddings(torch.randn(2, 8, 14), torch.randn(2, 8, 9, 25, 25)).shape == (2, net.embedding_dim) + + +def test_xgboost_feature_layout(): + columns = hurricast_xgboost_columns(8) + assert len(columns) == 14 * 8 + 16 + assert columns[:30] == [f"{name}_0" for name in HURRICAST_STAT_FEATURES] # every feature of the oldest step + assert all(not c.startswith("cat") for c in columns[30:]) # later steps: numerical features only + x_stat = torch.arange(2 * 8 * 30, dtype=torch.float32).reshape(2, 8, 30) + features = hurricast_xgboost_features(x_stat, torch.ones(2, 142)) + assert features.shape == (2, 128 + 142) + np.testing.assert_array_equal(features[0, :30], np.arange(30)) + np.testing.assert_array_equal(features[0, 30:32], [30, 31]) # LAT_1, LON_1 + with pytest.raises(ValueError, match=r"\(batch, T, 30\)"): + hurricast_xgboost_features(torch.zeros(2, 8, 14)) + + +def test_training_loss_matches_the_paper_formula(): + net = hurricast_network("intensity") + out, target = torch.randn(4, 1), torch.randn(4, 1) + l2 = sum((p**2).sum() for n, p in net.named_parameters() if "weight" in n) + torch.testing.assert_close(hurricast_training_loss(out, target, net, 0.01), ((out - target) ** 2).mean() + 2 / 4 * 0.01 * l2) + with pytest.raises(ValueError, match="shape"): + hurricast_training_loss(out, target[:, 0], net, 0.01) + + +def test_two_stage_fit_predict_save_load(tmp_path): + from sklearn.linear_model import Ridge + + torch.manual_seed(0) + model = build_model("hurricast", task="regression", target="displacement", estimator=Ridge(alpha=1.0)) + x = _inputs(n=12) + displacement = torch.randn(12, 2) + targets = (x["position"] + displacement).unsqueeze(1) # tc.track_intensity layout: position 24 h ahead + model.fit(x, targets, x, targets, epochs=2, batch_size=4) + torch.testing.assert_close(model.target_mean, displacement.mean(0), rtol=1e-5, atol=1e-5) + with torch.no_grad(): + out = model(x) + assert out.shape == (12, 2) + features = model.xgboost_features(x) + assert features.shape == (12, 128 + 142) + expected = model.xgboost.estimator.predict(features) * model.target_std.numpy() + model.target_mean.numpy() + np.testing.assert_allclose(out.numpy(), expected, rtol=1e-5, atol=1e-5) + path = tmp_path / "hurricast.joblib" + model.save(path) + restored = Hurricast.load(path) + with torch.no_grad(): + torch.testing.assert_close(restored(x), out) + from pyhazards.engine import Trainer + + with pytest.raises(TypeError, match="two stages"): + Trainer(model, device="cpu").fit(None) + + +def test_network_training_keeps_the_best_validation_epoch(): + torch.manual_seed(0) + model = build_model("hurricast", task="regression", predictor="network") + x = _inputs(n=8) + before = {k: v.clone() for k, v in model.network.state_dict().items()} + model.fit(x, torch.randn(8) * 10 + 50, x, torch.randn(8) * 10 + 50, epochs=2, batch_size=4, learning_rate=1e-3) + assert any(not torch.equal(before[k], v) for k, v in model.network.state_dict().items()) + assert not model.network.training + history = model.fit_network(x, torch.randn(8, 1), val=(x, torch.randn(8, 1)), epochs=3, batch_size=4) + assert len(history) == 3 + with pytest.raises(ValueError, match="batch_size"): + model.fit_network(x, torch.randn(8, 1), batch_size=64) + + +def test_xgboost_stage(): + pytest.importorskip("xgboost") + x = _inputs(n=40) + y = torch.randn(40) * 10 + 60 + model = build_model("hurricast", task="regression", n_jobs=1, n_estimators=5) + model.fit(x, y, train_network=False) + with torch.no_grad(): + assert model(x).shape == (40, 1) + assert model.xgboost.estimator.get_params()["max_depth"] == 8 + stat_only = build_model("hurricast", task="regression", use_embeddings=False, n_jobs=1, n_estimators=5) + assert stat_only.network is None + stat_only.fit({"x_stat": x["x_stat"]}, y) + assert stat_only({"x_stat": x["x_stat"]}).shape == (40, 1) diff --git a/tests/test_hydrographnet.py b/tests/test_hydrographnet.py new file mode 100644 index 00000000..c550a3c1 --- /dev/null +++ b/tests/test_hydrographnet.py @@ -0,0 +1,227 @@ +"""HydroGraphNet (PhysicsNeMo MeshGraphKAN) and its mesh data: shapes, counts, validation, reader and rollout.""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest +import torch + +from pyhazards.configs import load_experiment_config +from pyhazards.datasets import load_dataset +from pyhazards.datasets.flood.hydrograph import ( + hydrograph_collate, + read_hydrograph, + read_static, + synthetic_hydrograph_mesh, + write_hydrograph_files, +) +from pyhazards.engine.runner import BenchmarkRunner +from pyhazards.models import build_model +from pyhazards.models.hydrographnet import HydroGraphNet, HydroGraphNetLoss, hydrographnet_physics_loss + + +def _n_params(model) -> int: + return sum(p.numel() for p in model.parameters()) + + +def _ring(num_nodes: int) -> torch.Tensor: + src = torch.arange(num_nodes) + return torch.stack([torch.cat([src, src]), torch.cat([(src + 1) % num_nodes, (src - 1) % num_nodes])]) + + +def test_parameter_count_and_layout_at_hydrographnet_configuration(): + model = build_model("hydrographnet", task="regression") + assert _n_params(model) == 2_318_722 + assert _n_params(model.edge_encoder) == 33_792 + assert _n_params(model.node_encoder) == 20_608 + assert _n_params(model.processor) == 2_231_040 + assert _n_params(model.node_decoder) == 33_282 + keys = list(model.state_dict()) + assert keys[:10] == [ + "edge_encoder.model.0.weight", + "edge_encoder.model.0.bias", + "edge_encoder.model.2.weight", + "edge_encoder.model.2.bias", + "edge_encoder.model.4.weight", + "edge_encoder.model.4.bias", + "edge_encoder.model.5.weight", # LayerNorm + "edge_encoder.model.5.bias", + "node_encoder.fourier_coeffs", + "node_encoder.bias", + ] + assert "processor.processor_layers.29.node_mlp.model.5.weight" in keys + assert not any(key.startswith("node_decoder.model.5") for key in keys) # no LayerNorm on the decoder + + +def test_forward_accepts_tensors_graph_objects_and_mappings(): + torch.manual_seed(0) + model = HydroGraphNet(processor_size=2, hidden_dim_processor=16, hidden_dim_node_encoder=16, + hidden_dim_edge_encoder=16, hidden_dim_node_decoder=16).eval() + nodes, edge_index = torch.randn(10, 16), _ring(10) + edges = torch.randn(edge_index.shape[1], 3) + + class Graph: + pass + + graph = Graph() + graph.edge_index = edge_index + with torch.no_grad(): + out = model(nodes, edges, edge_index) + assert out.shape == (10, 2) + torch.testing.assert_close(model(nodes, edges, graph), out) + torch.testing.assert_close(model({"node_features": nodes, "edge_features": edges, "edge_index": edge_index}), out) + + +def test_sum_aggregation_is_not_mean(): + torch.manual_seed(0) + summed = HydroGraphNet(processor_size=1, hidden_dim_processor=8, hidden_dim_node_encoder=8, hidden_dim_edge_encoder=8, hidden_dim_node_decoder=8) + averaged = HydroGraphNet(processor_size=1, hidden_dim_processor=8, hidden_dim_node_encoder=8, hidden_dim_edge_encoder=8, hidden_dim_node_decoder=8, aggregation="mean") + averaged.load_state_dict(summed.state_dict()) + nodes, edge_index = torch.randn(6, 16), _ring(6) + edges = torch.randn(12, 3) + with torch.no_grad(): + assert not torch.allclose(summed(nodes, edges, edge_index), averaged(nodes, edges, edge_index)) + + +@pytest.mark.parametrize( + "nodes, edges, edge_index", + [ + (torch.randn(10, 15), torch.randn(20, 3), _ring(10)), + (torch.randn(10, 16), torch.randn(20, 2), _ring(10)), + (torch.randn(10, 16), torch.randn(19, 3), _ring(10)), + (torch.randn(10, 16), torch.randn(20, 3), torch.zeros(3, 20, dtype=torch.long)), + ], +) +def test_bad_inputs_raise(nodes, edges, edge_index): + model = HydroGraphNet(processor_size=1, hidden_dim_processor=8, hidden_dim_node_encoder=8, hidden_dim_edge_encoder=8, hidden_dim_node_decoder=8) + with pytest.raises(ValueError, match="shape|edge"): + model(nodes, edges, edge_index) + + +def test_builder_validation(): + with pytest.raises(ValueError, match="regression"): + build_model("hydrographnet", task="segmentation") + with pytest.raises(ValueError, match="Unknown"): + build_model("hydrographnet", task="regression", hidden_dim=64) + with pytest.raises(ValueError, match="aggregation"): + HydroGraphNet(aggregation="max") + with pytest.raises(ValueError, match="mlp_activation_fn"): + HydroGraphNet(mlp_activation_fn="swishy") + + +def test_rollout_updates_windows_and_forcings(): + torch.manual_seed(0) + model = HydroGraphNet(processor_size=1, hidden_dim_processor=8, hidden_dim_node_encoder=8, hidden_dim_edge_encoder=8, hidden_dim_node_decoder=8).eval() + nodes, edge_index = torch.randn(7, 16), _ring(7) + edges = torch.randn(14, 3) + inflow, precipitation = torch.randn(5), torch.randn(5) + out = model.rollout(nodes, edges, edge_index, inflow, precipitation) + assert out["water_depth"].shape == out["volume"].shape == (5, 7) + with torch.no_grad(): + first = model(nodes, edges, edge_index) + torch.testing.assert_close(out["water_depth"][0], nodes[:, 13] + first[:, 0]) + torch.testing.assert_close(out["volume"][0], nodes[:, 15] + first[:, 1]) + with pytest.raises(ValueError, match="shape"): + model.rollout(nodes[:, :15], edges, edge_index, inflow, precipitation) + + +def test_physics_loss_is_zero_for_volume_inside_the_continuity_bounds(): + physics = { + "past_volume": torch.tensor([0.0]), + "future_volume": torch.tensor([0.0]), + "avg_inflow": torch.tensor([10.0]), + "avg_precipitation": torch.tensor([0.0]), + "next_inflow": torch.tensor([0.0]), + "next_precip": torch.tensor([0.0]), + "volume_mean": torch.tensor([0.0]), + "volume_std": torch.tensor([1.0]), + "num_nodes": torch.tensor([4.0]), + "area_sum": torch.tensor([100.0]), + "infiltration_area_sum": torch.tensor([1.0]), + } + pred = torch.zeros(4, 2) + assert float(hydrographnet_physics_loss(pred, physics, delta_t=1.0)) == 0.0 + pred[:, 1] = 10.0 # 40 m3 gained but only 10 m3 entered: term1 = ((40 - 10) / 100)^2 + assert float(hydrographnet_physics_loss(pred, physics, delta_t=1.0)) == pytest.approx(0.3**2) + loss, parts = HydroGraphNetLoss(physics_loss_weight=2.0, delta_t=1.0)(pred, torch.zeros(4, 2), physics) + assert float(parts["physics_loss"]) == pytest.approx(0.3**2) + assert float(loss) == pytest.approx(float(parts["mse_loss"]) + 2.0 * 0.3**2) + loss, parts = HydroGraphNetLoss(use_physics_loss=False)(pred, torch.zeros(4, 2), physics) + assert set(parts) == {"total_loss", "mse_loss"} + with pytest.raises(ValueError, match="missing"): + hydrographnet_physics_loss(pred, {"past_volume": torch.tensor([0.0])}) + + +def _write_fixture(tmp_path, test_ids=("H4",)): + static, series = synthetic_hydrograph_mesh(nodes=20, hydrographs=4, steps=50, seed=1) + write_hydrograph_files(tmp_path, static, series, extra_cells=3, train_ids=["H1", "H2", "H3", "H4"]) + return static, series + + +def test_reader_follows_release_layout(tmp_path): + static, series = _write_fixture(tmp_path) + raw = read_static(tmp_path) + assert raw["xy_coords"].shape == (20, 2) and raw["area"].shape == (20, 1) + np.testing.assert_allclose(raw["elevation"][:, 0], static["elevation"][:, 0], atol=1e-8) + hydrograph = read_hydrograph(tmp_path, "H1", num_points=20) + peak = int(np.argmax(series["H1"]["inflow_hydrograph"])) + assert hydrograph["water_depth"].shape == (min(50, peak + 25), 20) + np.testing.assert_allclose(hydrograph["precipitation"], series["H1"]["precipitation"][: peak + 25], rtol=1e-6, atol=1e-12) + + with pytest.raises(ValueError, match="test_ids"): + load_dataset("hydrographnet_white_river", data_dir=str(tmp_path)).load() # train.txt lists every hydrograph + bundle = load_dataset("hydrographnet_white_river", data_dir=str(tmp_path), test_ids=["H4"], rollout_length=10).load() + assert bundle.metadata["train_ids"] == ["H1", "H2", "H3"] and bundle.metadata["test_ids"] == ["H4"] + windows = bundle.get_split("train").inputs + inputs, target = windows[0] + assert inputs["node_features"].shape == (20, 16) + assert inputs["edge_index"].shape == (2, 80) and inputs["edge_features"].shape == (80, 3) + assert target.shape == (20, 2) + assert {"past_volume", "future_volume", "area_sum", "infiltration_area_sum"} <= set(inputs["physics"]) + rollouts = bundle.get_split("test").inputs + inputs, targets = rollouts[0] + assert inputs["inflow"].shape == (10,) and targets["water_depth"].shape == (10, 20) + + (tmp_path / "test.txt").write_text("H4\n", encoding="utf-8") + with pytest.raises(FileNotFoundError): + load_dataset("hydrographnet_white_river", data_dir=str(tmp_path), test_ids="test.txt", norm_stats="files").load() + for name, stats in (("static_norm_stats.json", bundle.metadata["static_stats"]), ("dynamic_norm_stats.json", bundle.metadata["dynamic_stats"])): + (tmp_path / name).write_text(json.dumps(stats), encoding="utf-8") + files = load_dataset("hydrographnet_white_river", data_dir=str(tmp_path), test_ids="test.txt", norm_stats="files", rollout_length=10).load() + assert files.metadata["dynamic_stats"] == bundle.metadata["dynamic_stats"] + with pytest.raises(ValueError, match="data_dir"): + load_dataset("hydrographnet_white_river") + + +def test_collate_offsets_edges_and_stacks_physics(): + bundle = load_dataset("flood_mesh_synthetic", micro=True).load() + windows = bundle.get_split("train").inputs + batch, target = hydrograph_collate([windows[0], windows[3]]) + n = windows[0][0]["node_features"].shape[0] + assert batch["node_features"].shape == (2 * n, 16) and target.shape == (2 * n, 2) + assert int(batch["edge_index"].max()) == 2 * n - 1 + assert batch["physics"]["past_volume"].shape == (2,) and batch["physics"]["past_volume"].dtype == torch.float32 + assert torch.equal(batch["batch"], torch.repeat_interleave(torch.arange(2), n)) + model = HydroGraphNet(processor_size=1, hidden_dim_processor=8, hidden_dim_node_encoder=8, hidden_dim_edge_encoder=8, hidden_dim_node_decoder=8) + pred = model(batch) + loss, parts = HydroGraphNetLoss()(pred, target, batch["physics"], batch["batch"]) + loss.backward() + assert torch.isfinite(loss) and set(parts) == {"total_loss", "mse_loss", "physics_loss"} + + +def test_synthetic_mesh_bundle_is_marked_synthetic(): + bundle = load_dataset("flood_mesh_synthetic", micro=True).load() + assert bundle.metadata["synthetic"] is True + assert bundle.metadata["inundation_layout"] == "mesh_rollout" + assert set(bundle.splits) == {"train", "test"} + + +def test_smoke_config_scores_rollouts_in_metres(tmp_path): + summary = BenchmarkRunner().run(load_experiment_config("pyhazards/configs/flood/hydrographnet_smoke.yaml"), output_dir=str(tmp_path)) + assert summary.hazard_task == "flood.inundation" + for metric in ("rollout_rmse", "pixel_mae", "rmse", "csi_1cm", "csi_10cm", "csi_50cm", "relative_l2", "nse", "pearson_r"): + assert metric in summary.metrics + assert len(summary.metadata["rollout_rmse_per_step_m"]) == 6 + assert summary.metrics["rollout_rmse"] == pytest.approx(np.mean(summary.metadata["rollout_rmse_per_step_m"])) diff --git a/tests/test_model_catalog.py b/tests/test_model_catalog.py index a1f4b13b..09ea51a7 100644 --- a/tests/test_model_catalog.py +++ b/tests/test_model_catalog.py @@ -1,8 +1,18 @@ +import importlib.util + +import pytest +import torch +from pydantic import ValidationError + from pyhazards.model_catalog import ( + SmokeFitSpec, + _make_fit_targets, + card_by_registry_name, load_model_cards, model_catalog_alignment_issues, render_api_page, render_model_page, + run_smoke_test, ) @@ -25,17 +35,32 @@ def test_model_page_lists_generated_hazard_sections() -> None: assert ".. tab-item:: Hurricane" not in page assert ":doc:`DNN-LSTM-AutoEncoder `" in page assert ":doc:`Wildfire Forecasting `" in page - assert ":doc:`WildfireSpreadTS `" in page + assert ":doc:`WildfireSpreadTS Baselines `" in page + assert ":doc:`U-TAE `" in page + assert ":doc:`SegFormer `" in page + assert ":doc:`Prithvi-EO-2.0 BurnScars `" in page + assert ":doc:`Prithvi-EO-2.0-TL `" in page assert ":doc:`ASUFM `" in page - assert ":doc:`ForeFire Adapter `" in page - assert ":doc:`WRF-SFIRE Adapter `" in page + assert ":doc:`Swin-Unet `" in page + assert ":doc:`Earthfarseer `" in page + assert ":doc:`Rainformer `" in page + # ForeFire and WRF-SFIRE are external simulators (pyhazards.simulators, datasets/wrf_sfire), not models. + assert "models_forefire" not in page + assert "models_wrf_sfire" not in page assert ":doc:`FireCastNet `" in page assert ":doc:`WaveCastNet `" in page - assert ":doc:`GraphCast TC Adapter `" in page - assert "Wildfire Danger Prediction and Understanding with Deep Learning" in page + assert ":doc:`Hurricast `" in page + # GraphCast, Pangu-Weather and FourCastNet are foundation-model pipelines (pyhazards.forecasts), not models. + assert "models_graphcast_tc" not in page and "models_pangu_tc" not in page and "models_fourcastnet_tc" not in page + assert "Wildfire Danger Prediction and Understanding With Deep Learning" in page assert "`Repository `_" in page assert page.count("Implemented Models") == 5 + # Only flood's floodcast is still a stand-in (no released code or full specification), plus the overview + # section. FourCastNet / GraphCast / Pangu-Weather are forecast pipelines (pyhazards.forecasts), not models. assert page.count("Experimental Adapters") == 2 + assert ":doc:`EQNet `" in page and "EQNet (stand-in)" not in page + assert ":doc:`HydroGraphNet `" in page + assert ":doc:`UrbanFloodCast `" in page assert "Core Baselines" not in page assert "Variants and Additional Implementations" not in page assert page.count(":doc:`DNN-LSTM-AutoEncoder `") == 1 @@ -54,7 +79,58 @@ def test_hidden_models_are_omitted_from_public_catalog_pages() -> None: assert api_page.count("Experimental Adapters") == 1 assert "Core Baselines" not in api_page assert "Variants and Additional Implementations" not in api_page - assert ":doc:`GraphCast TC Adapter `" in api_page + assert ":doc:`Hurricast `" in api_page + assert "models_graphcast_tc" not in api_page assert "Developer Registry Workflow" in api_page assert "Catalog Summary" in api_page assert "Hurricane" not in api_page + + +def test_smoke_test_fits_estimator_models_first() -> None: + card = card_by_registry_name(load_model_cards())["random_forest"] + assert card.smoke_test.fit is not None + result = run_smoke_test(card) + assert result["ok"] and result["skipped"] is None + assert result["actual_shape"] == [4, 2] + + +def test_smoke_test_skips_missing_optional_packages() -> None: + cards = card_by_registry_name(load_model_cards()) + card = cards["xgboost"].model_copy(deep=True) + card.smoke_test.requires = ["pyhazards_no_such_package"] + result = run_smoke_test(card) + assert result["ok"] and "pyhazards_no_such_package" in result["skipped"] + assert result["actual_shape"] is None and result["expected_shape"] == [4, 2] + + xgboost_result = run_smoke_test(cards["xgboost"]) + assert xgboost_result["ok"] + assert (xgboost_result["skipped"] is None) == (importlib.util.find_spec("xgboost") is not None) + + +def test_smoke_fit_spec_validation_and_targets() -> None: + spec = SmokeFitSpec.model_validate( + {"inputs": {"shape": [6, 3]}, "targets": {"shape": [6], "dtype": "int64"}, "num_classes": 3} + ) + torch.manual_seed(0) + targets = _make_fit_targets(spec) + assert targets.dtype == torch.int64 and targets.shape == (6,) + assert set(targets.tolist()) == {0, 1, 2} + regression = SmokeFitSpec.model_validate({"inputs": {"shape": [4, 3]}, "targets": {"shape": [4, 2]}}) + assert _make_fit_targets(regression).dtype == torch.float32 + with pytest.raises(ValidationError): + SmokeFitSpec.model_validate({"inputs": {"shape": [6, 3]}, "targets": {"shape": [5]}}) + with pytest.raises(ValidationError): + SmokeFitSpec.model_validate( + {"inputs": {"shape": [2, 3]}, "targets": {"shape": [2], "dtype": "int64"}, "num_classes": 3} + ) + + +def test_touched_card_names_skips_deleted_cards() -> None: + from pyhazards.model_catalog import touched_card_names + + cards = load_model_cards() + names = touched_card_names( + cards, + ["pyhazards/model_cards/utae.yaml", "pyhazards/model_cards/removed_model.yaml"], + ) + assert names == ["utae"] diff --git a/tests/test_neuralhydrology.py b/tests/test_neuralhydrology.py new file mode 100644 index 00000000..74010a26 --- /dev/null +++ b/tests/test_neuralhydrology.py @@ -0,0 +1,117 @@ +"""NeuralHydrology LSTM and EA-LSTM without the reference code: sizes, outputs, 2019 checkpoints, validation.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.neuralhydrology_lstm import convert_kratzert2019_state_dict + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "name, kwargs, expected", + [ + ("neuralhydrology_lstm", {}, 297_217), # Kratzert et al. (2019) LSTM with static inputs + ("neuralhydrology_lstm", {"n_static": 0}, 269_569), # ... without static inputs + ("neuralhydrology_ealstm", {}, 208_641), # EA-LSTM + ], +) +def test_parameter_counts(name, kwargs, expected): + assert _n_params(build_model(name, task="regression", **kwargs)) == expected + + +def test_lstm_outputs_and_forget_bias(): + model = build_model("neuralhydrology_lstm", task="regression", hidden_size=16).eval() + assert torch.all(model.lstm.bias_hh_l0[16:32] == 5.0) + out = model({"x_d": torch.randn(3, 40, 5), "x_s": torch.randn(3, 27)}) + assert out["y_hat"].shape == (3, 40, 1) + assert out["lstm_output"].shape == (3, 40, 16) + assert out["h_n"].shape == out["c_n"].shape == (3, 1, 16) + torch.testing.assert_close(out["h_n"][:, 0], out["lstm_output"][:, -1]) + assert list(model.state_dict()) == ["lstm.weight_ih_l0", "lstm.weight_hh_l0", "lstm.bias_ih_l0", "lstm.bias_hh_l0", + "head.net.0.weight", "head.net.0.bias"] + + +def test_ealstm_input_gate_uses_only_static_inputs(): + model = build_model("neuralhydrology_ealstm", task="regression", hidden_size=8, output_dropout=0.0).eval() + assert torch.equal(model.dynamic_gates.weight_hh, torch.eye(8).repeat(1, 3)) + assert torch.all(model.dynamic_gates.bias[:8] == 5.0) and torch.all(model.dynamic_gates.bias[8:] == 0) + x_d, x_s = torch.randn(2, 25, 5), torch.randn(2, 27) + out = model({"x_d": x_d, "x_s": x_s}) + assert out["y_hat"].shape == (2, 25, 1) and out["h_n"].shape == out["c_n"].shape == (2, 25, 8) + # Hand-written recurrence of Kratzert et al. (2019), Eqs. 7-10. + i = torch.sigmoid(x_s @ model.input_gate.weight.t() + model.input_gate.bias) + h = c = torch.zeros(2, 8) + for t in range(25): + gates = h @ model.dynamic_gates.weight_hh + x_d[:, t] @ model.dynamic_gates.weight_ih + model.dynamic_gates.bias + f, o, g = gates.chunk(3, 1) + c = torch.sigmoid(f) * c + i * torch.tanh(g) + h = torch.sigmoid(o) * torch.tanh(c) + torch.testing.assert_close(out["h_n"][:, -1], h) + torch.testing.assert_close(out["y_hat"][:, -1], model.head.net(h)) + + +def test_kratzert2019_lstm_checkpoint_conversion(): + """A checkpoint in the 2019 layout (single bias, gates f, i, o, g) gives the 2019 recurrence.""" + torch.manual_seed(0) + hidden, n_in = 6, 32 + state = { + "lstm.weight_ih": torch.randn(n_in, 4 * hidden) * 0.3, + "lstm.weight_hh": torch.randn(hidden, 4 * hidden) * 0.3, + "lstm.bias": torch.randn(4 * hidden), + "fc.weight": torch.randn(1, hidden), + "fc.bias": torch.randn(1), + } + model = build_model("neuralhydrology_lstm", task="regression", hidden_size=hidden).eval() + model.load_state_dict(convert_kratzert2019_state_dict(state), strict=True) + x_d, x_s = torch.randn(3, 12, 5), torch.randn(3, 27) + x = torch.cat([x_d, x_s.unsqueeze(1).repeat(1, 12, 1)], dim=-1) + h = c = torch.zeros(3, hidden) + for t in range(12): # papercode/lstm.py + gates = torch.addmm(state["lstm.bias"].expand(3, -1), h, state["lstm.weight_hh"]) + x[:, t] @ state["lstm.weight_ih"] + f, i, o, g = gates.chunk(4, 1) + c = torch.sigmoid(f) * c + torch.sigmoid(i) * torch.tanh(g) + h = torch.sigmoid(o) * torch.tanh(c) + expected = h @ state["fc.weight"].t() + state["fc.bias"] + torch.testing.assert_close(model({"x_d": x_d, "x_s": x_s})["y_hat"][:, -1], expected, rtol=1e-5, atol=1e-6) + + +def test_kratzert2019_ealstm_checkpoint_conversion(): + torch.manual_seed(1) + hidden = 4 + state = { + "lstm.weight_ih": torch.randn(5, 3 * hidden), + "lstm.weight_hh": torch.randn(hidden, 3 * hidden), + "lstm.weight_sh": torch.randn(27, hidden), + "lstm.bias": torch.randn(3 * hidden), + "lstm.bias_s": torch.randn(hidden), + "fc.weight": torch.randn(1, hidden), + "fc.bias": torch.randn(1), + } + model = build_model("neuralhydrology_ealstm", task="regression", hidden_size=hidden) + model.load_state_dict(convert_kratzert2019_state_dict(state), strict=True) + x_s = torch.randn(2, 27) + torch.testing.assert_close(model.input_gate(x_s), x_s @ state["lstm.weight_sh"] + state["lstm.bias_s"]) + + +@pytest.mark.parametrize("name", ["neuralhydrology_lstm", "neuralhydrology_ealstm"]) +def test_bad_inputs_raise(name): + model = build_model(name, task="regression", hidden_size=8) + with pytest.raises(ValueError, match="shape"): + model({"x_d": torch.randn(2, 10, 4), "x_s": torch.randn(2, 27)}) + with pytest.raises(ValueError, match="x_s"): + model({"x_d": torch.randn(2, 10, 5)}) + with pytest.raises(ValueError, match="mapping"): + model(torch.randn(2, 10, 5)) + with pytest.raises(ValueError): + build_model(name, task="classification") + + +def test_ealstm_needs_static_inputs(): + with pytest.raises(ValueError, match="static"): + build_model("neuralhydrology_ealstm", task="regression", n_static=0) diff --git a/tests/test_phasenet.py b/tests/test_phasenet.py new file mode 100644 index 00000000..7e5414e6 --- /dev/null +++ b/tests/test_phasenet.py @@ -0,0 +1,97 @@ +import math + +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.phasenet import PhaseNet, _tf_same_padding, state_dict_from_tf_checkpoint + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +def test_released_configuration_has_268443_parameters(): + model = build_model("phasenet", task="picking") + assert isinstance(model, PhaseNet) + assert _n_params(model) == 268_443 + widths = [getattr(model, f"DownConv_{d}").__getattr__(f"down_conv1_{d + 1}").out_channels for d in range(5)] + assert widths == [8, 16, 32, 64, 128] + + +@pytest.mark.parametrize("length", [3000, 3001, 400, 7]) +def test_any_length_gives_per_sample_probabilities(length): + model = PhaseNet().eval() + with torch.no_grad(): + probabilities = model(torch.randn(2, 3, length)) + logits = model(torch.randn(2, 3, length), logits=True) + assert probabilities.shape == logits.shape == (2, 3, length) + torch.testing.assert_close(probabilities.sum(dim=1), torch.ones(2, length)) + + +def test_tensorflow_same_padding_is_asymmetric_for_strided_convolutions(): + assert _tf_same_padding(3000, 7, 4) == (1, 2) + assert _tf_same_padding(750, 7, 4) == (2, 3) + assert _tf_same_padding(47, 7, 4) == (2, 2) + assert _tf_same_padding(100, 7, 1) == (3, 3) + + +def test_input_validation_and_builder_arguments(): + model = PhaseNet() + with pytest.raises(ValueError, match="shape"): + model(torch.randn(3, 3000)) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(1, 2, 3000)) + with pytest.raises(ValueError, match="picking"): + build_model("phasenet", task="regression") + with pytest.raises(TypeError, match="hidden_dim"): + build_model("phasenet", task="picking", hidden_dim=32) + with pytest.raises(ValueError, match="default configuration"): + build_model("phasenet", task="picking", filters_root=4, pretrained="original") + + +def test_tensorflow_variables_map_onto_the_state_dict(): + model = PhaseNet() + variables = {} + for name, tensor in model.state_dict().items(): + if name.endswith("num_batches_tracked"): + continue + scope, layer, kind = name.split(".") + array = tensor.numpy() + if kind == "weight" and "conv" in layer: + array = array.transpose(2, 1, 0)[:, None] # back to the TF kernel layout (k, 1, ., .) + tf_kind = "kernel" + else: + tf_kind = {"weight": "gamma", "bias": "beta" if "_bn" in layer else "bias", + "running_mean": "moving_mean", "running_var": "moving_variance"}[kind] + variables[f"{scope}/{layer}/{tf_kind}"] = array + 1.0 + variables["global_step"] = np.array(3) + variables["Input/input_conv/kernel/Adam"] = np.zeros((7, 1, 3, 8), dtype=np.float32) + converted = state_dict_from_tf_checkpoint(variables) + restored = PhaseNet() + restored.load_state_dict(converted, strict=True) + for name, tensor in model.state_dict().items(): + if not name.endswith("num_batches_tracked"): + torch.testing.assert_close(restored.state_dict()[name], tensor + 1.0) + + +def test_annotate_normalises_and_extract_picks_finds_peaks(): + model = PhaseNet().eval() + raw = torch.randn(2, 3, 3000) * 1e4 + 5.0 + with torch.no_grad(): + scaled = model.annotate(raw) + reference = model.annotate(raw * 3.0 - 2.0) # per-channel standardisation removes scale/offset + torch.testing.assert_close(scaled, reference, rtol=1e-4, atol=1e-5) + + annotations = torch.zeros(1, 3, 1000) + annotations[0, 1, 300] = 0.9 + annotations[0, 1, 320] = 0.7 # within 0.5 s of a higher peak: removed + annotations[0, 1, 600] = 0.4 # below 0.5 + annotations[0, 2, 800] = 0.6 + picks = model.extract_picks(annotations) + assert [i for i, _ in picks[0]["P"]] == [300.0] + assert [i for i, _ in picks[0]["S"]] == [800.0] + assert math.isclose(picks[0]["P"][0][1], 0.9, rel_tol=1e-6) + picks = model.extract_picks(annotations, p_threshold=0.3, min_distance=10) + assert [i for i, _ in picks[0]["P"]] == [300.0, 320.0, 600.0] diff --git a/tests/test_picking_metrics.py b/tests/test_picking_metrics.py new file mode 100644 index 00000000..0f68d649 --- /dev/null +++ b/tests/test_picking_metrics.py @@ -0,0 +1,66 @@ +import math + +import numpy as np +import pytest + +from pyhazards.metrics.picking import ( + PICKING_PROTOCOLS, + detect_peaks, + detection_scores, + peak_picks, + score_picks, + trigger_onset, +) + + +def test_detect_peaks_reference_examples(): + # Examples from the docstring of Duarte's detect_peaks. + assert detect_peaks([0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0], mpd=2).tolist() == [1, 5, 9] + assert detect_peaks([0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0], mpd=4).tolist() == [5] + assert detect_peaks([0, 1, 1, 0, 1, 1, 0], edge="both").tolist() == [1, 2, 4, 5] + assert detect_peaks([0, 1, 1, 0, 1, 1, 0]).tolist() == [1, 4] + assert detect_peaks([-2, 1, -2, 2, 1, 1, 3, 0], threshold=2).tolist() == [1, 6] + assert detect_peaks([0, 3, 0, 1, 0], mph=2).tolist() == [1] + assert detect_peaks([0, 1]).tolist() == [] + x = np.array([0, 1, 0, np.nan, 0, 2, 0], dtype=float) + assert detect_peaks(x).tolist() == [1, 5] + + +def test_trigger_onset_on_off_semantics(): + assert trigger_onset([0, 0, 1, 1, 1, 0, 0], 0.5, 0.5).tolist() == [[2, 4]] + assert trigger_onset([1, 1, 0, 0, 1], 0.5, 0.5).tolist() == [[0, 1], [4, 4]] + assert trigger_onset([0, 0.6, 0.4, 0.6, 0.2, 0], 0.5, 0.1).tolist() == [[1, 4]] + assert trigger_onset([0, 0.5, 0.5, 0], 0.5, 0.5).tolist() == [[1, 2]] + assert trigger_onset([0, 0.3, 0.6, 0.3, 0.1], 0.5, 0.2).tolist() == [[2, 3]] + assert trigger_onset([0.2] * 5, 0.5, 0.5).shape == (0, 2) + with pytest.raises(ValueError, match="thres2"): + trigger_onset([0, 1], 0.2, 0.5) + + +def test_score_picks_follows_the_phasenet_counting(): + tolerance, window = 10, 50 # 0.1 s and 0.5 s at 100 Hz + predicted = [[100.0, 400.0], [205.0], [], [math.nan]] + manual = [[103.0], [230.0], [50.0], [math.nan]] + score = score_picks(predicted, manual, tolerance, window) + assert (score.n_true, score.n_pred, score.n_tp) == (3, 3, 1) + assert sorted(score.residuals) == [-25.0, -3.0] + metrics = score.metrics(100.0) + assert metrics["precision"] == pytest.approx(1 / 3) + assert metrics["recall"] == pytest.approx(1 / 3) + assert metrics["f1"] == pytest.approx(1 / 3) + assert metrics["residual_mean"] == pytest.approx(-0.14) + assert metrics["mae"] == pytest.approx(0.14) + + +def test_empty_scores_are_zero_and_nan(): + metrics = score_picks([[]], [[math.nan]], 10, 50).metrics(100.0) + assert metrics["precision"] == metrics["recall"] == metrics["f1"] == 0.0 + assert math.isnan(metrics["residual_mean"]) and math.isnan(metrics["mae"]) + + +def test_protocols_and_detection_scores(): + assert PICKING_PROTOCOLS["phasenet"] == {"tolerance_s": 0.1, "residual_window_s": 0.5} + assert PICKING_PROTOCOLS["eqtransformer"]["tolerance_s"] == 0.5 + scores = detection_scores([True, True, False, False], [True, False, True, False]) + assert scores == {"precision": 0.5, "recall": 0.5, "f1": 0.5} + assert peak_picks([0, 0.2, 0.9, 0.1, 0], 0.5, 1) == [(2.0, 0.9)] diff --git a/tests/test_prithvi.py b/tests/test_prithvi.py new file mode 100644 index 00000000..0bd3ad62 --- /dev/null +++ b/tests/test_prithvi.py @@ -0,0 +1,192 @@ +"""Prithvi-EO-2.0 ports: parameter counts, shapes, input validation and the weight loader. + +Numerical equivalence with TerraTorch 0.99.8 and the official prithvi_mae.py, including the released +checkpoints, lives in tests/oracle/test_prithvi_oracle.py. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models import prithvi +from pyhazards.models.prithvi import ( + PRITHVI_WEIGHTS, + PrithviMAE, + download_weights, + finetuned_state_dict_to_model, + load_pretrained_state_dict, + mae_state_dict_to_encoder, +) + +TINY = dict(embed_dim=64, depth=4, num_heads=2, select_indices=(0, 1, 2, 3), decoder_channels=(32, 16, 8, 4)) +TL_TINY_MAE = dict( + img_size=32, num_frames=4, in_chans=6, embed_dim=64, depth=4, num_heads=2, decoder_embed_dim=32, + decoder_depth=1, decoder_num_heads=2, coords_encoding=["time", "location"], coords_scale_learn=True, +) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "name, kwargs, expected", + [ + ("prithvi_burnscars", {}, 324_204_674), + ("prithvi_eo_2_tl", {}, 324_204_676), + ("prithvi_eo_2_tl", {"variant": "600m"}, 656_889_540), + ], +) +def test_parameter_counts(name, kwargs, expected): + with torch.device("meta"): + model = build_model(name, task="segmentation", **kwargs) + assert _n_params(model) == expected + + +def test_encoder_and_mae_parameter_counts(): + with torch.device("meta"): + tl = build_model("prithvi_eo_2_tl", task="segmentation") + tl600 = build_model("prithvi_eo_2_tl", task="segmentation", variant="600m") + mae = PrithviMAE( + num_frames=4, in_chans=6, embed_dim=1024, depth=24, num_heads=16, + coords_encoding=["time", "location"], coords_scale_learn=True, + ) + assert _n_params(tl.encoder) == 303_886_338 + assert _n_params(tl600.encoder) == 631_188_482 + assert _n_params(mae) == 330_419_716 + assert tl.neck[0].indices == [5, 11, 17, 23] + assert tl600.neck[0].indices == [7, 15, 23, 31] + + +def test_state_dict_follows_terratorch_layout(): + keys = list(build_model("prithvi_burnscars", task="segmentation", **TINY).state_dict()) + assert keys[:3] == ["encoder.cls_token", "encoder.pos_embed", "encoder.patch_embed.proj.weight"] + assert "encoder.blocks.3.attn.qkv.weight" in keys and "encoder.blocks.3.mlp.fc2.bias" in keys + assert "decoder.decoder.blocks.3.conv2.1.running_var" in keys + assert "head.head.2.weight" in keys + assert keys[-1] == "neck.2.fpn2.0.bias" + tl_keys = build_model("prithvi_eo_2_tl", task="segmentation", **TINY).state_dict() + assert {"encoder.temporal_embed_enc.scale", "encoder.location_embed_enc.scale"} <= set(tl_keys) + + +@pytest.mark.parametrize("size", [(64, 64), (70, 90), (40, 96)]) +def test_burnscars_output_shape(size): + model = build_model("prithvi_burnscars", task="segmentation", **TINY).eval() + x = torch.randn(2, 6, *size) + with torch.no_grad(): + out = model(x) + assert out.shape == (2, 2) + size + torch.testing.assert_close(model(x[:, :, None]), out) + + +def test_tl_coordinates_and_multitemporal_input(): + model = build_model("prithvi_eo_2_tl", task="segmentation", num_frames=3, num_classes=4, **TINY).eval() + x = torch.randn(2, 6, 3, 64, 64) + temporal = torch.tensor([[[2020, 10], [2020, 100], [2020, 200]]] * 2) # integer years / days are accepted + location = torch.tensor([[30.0, -100.0], [31.0, -101.0]]) + with torch.no_grad(): + out = model(x, temporal_coords=temporal, location_coords=location) + assert out.shape == (2, 4, 64, 64) + assert not torch.allclose(out, model(x)) + assert not torch.allclose(out, model(x, temporal_coords=temporal)) + assert model.neck[2].fpn1[0].in_channels == 3 * 64 # frames stacked along channels + + +def test_input_validation(): + model = build_model("prithvi_burnscars", task="segmentation", **TINY) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(2, 6, 64)) + with pytest.raises(ValueError, match="channels"): + model(torch.randn(2, 5, 64, 64)) + with pytest.raises(ValueError, match="T=1"): + model(torch.randn(2, 6, 2, 64, 64)) + with pytest.raises(ValueError, match="too small"): + model(torch.randn(1, 6, 8, 8)) + tl = build_model("prithvi_eo_2_tl", task="segmentation", **TINY) + x = torch.randn(2, 6, 64, 64) + with pytest.raises(ValueError, match="temporal_coords"): + tl(x, temporal_coords=torch.zeros(2, 2)) + with pytest.raises(ValueError, match="temporal_coords"): + tl(x, temporal_coords=torch.zeros(2, 2, 2)) + with pytest.raises(ValueError, match="location_coords"): + tl(x, location_coords=torch.zeros(2, 3)) + + +def test_builder_validation(): + with pytest.raises(ValueError, match="segmentation"): + build_model("prithvi_burnscars", task="classification") + with pytest.raises(ValueError, match="segmentation"): + build_model("prithvi_eo_2_tl", task="regression") + with pytest.raises(ValueError, match="variant"): + build_model("prithvi_eo_2_tl", task="segmentation", variant="100m") + with pytest.raises(ValueError, match="default architecture"): + build_model("prithvi_burnscars", task="segmentation", pretrained=True, depth=4) + with pytest.raises(ValueError, match="official TL weights"): + build_model("prithvi_eo_2_tl", task="segmentation", pretrained=True, in_channels=4) + with pytest.raises(ValueError, match="select_indices"): + build_model("prithvi_burnscars", task="segmentation", embed_dim=64, depth=4, num_heads=2) + + +def test_mae_patchify_and_reconstruction_shapes(): + mae = PrithviMAE(**TL_TINY_MAE).eval() + x = torch.randn(2, 6, 4, 32, 32) + assert torch.equal(mae.unpatchify(mae.patchify(x), image_size=(32, 32)), x) + temporal = torch.tensor([[[2018.0, 26], [2018, 106], [2018, 201], [2018, 266]]] * 2) + with torch.no_grad(): + loss, pred, mask = mae(x, temporal_coords=temporal, location_coords=torch.tensor([[25.0, -104.0]] * 2)) + assert loss.ndim == 0 and torch.isfinite(loss) + assert pred.shape == (2, 16, 16 * 16 * 6) + assert mask.shape == (2, 16) and mask.sum().item() == 2 * 12 # 75 % of the patches are masked + + +def test_weights_are_pinned(): + for spec in PRITHVI_WEIGHTS.values(): + assert spec.repo_id.startswith("ibm-nasa-geospatial/") + assert len(spec.revision) == 40 and len(spec.sha256) == 64 + assert spec.num_bytes > 10**9 + + +def test_download_weights_uses_cache(tmp_path, monkeypatch): + spec = prithvi.PretrainedWeights("org/repo", "a" * 40, "w.pt", "b" * 64, 4) + calls = [] + + def fake_download(url, dst, hash_prefix=None, progress=True): + calls.append((url, hash_prefix)) + Path(dst).write_bytes(b"1234") + + monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download) + monkeypatch.delenv("HF_ENDPOINT", raising=False) + path = download_weights(spec, cache_dir=tmp_path) + assert path == tmp_path / "org--repo" / ("a" * 40) / "w.pt" + assert calls == [(f"https://huggingface.co/org/repo/resolve/{'a' * 40}/w.pt", "b" * 64)] + assert download_weights(spec, cache_dir=tmp_path) == path + assert len(calls) == 1 + monkeypatch.setenv("HF_ENDPOINT", "https://mirror.example/") + assert spec.url.startswith("https://mirror.example/org/repo/resolve/") + + +def test_finetuned_checkpoint_key_mapping(tmp_path): + torch.manual_seed(0) + source = build_model("prithvi_burnscars", task="segmentation", **TINY).eval() + path = tmp_path / "finetuned.pt" + torch.save({"epoch": 1, "state_dict": {"model." + k: v for k, v in source.state_dict().items()}}, path) + state = load_pretrained_state_dict("prithvi_eo_v2_300_burnscars", weights_path=path) + target = build_model("prithvi_burnscars", task="segmentation", **TINY).eval() + target.load_state_dict(finetuned_state_dict_to_model(state), strict=True) + x = torch.randn(1, 6, 64, 64) + with torch.no_grad(): + torch.testing.assert_close(target(x), source(x)) + + +def test_mae_checkpoint_to_encoder_mapping(): + torch.manual_seed(0) + mae = PrithviMAE(**TL_TINY_MAE) + model = build_model("prithvi_eo_2_tl", task="segmentation", img_size=32, **TINY) + model.encoder.load_state_dict(mae_state_dict_to_encoder(mae.state_dict(), model.encoder), strict=True) + for key, value in model.encoder.state_dict().items(): + if key != "pos_embed": # 1-frame table instead of the 4-frame pretraining table + assert torch.equal(value, mae.encoder.state_dict()[key]), key diff --git a/tests/test_prompted.py b/tests/test_prompted.py new file mode 100644 index 00000000..265b5fca --- /dev/null +++ b/tests/test_prompted.py @@ -0,0 +1,516 @@ +"""Tests of the SmokeBench prompted-baseline module (no network, GPU, API key, Pillow or OpenCV needed).""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path +from typing import List, Tuple + +import numpy as np +import pytest +import torch + +from pyhazards.prompted import ( + CLASSIFICATION_PROMPT, + DETECTION_PROMPT, + GRID_PROMPT, + PROMPTS, + TASKS, + TEMPERATURE, + TILE_PROMPT, + PromptedBackend, + available_backends, + build_backend, + evaluate_smokebench, +) +from pyhazards.prompted import runner as runner_module +from pyhazards.prompted.catalog import DOCS_PAGE_PATH, load_prompted_cards, render_prompted_page +from pyhazards.prompted.geometry import covered_cells, crop_tiles, tile_rects +from pyhazards.prompted.metrics import ( + AREA_BIN_EDGES, + CONTRAST_BIN_EDGES, + CONTRAST_BIN_EDGES_PRINTED, + accuracy, + assign_bin, + binned_means, + box_iou, + detection_iou, + opencv_gray, + quantile_edges, + set_iou, + smoke_area, + weber_contrast, +) +from pyhazards.prompted.parsers import ( + answer_kind, + parse_classification, + parse_detection, + parse_grid, + parse_tile, + strip_json_fence, +) + +# -------------------------------------------------------------------------------------------------- +# Prompts: byte-identical to the boxes of arXiv:2512.11215v1, sec/4_experiment.tex, rendered as text. +# -------------------------------------------------------------------------------------------------- + +PAPER_CLASSIFICATION = ( + "Please look at this image. Detect if the image contains smoke. If you can find any smoke, return True. " + "Otherwise, return False. Do not return any other words." +) +PAPER_GRID = ( + "Please look at this image, which is divided into several numbered regions (from left to right, top to " + "bottom). Please output the numbered regions that contain smoke in JSON format as a list of dicts like " + '[{"region": 1}, {"region": 2}]. If you cannot find any smoke, return an empty list []. without other words' +) +PAPER_DETECTION = ( + "Detect all smoke and output bounding boxes in the format [[x1, y1, x2, y2], [x1, y1, x2, y2]]. If you " + "cannot find any smoke, return an empty list [] without other words. Do not return dictionaries." +) + + +def test_prompts_are_the_papers_verbatim(): + assert CLASSIFICATION_PROMPT == PAPER_CLASSIFICATION + assert TILE_PROMPT == PAPER_CLASSIFICATION # the tile task reuses the classification prompt + assert GRID_PROMPT == PAPER_GRID + assert DETECTION_PROMPT == PAPER_DETECTION + assert set(PROMPTS) == set(TASKS) == {"classification", "tile", "grid", "detection"} + assert TEMPERATURE == 0.5 + digests = {task: hashlib.sha256(PROMPTS[task].encode("utf-8")).hexdigest()[:16] for task in ("classification", "grid", "detection")} + assert digests == { + "classification": hashlib.sha256(PAPER_CLASSIFICATION.encode()).hexdigest()[:16], + "grid": hashlib.sha256(PAPER_GRID.encode()).hexdigest()[:16], + "detection": hashlib.sha256(PAPER_DETECTION.encode()).hexdigest()[:16], + } + for prompt in PROMPTS.values(): + assert prompt.isascii() and " " not in prompt and prompt == prompt.strip() + + +# -------------------------------------------------------------------------------------------------- +# Geometry +# -------------------------------------------------------------------------------------------------- + + +def test_tiles_are_a_3x4_partition(): + rects = tile_rects(1536, 2048) + assert len(rects) == 12 + assert rects[0] == (0, 0, 512, 512) and rects[3] == (1536, 0, 2048, 512) and rects[11] == (1536, 1024, 2048, 1536) + covered = np.zeros((1536, 2048), dtype=int) + for x1, y1, x2, y2 in rects: + covered[y1:y2, x1:x2] += 1 + assert covered.min() == covered.max() == 1 # non-overlapping and complete + # When H // 3 == W // 4 the authors' crop formula gives the same tiles. + assert tile_rects(1536, 2048, protocol="reference_code") == rects + assert tile_rects(1200, 1600, protocol="reference_code") == tile_rects(1200, 1600) + + +def test_tiles_of_3072x2048_frames_and_the_reference_quirk(): + paper = tile_rects(2048, 3072) + assert paper[0] == (0, 0, 768, 682) and paper[11] == (2304, 1364, 3072, 2046) + quirk = tile_rects(2048, 3072, protocol="reference_code") + # image[i*hb:(i+1)*wb, j*wb:(j+1)*hb] with hb = 682, wb = 768 + assert quirk[0] == (0, 0, 682, 768) and quirk[5] == (768, 682, 1364, 1536) and quirk[11] == (2304, 1364, 2728, 2304) + # The same on a small 20 x 30 image (hb = 6, wb = 7). + image = (np.arange(20 * 30 * 3) % 251).reshape(20, 30, 3).astype(np.uint8) + tiles = crop_tiles(image) + assert [t.shape for t in tiles] == [(6, 7, 3)] * 12 + assert np.array_equal(tiles[5], image[6:12, 7:14]) + quirk_tiles = crop_tiles(image, protocol="reference_code") + assert quirk_tiles[5].shape == (8, 5, 3) and np.array_equal(quirk_tiles[5], image[6:14, 7:12]) + assert quirk_tiles[11].shape == (8, 3, 3) # rows 12:21 clipped to 20, columns 21:24 + + +def test_partition_input_validation(): + with pytest.raises(ValueError, match="shape"): + crop_tiles(np.zeros((10, 10), dtype=np.uint8)) + with pytest.raises(ValueError, match="too small"): + tile_rects(2, 3) + with pytest.raises(ValueError, match="protocol"): + tile_rects(30, 40, protocol="other") + with pytest.raises(ValueError, match="x1, y1, x2, y2"): + covered_cells([[1, 2, 3]], 100, 100, (5, 5)) + + +def test_covered_cells_hand_cases(): + # 1536 x 2048 frame, 5 x 5 grid: cells are 307 x 409 pixels. + assert covered_cells([[10, 10, 20, 20]], 1536, 2048, (5, 5)) == [1] + assert covered_cells([[400, 300, 420, 320]], 1536, 2048, (5, 5)) == [1, 2, 6, 7] + # both box ends are inclusive pixel indices: x2 == 409 touches column 1 + assert covered_cells([[0, 0, 408, 306]], 1536, 2048, (5, 5)) == [1] + assert covered_cells([[0, 0, 409, 306]], 1536, 2048, (5, 5)) == [1, 2] + # union over several boxes + assert covered_cells([[0, 0, 5, 5], [2040, 1530, 2047, 1535]], 1536, 2048, (5, 5)) == [1, 25] + # tile layout (3 x 4) on a 2048 x 3072 frame: 682 x 768 tiles + assert covered_cells([[700, 600, 800, 700]], 2048, 3072, (3, 4)) == [1, 2, 5, 6] + + +def test_covered_cells_at_the_image_edge(): + # 2048 // 5 = 409 -> the last 3 columns (2045..2047) and x2 == W fall outside 5 * 409. + box = [[1900, 100, 2048, 200]] + assert covered_cells(box, 1536, 2048, (5, 5)) == [5] + # the authors' formula maps column index 5 of row 0 to id 6 (first cell of row 1) + assert covered_cells(box, 1536, 2048, (5, 5), protocol="reference_code") == [5, 6] + bottom = [[100, 1500, 200, 1536]] + assert covered_cells(bottom, 1536, 2048, (5, 5)) == [21] + assert covered_cells(bottom, 1536, 2048, (5, 5), protocol="reference_code") == [21, 26] + + +# -------------------------------------------------------------------------------------------------- +# Parsers +# -------------------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "answer, smoke, kind", + [ + ("True", True, "true"), + ("False", False, "false"), + ("True.", True, "true"), + ("Answer: True", True, "true"), + ("False, but maybe True", True, "true"), + ("true", False, "other"), # case-sensitive, as in the authors' script + ("TRUE", False, "other"), + ("", False, "other"), + ("I cannot determine whether there is smoke.", False, "other"), + ("No smoke.", False, "other"), + ], +) +def test_classification_parsing(answer, smoke, kind): + assert parse_classification(answer) is smoke + assert answer_kind(answer) == kind + + +def test_tile_parsing_accepts_lowercase(): + assert parse_tile("True") and parse_tile("true") and parse_tile("It is true.") + assert not parse_tile("False") and not parse_tile("TRUE") and not parse_tile("") + + +@pytest.mark.parametrize( + "answer, cells", + [ + ('[{"region": 1}, {"region": 7}]', {1, 7}), + ('```json\n[{"region": 12}]\n```', {12}), + ("[]", set()), + ("No smoke is visible.", set()), + ("Regions 3 and 3 and 26", {3, 26}), # duplicates collapse, out-of-range ids are kept + ('[{"region": 0}]', {0}), + ('{"regions": [4, 5]}', {4, 5}), + ], +) +def test_grid_parsing(answer, cells): + assert parse_grid(answer) == cells + + +@pytest.mark.parametrize( + "answer, boxes", + [ + ("[[10, 20, 30, 40]]", [[10, 20, 30, 40]]), + ("[[1, 2, 3, 4], [5, 6, 7, 8]]", [[1, 2, 3, 4], [5, 6, 7, 8]]), + ("Boxes: [[1.5, 2, 3, 4]] done", [[1.5, 2, 3, 4]]), + ("```json\n[[1, 2, 3, 4]]\n```", [[1, 2, 3, 4]]), + ("[]", [[0, 0, 0, 0]]), + ("[[]]", [[0, 0, 0, 0]]), + ("[[], [1, 2, 3, 4]]", [[1, 2, 3, 4]]), + ("no smoke", [[0, 0, 0, 0]]), + ('[{"bbox": [1, 2, 3, 4]}]', [[0, 0, 0, 0]]), # dictionaries are not boxes + ("[[1, 2, 3, 4], [5, 6", [[0, 0, 0, 0]]), # truncated JSON + ("[[[1, 2, 3, 4]]]", [[0, 0, 0, 0]]), # the non-greedy span is unbalanced + ("[[1, 2, 3]]", [[1, 2, 3]]), # kept; scored as malformed + ('[["a", "b", "c", "d"]]', [["a", "b", "c", "d"]]), + ("[[1, 2, 3, 4]] and [[5, 6, 7, 8]]", [[1, 2, 3, 4]]), # first span only + ], +) +def test_detection_parsing(answer, boxes): + assert parse_detection(answer) == boxes + + +def test_json_fence_stripping(): + assert strip_json_fence('```json\n[{"region": 2}]\n```') == '[{"region": 2}]' + assert strip_json_fence(" True \n") == "True" + assert strip_json_fence("text ```json [1] ``` more") == "[1]" + + +# -------------------------------------------------------------------------------------------------- +# Metrics +# -------------------------------------------------------------------------------------------------- + + +def test_accuracy_and_set_iou_hand_cases(): + assert accuracy([True, False, True, False], [True, True, True, False]) == 0.75 + assert set_iou([1, 2, 3], [2, 3, 4, 5]) == pytest.approx(2 / 5) + assert set_iou([], [7]) == 0.0 + assert set_iou([7], [7]) == 1.0 + with pytest.raises(ValueError): + set_iou([], []) + with pytest.raises(ValueError): + accuracy([True], []) + + +def test_box_iou_matches_hand_computation(): + pred = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15], [20, 20, 30, 30]]) + gt = torch.tensor([[5, 5, 15, 15]]) + iou = box_iou(pred, gt) + assert iou.shape == (3, 1) + assert iou[:, 0].tolist() == pytest.approx([25 / 175, 1.0, 0.0]) + with pytest.raises(ValueError, match="shape"): + box_iou(torch.zeros(2, 3), gt) + + +def test_detection_iou_takes_the_best_pair_and_flags_malformed_boxes(): + gt = [(100, 100, 200, 200)] + assert detection_iou([[0, 0, 0, 0]], gt) == (0.0, None) + score, problem = detection_iou([[100, 100, 150, 200], [100, 100, 200, 200], [0, 0, 10, 10]], gt) + assert score == pytest.approx(1.0) and problem is None + assert detection_iou([[150, 100, 250, 200]], gt)[0] == pytest.approx(5000 / 15000) + assert detection_iou([[1.5, 2, 3, 4]], gt) == (0.0, None) + assert detection_iou([[1, 2, 3]], gt) == (0.0, "malformed") + assert detection_iou([["a", "b", "c", "d"]], gt) == (0.0, "non_numeric") + assert detection_iou([[1, 2, 3, 4], [1, 2]], gt) == (0.0, "non_numeric") # ragged + assert detection_iou([[5, 5, 5, 5]], [(5, 5, 5, 5)]) == (0.0, "nan") # zero union + + +def test_opencv_grey_conversion_constants(): + pixels = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255], [0, 0, 0]]], dtype=np.uint8) + # cv2.cvtColor(BGR2GRAY) of pure red, green, blue, white and black + assert opencv_gray(pixels).tolist() == [[76, 150, 29, 255, 0]] + + +def test_weber_contrast_hand_case(): + image = np.full((100, 100, 3), 100, dtype=np.uint8) + image[40:60, 40:60] = 120 # box pixels y1:y2, x1:x2 + assert weber_contrast(image, [(40, 40, 60, 60)]) == pytest.approx(0.2) + # zero-valued frame pixels are ignored; the frame is clipped at the image border + image[20:30, 20:80] = 0 + assert weber_contrast(image, [(40, 40, 60, 60)]) == pytest.approx(0.2) + assert weber_contrast(image, [(0, 0, 100, 100)]) == 0.0 # no frame left + assert smoke_area([(10, 20, 30, 60), (0, 0, 1000, 1000)]) == 800 # first box only + + +def test_bins_use_the_papers_quintiles(): + assert AREA_BIN_EDGES == (42, 4356, 11232, 28565, 83157, 2232020) + assert [float(f"{edge:.3g}") for edge in CONTRAST_BIN_EDGES[1:]] == list(CONTRAST_BIN_EDGES_PRINTED[1:]) + assert [assign_bin(v, AREA_BIN_EDGES) for v in (1, 42, 4356, 4357, 11232, 83157, 83158, 10**8)] == [0, 0, 0, 1, 1, 3, 4, 4] + means = binned_means([1.0, 0.0, 1.0], [100, 5000, 90000], AREA_BIN_EDGES, ["a", "b", "c", "d", "e"]) + assert means == {"a": {"mean": 1.0, "n": 1}, "b": {"mean": 0.0, "n": 1}, "c": {"mean": None, "n": 0}, "d": {"mean": None, "n": 0}, "e": {"mean": 1.0, "n": 1}} + + +def test_quantile_edges_match_pandas_qcut(): + pandas = pytest.importorskip("pandas") + values = np.random.default_rng(0).integers(40, 2_000_000, size=503).tolist() + edges = quantile_edges(values) + categories = pandas.qcut(pandas.Series(values), 5).cat.categories + assert edges[1:-1] == pytest.approx([interval.right for interval in categories[:-1]]) + codes = pandas.qcut(pandas.Series(values), 5).cat.codes.tolist() + assert [assign_bin(v, edges) for v in values] == codes + + +# -------------------------------------------------------------------------------------------------- +# Runner with a deterministic fake backend +# -------------------------------------------------------------------------------------------------- + + +@dataclass +class FakeSample: + image_id: str + label: bool + boxes: Tuple[Tuple[int, int, int, int], ...] = () + + +class FakeDataset(list): + """Synthetic 60 x 80 frames: smoke images carry a bright box, smoke-free ones are flat.""" + + def load_image(self, sample): + image = np.full((60, 80, 3), 50, dtype=np.uint8) + for x1, y1, x2, y2 in sample.boxes: + image[y1:y2, x1:x2] = 200 + return image + + +class FakeBackend(PromptedBackend): + name = "fake" + model_id = "fake/deterministic" + + def __init__(self, grid_answer='[{"region": 1}, {"region": 2}]', box_answer="[[0, 0, 40, 30]]"): + super().__init__() + self.calls: List[Tuple[Tuple[int, ...], str]] = [] + self.grid_answer, self.box_answer = grid_answer, box_answer + + def generate(self, image, prompt): + self.calls.append((image.shape, prompt)) + if prompt == CLASSIFICATION_PROMPT: + return "True" if image.max() > 150 else "False" + if prompt == GRID_PROMPT: + return self.grid_answer + return self.box_answer + + +def _dataset(): + return FakeDataset( + [ + FakeSample("seq/1_+00060", True, ((0, 0, 20, 15),)), # top-left corner (tile 1) + FakeSample("seq/2_+00120", True, ((30, 20, 50, 40),)), # centre: tiles 6, 7, 10, 11 overlap + FakeSample("seq/3_+00180", True, ((5, 5, 6, 6),)), # tiny smoke, still bright + FakeSample("seq/4_-00060", False), + FakeSample("seq/5_-00120", False), + ] + ) + + +def test_runner_classification_report(tmp_path): + backend = FakeBackend() + report = evaluate_smokebench(backend, _dataset(), "classification", output_dir=tmp_path) + metrics = report["metrics"] + assert metrics["accuracy_smoke"] == 1.0 and metrics["accuracy_smoke_free"] == 1.0 and metrics["accuracy_all"] == 1.0 + assert metrics["n_smoke"] == 3 and metrics["n_smoke_free"] == 2 + assert metrics["answers"] == {"true": 3, "false": 2} + assert sum(item["n"] for item in metrics["by_area"].values()) == 3 + assert metrics["by_area"]["Very Small"] == {"mean": 1.0, "n": 3} # areas 300, 400 and 1 pixels + assert report["prompt"] == CLASSIFICATION_PROMPT and report["task"] == "classification" + assert report["paper_reported"] is None # not a SmokeBench model + records = [json.loads(line) for line in (tmp_path / "records.jsonl").read_text().splitlines()] + assert [r["image_id"] for r in records] == [s.image_id for s in _dataset()] + assert records[0]["contrast"] > 0 and "contrast" not in records[3] + saved = json.loads((tmp_path / "report.json").read_text()) + assert saved["metrics"]["accuracy_all"] == 1.0 + assert len(backend.calls) == 5 and all(shape == (60, 80, 3) for shape, _ in backend.calls) + + +def test_runner_tile_task_scores_tile_sets(): + backend = FakeBackend() + report = evaluate_smokebench(backend, _dataset(), "tile") + # 60 x 80 frame -> 20 x 20 tiles; the fake model says True for tiles with bright pixels. + # Box ends are inclusive, so (0, 0, 20, 15) also covers tile 2 and (30, 20, 50, 40) tiles 10-11: + # IoUs {1} vs {1, 2} = 0.5, {6, 7} vs {6, 7, 10, 11} = 0.5, {1} vs {1} = 1. + assert report["metrics"]["n_smoke"] == 3 and report["metrics"]["miou"] == pytest.approx(2 / 3) + assert report["metrics"]["mean_predicted_tiles"] == pytest.approx(4 / 3) + assert len(backend.calls) == 36 and all(shape == (20, 20, 3) for shape, _ in backend.calls) + assert all(prompt == TILE_PROMPT for _, prompt in backend.calls) + + +def test_runner_tile_targets_include_boundary_tiles(): + # Box (30, 20, 50, 40) ends exactly on tile boundaries x = 40 / y = 40: inclusive ends add tiles. + assert covered_cells([(30, 20, 50, 40)], 60, 80, (3, 4)) == [6, 7, 10, 11] + + +def test_runner_grid_task_with_a_stub_overlay(monkeypatch): + monkeypatch.setattr(runner_module, "draw_grid_overlay", lambda image, layout: image) + backend = FakeBackend(grid_answer='[{"region": 1}, {"region": 2}]') + report = evaluate_smokebench(backend, _dataset(), "grid") + # 60 x 80 frame, 5 x 5 grid of 12 x 16 cells; targets {1, 2, 6, 7}, {7, 8, 9, 12, 13, 14, 17, 18, 19}, {1} + expected = np.mean([0.5, 0.0, 0.5]) + assert report["metrics"]["miou"] == pytest.approx(expected) + assert report["metrics"]["answers_without_ids"] == 0 + + +def test_runner_detection_task(): + backend = FakeBackend(box_answer="[[0, 0, 20, 15], [30, 20, 50, 40]]") + report = evaluate_smokebench(backend, _dataset(), "detection") + # third image: best pair is (0,0,20,15) vs (5,5,6,6) -> 1 / 300 + assert report["metrics"]["miou"] == pytest.approx(np.mean([1.0, 1.0, 1 / 300])) + assert report["metrics"]["empty_predictions"] == 0 + bad = evaluate_smokebench(FakeBackend(box_answer="I see no smoke"), _dataset(), "detection") + assert bad["metrics"]["miou"] == 0.0 and bad["metrics"]["empty_predictions"] == 3 + + +def test_runner_resumes_and_refuses_a_different_run(tmp_path): + evaluate_smokebench(FakeBackend(), _dataset(), "classification", output_dir=tmp_path, limit=2) + backend = FakeBackend() + report = evaluate_smokebench(backend, _dataset(), "classification", output_dir=tmp_path) + assert len(backend.calls) == 3 # the first two images were reused + assert report["metrics"]["n_smoke"] + report["metrics"]["n_smoke_free"] == 5 + with pytest.raises(ValueError, match="different run"): + evaluate_smokebench(FakeBackend(), _dataset(), "detection", output_dir=tmp_path) + fresh = FakeBackend() + evaluate_smokebench(fresh, _dataset(), "classification", output_dir=tmp_path, resume=False) + assert len(fresh.calls) == 5 + + +def test_runner_attaches_the_papers_numbers_for_smokebench_models(): + backend = FakeBackend() + backend.name = "qwen2_5_vl_7b" + report = evaluate_smokebench(backend, _dataset(), "classification") + assert report["paper_reported"]["area"]["Overall"] == 0.380 + assert report["paper_reported"]["smoke_free"] == 0.982 + + +def test_runner_input_validation(): + with pytest.raises(ValueError, match="task"): + evaluate_smokebench(FakeBackend(), _dataset(), "segmentation") + with pytest.raises(ValueError, match="protocol"): + evaluate_smokebench(FakeBackend(), _dataset(), "tile", protocol="loose") + with pytest.raises(ValueError, match="no samples"): + evaluate_smokebench(FakeBackend(), FakeDataset([FakeSample("seq/4_-00060", False)]), "tile") + with pytest.raises(ValueError, match="load_image"): + evaluate_smokebench(FakeBackend(), list(_dataset()), "classification") + with pytest.raises(ValueError, match="RGB uint8"): + evaluate_smokebench(FakeBackend(), _dataset(), "classification", load_image=lambda s: np.zeros((4, 4))) + + +# -------------------------------------------------------------------------------------------------- +# Cards, docs and backend construction +# -------------------------------------------------------------------------------------------------- + + +def test_cards_cover_the_backend_presets_and_render_the_docs_page(): + cards = load_prompted_cards() + assert [card.name for card in cards] == ["idefics2_8b", "qwen2_5_vl_7b", "qwen2_5_vl_32b", "internvl3_14b", "gemini_2_5_pro", "gpt_4o"] + assert sorted(card.name for card in cards) == available_backends() + for card in cards: + for task in card.smokebench_tasks: + numbers = getattr(card.smokebench_reported, task) + if numbers.area is not None: + assert numbers.area["Overall"] == numbers.contrast["Overall"], card.name + page = render_prompted_page(cards) + assert DOCS_PAGE_PATH.read_text(encoding="utf-8") == page, "run scripts/render_prompted_docs.py" + for text in (PAPER_CLASSIFICATION, PAPER_GRID, PAPER_DETECTION, "arxiv.org/abs/2502.13923", "arxiv.org/abs/2507.06261", "arxiv.org/abs/2504.10479", "arxiv.org/abs/2405.02246", "arxiv.org/abs/2410.21276", "arxiv.org/abs/2512.11215"): + assert text in page + + +def test_models_page_and_index_link_the_prompted_page(): + root = Path(__file__).resolve().parents[1] + assert ":doc:`pyhazards_prompted`" in (root / "docs" / "source" / "pyhazards_models.rst").read_text(encoding="utf-8") + assert "pyhazards_prompted" in (root / "docs" / "source" / "index.rst").read_text(encoding="utf-8") + + +def test_build_backend_names_and_missing_optional_packages(monkeypatch): + with pytest.raises(KeyError, match="unknown prompted backend"): + build_backend("llama4") + import importlib.util + + if importlib.util.find_spec("openai") is None: + with pytest.raises(ImportError, match=r"pyhazards\[prompted-openai\]"): + build_backend("gpt_4o") + else: + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(RuntimeError, match="OPENAI_API_KEY"): + build_backend("gpt_4o") + if importlib.util.find_spec("google") is None or importlib.util.find_spec("google.genai") is None: + with pytest.raises(ImportError, match=r"pyhazards\[prompted-gemini\]"): + build_backend("gemini_2_5_pro") + else: + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + monkeypatch.delenv("GOOGLE_API_KEY", raising=False) + with pytest.raises(RuntimeError, match="GEMINI_API_KEY"): + build_backend("gemini_2_5_pro") + if importlib.util.find_spec("transformers") is None: + with pytest.raises(ImportError, match=r"pyhazards\[prompted-hf\]"): + build_backend("qwen2_5_vl_7b") + + +def test_grid_overlay_draws_cell_lines_and_numbers(): + pytest.importorskip("cv2") + from pyhazards.prompted.geometry import draw_grid_overlay + + image = np.full((120, 160, 3), 40, dtype=np.uint8) + overlay = draw_grid_overlay(image) + assert overlay.shape == image.shape and overlay.dtype == np.uint8 + assert np.array_equal(image, np.full((120, 160, 3), 40, dtype=np.uint8)) # input untouched + # white 1-pixel outlines on the 24 x 32 cell borders + assert (overlay[24, 5] == 255).all() and (overlay[5, 32] == 255).all() and (overlay[0, 7] == 255).all() + # the numbers are red (R = 255, G = B = 0) near each cell centre + red = (overlay[..., 0] == 255) & (overlay[..., 1] == 0) & (overlay[..., 2] == 0) + assert red[0:24, 0:32].any() and red[96:120, 128:160].any() + with pytest.raises(ValueError, match="uint8"): + draw_grid_overlay(image.astype(np.float32)) diff --git a/tests/test_prompted_backends.py b/tests/test_prompted_backends.py new file mode 100644 index 00000000..dcc43d1e --- /dev/null +++ b/tests/test_prompted_backends.py @@ -0,0 +1,194 @@ +"""Request construction of the prompted backends with fake models / clients (needs Pillow; no network).""" + +from __future__ import annotations + +import base64 +import io +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +PIL = pytest.importorskip("PIL.Image") + +from pyhazards.prompted import CLASSIFICATION_PROMPT, GRID_PROMPT, build_backend # noqa: E402 +from pyhazards.prompted.backends import GeminiBackend, Idefics2Backend, InternVL3Backend, OpenAIBackend, Qwen25VLBackend # noqa: E402 + +IMAGE = (np.arange(30 * 40 * 3) % 256).reshape(30, 40, 3).astype(np.uint8) + + +class FakeInputs(dict): + def to(self, device, dtype=None): + self.moved = (device, dtype) + return self + + +class FakeTokenizer: + pad_token = None + eos_token = "" + padding_side = "right" + + +class FakeProcessor: + """Records what the backend sends; 'tokenizes' each text into 5 prompt tokens.""" + + def __init__(self): + self.tokenizer = FakeTokenizer() + self.image_processor = SimpleNamespace(do_image_splitting=True) + self.calls = [] + + def apply_chat_template(self, conversation, **kwargs): + self.calls.append(("chat", conversation, kwargs)) + if kwargs.get("tokenize"): + return FakeInputs(input_ids=torch.zeros(len(conversation), 5, dtype=torch.long)) + return "" + + def __call__(self, text=None, images=None, **kwargs): + self.calls.append(("call", text, images, kwargs)) + return FakeInputs(input_ids=torch.zeros(len(text), 5, dtype=torch.long)) + + def batch_decode(self, tokens, **kwargs): + self.calls.append(("decode", tokens.tolist(), kwargs)) + return [self.answer] * tokens.shape[0] + + +class FakeModel: + device = "cpu" + dtype = torch.bfloat16 + config = SimpleNamespace(_commit_hash="abc123") + + def __init__(self): + self.generate_kwargs = [] + + def eval(self): + return self + + def generate(self, input_ids, **kwargs): + self.generate_kwargs.append(kwargs) + new = torch.full((input_ids.shape[0], 2), 7, dtype=torch.long) + return torch.cat([input_ids, new], dim=1) + + +def _backend(cls, answer, **kwargs): + processor, model = FakeProcessor(), FakeModel() + processor.answer = answer + return cls(model=model, processor=processor, **kwargs), model, processor + + +def test_qwen_backend_resizes_to_448_and_strips_fences(): + backend, model, processor = _backend(Qwen25VLBackend, '```json\n[{"region": 3}]\n```') + assert backend.generate(IMAGE, GRID_PROMPT) == '[{"region": 3}]' + kind, conversation, kwargs = processor.calls[0] + assert kind == "chat" and kwargs == {"tokenize": False, "add_generation_prompt": True} + content = conversation[0]["content"] + assert content[0]["type"] == "image" and content[0]["image"].size == (448, 448) + assert content[1] == {"type": "text", "text": GRID_PROMPT} + _, texts, images, call_kwargs = processor.calls[1] + assert texts == [""] and images[0].size == (448, 448) and call_kwargs["padding"] is True + assert model.generate_kwargs == [{"max_new_tokens": 128, "do_sample": True, "temperature": 0.5}] + _, decoded, decode_kwargs = processor.calls[2] + assert decoded == [[7, 7]] # only the new tokens are decoded + assert decode_kwargs == {"skip_special_tokens": True, "clean_up_tokenization_spaces": False} + assert backend.describe()["revision"] == "abc123" and backend.describe()["image_size"] == (448, 448) + + +def test_qwen_backend_batches_tiles_with_left_padding_and_greedy_option(): + backend, model, processor = _backend(Qwen25VLBackend, "True", do_sample=False, image_size=None) + answers = backend.generate_batch([IMAGE, IMAGE[:, :20]], CLASSIFICATION_PROMPT) + assert answers == ["True", "True"] + assert processor.tokenizer.padding_side == "left" + assert processor.calls[2][2][0].size == (40, 30) and processor.calls[2][2][1].size == (20, 30) + assert model.generate_kwargs == [{"max_new_tokens": 128, "do_sample": False}] + + +def test_internvl_backend_uses_the_chat_template_with_tokenization(): + backend, model, processor = _backend(InternVL3Backend, "False") + assert backend.generate(IMAGE, CLASSIFICATION_PROMPT) == "False" + kind, conversations, kwargs = processor.calls[0] + assert kind == "chat" and kwargs["tokenize"] and kwargs["return_dict"] and kwargs["add_generation_prompt"] + assert conversations[0][0]["content"][0]["image"].size == (40, 30) # native resolution + assert model.generate_kwargs == [{"max_new_tokens": 256, "do_sample": True, "temperature": 0.5}] + assert backend.dtype == "float32" + + +def test_idefics2_backend_raw_prompt_for_images_and_chat_batch_for_tiles(): + backend, model, processor = _backend(Idefics2Backend, " True") + assert processor.image_processor.do_image_splitting is False + assert backend.generate(IMAGE, CLASSIFICATION_PROMPT) == "True" + _, texts, images, _ = processor.calls[0] + assert texts == ["\n" + CLASSIFICATION_PROMPT] and len(images) == 1 and len(images[0]) == 1 + assert model.generate_kwargs[-1] == {"max_new_tokens": 256, "do_sample": True, "temperature": 0.5} + processor.calls.clear() + assert backend.generate_batch([IMAGE] * 3, CLASSIFICATION_PROMPT) == ["True"] * 3 + assert [call[0] for call in processor.calls] == ["chat", "chat", "chat", "call", "decode"] + assert processor.tokenizer.padding_side == "left" and processor.tokenizer.pad_token == "" + assert model.generate_kwargs[-1] == {"max_new_tokens": 16, "do_sample": True, "temperature": 0.5} + + +class FakeGeminiModels: + def __init__(self): + self.requests = [] + + def generate_content(self, **kwargs): + self.requests.append(kwargs) + return SimpleNamespace(text="True", model_version="gemini-2.5-pro-test") + + +class FakeOpenAICompletions: + def __init__(self): + self.requests = [] + + def create(self, **kwargs): + self.requests.append(kwargs) + return SimpleNamespace(model="gpt-4o-2024-08-06", choices=[SimpleNamespace(message=SimpleNamespace(content="False"))]) + + +def _decode_jpeg(data: bytes) -> np.ndarray: + return np.asarray(PIL.open(io.BytesIO(data)).convert("RGB")) + + +def test_gemini_request_layout(): + client = SimpleNamespace(models=FakeGeminiModels()) + backend = build_backend("gemini_2_5_pro", client=client) + assert backend.generate(IMAGE, CLASSIFICATION_PROMPT) == "True" + assert backend.last_served_model == "gemini-2.5-pro-test" and backend.name == "gemini_2_5_pro" + request = client.models.requests[0] + assert request["model"] == "gemini-2.5-pro" and request["config"] == {"temperature": 0.5} + image_part, text_part = request["contents"][0]["parts"] + assert text_part == {"text": CLASSIFICATION_PROMPT} + assert image_part["inline_data"]["mime_type"] == "image/jpeg" + assert np.abs(_decode_jpeg(image_part["inline_data"]["data"]).astype(int) - IMAGE).mean() < 8 + + +def test_openai_request_layout(): + client = SimpleNamespace(chat=SimpleNamespace(completions=FakeOpenAICompletions())) + backend = OpenAIBackend(client=client) + assert backend.generate(IMAGE, CLASSIFICATION_PROMPT) == "False" + assert backend.last_served_model == "gpt-4o-2024-08-06" + request = client.chat.completions.requests[0] + assert request["model"] == "gpt-4o" and request["temperature"] == 0.5 and request["max_tokens"] == 300 + text_part, image_part = request["messages"][0]["content"] + assert text_part == {"type": "text", "text": CLASSIFICATION_PROMPT} + url = image_part["image_url"]["url"] + assert url.startswith("data:image/jpeg;base64,") + assert _decode_jpeg(base64.b64decode(url.split(",", 1)[1])).shape == IMAGE.shape + + +def test_backends_reject_non_rgb_arrays(): + backend = GeminiBackend(client=SimpleNamespace(models=FakeGeminiModels())) + with pytest.raises(ValueError, match="RGB uint8"): + backend.generate(IMAGE.astype(np.float32), CLASSIFICATION_PROMPT) + + +def test_presets_pin_revisions_and_keep_the_card_name_only_for_the_card_model(): + from pyhazards.prompted.backends import REVISIONS + + client = SimpleNamespace(models=FakeGeminiModels()) + assert build_backend("gemini_2_5_pro", client=client).name == "gemini_2_5_pro" + assert build_backend("gemini_2_5_pro", client=client, model_id="gemini-3.1-pro-preview").name == "gemini" + processor, model = FakeProcessor(), FakeModel() + qwen = build_backend("qwen2_5_vl_7b", model=model, processor=processor) + assert qwen.name == "qwen2_5_vl_7b" and qwen.revision == REVISIONS["Qwen/Qwen2.5-VL-7B-Instruct"] + other = build_backend("qwen2_5_vl_7b", model=model, processor=processor, model_id="Qwen/Qwen2.5-VL-3B-Instruct") + assert other.name == "qwen2_5_vl" and other.revision is None diff --git a/tests/test_rainformer.py b/tests/test_rainformer.py new file mode 100644 index 00000000..d2f36e87 --- /dev/null +++ b/tests/test_rainformer.py @@ -0,0 +1,131 @@ +"""Rainformer: parameter counts, stage geometry, layouts, the segmentation adaptation, validation. + +Numerical equivalence with the official code (and its KNMI weights) lives in +tests/oracle/test_rainformer_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.rainformer import Rainformer, rainformer_stage_sizes + +SMALL = dict(history=3, img_size=64, hidden_dim=8, heads=(1, 1, 1, 1), head_dim=4, window_size=2) + + +def _n_params(model: torch.nn.Module, trainable: bool = False) -> int: + return sum(p.numel() for p in model.parameters() if p.requires_grad or not trainable) + + +def test_rainformer_default_parameter_count(): + with torch.device("meta"): + model = build_model("rainformer", task="forecasting") + assert model.input_channel == 9 and model.img_size == (288, 288) + assert _n_params(model) == 187_661_990 # official Net(...) of train.py, masks included + assert _n_params(model, trainable=True) == 187_557_014 + + +def test_rainformer_stage_sizes_follow_the_input_size(): + assert rainformer_stage_sizes(288, (4, 2, 2, 2)) == [ + (72, 72), (36, 36), (18, 18), (9, 9), (18, 18), (36, 36), (72, 72), (288, 288) + ] + assert rainformer_stage_sizes((256, 128), (4, 2, 2, 2))[3] == (8, 4) + with pytest.raises(ValueError): + rainformer_stage_sizes(100, (4, 2, 2, 2)) + + +def test_rainformer_256_input_needs_another_window_size(): + # Sim2Real-Fire's 256x256 frames give 64/32/16/8 maps, which window 9 does not divide. + with pytest.raises(ValueError, match="window_size 9"): + build_model("rainformer", task="forecasting", img_size=256) + with torch.device("meta"): + model = build_model("rainformer", task="forecasting", img_size=256, window_size=8) + assert model.stage_sizes[3] == (8, 8) + + +def test_rainformer_official_and_time_major_layouts_agree(): + model = build_model("rainformer", task="forecasting", in_channels=2, **SMALL).eval() + x = torch.randn(2, 3, 2, 64, 64) + with torch.no_grad(): + out = model(x) + torch.testing.assert_close(out.flatten(1, 2), model(x.flatten(1, 2))) + assert out.shape == (2, 3, 2, 64, 64) + + +def test_rainformer_segmentation_adaptation_keeps_reference_names(): + torch.manual_seed(0) + core = build_model("rainformer", task="forecasting", in_channels=2, **SMALL) + torch.manual_seed(0) + seg = build_model("rainformer", task="segmentation", in_channels=2, **SMALL) + core_state, seg_state = core.state_dict(), seg.state_dict() + assert list(seg_state) == list(core_state) + ["segmentation_head.weight", "segmentation_head.bias"] + for key, value in core_state.items(): + assert torch.equal(value, seg_state[key]), key + + core.eval() + seg.eval() + x = torch.randn(2, 3, 2, 64, 64) + with torch.no_grad(): + logits = seg(x) + torch.testing.assert_close(logits, seg.segmentation_head(core(x)[:, 0])) + assert logits.shape == (2, 1, 64, 64) + with pytest.raises(ValueError): + seg(x.flatten(1, 2)) # the adaptation needs the (batch, time, channels, H, W) layout + + +def test_rainformer_unused_gate_convolutions_get_no_gradient(): + model = build_model("rainformer", task="forecasting", **SMALL) + model(torch.randn(1, 3, 64, 64)).sum().backward() + gate = model.stage1.layers[0][4] + assert gate.conv_1[0].weight.grad is not None + assert gate.conv_2[0].weight.grad is None and gate.conv_3[0].weight.grad is None + assert not model.stage1.layers[0][1].attention_block.fn.fn.upper_lower_mask.requires_grad + + +def test_rainformer_extra_stage_groups_reuse_the_stage_input(): + # Reference behaviour: with layers > 2 every group reads the stage input; the last one wins. + torch.manual_seed(0) + deep = build_model("rainformer", task="forecasting", **{**SMALL, "layers": (4, 2, 2, 2)}).eval() + torch.manual_seed(1) + shallow = build_model("rainformer", task="forecasting", **SMALL).eval() + state = {} + for key, value in deep.state_dict().items(): # layers[0] sets stage1 and stage8: keep group 1 + if key.startswith(("stage1.layers.0.", "stage8.layers.0.")): + continue + state[key.replace("stage1.layers.1.", "stage1.layers.0.").replace("stage8.layers.1.", "stage8.layers.0.")] = value + shallow.load_state_dict(state, strict=True) + x = torch.randn(1, 3, 64, 64) + with torch.no_grad(): + torch.testing.assert_close(deep(x), shallow(x)) + + +@pytest.mark.parametrize("shape", [(1, 4, 64, 64), (1, 3, 32, 32), (1, 2, 2, 64, 64), (3, 64, 64)]) +def test_rainformer_bad_input_shapes_raise(shape): + model = build_model("rainformer", task="forecasting", **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "overrides", + [dict(layers=(1, 2, 2, 2)), dict(layers=(2, 2, 2)), dict(window_size=1), dict(window_size=3), dict(hidden_dim=6), dict(history=0)], +) +def test_rainformer_rejects_unsupported_configurations(overrides): + with pytest.raises(ValueError): + build_model("rainformer", task="forecasting", **{**SMALL, **overrides}) + + +def test_rainformer_rejects_unknown_task(): + with pytest.raises(ValueError): + build_model("rainformer", task="regression", **SMALL) + + +def test_rainformer_class_defaults_are_the_official_configuration(): + with torch.device("meta"): + model = Rainformer() + attention = model.stage4.layers[0][1].attention_block.fn.fn + assert (attention.heads, attention.head_dim, attention.window_size) == (24, 32, 9) + assert model.stage1.patch_partition.linear.in_features == 9 * 16 + assert model.stage8.layers[0][4].conv_1[1].normalized_shape == (18, 288, 288) diff --git a/tests/test_segformer.py b/tests/test_segformer.py new file mode 100644 index 00000000..0122ac44 --- /dev/null +++ b/tests/test_segformer.py @@ -0,0 +1,146 @@ +"""SegFormer: configurations, parameter counts, shapes and input validation. + +Numerical equivalence with transformers and the official checkpoints lives in +tests/oracle/test_segformer_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch +import torch.nn.functional as F + +from pyhazards.models import build_model +from pyhazards.models.segformer import SEGFORMER_VARIANTS, SegFormer, adapt_first_conv_weight + +# transformers SegformerForSemanticSegmentation, 3 channels, 150 classes (ADE20K). SegFormer paper +# Table 1: 3.8M, 13.7M, 27.5M, 47.3M, 64.1M, 84.7M. +ADE20K_PARAMS = { + "b0": 3_752_694, + "b1": 13_715_798, + "b2": 27_461_974, + "b3": 47_337_814, + "b4": 64_108_374, + "b5": 84_708_694, +} + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize("variant", sorted(SEGFORMER_VARIANTS)) +def test_parameter_counts_match_paper_table1(variant): + with torch.device("meta"): + model = SegFormer(in_channels=3, num_labels=150, variant=variant) + assert _n_params(model) == ADE20K_PARAMS[variant] + + +@pytest.mark.parametrize( + "in_channels, expected", + [ + (40, 27_463_425), # WSTS+ T=1, all features: reported 27.5M + (120, 27_714_305), # WSTS+ T=5 with WildfireSpreadTS static-feature deduplication: reported 27.7M + ], +) +def test_wsts_plus_parameter_counts(in_channels, expected): + with torch.device("meta"): + model = build_model("segformer", task="segmentation", in_channels=in_channels) + assert _n_params(model) == expected + + +def test_decoder_width_follows_variant(): + for variant, spec in SEGFORMER_VARIANTS.items(): + with torch.device("meta"): + model = SegFormer(in_channels=3, num_labels=2, variant=variant) + assert model.decode_head.linear_fuse.out_channels == spec["decoder_hidden_size"] + assert model.decode_head.linear_fuse.out_channels == (256 if variant in ("b0", "b1") else 768) + + +@pytest.mark.parametrize("height, width", [(64, 64), (33, 47), (128, 96)]) +def test_output_is_upsampled_to_input_size(height, width): + model = build_model("segformer", task="segmentation", variant="b0", in_channels=6, out_channels=3).eval() + x = torch.randn(2, 6, height, width) + with torch.no_grad(): + out = model(x) + raw = model.raw_logits(x) + assert out.shape == (2, 3, height, width) + assert raw.shape == (2, 3, -(-height // 4), -(-width // 4)) + torch.testing.assert_close(out, F.interpolate(raw, size=(height, width), mode="bilinear", align_corners=False)) + + +def test_upsample_flag_returns_quarter_resolution(): + model = build_model("segformer", task="segmentation", variant="b0", in_channels=4, upsample=False).eval() + with torch.no_grad(): + assert model(torch.randn(1, 4, 64, 64)).shape == (1, 1, 16, 16) + + +def test_multiday_input_is_flattened_time_major(): + model = build_model("segformer", task="segmentation", variant="b0", in_channels=3, history=2).eval() + x = torch.randn(1, 2, 3, 32, 32) + with torch.no_grad(): + torch.testing.assert_close(model(x), model(torch.cat([x[:, 0], x[:, 1]], dim=1))) + + +@pytest.mark.parametrize("shape", [(2, 3, 64), (2, 4, 64, 64), (1, 3, 28, 64), (1, 3, 64, 20), (1, 2, 2, 3, 4, 4)]) +def test_bad_input_shapes_raise(shape): + model = build_model("segformer", task="segmentation", variant="b0", in_channels=3) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +def test_smallest_valid_input(): + model = build_model("segformer", task="segmentation", variant="b0", in_channels=3).eval() + with torch.no_grad(): + assert model(torch.randn(1, 3, 29, 29)).shape == (1, 1, 29, 29) + + +def test_bad_configuration_raises(): + with pytest.raises(ValueError): + build_model("segformer", task="segmentation", in_channels=3, variant="b6") + with pytest.raises(ValueError): + build_model("segformer", task="classification", in_channels=3) + with pytest.raises(ValueError): + build_model("segformer", task="segmentation", in_channels=3, history=0) + with pytest.raises(ValueError): + build_model("segformer", task="segmentation", in_channels=3, variant="b0", encoder_weights="/nonexistent.bin") + + +def test_first_conv_adaptation_rule(): + weight = torch.randn(32, 3, 7, 7) + assert adapt_first_conv_weight(weight, 3) is weight + torch.testing.assert_close(adapt_first_conv_weight(weight, 1), weight.sum(1, keepdim=True)) + adapted = adapt_first_conv_weight(weight, 7) + assert adapted.shape == (32, 7, 7, 7) + for i in range(7): + torch.testing.assert_close(adapted[:, i], weight[:, i % 3] * (3 / 7)) + + +def test_load_hf_state_dict_accepts_all_transformers_layouts(tmp_path): + source = SegFormer(in_channels=3, num_labels=2, variant="b0") + full = source.state_dict() + encoder = source.segformer.state_dict() + classification = {"segformer." + key: value for key, value in encoder.items()} + classification["classifier.weight"] = torch.zeros(1000, 256) + classification["classifier.bias"] = torch.zeros(1000) + + for state, part in [(full, None), (encoder, "segformer"), (classification, "segformer")]: + target = SegFormer(in_channels=3, num_labels=2, variant="b0") + target.load_hf_state_dict(state) + expected = source if part is None else source.segformer + loaded = target if part is None else target.segformer + for key, value in expected.state_dict().items(): + assert torch.equal(loaded.state_dict()[key], value), key + + with pytest.raises(RuntimeError): + SegFormer(in_channels=3, num_labels=2, variant="b1").load_hf_state_dict(classification) + + # A local checkpoint passed as encoder_weights loads the encoder and adapts the stem. + path = tmp_path / "pytorch_model.bin" + torch.save(classification, path) + model = build_model("segformer", task="segmentation", variant="b0", in_channels=5, encoder_weights=str(path)) + stem = "encoder.patch_embeddings.0.proj.weight" + torch.testing.assert_close(model.segformer.state_dict()[stem], adapt_first_conv_weight(encoder[stem], 5)) + for key, value in encoder.items(): + if key != stem: + assert torch.equal(model.segformer.state_dict()[key], value), key diff --git a/tests/test_seisbench_reader.py b/tests/test_seisbench_reader.py new file mode 100644 index 00000000..efeb73fa --- /dev/null +++ b/tests/test_seisbench_reader.py @@ -0,0 +1,168 @@ +"""SeisBench-format and STEAD-layout reader on small fixtures that follow the real file layouts.""" + +import csv +import math + +import h5py +import numpy as np +import pytest +import torch + +from pyhazards.datasets import load_dataset +from pyhazards.datasets.earthquake import parse_trace_name + + +def _write_csv(path, rows): + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def _seisbench_chunk(root, chunk="", n=5, length=600, offset=0.0, data_format=True): + """SeisBench layout: trace blocks ``bucket`` of shape (N, C, W) and a data_format group.""" + rng = np.random.default_rng(len(chunk)) + blocks = {"bucket0": rng.standard_normal((3, 3, length)), "bucket1": rng.standard_normal((n - 3, 3, length + 20))} + rows = [] + splits = ["train", "dev", "test", "train", "test"] + for k in range(n): + block, i = ("bucket0", k) if k < 3 else ("bucket1", k - 3) + rows.append( + { + "trace_start_time": "2020-01-01T00:00:00", + "trace_name": f"{block}${i},:3,:{length}", + "trace_sampling_rate_hz": "100.0", + "trace_p_arrival_sample": "" if k == 4 else str(100 + k), + "trace_s_arrival_sample": "" if k == 4 else str(300 + k), + "trace_category": "noise" if k == 4 else "earthquake_local", + "split": splits[k], + } + ) + _write_csv(root / f"metadata{chunk}.csv", rows) + with h5py.File(root / f"waveforms{chunk}.hdf5", "w") as handle: + for name, array in blocks.items(): + handle.create_dataset(f"data/{name}", data=(array + offset).astype("float32")) + if data_format: + group = handle.create_group("data_format") + group["dimension_order"] = "CW" + group["component_order"] = "ZNE" + group["sampling_rate"] = 100 + group["measurement"] = "velocity" + group["unit"] = "counts" + group["instrument_response"] = "not restituted" + return blocks, rows + + +def test_trace_block_names_are_parsed(): + assert parse_trace_name("bucket3$12,:3,:6000") == ("bucket3", (12, slice(None, 3), slice(None, 6000))) + assert parse_trace_name("b$1,0:3:1") == ("b", (1, slice(0, 3, 1))) + assert parse_trace_name("plain_trace") == ("plain_trace", None) + with pytest.raises(ValueError): + parse_trace_name("b$1,x") + + +def test_seisbench_format_with_trace_blocks(tmp_path): + blocks, _ = _seisbench_chunk(tmp_path) + bundle = load_dataset("seisbench_waveforms", path=str(tmp_path)).load() + assert bundle.metadata["component_order"] == "ZNE" + assert bundle.metadata["sampling_rate"] == 100.0 + assert bundle.metadata["synthetic"] is False + train, val, test = (bundle.get_split(name) for name in ("train", "val", "test")) + assert [len(train.inputs), len(val.inputs), len(test.inputs)] == [2, 1, 2] # "dev" -> val + torch.testing.assert_close(train.inputs[0], torch.from_numpy(blocks["bucket0"][0]).float()) + torch.testing.assert_close(train.inputs[1], torch.from_numpy(blocks["bucket1"][0, :, :600]).float()) + assert train.targets.tolist() == [[100.0, 300.0], [103.0, 303.0]] + assert test.targets[1].isnan().all() # noise trace + assert test.metadata["trace_names"] == ["bucket0$2,:3,:600", "bucket1$1,:3,:600"] + + +def test_chunks_window_category_and_limits(tmp_path): + _seisbench_chunk(tmp_path, "a") + _seisbench_chunk(tmp_path, "b", offset=10.0) + (tmp_path / "chunks").write_text("a\nb\n", encoding="utf-8") + bundle = load_dataset("seisbench_waveforms", path=str(tmp_path), window_samples=250, window_start=200).load() + test = bundle.get_split("test") + assert test.inputs.shape == (4, 3, 250) + assert test.targets[0, 0].isnan() and test.targets[0, 1].item() == 102.0 # P before the window + one = load_dataset("seisbench_waveforms", path=str(tmp_path), trace_category="noise").load() + assert len(one.get_split("test").inputs) == 2 and len(one.get_split("train").inputs) == 0 + micro = load_dataset("seisbench_waveforms", path=str(tmp_path), max_traces=1).load() + assert [len(micro.get_split(s).inputs) for s in ("train", "val", "test")] == [1, 1, 1] + padded = load_dataset("seisbench_waveforms", path=str(tmp_path), window_samples=700).load() + assert padded.get_split("train").inputs[0, :, 600:].abs().sum() == 0 + + +def test_unblocked_traces_without_data_format_need_component_order(tmp_path): + rng = np.random.default_rng(1) + rows = [] + with h5py.File(tmp_path / "waveforms.hdf5", "w") as handle: + for k in range(3): + name = f"IV.ABC..HH.{k}" + handle.create_dataset(f"data/{name}", data=rng.standard_normal((3, 1200)).astype("float32")) + rows.append({"trace_name": name, "trace_dt_s": "0.01", "trace_P_arrival_sample": "150", + "trace_S_arrival_sample": "450.0", "split": "test"}) + _write_csv(tmp_path / "metadata.csv", rows) + with pytest.raises(ValueError, match="component_order"): + load_dataset("seisbench_waveforms", path=str(tmp_path)).load() + bundle = load_dataset("seisbench_waveforms", path=str(tmp_path), preset="instance").load() # INSTANCE: E, N, Z + assert bundle.metadata["component_order"] == "ENZ" + assert bundle.get_split("test").targets.tolist() == [[150.0, 450.0]] * 3 + + +def test_stead_layout_and_test_split(tmp_path): + rng = np.random.default_rng(2) + names = ["AB.STA1_20190101000000_EV", "AB.STA2_20190101000000_EV", "AB.STA3_201901010000_NO"] + rows = [] + arrays = {} + with h5py.File(tmp_path / "merged.hdf5", "w") as handle: + for k, name in enumerate(names): + arrays[name] = rng.standard_normal((6000, 3)).astype("float32") # (samples, E/N/Z) + dataset = handle.create_dataset(f"data/{name}", data=arrays[name]) + noise = name.endswith("_NO") + dataset.attrs["p_arrival_sample"] = "None" if noise else 500.0 + k + rows.append({"network_code": "AB", "p_arrival_sample": "" if noise else str(500.0 + k), + "s_arrival_sample": "" if noise else str(900.0 + k), + "trace_category": "noise" if noise else "earthquake_local", "trace_name": name}) + _write_csv(tmp_path / "merged.csv", rows) + np.save(tmp_path / "test.npy", np.array(names[1:])) + bundle = load_dataset("seisbench_waveforms", path=str(tmp_path), preset="stead", test_trace_names=str(tmp_path / "test.npy")).load() + assert bundle.metadata["component_order"] == "ENZ" and bundle.metadata["layout"] == "stead" + train, test = bundle.get_split("train"), bundle.get_split("test") + torch.testing.assert_close(train.inputs[0], torch.from_numpy(arrays[names[0]].T)) + assert train.targets.tolist() == [[500.0, 900.0]] + assert test.targets[0].tolist() == [501.0, 901.0] and test.targets[1].isnan().all() + everything = load_dataset("seisbench_waveforms", path=str(tmp_path), layout="stead").load() + assert len(everything.get_split("test").inputs) == 3 + + +def test_reader_errors(tmp_path): + with pytest.raises(ValueError, match="path="): + load_dataset("seisbench_waveforms").load() + with pytest.raises(FileNotFoundError): + load_dataset("seisbench_waveforms", path=str(tmp_path / "missing")).load() + with pytest.raises(FileNotFoundError): + load_dataset("seisbench_waveforms", path=str(tmp_path)).load() + with pytest.raises(ValueError, match="preset"): + load_dataset("seisbench_waveforms", path=str(tmp_path), preset="nope").load() + _seisbench_chunk(tmp_path) + with pytest.raises(ValueError, match="window_samples"): + rows_mixed = tmp_path / "metadata.csv" + text = rows_mixed.read_text(encoding="utf-8").replace("bucket1$0,:3,:600", "bucket1$0,:3,:620") + rows_mixed.write_text(text, encoding="utf-8") + load_dataset("seisbench_waveforms", path=str(tmp_path)).load() + + +def test_synthetic_picking_windows_are_labelled_and_deterministic(): + first = load_dataset("earthquake_waveforms_synthetic", micro=True).load() + second = load_dataset("earthquake_waveforms_synthetic", micro=True).load() + torch.testing.assert_close(first.get_split("train").inputs, second.get_split("train").inputs) + test = first.get_split("test") + assert test.inputs.shape == (4, 3, 6000) + assert first.metadata["synthetic"] is True and first.metadata["component_order"] == "ZNE" + events = ~test.targets.isnan().any(dim=1) + assert events.any() and (~events).any() + assert bool((test.targets[events, 1] > test.targets[events, 0]).all()) + short = load_dataset("earthquake_waveforms_synthetic", samples=6, length=512).load() + arrivals = short.get_split("train").targets + finite = arrivals[~arrivals.isnan()] + assert finite.max() < 512 and not math.isnan(float(finite.min())) diff --git a/tests/test_swin_unet.py b/tests/test_swin_unet.py new file mode 100644 index 00000000..b30ea467 --- /dev/null +++ b/tests/test_swin_unet.py @@ -0,0 +1,95 @@ +"""Swin-Unet: configurations, shapes, input validation and the Swin-T initialisation mapping. + +Numerical equivalence with the official Swin-Unet lives in tests/oracle/test_swin_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.swin_unet import SwinUnet + +SMALL = dict(img_size=64, window_size=4) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "in_channels, out_channels, history, expected", + [ + (40, 1, 1, 27_224_964), # WSTS+ "All" features, 1 day (paper: 27.2M) + (3, 9, 1, 27_168_900), # official Synapse configuration + (40, 1, 5, 27_470_724), # WSTS+ 5-day data-level fusion (200 input channels) + ], +) +def test_swin_unet_parameter_counts(in_channels, out_channels, history, expected): + model = build_model( + "swin_unet", task="segmentation", in_channels=in_channels, out_channels=out_channels, history=history + ) + assert _n_params(model) == expected + + +def test_swin_unet_forward_shapes_and_time_flattening(): + model = build_model("swin_unet", task="segmentation", in_channels=3, history=2, **SMALL).eval() + x = torch.randn(2, 2, 3, 64, 64) + with torch.no_grad(): + out = model(x) + torch.testing.assert_close(out, model(x.flatten(1, 2))) + assert out.shape == (2, 1, 64, 64) + + +def test_swin_unet_default_input_size_is_224(): + model = build_model("swin_unet", task="segmentation", in_channels=7).eval() + with torch.no_grad(): + assert model(torch.randn(1, 7, 224, 224)).shape == (1, 1, 224, 224) + + +@pytest.mark.parametrize("shape", [(2, 4, 64, 64), (2, 3, 32, 32), (3, 64, 64), (2, 3, 3, 3, 64, 64)]) +def test_swin_unet_bad_input_shapes_raise(shape): + model = build_model("swin_unet", task="segmentation", in_channels=3, **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +def test_swin_unet_rejects_incompatible_geometry_and_task(): + with pytest.raises(ValueError): + build_model("swin_unet", task="segmentation", in_channels=3, img_size=100) + with pytest.raises(ValueError): + build_model("swin_unet", task="segmentation", in_channels=3, img_size=112) # odd 7x7 grid at stage 2 + with pytest.raises(ValueError): + build_model("swin_unet", task="regression", in_channels=3) + + +def test_swin_unet_decoder_mirrors_encoder_depths(): + model = SwinUnet(in_chans=3, depths=(2, 2, 6, 2)) + assert [len(layer.blocks) for layer in model.layers] == [2, 2, 6, 2] + assert [len(layer.blocks) for layer in list(model.layers_up)[1:]] == [6, 2, 2] + + +def test_swin_pretrained_mapping_fills_encoder_and_mirrored_decoder(): + torch.manual_seed(0) + donor = SwinUnet(in_chans=3, **SMALL) + swin_state = { + key: torch.randn_like(value) if value.is_floating_point() else value + for key, value in donor.state_dict().items() + if key.startswith(("patch_embed.", "layers.", "norm.")) + } + swin_state["head.weight"] = torch.randn(1000, 768) # classifier of the Swin checkpoint, ignored + + model = SwinUnet(in_chans=5, **SMALL) # 5-channel stem: shape differs, keeps its random init + stem_before = model.patch_embed.proj.weight.detach().clone() + model.load_swin_pretrained({"model": swin_state}) + state = model.state_dict() + + assert torch.equal(state["patch_embed.proj.weight"], stem_before) + assert torch.equal(state["patch_embed.norm.weight"], swin_state["patch_embed.norm.weight"]) + for stage in range(4): + encoder_key = f"layers.{stage}.blocks.0.mlp.fc1.weight" + assert torch.equal(state[encoder_key], swin_state[encoder_key]) + if stage < 3: # decoder step 3 - stage holds the mirrored blocks; step 0 has none + assert torch.equal(state[f"layers_up.{3 - stage}.blocks.0.mlp.fc1.weight"], swin_state[encoder_key]) + assert torch.equal(state["norm.weight"], swin_state["norm.weight"]) diff --git a/tests/test_swin_unetr.py b/tests/test_swin_unetr.py new file mode 100644 index 00000000..a1cc342a --- /dev/null +++ b/tests/test_swin_unetr.py @@ -0,0 +1,133 @@ +"""SwinUNETR: configurations, shapes, TS-SatFire's merging plan and input validation. + +Numerical equivalence with MONAI and TS-SatFire lives in tests/oracle/test_swin_unetr_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.swin_unetr import AdaptivePatchMerging, PatchMerging, PatchMergingV2, SwinUNETR, TemporalSwinUNETR + +SMALL = dict(feature_size=12, num_heads=3) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_ts_satfire_parameter_counts(): + with torch.device("meta"): + # SwinUNETR-3D prediction model (43 channels, 6 days, feature size 36, 3 heads): Table 3's 33.2M. + assert _n_params(build_model("swin_unetr", task="segmentation", in_channels=43)) == 33_191_942 + # SwinUNETR-2D (stock MONAI, feature size 48, 8 channels): Table 3's 25.2M. + assert _n_params(build_model("swin_unetr", task="segmentation", in_channels=8, spatial_dims=2)) == 25_151_996 + + +@pytest.mark.parametrize( + "history, scales", + [ + (6, [(2, 2, 2), (1, 2, 2), (1, 2, 2), (1, 2, 2)]), + (4, [(2, 2, 2), (2, 2, 2), (1, 2, 2), (1, 2, 2)]), + (2, [(2, 2, 2), (1, 2, 2), (1, 2, 2), (1, 2, 2)]), + (3, [(1, 2, 2), (1, 2, 2), (1, 2, 2), (1, 2, 2)]), + ], +) +def test_ts_satfire_merging_plan(history, scales): + model = build_model("swin_unetr", task="segmentation", in_channels=4, history=history, image_size=32, **SMALL) + assert isinstance(model, TemporalSwinUNETR) + assert model.swinViT.stage_scales == scales + assert model.window_size == (history, 4, 4) + assert model.patch_size == (1, 2, 2) + x = torch.randn(1, history, 4, 32, 32) + model.eval() + with torch.no_grad(): + assert model(x).shape == (1, 2, 32, 32) + model.time_reduction = "none" + assert model(x).shape == (1, 2, history, 32, 32) + + +def test_patch_merging_orders(): + x = torch.arange(8.0).reshape(1, 2, 2, 2, 1) # value = 4 d + 2 h + w + with torch.no_grad(): + for module, expected in ( + (PatchMergingV2(dim=1), [0, 1, 2, 3, 4, 5, 6, 7]), + (PatchMerging(dim=1), [0, 4, 2, 1, 5, 2, 1, 7]), # MONAI's v0.9.0 order, with repeats + (AdaptivePatchMerging(dim=1, merge=(True, True, True)), [0, 4, 2, 1, 6, 5, 3, 7]), + (AdaptivePatchMerging(dim=1, merge=(False, True, True)), [[0, 2, 1, 3], [4, 6, 5, 7]]), + ): + module.norm = torch.nn.Identity() + module.reduction = torch.nn.Identity() + assert module(x).flatten().tolist() == torch.tensor(expected, dtype=torch.float32).flatten().tolist() + + +def test_ts_satfire_naming_and_attention_versions(): + model = build_model("swin_unetr", task="segmentation", in_channels=4, history=2, image_size=32, **SMALL) + names = list(model.state_dict()) + assert names[-2:] == ["out.0.conv.conv.weight", "out.0.conv.conv.bias"] # TS-SatFire wraps the output block + assert "swinViT.layers1.0.blocks.0.attn.relative_position_bias_table" in names + assert "swinViT.layers1.0.downsample.norm.weight" in names + v2 = build_model("swin_unetr", task="segmentation", in_channels=4, history=2, image_size=32, attn_version="v2", **SMALL) + assert "swinViT.layers1.0.blocks.0.attn.cpb_mlp.0.weight" in v2.state_dict() + model_2d = build_model("swin_unetr", task="segmentation", in_channels=4, spatial_dims=2, image_size=32, feature_size=12) + assert list(model_2d.state_dict())[-2:] == ["out.conv.conv.weight", "out.conv.conv.bias"] + + +def test_monai_2d_forward_shape(): + model = build_model("swin_unetr", task="segmentation", in_channels=3, spatial_dims=2, image_size=64, feature_size=12).eval() + with torch.no_grad(): + assert model(torch.randn(2, 3, 64, 32)).shape == (2, 2, 64, 32) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 4, 32, 32), # missing time axis + (2, 2, 5, 32, 32), # wrong channel count + (2, 2, 4, 30, 32), # not divisible by the patch / merges + (2, 3, 4, 32, 32), # 3 days do not fit the merging plan built for 2 + ], +) +def test_bad_input_shapes_raise(shape): + model = build_model("swin_unetr", task="segmentation", in_channels=4, history=2, image_size=32, **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(downsample="patchmerging"), + dict(attn_version="ar"), # TS-SatFire's autoregressive attention is not ported + dict(feature_size=16), # MONAI's feature_size % 12 check + dict(num_heads=(5, 5, 5, 5)), + dict(depths=(2, 2, 2)), + dict(img_size=(30, 32)), + dict(norm_name="group"), + dict(drop_rate=2.0), + dict(downsample="ts_satfire"), # 3D only + ], +) +def test_bad_configurations_raise(kwargs): + config = dict(img_size=(32, 32), in_channels=3, out_channels=1, feature_size=12, spatial_dims=2) + config.update(kwargs) + with pytest.raises(ValueError): + SwinUNETR(**config) + + +def test_ts_satfire_configuration_errors(): + with pytest.raises(ValueError): # the merging plan needs img_size + SwinUNETR(None, 3, 2, feature_size=12, downsample="ts_satfire", patch_size=(1, 2, 2)) + with pytest.raises(ValueError): # TS-SatFire's img_size check: 48 is not divisible by 2**5 + SwinUNETR((2, 48, 32), 3, 2, feature_size=12, downsample="ts_satfire", patch_size=(1, 2, 2)) + with pytest.raises(ValueError): # Swin-V2 attention divides by window - 1 + SwinUNETR((2, 32, 32), 3, 2, feature_size=12, downsample="ts_satfire", patch_size=(1, 2, 2), window_size=(1, 4, 4), attn_version="v2") + + +def test_builder_validates_task_and_dims(): + with pytest.raises(ValueError): + build_model("swin_unetr", task="classification", in_channels=4) + with pytest.raises(ValueError): + build_model("swin_unetr", task="segmentation", in_channels=4, spatial_dims=1) diff --git a/tests/test_swinlstm.py b/tests/test_swinlstm.py new file mode 100644 index 00000000..0ae46f46 --- /dev/null +++ b/tests/test_swinlstm.py @@ -0,0 +1,120 @@ +"""SwinLSTM without the reference code: sizes, shapes, rollout semantics and input validation. + +The comparison with the official implementation and weights is in tests/oracle/test_swinlstm_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.swinlstm import SwinLSTM, SwinLSTMSegmenter + +SMALL = dict(img_size=16, embed_dim=16, depths_downsample=[2, 2], depths_upsample=[2, 2], num_heads=[2, 4], window_size=2) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_official_configurations(): + deep = build_model("swinlstm", task="forecasting") # Moving-MNIST SwinLSTM-D (official weights) + assert _n_params(deep) == 20_191_969 + assert len(deep.state_dict()) == 286 + assert [len(cell.Swin.layers) for cell in deep.Downsample.layers] == [2, 6] + # Upsample indexes depths_upsample=(6, 2) from the deepest level: 2 blocks at 8x8, then 6 at 16x16. + assert [len(cell.Swin.layers) for cell in deep.Upsample.layers] == [2, 6] + assert [cell.Swin.layers[0].input_resolution for cell in deep.Upsample.layers] == [(8, 8), (16, 16)] + base = build_model("swinlstm", task="forecasting", variant="b") + assert _n_params(base) == 2_778_417 + assert sorted({k.split(".")[0] for k in base.state_dict()}) == ["ST"] + + +def test_stochastic_depth_rates_follow_the_reference(): + deep = build_model("swinlstm", task="forecasting") + rates = lambda cell: [getattr(b.drop_path, "drop_prob", 0.0) for b in cell.Swin.layers] # noqa: E731 + down = [rates(cell) for cell in deep.Downsample.layers] + assert down[0][0] == 0.0 and down[1][-1] == pytest.approx(0.1) + # Decoder cells use their level's slice of the schedule in reverse order (flag=0 in the reference). + up = [rates(cell) for cell in deep.Upsample.layers] + assert up[0] == sorted(up[0], reverse=True) and up[1][-1] == 0.0 + base = build_model("swinlstm", task="forecasting", variant="b") + assert {rate for rate in rates(base.ST.layers[0])} == {0.1} + + +@pytest.mark.parametrize("variant", ["d", "b"]) +def test_forecasting_shapes_and_rollout(variant): + kwargs = dict(SMALL, depths=[2]) if variant == "b" else SMALL + model = build_model("swinlstm", task="forecasting", variant=variant, in_channels=2, num_output_frames=3, **kwargs).eval() + x = torch.rand(2, 4, 2, 16, 16) + with torch.no_grad(): + future = model(x) + everything = model(x, include_warmup=True) + assert future.shape == (2, 3, 2, 16, 16) + assert everything.shape == (2, 6, 2, 16, 16) + torch.testing.assert_close(everything[:, 3:], future) + assert ((future > 0) & (future < 1)).all() # sigmoid output + # The first prediction only depends on the input frames. + torch.testing.assert_close(model(x, num_output_frames=1), future[:, :1]) + # step() is the reference single-step forward. + states = () + for t in range(4): + output, *states = model.step(x[:, t], *states) + torch.testing.assert_close(output, future[:, 0]) + + +def test_segmentation_is_the_one_step_rollout_before_the_sigmoid(): + forecaster = build_model("swinlstm", task="forecasting", in_channels=1, **SMALL).eval() + segmenter = build_model("swinlstm", task="segmentation", in_channels=1, **SMALL).eval() + assert isinstance(segmenter, SwinLSTMSegmenter) + segmenter.load_state_dict(forecaster.state_dict(), strict=True) # same keys, no prefix + x = torch.rand(2, 3, 1, 16, 16) + with torch.no_grad(): + torch.testing.assert_close(torch.sigmoid(segmenter(x)), forecaster(x, num_output_frames=1)[:, 0]) + + +def test_segmentation_with_many_input_channels(): + model = build_model("swinlstm", task="segmentation", in_channels=7, **SMALL) + assert model.Upsample.Unembed.Conv.out_channels == 1 + assert model.Upsample.patch_embed.proj.in_channels == 7 + logits = model(torch.randn(2, 3, 7, 16, 16)) + assert logits.shape == (2, 1, 16, 16) + logits.mean().backward() + + +def test_input_validation(): + model = build_model("swinlstm", task="forecasting", in_channels=2, **SMALL) + with pytest.raises(ValueError, match="shape"): + model(torch.rand(2, 2, 16, 16)) + with pytest.raises(ValueError, match="frames of shape"): + model(torch.rand(2, 3, 1, 16, 16)) + with pytest.raises(ValueError, match="frames of shape"): + model(torch.rand(2, 3, 2, 32, 32)) + with pytest.raises(ValueError, match="num_output_frames"): + model(torch.rand(2, 3, 2, 16, 16), num_output_frames=0) + with pytest.raises(ValueError, match="out_chans == in_chans"): + SwinLSTM(in_chans=2, out_chans=1, **SMALL)(torch.rand(1, 2, 2, 16, 16), num_output_frames=2) + with pytest.raises(ValueError, match="state arguments"): + model.step(torch.rand(1, 2, 16, 16), None) + + +@pytest.mark.parametrize( + "kwargs, message", + [ + (dict(patch_size=4), "patch_size must be 2"), + (dict(img_size=18), "cannot be halved"), + (dict(img_size=24, window_size=4), "not divisible by window size"), + (dict(variant="c"), "variant"), + (dict(depths_upsample=[2]), "equal length"), + (dict(num_heads=[2]), "num_heads"), + ], +) +def test_configuration_validation(kwargs, message): + with pytest.raises(ValueError, match=message): + build_model("swinlstm", task="forecasting", **{**SMALL, **kwargs}) + + +def test_unknown_task(): + with pytest.raises(ValueError, match="forecasting"): + build_model("swinlstm", task="classification") diff --git a/tests/test_tc_benchmarks.py b/tests/test_tc_benchmarks.py index 76bce908..938acdb2 100644 --- a/tests/test_tc_benchmarks.py +++ b/tests/test_tc_benchmarks.py @@ -1,13 +1,146 @@ +import math + +import pytest +import torch + +from pyhazards.benchmarks.tc import ( + great_circle_distance_km, + intensity_metrics, + tcn_equirectangular_distance_km, + track_intensity_metrics, +) from pyhazards.configs import load_experiment_config +from pyhazards.datasets.base import DataBundle, DataSplit, FeatureSpec, LabelSpec from pyhazards.engine.runner import BenchmarkRunner +TC_CONFIGS = [ + "hurricast_smoke", + "tropicalcyclone_mlp_smoke", + "tropicyclonenet_smoke", + "saf_net_smoke", + "tcif_fusion_smoke", +] -def test_tc_vertical_slice(tmp_path): - config = load_experiment_config("pyhazards/configs/tc/hurricast_smoke.yaml") - summary = BenchmarkRunner().run(config, output_dir=str(tmp_path)) +def test_great_circle_distance_in_km(): + one_degree = 2 * math.pi * 6371.0 / 360 + assert float(great_circle_distance_km(10.0, 120.0, 11.0, 120.0)) == pytest.approx(one_degree, rel=1e-9) + # Across the dateline, with either longitude convention. + assert float(great_circle_distance_km(0.0, 179.5, 0.0, -179.5)) == pytest.approx(one_degree, rel=1e-9) + assert float(great_circle_distance_km(0.0, 179.5, 0.0, 180.5)) == pytest.approx(one_degree, rel=1e-9) + # A degree of longitude shrinks with the cosine of latitude. + assert float(great_circle_distance_km(60.0, 0.0, 60.0, 1.0)) == pytest.approx(one_degree * 0.5, rel=1e-3) + # TropiCycloneNet's formula: 111 km per degree, longitude scaled by cos(observed latitude). + assert float(tcn_equirectangular_distance_km(11.0, 120.0, 10.0, 120.0)) == pytest.approx(111.0) + assert float(tcn_equirectangular_distance_km(60.0, 1.0, 60.0, 0.0)) == pytest.approx(55.5) + + +def test_best_of_k_is_per_lead_and_per_variable(): + target = {"lat": torch.zeros(1, 2, dtype=torch.float64), "lon": torch.zeros(1, 2, dtype=torch.float64), "wind": torch.full((1, 2), 50.0, dtype=torch.float64)} + # Sample 0 has the better track, sample 1 the better wind. + forecast = { + "lat": torch.tensor([[[0.1, 0.2], [1.0, 2.0]]], dtype=torch.float64), + "lon": torch.zeros(1, 2, 2, dtype=torch.float64), + "wind": torch.tensor([[[40.0, 30.0], [49.0, 52.0]]], dtype=torch.float64), + } + metrics = track_intensity_metrics(forecast, target, [12, 24]) + km = 2 * math.pi * 6371.0 / 360 + assert metrics["best_of_k_track_error_km_12h"] == pytest.approx(0.1 * km, rel=1e-6) + assert metrics["best_of_k_track_error_km_24h"] == pytest.approx(0.2 * km, rel=1e-6) + assert metrics["best_of_k_intensity_mae_12h"] == pytest.approx(1.0) + assert metrics["best_of_k_intensity_mae_24h"] == pytest.approx(2.0) + # Deterministic metrics score the sample mean. + assert metrics["intensity_mae_12h"] == pytest.approx(5.5) + assert metrics["track_error_km_24h"] == pytest.approx(1.1 * km, rel=1e-3) + assert metrics["num_samples"] == 2 + + +def test_nan_targets_are_skipped(): + target = {"lat": torch.tensor([[0.0], [float("nan")]]), "lon": torch.zeros(2, 1), "pres": torch.tensor([[1000.0], [990.0]])} + forecast = {"lat": torch.tensor([[1.0], [5.0]]), "lon": torch.zeros(2, 1), "pres": torch.tensor([[1002.0], [995.0]])} + metrics = track_intensity_metrics(forecast, target, [24]) + assert metrics["track_error_km_24h"] == pytest.approx(2 * math.pi * 6371.0 / 360, rel=1e-6) + assert metrics["pressure_mae"] == pytest.approx(3.5) + + +def test_intensity_metrics_and_yearly_groups(): + metrics = intensity_metrics(torch.tensor([1.0, 2.0, 3.0, 10.0]), torch.tensor([0.0, 0.0, 0.0, 0.0]), [24], [2015, 2015, 2016, 2016]) + assert metrics["intensity_mae"] == pytest.approx(4.0) + assert metrics["intensity_mae_24h"] == pytest.approx(4.0) + assert metrics["intensity_mae_2015"] == pytest.approx(1.5) + assert metrics["intensity_mae_2016"] == pytest.approx(6.5) + assert metrics["intensity_mae_group_mean"] == pytest.approx(4.0) + assert metrics["intensity_rmse"] == pytest.approx(math.sqrt((1 + 4 + 9 + 100) / 4)) + + +class _Constant(torch.nn.Module): + def __init__(self, value): + super().__init__() + self.value = value + + def forward(self, x): + return torch.full((x.size(0), 1), self.value) + + +def test_prediction_transform_maps_scaled_outputs_to_units(tmp_path): + config = load_experiment_config("pyhazards/configs/tc/saf_net_smoke.yaml") + split = DataSplit(torch.zeros(3, 4), torch.tensor([20.0, 30.0, 40.0]), metadata={"groups": [2018] * 3}) + bundle = DataBundle( + splits={"test": split}, + feature_spec=FeatureSpec(), + label_spec=LabelSpec(), + metadata={"lead_hours": [24], "units": {"wind": "m/s"}, "prediction_transform": {"kind": "minmax", "min": 10.0, "max": 70.0}}, + ) + summary = BenchmarkRunner().run(config, model=_Constant(0.5), data=bundle, output_dir=str(tmp_path)) + assert summary.metrics["intensity_mae"] == pytest.approx(abs(40 - 20) / 3 + abs(40 - 30) / 3 + 0.0) + assert summary.metadata["units"]["intensity_mae"] == "m/s" + + +@pytest.mark.parametrize("name", TC_CONFIGS) +def test_tc_smoke_configs(name, tmp_path): + config = load_experiment_config(f"pyhazards/configs/tc/{name}.yaml") + summary = BenchmarkRunner().run(config, output_dir=str(tmp_path)) assert summary.benchmark_name == "tc" - assert summary.hazard_task == "tc.track_intensity" - assert "track_error" in summary.metrics - assert "intensity_mae" in summary.metrics - assert summary.metadata["source_dataset"] == "ibtracs_tracks" + for metric in config.benchmark.metrics: + assert metric in summary.metrics, metric + assert summary.metadata["synthetic"] is True + if config.benchmark.hazard_task == "tc.track_intensity": + assert summary.metadata["units"]["track_error_km"] == "km" + assert summary.metadata["lead_hours"] + + +class _Persistence(torch.nn.Module): + """Deterministic stand-in with a forecast() method: keeps the last observed TCND state.""" + + def forecast(self, batch): + last = batch["obs_traj"][-1] # (B, 4) normalised; time-first input + steps = torch.ones(1, 4) + return { + "lon": (last[:, 0:1] * 5 + 180) * steps, + "lat": (last[:, 1:2] * 5) * steps, + "pres": (last[:, 2:3] * 50 + 960) * steps, + "wind": (last[:, 3:4] * 25 + 40) * steps, + } + + +def test_batched_scoring_matches_one_pass(tmp_path): + from pyhazards.datasets import load_dataset + from pyhazards.models import build_model + + config = load_experiment_config("pyhazards/configs/tc/saf_net_smoke.yaml") + data = load_dataset("safnet_cma_era_interim_synthetic", samples=20).load() + torch.manual_seed(0) + model = build_model("saf_net", task="regression") + whole = BenchmarkRunner().run(config, model=model, data=data, output_dir=str(tmp_path)) + config.benchmark.params = {"batch_size": 2} + chunked = BenchmarkRunner().run(config, model=model, data=data, output_dir=str(tmp_path)) + assert whole.metrics == pytest.approx(chunked.metrics) + + # Time-first TCND inputs are sliced along their batch axis (metadata["batch_dims"]). + config = load_experiment_config("pyhazards/configs/tc/tropicyclonenet_smoke.yaml") + data = load_dataset("tropicyclonenet_dataset_synthetic", samples=30).load() + whole = BenchmarkRunner().run(config, model=_Persistence(), data=data, output_dir=str(tmp_path)) + config.benchmark.params = {"batch_size": 2} + chunked = BenchmarkRunner().run(config, model=_Persistence(), data=data, output_dir=str(tmp_path)) + assert whole.metrics == pytest.approx(chunked.metrics) + assert whole.metrics["track_error_km_24h"] > 0 diff --git a/tests/test_tc_datasets.py b/tests/test_tc_datasets.py new file mode 100644 index 00000000..a4c1a47b --- /dev/null +++ b/tests/test_tc_datasets.py @@ -0,0 +1,270 @@ +import csv +from pathlib import Path + +import numpy as np +import pytest +import torch + +from pyhazards.datasets import available_datasets, load_dataset +from pyhazards.datasets.tc import build_track_samples, read_ibtracs, read_tcnd_track +from pyhazards.datasets.tc.tcnd import GPH_RANGE, gph_to_image +from pyhazards.models.tropicalcyclone_mlp import SHIPS_PREDICTORS + +FIXTURES = Path(__file__).resolve().parent / "fixtures" +IBTRACS_CSV = FIXTURES / "ibtracs" / "ibtracs.fixture.list.v04r01.csv" +IBTRACS_NC = FIXTURES / "ibtracs" / "IBTrACS.fixture.v04r01.nc" +SHIPS_CSV = FIXTURES / "ships_xu2021" / "train_global_fill_REA_na_wo_img_scaled.fixture.csv" +ERA5_NC = FIXTURES / "era5" / "era5.pressure_levels.ophelia_2023092200_2023092300.fixture.nc" +TCND = FIXTURES / "tcnd" + + +def _raw_rows(sid): + with IBTRACS_CSV.open(newline="") as handle: + rows = list(csv.DictReader(handle)) + return [row for row in rows[1:] if row["SID"] == sid] # rows[0] is the units row + + +def test_ibtracs_csv_layout_is_parsed(): + table = read_ibtracs(IBTRACS_CSV) + assert set(table["SID"]) == {"2023265N29284", "2026058S18168", "2023266N16116", "2025214N26167"} + assert set(table["BASIN"]) == {"NA", "WP", "SP"} # "NA" (North Atlantic) is not a missing value + assert table["LAT"].dtype.kind == "f" and table["USA_WIND"].dtype.kind == "f" + assert table["ISO_TIME"].dtype.kind == "M" + assert table.loc[table["NAME"] == "OPHELIA", "SEASON"].iloc[0] == 2023 + urmil = table[table["SID"] == "2026058S18168"] + assert urmil["LON"].max() > 180 # merged positions stay continuous across the dateline + assert urmil["USA_LON"].max() < 180 and urmil["USA_LON"].min() < 0 # agency positions wrap + assert np.isnan(table["WMO_WIND"]).any() # blanks (" ") are missing values + assert "US-PROVISIONAL_spur" in set(table["TRACK_TYPE"]) + + +def test_ibtracs_netcdf_matches_csv(): + csv_table = read_ibtracs(IBTRACS_CSV) + nc_table = read_ibtracs(IBTRACS_NC) + assert len(nc_table) == len(csv_table) + for column in ("SID", "BASIN", "NAME", "NATURE", "TRACK_TYPE", "WMO_AGENCY", "USA_AGENCY"): + assert list(nc_table[column]) == list(csv_table[column]), column + assert (nc_table["ISO_TIME"].values == csv_table["ISO_TIME"].values).all() + for column in ("LAT", "LON", "WMO_WIND", "WMO_PRES", "USA_WIND", "USA_PRES", "USA_LON", "CMA_WIND", "TOKYO_PRES", "DIST2LAND", "STORM_SPEED"): + np.testing.assert_allclose(nc_table[column].to_numpy(float), csv_table[column].to_numpy(float), atol=1e-4, equal_nan=True, err_msg=column) + + +def test_track_windows_follow_the_raw_rows(): + table = read_ibtracs(IBTRACS_CSV) + x, y, meta = build_track_samples(table, variables=("lat", "lon", "wind", "pres"), history=4, lead_hours=(6, 12, 18, 24)) + assert x.shape[1:] == (4, 4) and y.shape[1:] == (4, 4) + assert "2025214N26167" not in meta["sid"] # spur tracks are skipped by default + # First OPHELIA window, recomputed from the raw CSV rows at synoptic hours. + rows = [r for r in _raw_rows("2023265N29284") if r["ISO_TIME"][11:13] in {"00", "06", "12", "18"}] + values = [[float(r[c]) if r[c].strip() else np.nan for c in ("LAT", "LON", "USA_WIND", "USA_PRES")] for r in rows] + first = next(i for i in range(3, len(values) - 4) if not np.isnan(values[i - 3 : i + 5]).any()) + k = meta["sid"].index("2023265N29284") + np.testing.assert_allclose(x[k], values[first - 3 : first + 1], rtol=1e-6) + np.testing.assert_allclose(y[k], values[first + 1 : first + 5], rtol=1e-6) + assert meta["iso_time"][k] == rows[first]["ISO_TIME"].replace(" ", "T") + + # Agency positions are unwrapped inside a window, like the merged ones. + x_usa, y_usa, meta_usa = build_track_samples(table, variables=("lat", "lon", "wind"), positions="agency", history=2, lead_hours=(24,)) + urmil = [i for i, sid in enumerate(meta_usa["sid"]) if sid == "2026058S18168"] + lons = np.concatenate([x_usa[urmil][..., 1], y_usa[urmil][..., 1]], axis=1) + assert np.abs(np.diff(lons, axis=1)).max() < 90 # no 360-degree jump at the dateline + assert lons.max() > 180 and table.loc[table["SID"] == "2026058S18168", "USA_LON"].min() < -170 + with pytest.raises(ValueError, match="multiples of 6"): + build_track_samples(table, lead_hours=(3,)) + with pytest.raises(ValueError, match="WMO has no position"): + build_track_samples(table, agency="wmo", positions="agency") + + +def test_ibtracs_dataset_bundle(tmp_path): + bundle = load_dataset("ibtracs_tracks", path=str(IBTRACS_NC), variables=["lat", "lon", "wind"], history=2, lead_hours=[12, 24], test_seasons=[2026]).load() + assert bundle.metadata["units"] == {"lat": "degrees_north", "lon": "degrees_east", "wind": "kt"} + assert bundle.metadata["lead_hours"] == [12, 24] and bundle.metadata["synthetic"] is False + test = bundle.splits["test"] + assert set(test.metadata["season"]) == {2026} and test.inputs.shape[1:] == (2, 3) and test.targets.shape[1:] == (2, 3) + assert set(bundle.splits["train"].metadata["season"]) == {2023} + basin = load_dataset("ibtracs_tracks", path=str(IBTRACS_CSV), variables=["lat", "lon"], basins=["NA"]).load() + for split in basin.splits.values(): + assert set(split.metadata["basin"]) <= {"NA"} + with pytest.raises(ValueError, match="needs path"): + load_dataset("ibtracs_tracks") + with pytest.raises(FileNotFoundError, match="download=True"): + load_dataset("ibtracs_tracks", cache_dir=str(tmp_path)) + + +def test_ships_xu2021_loyo_split(): + bundle = load_dataset("ships_xu2021", path=str(SHIPS_CSV), leave_out_year=2018, val_fraction=0.25, seed=0).load() + train, val, test = (bundle.splits[name] for name in ("train", "val", "test")) + assert test.inputs.shape == (3, 121) and set(test.metadata["groups"]) == {2018} + # Training uses reanalysis rows only (AL 2016 and EP 1982), never operational ones. + assert len(train.targets) + len(val.targets) == 5 + assert set(train.metadata["basin"]) | set(val.metadata["basin"]) == {"AL", "EP"} + import pandas as pd + + raw = pd.read_csv(SHIPS_CSV) + expected = raw[(raw.year == 2018) & (raw.type == "opr")] + np.testing.assert_allclose(test.inputs.numpy(), expected[list(SHIPS_PREDICTORS)].to_numpy(np.float32)) + np.testing.assert_allclose(test.targets.numpy(), expected["dvs24"].to_numpy(np.float32)) + assert bundle.metadata["units"] == {"wind": "kt"} and bundle.metadata["hazard_task"] == "tc.intensity" + fold_2011 = load_dataset("ships_xu2021", path=str(SHIPS_CSV), leave_out_year=2011, val_fraction=0.0).load() + assert len(fold_2011.splits["test"].targets) == 2 and len(fold_2011.splits["train"].targets) == 5 + + +def _write_gph(root: Path): + """GPH crops in the official layout (100 x 100 float64 geopotential, m^2 s^-2).""" + rng = np.random.default_rng(0) + _, dates, _ = read_tcnd_track(TCND / "BST_data" / "EP" / "test" / "EP2018BSTCARLOTTA.txt") + storm = root / "EP" / "2018" / "CARLOTTA" + storm.mkdir(parents=True) + for date in dates: + np.save(storm / f"{date}.npy", rng.uniform(55000.0, 59500.0, size=(100, 100))) + return root + + +def test_tcnd_reader(tmp_path): + gph = _write_gph(tmp_path / "ERA5_gph500") + bundle = load_dataset( + "tropicyclonenet_dataset", data1d_dir=str(TCND / "BST_data"), env_dir=str(TCND / "Env_data"), gph_dir=str(gph), areas=["EP"], splits=["test"] + ).load() + test = bundle.splits["test"] + values, dates, names = read_tcnd_track(TCND / "BST_data" / "EP" / "test" / "EP2018BSTCARLOTTA.txt") + assert len(values) == 18 and set(names) == {"CARLOTTA"} + n = 18 - 12 + 1 + assert test.inputs["obs_traj"].shape == (8, n, 4) and test.inputs["image_obs"].shape == (n, 1, 8, 64, 64) + assert test.targets.shape == (n, 4, 4) + torch.testing.assert_close(test.inputs["obs_traj"][:, 0], torch.as_tensor(values[:8, 2:6], dtype=torch.float32)) + assert torch.all(test.inputs["obs_traj_rel"][0] == 0) + # Targets in physical units: lat = 5 * y, lon = 5 * x + 180, pres = 50 * p + 960, wind = 25 * w + 40. + future = values[8:12, 2:6] + expected = np.stack([5 * future[:, 1], 5 * future[:, 0] + 180, 50 * future[:, 2] + 960, 25 * future[:, 3] + 40], axis=-1) + np.testing.assert_allclose(test.targets[0].numpy(), expected, rtol=1e-6) + # Env-Data: the 12/24-hour direction history is -1 at the first steps and filled from later ones. + direction24 = test.inputs["env_data"]["history_direction24"][0] + assert direction24.shape == (8, 8) and torch.all(direction24.sum(dim=-1) == 1) + assert torch.all((test.inputs["image_obs"] >= 0) & (test.inputs["image_obs"] <= 1)) + assert bundle.metadata["units"] == {"wind": "m/s", "pres": "hPa"} + with pytest.raises(FileNotFoundError): + load_dataset("tropicyclonenet_dataset", root=str(tmp_path / "missing")) + + +def test_gph_scaling(): + low, high = GPH_RANGE + image = gph_to_image(np.full((100, 100), (low + high) / 2)) + assert image.shape == (64, 64) and np.allclose(image, 0.5) + assert gph_to_image(np.full((100, 100), high + 1000)).max() == 1.0 + + +def test_synthetic_datasets_are_labelled_synthetic(): + names = [ + "tc_tracks_synthetic", + "ships_xu2021_synthetic", + "safnet_cma_era_interim_synthetic", + "tropicyclonenet_dataset_synthetic", + "hurricast_synthetic", + "tcif_fusion_synthetic", + ] + assert set(names) <= set(available_datasets()) + assert not {"tcbench_alpha", "tropicyclonenet_dataset_alias"} & set(available_datasets()) + for name in names: + bundle = load_dataset(name, micro=True).load() + assert bundle.metadata["synthetic"] is True and bundle.metadata["dataset"] == name + tcnd = load_dataset("tropicyclonenet_dataset_synthetic", micro=True).load().splits["test"] + assert tcnd.inputs["image_obs"].shape[1:] == (1, 8, 64, 64) and tcnd.targets.shape[1:] == (4, 4) + + +def test_hurricast_statistics_and_windows(): + from pyhazards.datasets.tc.hurricast import hurricast_storms, hurricast_windows, wind_category + from pyhazards.models.hurricast import HURRICAST_STAT_FEATURES as NAMES + + table = read_ibtracs(IBTRACS_CSV) + storms = {s["sid"]: s for s in hurricast_storms(table, min_wind=34, min_steps=5)} + assert set(storms) == {"2023265N29284", "2026058S18168"} # the WP storms never reach 34 kt + assert hurricast_storms(table) == [] # the paper's selection needs more than 20 steps of 34 kt + ophelia = storms["2023265N29284"] + times = ophelia["times"].astype("datetime64[m]").astype(str) + assert times[0] == "2023-09-22T00:00" and "2023-09-23T10:15" not in times # first 34 kt; off-grid row dropped + assert np.all(np.diff(ophelia["times"]).astype("timedelta64[h]") == np.timedelta64(3, "h")) + f = ophelia["features"] + assert np.isfinite(f).all() and f.shape == (23, 30) + rows = [r for r in _raw_rows("2023265N29284") if r["ISO_TIME"] >= "2023-09-22 00:00:00" and r["ISO_TIME"][14:16] == "00"] + np.testing.assert_allclose(f[:, NAMES.index("LAT")], [float(r["LAT"]) for r in rows]) + np.testing.assert_allclose(f[1, NAMES.index("WMO_WIND")], (35 + 40) / 2) # interpolated 03 UTC wind + np.testing.assert_allclose(f[1:, NAMES.index("STORM_DISPLACEMENT_X")], np.diff(f[:, NAMES.index("LAT")])) + assert f[0, NAMES.index("STORM_DISPLACEMENT_X")] == 0 + assert np.all(f[:, NAMES.index("cat_basin_AN")] == 1) and f[:, NAMES.index("cat_nature_TS")].sum() > 0 + np.testing.assert_allclose(f[:, NAMES.index("cat_storm_category")], wind_category(f[:, NAMES.index("WMO_WIND")])) + assert list(wind_category([33, 34, 64, 83, 96, 113, 137, np.nan])) == [0, 1, 2, 3, 4, 5, 6, 7] + + windows = hurricast_windows([ophelia, storms["2026058S18168"]], window_size=8, predict_at=8) + assert windows["x_stat"].shape == (8, 8, 30) # URMIL's 7 steps are too short + first = windows["x_stat"][0] + np.testing.assert_allclose(first, f[:8]) + np.testing.assert_allclose(windows["position"][0], f[7, [0, 1]]) + np.testing.assert_allclose(windows["intensity"][0], f[15, NAMES.index("WMO_WIND")]) + np.testing.assert_allclose(windows["displacement"][0], f[15, [0, 1]] - f[7, [0, 1]], atol=1e-9) + # Outside the North Atlantic and Eastern Pacific, 10-minute winds become 1-minute winds (/ 0.93). + urmil = hurricast_windows([storms["2026058S18168"]], window_size=2, predict_at=2) + raw = storms["2026058S18168"]["features"] + np.testing.assert_allclose(urmil["x_stat"][0, :, NAMES.index("WMO_WIND")], raw[:2, NAMES.index("WMO_WIND")] / 0.93) + np.testing.assert_allclose(urmil["intensity"][0], raw[3, NAMES.index("WMO_WIND")] / 0.93) + + +def _ophelia_bundle(**kwargs): + params = dict(path=str(IBTRACS_CSV), era5=str(ERA5_NC), min_steps=5, max_steps=17, train_seasons=[2023], val_seasons=None, test_seasons=None) + params.update(kwargs) + return load_dataset("hurricast_ibtracs_era5", **params).load() + + +def test_hurricast_dataset_reads_era5_maps(): + import netCDF4 + + bundle = _ophelia_bundle(standardize=False) + train = bundle.splits["train"] + assert train.inputs["x_viz"].shape == (2, 8, 9, 25, 25) and train.inputs["x_stat"].shape == (2, 8, 30) + assert train.metadata["iso_time"] == ["2023-09-22T21:00:00", "2023-09-23T00:00:00"] + assert bundle.metadata["map_channels"][:3] == ["u225", "u500", "u700"] and bundle.metadata["hazard_task"] == "tc.intensity" + # First step of the first window: OPHELIA at 29.5N 75.3W, 2023-09-22 00 UTC -> centre 30N 75W. + with netCDF4.Dataset(ERA5_NC) as nc: + lat, lon, levels = nc["latitude"][:], nc["longitude"][:], list(nc["pressure_level"][:]) + rows = [int(np.flatnonzero(lat == value)[0]) for value in range(42, 17, -1)] + cols = [int(np.flatnonzero(lon == value)[0]) for value in range(-87, -62)] + for channel, (var, level) in enumerate((v, l) for v in ("u", "v", "z") for l in (225, 500, 700)): + expected = nc[var][0, levels.index(level)][np.ix_(rows, cols)] + np.testing.assert_array_equal(train.inputs["x_viz"][0, 0, channel].numpy(), expected) + torch.testing.assert_close(train.targets, torch.tensor([35.0, 30.0])) # WMO wind 24 h after 21 and 00 UTC + + standardized = _ophelia_bundle() + stats = standardized.metadata["standardization"] + maps = standardized.splits["train"].inputs["x_viz"] + assert torch.allclose(maps.mean(dim=(0, 1, 3, 4)), torch.zeros(9), atol=1e-4) + assert len(stats["map_mean"]) == 9 and stats["stat_std"][2] != 1.0 + cos_lat = standardized.splits["train"].inputs["x_stat"][..., 10] + assert torch.all((cos_lat > 0.8) & (cos_lat < 0.9)) # cyclic encodings are not standardised + + track = _ophelia_bundle(target="displacement", standardize=False) + t = track.splits["train"] + assert t.targets.shape == (2, 1, 2) and track.metadata["target_variables"] == ["lat", "lon"] + stats_only = _ophelia_bundle(era5=None) + assert "x_viz" not in stats_only.splits["train"].inputs + + +def test_era5_layouts_and_errors(): + import xarray as xr + + from pyhazards.datasets.tc.hurricast import era5_maps, open_era5 + + cds = open_era5(ERA5_NC) + times, lats, lons = [np.datetime64("2023-09-22T06:00")], [30.3], [-75.1] + expected = era5_maps(cds, times, lats, lons) + # NCAR RDA layout: upper-case variables, "level", "time", longitudes 0-360, levels ascending. + with xr.open_dataset(ERA5_NC) as raw: + rda = raw.rename({"u": "U", "v": "V", "z": "Z", "pressure_level": "level", "valid_time": "time"}).sortby("level") + rda = rda.assign_coords(longitude=(rda.longitude % 360)).load() + np.testing.assert_array_equal(era5_maps(rda, times, lats, lons), expected) + with pytest.raises(KeyError, match="lacks the maps"): + era5_maps(cds, [np.datetime64("2023-09-25T00:00")], lats, lons) + with pytest.raises(KeyError, match="lacks the maps"): + era5_maps(cds, times, [10.0], lons) # outside the stored area + with pytest.raises(ValueError, match="no z variable"): + open_era5(cds.drop_vars("z")) + with pytest.raises(ValueError, match="needs path"): + load_dataset("hurricast_ibtracs_era5") diff --git a/tests/test_tc_models.py b/tests/test_tc_models.py index f62e41e5..413c020d 100644 --- a/tests/test_tc_models.py +++ b/tests/test_tc_models.py @@ -1,48 +1,146 @@ +import hashlib + +import pytest import torch -from pyhazards.configs import load_experiment_config -from pyhazards.engine.runner import BenchmarkRunner +from pyhazards.datasets.tc.synthetic import synthetic_tcnd_batch from pyhazards.models import build_model +from pyhazards.models.tropicalcyclone_mlp import SHIPS_PREDICTORS, load_keras_weights +from pyhazards.models.tropicyclonenet import ( + ENV_FEATURES, + TrajectoryDiscriminator, + TropiCycloneNet, + load_tropicyclonenet_checkpoint, +) + + +def _n_params(model): + return sum(p.numel() for p in model.parameters()) + + +def test_tropicalcyclone_mlp_is_the_official_24h_model(): + model = build_model("tropicalcyclone_mlp", task="regression") + assert _n_params(model) == 4_448_257 + assert len(SHIPS_PREDICTORS) == 121 and len(set(SHIPS_PREDICTORS)) == 121 + assert model(torch.randn(3, 121)).shape == (3, 1) + for name in model.layer_names: + assert torch.count_nonzero(getattr(model, name).bias) == 0 + with pytest.raises(ValueError, match="predictors shaped"): + model(torch.randn(3, 120)) + with pytest.raises(ValueError, match="regression"): + build_model("tropicalcyclone_mlp", task="classification") + + +def test_tropicalcyclone_mlp_loads_keras_weight_lists(): + model = build_model("tropicalcyclone_mlp", task="regression", input_dim=4, hidden_dims=[3, 2]) + kernels = [torch.randn(4, 3), torch.randn(3), torch.randn(3, 2), torch.randn(2), torch.randn(2, 1), torch.randn(1)] + load_keras_weights(model, [k.numpy() for k in kernels]) + x = torch.randn(5, 4) + expected = torch.relu(torch.sigmoid(x @ kernels[0] + kernels[1]) @ kernels[2] + kernels[3]) @ kernels[4] + kernels[5] + torch.testing.assert_close(model(x), expected) + with pytest.raises(ValueError, match="expected 6 arrays"): + load_keras_weights(model, [k.numpy() for k in kernels[:4]]) + + +def test_saf_net_parameters_shapes_and_validation(): + model = build_model("saf_net", task="regression").eval() + assert _n_params(model) == 880_233 + wide, deep = torch.rand(2, 96), torch.rand(2, 2, 4, 31, 31, 4) + out = model(wide, deep) + assert out.shape == (2, 1) and torch.all(out >= 0) + torch.testing.assert_close(model({"wide": wide, "deep": deep}), out) + with pytest.raises(ValueError, match="deep inputs shaped"): + model(wide, torch.rand(2, 2, 4, 31, 31, 3)) + with pytest.raises(ValueError, match="needs both"): + model(wide) + + +def test_tropicyclonenet_generator_and_discriminator(): + model = build_model("tropicyclonenet", task="regression").eval() + assert isinstance(model, TropiCycloneNet) + assert _n_params(model) == 4_767_195 + assert _n_params(TrajectoryDiscriminator()) == 231_009 + batch = synthetic_tcnd_batch(3, generator=torch.Generator().manual_seed(0))["inputs"] + with torch.no_grad(): + rel, frames, logits, index = model(batch, num_samples=6) + assert rel.shape == (4, 6, 3, 4) and frames.shape == (3, 1, 12, 64, 64) + assert logits.shape == (3, 6) and index.shape == (3, 6) + with torch.no_grad(): + every = model(batch, all_g_out=True)[0] + assert every.shape == (4, 6, 3, 4) + + # Env features may also sit at the top level of the mapping (smoke-test layout). + flat = {key: value for key, value in batch.items() if key != "env_data"} + flat.update(batch["env_data"]) + with torch.no_grad(): + torch.manual_seed(0) + a = model(flat, num_samples=2)[0] + torch.manual_seed(0) + b = model(batch, num_samples=2)[0] + torch.testing.assert_close(a, b) + + +def test_tropicyclonenet_forecast_is_cumulative_and_in_physical_units(): + model = build_model("tropicyclonenet", task="regression").eval() + batch = synthetic_tcnd_batch(2, generator=torch.Generator().manual_seed(1))["inputs"] + with torch.no_grad(): + torch.manual_seed(5) + forecast = model.forecast(batch, num_samples=6) + torch.manual_seed(5) + rel = model(batch, num_samples=6)[0] + assert set(forecast) >= {"lat", "lon", "pres", "wind", "logits", "generator_index"} + assert forecast["lat"].shape == (2, 6, 4) + last = batch["obs_traj"][-1] # (B, 4) normalised lon, lat, pres, wind + expected_lon = (last[:, 0].view(2, 1, 1) + torch.cumsum(rel[..., 0].permute(2, 1, 0), dim=-1)) * 5 + 180 + expected_wind = (last[:, 3].view(2, 1, 1) + torch.cumsum(rel[..., 3].permute(2, 1, 0), dim=-1)) * 25 + 40 + torch.testing.assert_close(forecast["lon"], expected_lon) + torch.testing.assert_close(forecast["wind"], expected_wind) + + +def test_tropicyclonenet_validation_and_checkpoint_guard(tmp_path): + model = build_model("tropicyclonenet", task="regression") + batch = synthetic_tcnd_batch(2)["inputs"] + bad = dict(batch, image_obs=torch.rand(2, 1, 8, 32, 32)) + with pytest.raises(ValueError, match="image_obs must be shaped"): + model(bad) + env = dict(batch["env_data"]) + env.pop(ENV_FEATURES[0][0]) + with pytest.raises(ValueError, match="env_data is missing"): + model(dict(batch, env_data=env)) + with pytest.raises(ValueError, match="pooling"): + TropiCycloneNet(pooling_type="pool_net") + with pytest.raises(ValueError, match="obs_len=8"): + TropiCycloneNet(obs_len=6) + fake = tmp_path / "checkpoint.pt" + torch.save({"g_state": model.state_dict()}, fake) + with pytest.raises(ValueError, match="sha256"): + load_tropicyclonenet_checkpoint(fake) + restored = load_tropicyclonenet_checkpoint(fake, verify_sha256=False) + assert hashlib.sha256(fake.read_bytes()).hexdigest() + for key, value in model.state_dict().items(): + assert torch.equal(restored.state_dict()[key], value) + + +def test_weather_model_placeholders_are_not_registered(): + # FourCastNet, GraphCast and Pangu-Weather are forecast + tracker pipelines (pyhazards.forecasts). + from pyhazards.models import available_models + + assert not {"graphcast_tc", "pangu_tc", "fourcastnet_tc"} & set(available_models()) + +def test_ported_cyclone_models_are_core_and_cite_their_papers(): + from pyhazards.model_catalog import load_model_cards -def test_storm_breadth_models_forward(): - x = torch.randn(2, 6, 8) - model_names = [ - "tropicalcyclone_mlp", - "tropicyclonenet", - "saf_net", - "tcif_fusion", - "graphcast_tc", - "pangu_tc", - "fourcastnet_tc", - ] - for name in model_names: - kwargs = { - "input_dim": 8, - "horizon": 5, - "output_dim": 3, - } - if name in {"tropicalcyclone_mlp", "fourcastnet_tc"}: - kwargs["history"] = 6 - model = build_model(name=name, task="regression", **kwargs) - preds = model(x) - assert preds.shape == (2, 5, 3) - - -def test_tc_breadth_configs(tmp_path): - for config_name in [ - "pyhazards/configs/tc/tropicalcyclone_mlp_smoke.yaml", - "pyhazards/configs/tc/tropicyclonenet_smoke.yaml", - "pyhazards/configs/tc/saf_net_smoke.yaml", - "pyhazards/configs/tc/tcif_fusion_smoke.yaml", - "pyhazards/configs/tc/graphcast_tc_smoke.yaml", - "pyhazards/configs/tc/pangu_tc_smoke.yaml", - "pyhazards/configs/tc/fourcastnet_tc_smoke.yaml", - ]: - summary = BenchmarkRunner().run( - load_experiment_config(config_name), - output_dir=str(tmp_path), - ) - assert summary.hazard_task == "tc.track_intensity" - assert "track_error" in summary.metrics - assert "intensity_mae" in summary.metrics + cards = {card.model_name: card for card in load_model_cards()} + expected = { + "tropicalcyclone_mlp": "10.1175/WAF-D-20-0104.1", + "saf_net": "10.1016/j.patrec.2021.11.012", + "hurricast": "10.1175/WAF-D-21-0091.1", + "tcif_fusion": "10.1088/1748-9326/ad1bde", + } + for name, doi in expected.items(): + card = cards[name] + assert card.catalog_status == "core" and doi in card.paper.url, name + assert card.reproduction is not None and card.reproduction.oracle_test, name + assert cards["hurricast"].reproduction.parameter_count == 2_969_771 + assert cards["tcif_fusion"].reproduction.parameter_count == 299_588_223 diff --git a/tests/test_tcif_fusion.py b/tests/test_tcif_fusion.py new file mode 100644 index 00000000..43275d34 --- /dev/null +++ b/tests/test_tcif_fusion.py @@ -0,0 +1,110 @@ +import numpy as np +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.tcif_fusion import ( + TCIFFusion, + apply_model_knowledge, + era5_all, + load_keras_weights, + model_knowledge_heatmaps, +) + +SMALL = {"grid_size": 9, "ir_size": 32, "widths": (4, 8, 8), "vgg_filters": (4, 4, 8, 8, 8), "vgg_fc": 16} + + +def _n_params(model): + return sum(p.numel() for p in model.parameters()) + + +def _inputs(batch=2, grid=9, ir=32, all_channels=None, seed=0): + g = torch.Generator().manual_seed(seed) + x = { + "u": torch.randn(batch, grid, grid, 5, 4, generator=g), + "v": torch.randn(batch, grid, grid, 5, 4, generator=g), + "w": torch.randn(batch, grid, grid, 5, 4, generator=g), + "sst": torch.rand(batch, grid, grid, 5, 1, generator=g), + "his": torch.rand(batch, 30, generator=g), + "ir": torch.rand(batch, ir, ir, 5, generator=g), + } + if all_channels is not None: + x["all"] = torch.randn(batch, grid, grid, all_channels, generator=g) + return x + + +def test_parameter_counts_of_the_paper_and_notebook_graphs(): + with torch.device("meta"): + paper = build_model("tcif_fusion", task="regression") + notebook = build_model("tcif_fusion", task="regression", all_channels=85) + assert _n_params(paper) == 299_588_223 + assert _n_params(notebook) == 299_611_263 + assert paper.era5_flat_dim == 212_992 and paper.all_channels == 65 + names = paper.keras_layer_names() + assert len(names) == 42 + 25 + 14 + assert names["conv3d_1"] == "u_block1.conv1" and names["conv2d_10"] == "ir.conv1_1" and names["dense_14"] == "output" + + +def test_forward_shapes_inputs_and_validation(): + model = build_model("tcif_fusion", task="regression", **SMALL).eval() + x = _inputs() + with torch.no_grad(): + out = model(x) + explicit = model({**x, "all": era5_all(x["u"], x["v"], x["w"], x["sst"])}) + positional = model(x["u"], x["v"], x["w"], x["sst"], None, x["his"], x["ir"]) + assert out.shape == (2, 1) + torch.testing.assert_close(explicit, out) + torch.testing.assert_close(positional, out) + assert era5_all(x["u"], x["v"], x["w"], x["sst"]).shape == (2, 9, 9, 65) + with pytest.raises(ValueError, match="missing"): + model({k: v for k, v in x.items() if k != "ir"}) + with pytest.raises(ValueError, match="must be shaped"): + model({**x, "u": x["u"].permute(0, 4, 1, 2, 3)}) + notebook = build_model("tcif_fusion", task="regression", all_channels=85, **SMALL) + with pytest.raises(ValueError, match="pass inputs\\['all'\\]"): + notebook(x) + assert notebook(_inputs(all_channels=85)).shape == (2, 1) + with pytest.raises(ValueError, match="regression"): + build_model("tcif_fusion", task="classification") + + +def test_keras_weights_are_transposed_into_place(): + model = TCIFFusion(**SMALL) + modules = dict(model.named_modules()) + rng = np.random.default_rng(0) + weights = {} + for keras_name, module_name in model.keras_layer_names().items(): + weight = modules[module_name].weight + if weight.ndim == 5: + shape = (*weight.shape[2:], weight.shape[1], weight.shape[0]) + elif weight.ndim == 4: + shape = (*weight.shape[2:], weight.shape[1], weight.shape[0]) + else: + shape = (weight.shape[1], weight.shape[0]) + weights[keras_name] = [rng.standard_normal(shape).astype("float32"), rng.standard_normal(weight.shape[0]).astype("float32")] + load_keras_weights(model, weights) + np.testing.assert_array_equal(model.u_block1.conv1.weight[3, 2].detach().numpy(), weights["conv3d_1"][0][:, :, :, 2, 3]) + np.testing.assert_array_equal(model.ir.conv1_1.weight[1, 0].detach().numpy(), weights["conv2d_10"][0][:, :, 0, 1]) + np.testing.assert_array_equal(model.output.weight.detach().numpy(), weights["dense_14"][0].T) + with pytest.raises(ValueError, match="missing Keras layers"): + load_keras_weights(model, {k: v for k, v in weights.items() if k != "dense_3"}) + + +def test_model_knowledge_step(): + torch.manual_seed(0) + model = build_model("tcif_fusion", task="regression", **SMALL) + x = _inputs() + heatmaps = model_knowledge_heatmaps(model, x) + assert model.training # restored + assert heatmaps["u"].shape == (2, 9, 9, 5) and heatmaps["sst"].shape == (2, 9, 9, 5) and heatmaps["ir"].shape == (2, 32, 32) + guided = apply_model_knowledge(x, heatmaps) + torch.testing.assert_close(guided["w"], x["w"] * heatmaps["w"].abs().unsqueeze(-1)) + torch.testing.assert_close(guided["ir"], x["ir"] * heatmaps["ir"].abs().unsqueeze(-1)) + torch.testing.assert_close(guided["all"], era5_all(guided["u"], guided["v"], guided["w"], guided["sst"])) + assert guided["his"] is x["his"] + # The heatmap of an input is its channel mean weighted by the spatially averaged gradient. + sst = x["sst"].clone().requires_grad_(True) + model.eval() + grad = torch.autograd.grad(model({**x, "sst": sst}).sum(), sst)[0] + expected = (x["sst"] * grad.mean(dim=(1, 2), keepdim=True)).mean(-1) + torch.testing.assert_close(heatmaps["sst"], expected) diff --git a/tests/test_tcn.py b/tests/test_tcn.py new file mode 100644 index 00000000..ea8e7aa3 --- /dev/null +++ b/tests/test_tcn.py @@ -0,0 +1,120 @@ +"""TCN: configurations, shapes, causality, state-dict layout and input validation. + +Numerical equivalence with locuslab/TCN lives in tests/oracle/test_tcn_oracle.py. +""" + +from __future__ import annotations + +import copy + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.tcn import TCN, TemporalConvNet, to_official_state_dict + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "kwargs, expected", + [ + ({}, 96_001), # official adding-problem script defaults (8 x 30, kernel 7) + (dict(hidden_dim=24, num_levels=8, kernel_size=8), 70_369), # paper Table 2, adding T=600 (~70K) + (dict(input_dim=1, out_dim=10, hidden_dim=25, num_levels=8, kernel_size=7), 66_910), # seq. MNIST + ], +) +def test_parameter_counts(kwargs, expected): + assert _n_params(build_model("tcn", task="regression", **kwargs)) == expected + + +def test_forward_shapes(): + model = build_model("tcn", task="classification", input_dim=5, out_dim=3, hidden_dim=8, num_levels=3, kernel_size=2).eval() + x = torch.randn(4, 6, 5) # (batch, time, features) + with torch.no_grad(): + assert model(x).shape == (4, 3) + model.readout = "sequence" + with torch.no_grad(): + assert model(x).shape == (4, 6, 3) + + +def test_last_step_readout_matches_sequence_readout(): + model = TCN(4, 2, [8, 8], kernel_size=3, dropout=0.0).eval() + x = torch.randn(2, 9, 4) + with torch.no_grad(): + last = model(x) + model.readout = "sequence" + torch.testing.assert_close(last, model(x)[:, -1]) + + +def test_outputs_are_causal_with_the_documented_receptive_field(): + torch.manual_seed(0) + net = TemporalConvNet(2, [4, 4, 4], kernel_size=3, dropout=0.0).eval() + field = net.receptive_field + assert field == 1 + 2 * 2 * (2**3 - 1) + with torch.no_grad(): + for parameter in net.parameters(): + parameter.abs_() # positive weights and inputs keep every ReLU active, so no path is cut + length, t = 64, 50 + x = torch.rand(1, 2, length) + with torch.no_grad(): + base = net(x) + future = x.clone() + future[:, :, t + 1 :] += 1.0 + torch.testing.assert_close(net(future)[:, :, : t + 1], base[:, :, : t + 1], rtol=0, atol=0) + too_old = x.clone() + too_old[:, :, t - field] += 1.0 # just outside the receptive field of step t + assert torch.equal(net(too_old)[:, :, t], base[:, :, t]) + oldest = x.clone() + oldest[:, :, t - field + 1] += 1.0 # the oldest input step t can see + assert not torch.equal(net(oldest)[:, :, t], base[:, :, t]) + + +def test_official_state_dict_layout_round_trips(): + model = build_model("tcn", task="regression", input_dim=3, hidden_dim=6, num_levels=2, kernel_size=2) + official = to_official_state_dict(model.state_dict()) + assert list(official)[:3] == ["tcn.network.0.conv1.bias", "tcn.network.0.conv1.weight_g", "tcn.network.0.conv1.weight_v"] + assert "tcn.network.0.net.0.weight_v" in official # the official code registers each conv twice + assert "tcn.network.0.downsample.weight" in official + assert "tcn.network.1.downsample.weight" not in official # same width: identity residual + restored = build_model("tcn", task="regression", input_dim=3, hidden_dim=6, num_levels=2, kernel_size=2) + restored.load_state_dict(official, strict=True) + x = torch.randn(2, 5, 3) + model.eval() + restored.eval() + with torch.no_grad(): + torch.testing.assert_close(restored(x), model(x)) + + +def test_model_can_be_deep_copied(): + model = build_model("tcn", task="regression", input_dim=3, hidden_dim=6, num_levels=2) + clone = copy.deepcopy(model) + x = torch.randn(1, 4, 3) + model.eval() + clone.eval() + with torch.no_grad(): + torch.testing.assert_close(clone(x), model(x)) + + +@pytest.mark.parametrize("shape", [(2, 5), (2, 5, 4), (2, 1, 5, 3)]) +def test_bad_input_shapes_raise(shape): + model = build_model("tcn", task="regression", input_dim=3, hidden_dim=4, num_levels=2) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(task="segmentation"), + dict(task="regression", kernel_size=1), + dict(task="regression", readout="mean"), + dict(task="regression", head_init="xavier"), + dict(task="regression", num_channels=[]), + ], +) +def test_bad_configurations_raise(kwargs): + with pytest.raises(ValueError): + build_model("tcn", **kwargs) diff --git a/tests/test_trajgru.py b/tests/test_trajgru.py new file mode 100644 index 00000000..d6b00daf --- /dev/null +++ b/tests/test_trajgru.py @@ -0,0 +1,145 @@ +"""TrajGRU without the reference code: sizes, the warp, shapes, states and validation. + +The comparison with the official MXNet implementation and its released weights is in +tests/oracle/test_trajgru_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.trajgru import TrajGRU, TrajGRUCell, TrajGRUSegmenter, load_hko7_params, warp + +SMALL = dict(config="movingmnist", num_filter=(8, 12, 12), L=3, first_conv=(4, 3, 1, 1), last_deconv=(4, 3, 1, 1)) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize( + "kwargs, expected", + [ + ({}, 12_150_053), # HKO-7 TrajGRU (trajgru_55_55_33_1_64_1_192_1_192_13_13_9_b4.yml) + (dict(layer_type="ConvGRU"), 13_649_081), # HKO-7 ConvGRU baseline (convgru_55_55_33_..._b4.yml) + (dict(config="movingmnist"), 4_000_397), # MovingMNIST++ TrajGRU-L13: paper Table 1, 4.00M + (dict(config="movingmnist", L=9), 3_421_277), # Traj-L9, 3.42M + (dict(config="movingmnist", layer_type="ConvGRU", h2h_kernel=5), 4_767_505), # Conv-K5-D1, 4.77M + (dict(config="movingmnist", layer_type="ConvGRU", h2h_kernel=7), 8_011_537), # Conv-K7-D1, 8.01M + ], +) +def test_parameter_counts(kwargs, expected): + assert _n_params(build_model("trajgru", task="forecasting", **kwargs)) == expected + + +def test_parameter_names_follow_mxnet_names(): + model = build_model("trajgru", task="forecasting") + names = {key.replace(".", "_") for key in model.state_dict()} + assert {"econv1_weight", "ebrnn1_0_i2h_weight", "ebrnn1_0_f_out_bias", "edown1_conv_weight", + "fbrnn3_0_h2h_weight", "fup2_deconv_weight", "fdeconv1_weight", "conv_final_bias", "out_weight"} <= names + # The top forecaster block runs without input; deconvolutions have no bias. + assert not any(name.startswith(("fbrnn3_0_i2h", "fbrnn3_0_i2f")) for name in names) + assert "fup1_deconv_bias" not in names and "fdeconv1_bias" not in names + assert model.econv1.in_channels == 4 # frame + x, y and ones channels + + +def test_flow_layers_start_at_zero(): + model = build_model("trajgru", task="forecasting", config="movingmnist") + for module in model.modules(): + if isinstance(module, TrajGRUCell): + assert not module.f_out.weight.any() and not module.f_out.bias.any() + assert model.ebrnn1[0].h2h.weight.std() > 0 + assert not model.ebrnn1[0].h2h.bias.any() + + +def test_warp_with_hand_computed_flows(): + data = torch.arange(16.0).view(1, 1, 4, 4) + zero = torch.zeros(1, 2, 4, 4) + torch.testing.assert_close(warp(data, zero), data) + + shift_x = zero.clone() + shift_x[:, 0] = 1.0 # output (y, x) samples the input at (y, x - 1); zeros enter at the border + expected = torch.tensor([[0.0, 0, 1, 2], [0, 4, 5, 6], [0, 8, 9, 10], [0, 12, 13, 14]]).view(1, 1, 4, 4) + torch.testing.assert_close(warp(data, shift_x), expected) + + half_y = zero.clone() + half_y[:, 1] = 0.5 # halfway to the previous row + previous = torch.cat([torch.zeros(1, 1, 1, 4), data[:, :, :-1]], dim=2) + torch.testing.assert_close(warp(data, half_y), 0.5 * (data + previous)) + + # Two links on a non-square map: outputs are concatenated link by link. + wide = torch.arange(30.0).view(1, 2, 3, 5) + flows = torch.zeros(1, 4, 3, 5) + flows[:, 2] = -2.0 # second link: sample at x + 2 + out = warp(wide, flows) + assert out.shape == (1, 4, 3, 5) + torch.testing.assert_close(out[:, :2], wide) + torch.testing.assert_close(out[:, 2:, :, :3], wide[:, :, :, 2:]) + assert not out[:, 2:, :, 3:].any() + + +def test_forecasting_and_segmentation_shapes(): + model = build_model("trajgru", task="forecasting", in_channels=2, num_output_frames=4, **SMALL).eval() + x = torch.rand(3, 5, 2, 32, 32) + with torch.no_grad(): + y = model(x) + assert y.shape == (3, 4, 1, 32, 32) + assert model(x, num_output_frames=2).shape == (3, 2, 1, 32, 32) + prediction, states = model(x, return_states=True) + torch.testing.assert_close(prediction, y) + assert [len(block) for block in states] == [1, 1, 1] + assert [block[0].shape for block in states] == [(3, 8, 32, 32), (3, 12, 16, 16), (3, 12, 8, 8)] + # Zero initial states are the default. + torch.testing.assert_close(model(x, initial_states=[[torch.zeros_like(s[0])] for s in states]), y) + segmenter = build_model("trajgru", task="segmentation", in_channels=2, **SMALL).eval() + assert isinstance(segmenter, TrajGRUSegmenter) + segmenter.load_state_dict(model.state_dict(), strict=True) # same keys, no prefix + with torch.no_grad(): + torch.testing.assert_close(segmenter(x), y[:, 0]) + logits = segmenter(x) + assert logits.shape == (3, 1, 32, 32) + + +def test_convgru_blocks_and_gradients(): + model = build_model("trajgru", task="segmentation", layer_type="ConvGRU", h2h_kernel=3, h2h_dilate=2, **SMALL) + assert model.ebrnn1[0].h2h.dilation == (2, 2) and model.ebrnn1[0].h2h.padding == (2, 2) + out = model(torch.rand(2, 3, 1, 16, 16)) + out.mean().backward() + assert out.shape == (2, 1, 16, 16) + assert model.econv1.weight.grad is not None + + +def test_load_hko7_params_round_trip(): + source = build_model("trajgru", task="forecasting", **SMALL) + for parameter in source.parameters(): + torch.nn.init.normal_(parameter) + params = {"arg:" + key.replace(".", "_"): value.numpy() for key, value in source.state_dict().items()} + target = build_model("trajgru", task="forecasting", **SMALL) + load_hko7_params(target, params) + for key, value in source.state_dict().items(): + assert torch.equal(target.state_dict()[key], value), key + params.pop("arg:out_bias") + with pytest.raises(KeyError, match="out_bias"): + load_hko7_params(target, params) + + +def test_input_validation(): + model = build_model("trajgru", task="forecasting", **SMALL) + with pytest.raises(ValueError, match="shape"): + model(torch.rand(2, 1, 32, 32)) + with pytest.raises(ValueError, match="input channels"): + model(torch.rand(2, 3, 2, 32, 32)) + with pytest.raises(ValueError, match="up-sampling"): + model(torch.rand(1, 3, 1, 30, 30)) # 30 -> 15 -> 8 -> up 16 != 15 + with pytest.raises(ValueError, match="up-sampling"): + build_model("trajgru", task="forecasting")(torch.rand(1, 2, 1, 256, 256)) # HKO-7 needs e.g. 480 + with pytest.raises(ValueError, match="layer_type"): + build_model("trajgru", task="forecasting", layer_type="LSTM") + with pytest.raises(ValueError, match="config"): + build_model("trajgru", task="forecasting", config="sevir") + with pytest.raises(ValueError, match="preserve"): + TrajGRU(i2h_kernel=5, i2h_pad=1) + with pytest.raises(ValueError, match="forecasting"): + build_model("trajgru", task="classification") diff --git a/tests/test_ts_satfire.py b/tests/test_ts_satfire.py new file mode 100644 index 00000000..6d0b5e3f --- /dev/null +++ b/tests/test_ts_satfire.py @@ -0,0 +1,77 @@ +"""TS-SatFire prediction baselines: configurations, parameter counts and shapes. + +The comparison with TS-SatFire's own models lives in tests/oracle/test_ts_satfire_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import TS_SATFIRE_BASELINES, build_model +from pyhazards.models.attention_unet import TemporalAttentionUnet +from pyhazards.models.swin_unetr import TemporalSwinUNETR +from pyhazards.models.unet3d import TemporalUNet +from pyhazards.models.unetr import TemporalUNETR + +EXPECTED = { + "unet3d": (TemporalUNet, 31_712_970), + "attention_unet3d": (TemporalAttentionUnet, 94_555_506), + "unetr3d": (TemporalUNETR, 28_816_866), + "swinunetr3d": (TemporalSwinUNETR, 33_191_942), +} + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_baselines_are_complete(): + assert set(TS_SATFIRE_BASELINES) == set(EXPECTED) + + +@pytest.mark.parametrize("baseline", TS_SATFIRE_BASELINES) +def test_default_configuration_parameter_counts(baseline): + cls, count = EXPECTED[baseline] + with torch.device("meta"): + model = build_model("ts_satfire", task="segmentation", baseline=baseline) + assert isinstance(model, cls) + assert _n_params(model) == count + + +def test_default_is_swinunetr3d(): + model = build_model("ts_satfire", task="segmentation", history=2, image_size=32) + assert isinstance(model, TemporalSwinUNETR) + assert model.window_size == (2, 4, 4) + + +# attention_unet3d (94.5M parameters) is left out for speed; tests/test_attention_unet.py covers its shapes. +@pytest.mark.parametrize("baseline", ["unet3d", "unetr3d", "swinunetr3d"]) +def test_forward_shapes(baseline): + model = build_model("ts_satfire", task="segmentation", baseline=baseline, in_channels=6, history=2, image_size=32) + model.eval() + with torch.no_grad(): + assert model(torch.randn(1, 2, 6, 32, 32)).shape == (1, 2, 32, 32) + + +def test_options(): + with torch.device("meta"): + v0 = build_model("ts_satfire", task="segmentation", baseline="unetr3d", unetr_version="v0") + assert _n_params(v0) == 97_922_658 + wide = build_model("ts_satfire", task="segmentation", baseline="unetr3d", feature_size=36) + assert _n_params(wide) == 38_282_426 + heads = build_model("ts_satfire", task="segmentation", baseline="swinunetr3d", num_heads=6) + assert _n_params(heads) == 33_204_878 + short = build_model("ts_satfire", task="segmentation", baseline="swinunetr3d", history=2) + assert short.swinViT.stage_scales[0] == (2, 2, 2) + + +def test_bad_arguments_raise(): + with pytest.raises(ValueError): + build_model("ts_satfire", task="classification") + with pytest.raises(ValueError): + build_model("ts_satfire", task="segmentation", baseline="segmenter") + with pytest.raises(ValueError): + build_model("ts_satfire", task="segmentation", baseline="unetr3d", unetr_version="v1") + with pytest.raises(ValueError): + build_model("ts_satfire", task="segmentation", history=0) diff --git a/tests/test_unet.py b/tests/test_unet.py new file mode 100644 index 00000000..f9b73bac --- /dev/null +++ b/tests/test_unet.py @@ -0,0 +1,106 @@ +"""U-Net (Ronneberger et al., MICCAI 2015) rebuilt from the paper; the oracle test covers the release.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.unet import UNet, unet_input_size, unet_output_size + +SMALL = (2, 4, 8, 16, 32) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_unet_parameter_counts(): + paper = build_model("unet", task="segmentation") + assert _n_params(paper) == 31_030_658 # 1 input channel, 2 classes (paper Fig. 1) + convs = [m for m in paper.modules() if isinstance(m, (torch.nn.Conv2d, torch.nn.ConvTranspose2d))] + assert len(convs) == 23 # "In total the network has 23 convolutional layers" + assert [m.out_channels for m in convs if isinstance(m, torch.nn.ConvTranspose2d)] == [512, 256, 128, 64] + assert not any(isinstance(m, torch.nn.BatchNorm2d) for m in paper.modules()) + release = build_model("unet", task="segmentation", variant="phseg_v5") + assert _n_params(release) == 31_100_354 + + +def test_unet_feature_map_sizes_follow_fig1(): + model = UNet(1, 2, channels=SMALL).eval() + sizes = {} + for name in ["conv_d0b_c", "conv_d1b_c", "conv_d2b_c", "conv_d3b_c", "conv_d4b_c", "conv_u3c_d", "conv_u2c_d", "conv_u1c_d", "conv_u0c_d"]: + getattr(model, name).register_forward_hook(lambda m, i, o, name=name: sizes.__setitem__(name, o.shape[-1])) + with torch.no_grad(): + out = model(torch.randn(1, 1, 572, 572)) + assert out.shape == (1, 2, 388, 388) + assert list(sizes.values()) == [568, 280, 136, 64, 28, 52, 100, 196, 388] + + +def test_unet_size_helpers(): + assert unet_output_size(572) == 388 + assert unet_input_size(388) == 572 + assert unet_output_size(188) == 4 and unet_input_size(1) == 188 + for output in range(1, 600, 7): + size = unet_input_size(output) + assert unet_output_size(size) >= output + assert size == 188 or unet_output_size(size - 16) < output + for bad in (187, 189, 200, 571, 64): + with pytest.raises(ValueError, match="16 \\* k \\+ 60"): + unet_output_size(bad) + assert unet_output_size(64, padding="same") == 64 + with pytest.raises(ValueError): + unet_output_size(60, padding="same") + + +def test_unet_rectangular_and_same_padding(): + model = UNet(3, 1, channels=SMALL).eval() + with torch.no_grad(): + assert model(torch.randn(2, 3, 188, 220)).shape == (2, 1, 4, 36) + same = build_model("unet", task="segmentation", in_channels=12, out_channels=1, padding="same", channels=SMALL).eval() + with torch.no_grad(): + assert same(torch.randn(2, 12, 64, 48)).shape == (2, 1, 64, 48) + with pytest.raises(ValueError): + same(torch.randn(2, 12, 64, 40)) + + +def test_unet_initialisation_and_dropout(): + torch.manual_seed(0) + model = build_model("unet", task="segmentation") + for name, param in model.named_parameters(): + if name.endswith(".bias"): + assert torch.count_nonzero(param) == 0, name + elif param.numel() >= 100_000: + fan_in = param.numel() / param.size(0) # (out, in, k, k) conv; (in, out, k, k) up-conv + assert abs(param.std().item() / (2.0 / fan_in) ** 0.5 - 1) < 0.02, name + assert model.dropout_d3c.p == model.dropout_d4c.p == 0.5 + small = UNet(1, 2, channels=SMALL, padding="same") + x = torch.randn(1, 1, 32, 32) + small.eval() + with torch.no_grad(): + torch.testing.assert_close(small(x), small(x)) + small.train() + torch.manual_seed(1) + first = small(x) + torch.manual_seed(2) + assert not torch.allclose(first, small(x)) + + +def test_unet_validation(): + model = UNet(1, 2, channels=SMALL) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(1, 188, 188)) + with pytest.raises(ValueError, match="channels"): + model(torch.randn(1, 3, 188, 188)) + with pytest.raises(ValueError): + model(torch.randn(1, 1, 190, 188)) + with pytest.raises(ValueError): + UNet(1, 2, channels=(64, 128, 256, 512)) + with pytest.raises(ValueError): + UNet(1, 2, padding="reflect") + with pytest.raises(ValueError): + UNet(1, 2, dropout=1.0) + with pytest.raises(ValueError): + build_model("unet", task="regression") + with pytest.raises(ValueError): + build_model("unet", task="segmentation", variant="caffe") diff --git a/tests/test_unet3d.py b/tests/test_unet3d.py new file mode 100644 index 00000000..4a094fa0 --- /dev/null +++ b/tests/test_unet3d.py @@ -0,0 +1,117 @@ +"""MONAI U-Net (unet3d): configurations, shapes and input validation. + +Numerical equivalence with MONAI and TS-SatFire lives in tests/oracle/test_unet3d_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.unet3d import TemporalUNet, UNet + +SMALL = dict(channels=(8, 16, 32)) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_ts_satfire_parameter_counts(): + with torch.device("meta"): + # U-Net-3D prediction model (43 channels; Table 3: 31.7M) and the 2D U-Net (8 channels; 10.6M). + assert _n_params(build_model("unet3d", task="segmentation", in_channels=43)) == 31_712_970 + assert _n_params(build_model("unet3d", task="segmentation", in_channels=8)) == 31_652_490 + assert _n_params(build_model("unet3d", task="segmentation", in_channels=8, spatial_dims=2)) == 10_552_458 + + +def test_default_strides_keep_time_and_halve_space(): + model = build_model("unet3d", task="segmentation", in_channels=43) + assert isinstance(model, TemporalUNet) + assert model.level_strides == [(1, 2, 2)] * 4 + assert model.size_multiple() == (1, 16, 16) + model_2d = build_model("unet3d", task="segmentation", in_channels=8, spatial_dims=2) + assert type(model_2d) is UNet + assert model_2d.level_strides == [(2, 2)] * 4 + + +def test_forward_shapes(): + model = build_model("unet3d", task="segmentation", in_channels=4, out_channels=1, **SMALL).eval() + x = torch.randn(2, 3, 4, 16, 16) + with torch.no_grad(): + assert model(x).shape == (2, 1, 16, 16) + model.time_reduction = "none" + assert model(x).shape == (2, 1, 3, 16, 16) + model_2d = build_model("unet3d", task="segmentation", in_channels=4, spatial_dims=2, num_res_units=2, **SMALL).eval() + with torch.no_grad(): + assert model_2d(torch.randn(2, 4, 12, 20)).shape == (2, 2, 12, 20) + + +def test_temporal_wrapper_is_the_3d_network_averaged_over_time(): + torch.manual_seed(0) + temporal = TemporalUNet(spatial_dims=3, in_channels=3, out_channels=2, strides=(1, 2, 2), stride_mode="shared", **SMALL) + plain = UNet(spatial_dims=3, in_channels=3, out_channels=2, strides=[(1, 2, 2)] * 2, **SMALL) + plain.load_state_dict(temporal.state_dict(), strict=True) + temporal.eval() + plain.eval() + x = torch.randn(2, 4, 3, 8, 8) + with torch.no_grad(): + torch.testing.assert_close(temporal(x), plain(x.transpose(1, 2)).mean(2)) + + +def test_monai_parameter_names(): + model = UNet(spatial_dims=2, in_channels=3, out_channels=1, strides=(2, 2), **SMALL) + names = list(model.state_dict()) + assert names[:4] == ["model.0.conv.weight", "model.0.conv.bias", "model.0.adn.A.weight", "model.1.submodule.0.conv.weight"] + assert "model.1.submodule.1.submodule.conv.weight" in names # bottom layer + assert names[-2:] == ["model.2.conv.weight", "model.2.conv.bias"] # top up-convolution: conv only + residual = UNet(spatial_dims=2, in_channels=3, out_channels=1, strides=(2, 2), num_res_units=2, **SMALL) + names = list(residual.state_dict()) + assert "model.0.conv.unit0.conv.weight" in names + assert "model.0.residual.weight" in names + assert "model.2.1.conv.unit0.conv.weight" in names + + +@pytest.mark.parametrize( + "spatial_dims, shape", + [ + (3, (2, 4, 16, 16)), # missing time axis + (3, (2, 3, 5, 16, 16)), # wrong channel count + (3, (2, 3, 4, 14, 16)), # height not divisible by 4 + (2, (2, 4, 16)), + (2, (2, 4, 18, 16)), + ], +) +def test_bad_input_shapes_raise(spatial_dims, shape): + model = build_model("unet3d", task="segmentation", in_channels=4, spatial_dims=spatial_dims, **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(strides=(2,)), + dict(strides=2), + dict(strides=(2, 2), stride_mode="mixed"), + dict(strides=[(2, 2, 2), 2]), + dict(strides=(2, 2), kernel_size=4), + dict(strides=(2, 2), channels=(8,)), + dict(strides=(2, 2), num_res_units=-1), + dict(strides=(2, 2), act="gelu"), + dict(strides=(2, 2), norm="group"), + ], +) +def test_bad_configurations_raise(kwargs): + config = dict(spatial_dims=2, in_channels=3, out_channels=1, channels=(8, 16, 32)) + config.update(kwargs) + with pytest.raises(ValueError): + UNet(**config) + + +def test_builder_validates_task_and_dims(): + with pytest.raises(ValueError): + build_model("unet3d", task="classification", in_channels=4) + with pytest.raises(ValueError): + build_model("unet3d", task="segmentation", in_channels=4, spatial_dims=1) diff --git a/tests/test_unetr.py b/tests/test_unetr.py new file mode 100644 index 00000000..3b867d32 --- /dev/null +++ b/tests/test_unetr.py @@ -0,0 +1,126 @@ +"""UNETR: configurations, shapes and input validation. + +Numerical equivalence with MONAI and TS-SatFire lives in tests/oracle/test_unetr_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.models import build_model +from pyhazards.models.unetr import UNETR, TemporalUNETR + +SMALL = dict(feature_size=8, hidden_size=32, mlp_dim=64, num_heads=4) + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +def test_ts_satfire_parameter_counts(): + with torch.device("meta"): + # Prediction script (43 channels, 6 days, feature size 16, hidden 384, MLP 1536). + assert _n_params(build_model("unetr", task="segmentation", in_channels=43)) == 28_816_866 + # AF/BA configuration of the paper text (8 channels, feature size 36): Table 3's 34.8M. + assert _n_params(build_model("unetr", task="segmentation", in_channels=8, feature_size=36)) == 34_806_506 + # UNETR-2D (stock MONAI, 8 channels): Table 3's 23.52M. + assert _n_params(build_model("unetr", task="segmentation", in_channels=8, spatial_dims=2)) == 23_521_186 + + +def test_ts_satfire_modifications(): + model = build_model("unetr", task="segmentation", in_channels=43) + assert isinstance(model, TemporalUNETR) + assert model.patch_size == (1, 16, 16) + assert model.kernel_size_up_down == (1, 2, 2) + assert model.feat_size == (6, 16, 16) + assert model.decoder3.conv_block.conv1.conv.weight.shape[-3:] == (1, 3, 3) + assert model.decoder4.conv_block.conv1.conv.weight.shape[-3:] == (3, 3, 3) + assert model.decoder2.transp_conv.conv.weight.shape[-3:] == (1, 2, 2) + + +def test_forward_shapes(): + model = build_model("unetr", task="segmentation", in_channels=5, history=3, image_size=32, **SMALL).eval() + x = torch.randn(2, 3, 5, 32, 32) + with torch.no_grad(): + assert model(x).shape == (2, 2, 32, 32) + model.time_reduction = "none" + assert model(x).shape == (2, 2, 3, 32, 32) + model_2d = build_model("unetr", task="segmentation", in_channels=5, spatial_dims=2, image_size=32, **SMALL).eval() + with torch.no_grad(): + assert model_2d(torch.randn(2, 5, 32, 32)).shape == (2, 2, 32, 32) + + +def test_temporal_wrapper_is_the_3d_network_averaged_over_time(): + torch.manual_seed(0) + temporal = build_model("unetr", task="segmentation", in_channels=3, history=2, image_size=16, **SMALL) + plain = UNETR( + in_channels=3, + out_channels=2, + img_size=(2, 16, 16), + norm_name="batch", + patch_size=(1, 16, 16), + kernel_size_up_down=(1, 2, 2), + decoder3_kernel_size=(1, 3, 3), + **SMALL, + ) + plain.load_state_dict(temporal.state_dict(), strict=True) + temporal.eval() + plain.eval() + x = torch.randn(2, 2, 3, 16, 16) + with torch.no_grad(): + torch.testing.assert_close(temporal(x), plain(x.transpose(1, 2)).mean(2)) + + +def test_monai_parameter_names(): + model = UNETR(in_channels=2, out_channels=1, img_size=32, spatial_dims=2, **SMALL) + names = list(model.state_dict()) + assert names[:2] == ["vit.patch_embedding.position_embeddings", "vit.patch_embedding.patch_embeddings.weight"] + assert "vit.blocks.11.attn.qkv.weight" in names + assert "vit.blocks.0.mlp.linear1.weight" in names + assert "encoder2.blocks.1.1.conv1.conv.weight" in names + assert "decoder5.transp_conv.conv.weight" in names + assert names[-2:] == ["out.conv.conv.weight", "out.conv.conv.bias"] + + +@pytest.mark.parametrize( + "shape", + [ + (2, 3, 32, 32), # missing time axis + (2, 3, 4, 32, 32), # wrong channel count + (2, 2, 3, 16, 32), # not the img_size the model was built for + (2, 3, 3, 32, 32), # wrong number of days + ], +) +def test_bad_input_shapes_raise(shape): + model = build_model("unetr", task="segmentation", in_channels=3, history=2, image_size=32, **SMALL) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(img_size=40), # not divisible by the patch + dict(img_size=32, num_heads=5), + dict(img_size=32, dropout_rate=1.5), + dict(img_size=32, patch_size=8), # patch must be kernel_size_up_down ** 4 + dict(img_size=32, decoder3_kernel_size=2), + dict(img_size=32, norm_name="group"), + dict(img_size=32, proj_type="linear"), + dict(img_size=32, spatial_dims=1), + dict(img_size=(32, 32, 32)), + ], +) +def test_bad_configurations_raise(kwargs): + config = dict(in_channels=3, out_channels=1, spatial_dims=2, feature_size=8, hidden_size=32, mlp_dim=64, num_heads=4) + config.update(kwargs) + with pytest.raises(ValueError): + UNETR(**config) + + +def test_builder_validates_task_and_dims(): + with pytest.raises(ValueError): + build_model("unetr", task="classification", in_channels=4) + with pytest.raises(ValueError): + build_model("unetr", task="segmentation", in_channels=4, spatial_dims=1) diff --git a/tests/test_urbanfloodcast.py b/tests/test_urbanfloodcast.py new file mode 100644 index 00000000..3e430a00 --- /dev/null +++ b/tests/test_urbanfloodcast.py @@ -0,0 +1,111 @@ +"""UrbanFloodCast DNO, its one-shot inputs and the inundation metrics: counts, shapes and validation.""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.configs import load_experiment_config +from pyhazards.datasets import load_dataset +from pyhazards.datasets.flood.urbanfloodcast import prepare_urbanfloodcast_event, synthetic_urbanfloodcast_event +from pyhazards.engine.runner import BenchmarkRunner +from pyhazards.metrics.inundation import ( + critical_success_index, + inundation_metrics, + nash_sutcliffe, + pearson_correlation, + relative_l2, +) +from pyhazards.models import build_model +from pyhazards.models.urbanfloodcast import UrbanFloodCast + + +def test_parameter_count_and_names_at_official_configuration(): + model = build_model("urbanfloodcast", task="regression") + assert sum(p.numel() for p in model.parameters()) == 4_470_437 + assert sum(p.numel() * (1 + p.is_complex()) for p in model.parameters()) == 8_937_637 + counts = {name: sum(p.numel() for p in getattr(model, name).parameters()) for name in ("fc", "fc0", "conv0", "conv7", "conv8", "fc1", "fc2")} + assert counts == {"fc": 144, "fc0": 170, "conv0": 1_280_560, "conv7": 627_760, "conv8": 2_560_840, "fc1": 840, "fc2": 123} + keys = set(model.state_dict()) + for key in ("conv0.conv.weights1", "conv0.mlp.mlp1.weight", "conv0.w.conv.weight", "conv0.normalize_layer.weight", "conv8.mlp.mlp2.bias"): + assert key in keys + assert "conv8.normalize_layer.weight" not in keys + assert model.conv0.conv.weights1.dtype == torch.complex64 + + +def test_forward_predicts_all_steps_at_once(): + torch.manual_seed(0) + model = UrbanFloodCast().eval() + x = torch.randn(2, 28, 30, 14, 1, 5) + with torch.no_grad(): + out = model(x) + assert out.shape == (2, 28, 30, 14, 3) + torch.testing.assert_close(model(x.reshape(2, 28, 30, 14, 5)), out) + + +@pytest.mark.parametrize( + "shape", + [(1, 28, 28, 14, 1, 4), (1, 26, 28, 14, 1, 5), (1, 28, 28, 13, 1, 5), (28, 28, 14, 5)], +) +def test_bad_shapes_raise(shape): + with pytest.raises(ValueError, match="shape|ndim"): + UrbanFloodCast()(torch.randn(*shape)) + + +def test_builder_validation(): + with pytest.raises(ValueError, match="regression"): + build_model("urbanfloodcast", task="segmentation") + with pytest.raises(ValueError, match="Unknown"): + build_model("urbanfloodcast", task="regression", history=4) + with pytest.raises(ValueError, match="pad"): + UrbanFloodCast(pad=1) + + +def test_one_shot_event_preparation(): + event = synthetic_urbanfloodcast_event(30, 31, 25, torch.Generator().manual_seed(0)) + event[0, 0, :, 0] = 0.0 + event[0, 0, :, 1:3] = 5.0 # discharge where the depth is zero is dropped + before = event.clone() + x, y, mask = prepare_urbanfloodcast_event(event) + assert torch.equal(event.nan_to_num(-1), before.nan_to_num(-1)) + assert x.shape == (30, 31, 24, 1, 5) and y.shape == mask.shape == (30, 31, 24, 3) + assert torch.all(x[0, 0, :, 0, 1:3] == 0) and torch.all(y[0, 0, :, 1:3] == 0) + assert torch.equal(x[:, :, 3, 0, :3], x[:, :, 0, 0, :3]) # the first step is repeated over the outputs + torch.testing.assert_close(x[..., 0, 3], torch.log(1 + before[:, :, 1:, 3] / 0.01) / 10) + assert torch.equal(mask, ~torch.isnan(before[:, :, 1:, :3])) + assert torch.isfinite(y).all() + with pytest.raises(ValueError, match="shape"): + prepare_urbanfloodcast_event(torch.zeros(4, 4, 25, 3)) + with pytest.raises(ValueError, match="steps"): + prepare_urbanfloodcast_event(torch.zeros(4, 4, 10, 5)) + + +def test_synthetic_dataset_layout(): + bundle = load_dataset("urbanfloodcast_synthetic", micro=True).load() + train = bundle.get_split("train") + assert train.inputs.shape[1:] == (32, 32, 24, 1, 5) and train.targets.shape[1:] == (32, 32, 24, 3) + assert train.metadata["mask"].dtype == torch.bool + assert bundle.metadata["synthetic"] is True and bundle.metadata["depth_channel"] == 0 + + +def test_metric_definitions(): + target = torch.tensor([[[0.0], [0.2], [0.6], [1.0]]]) + assert float(nash_sutcliffe(target, target)) == 1.0 + assert float(pearson_correlation(target, target)) == pytest.approx(0.75) # population cov / sample std, as the reference + assert float(relative_l2(target, target).sum()) == 0.0 + assert float(relative_l2(2 * target, target).sum()) == pytest.approx(1.0) + pred = torch.tensor([[[0.05], [0.0], [0.7], [0.3]]]) + # threshold 0.1: hits (0.6, 1.0), misses (0.2), false alarms none -> 2 / 3 + assert float(critical_success_index(pred, target, 0.1)) == pytest.approx(2 / 3) + metrics = inundation_metrics(pred.reshape(1, 4), target.reshape(1, 4)) + assert metrics["pixel_mae"] == pytest.approx((0.05 + 0.2 + 0.1 + 0.7) / 4) + assert metrics["iou"] == pytest.approx(1 / 3) # predicted wet (>= 0.5): 0.7; observed wet (> 0): 3 cells + with pytest.raises(ValueError, match="match"): + inundation_metrics(torch.zeros(2, 3), torch.zeros(2, 4)) + + +def test_smoke_config_scores_all_variables(tmp_path): + summary = BenchmarkRunner().run(load_experiment_config("pyhazards/configs/flood/urbanfloodcast_smoke.yaml"), output_dir=str(tmp_path)) + for metric in ("relative_l2", "nse", "pearson_r", "csi_1cm", "csi_10cm", "csi_50cm", "pixel_mae", "rmse", "iou", "f1"): + assert metric in summary.metrics + assert "rollout_rmse" not in summary.metrics diff --git a/tests/test_wavecastnet.py b/tests/test_wavecastnet.py new file mode 100644 index 00000000..ca9450e2 --- /dev/null +++ b/tests/test_wavecastnet.py @@ -0,0 +1,188 @@ +import pytest +import torch +import torch.nn.functional as F + +from pyhazards.metrics.wavefield import wavefield_acc, wavefield_metrics, wavefield_rfne, wavefield_rmse +from pyhazards.models import build_model +from pyhazards.models.wavecastnet import ( + ConvLEMCell, + WaveCastNet, + WaveCastNetLoss, + WaveCastNetSparse, + WavefieldMetrics, + load_wavecastnet_checkpoint, +) + + +def _count(model): + return sum(p.numel() for p in model.parameters()) + + +def _coords(stations=20, height=32, width=24, seed=0): + """Distinct (row, column) grid points.""" + flat = torch.randperm(height * width, generator=torch.Generator().manual_seed(seed))[:stations] + return torch.stack([flat // width, flat % width], dim=1) + + +def test_parameter_counts_and_official_names(): + dense = WaveCastNet() + assert _count(dense) == 10_093_242 + counts = {name: _count(module) for name, module in dense.named_children()} + assert counts == { + "encoder": 209_844, + "decoder": 331_920, + "encoder_1_convlem": 2_387_808, + "encoder_2_convlem": 2_387_808, + "decoder_1_convlem": 2_387_808, + "decoder_2_convlem": 2_387_808, + "conv1": 246, + } + state = dense.state_dict() + for key in ( + "encoder.model.encoder_layer1.layer.0.weight", + "encoder.model.encoder_layer3.layer.1.running_var", + "decoder.model.decoder_layer1.layer.0.weight", + "encoder_1_convlem.convx.weight", + "decoder_2_convlem.W_z4", + "conv1.bias", + ): + assert key in state + assert state["encoder_1_convlem.W_z1"].shape == (144, 43, 28) + assert state["encoder_1_convlem.convx.weight"].shape == (720, 144, 3, 3) + assert state["encoder_1_convlem.convy.weight"].shape == (576, 144, 3, 3) + + sparse = WaveCastNetSparse(station_coords=_coords(564, 344, 224)) + assert _count(sparse) == 16_535_430 + assert sparse.state_dict()["encoder.FC1.0.weight"].shape == (1204, 564) + assert sparse.state_dict()["encoder.FC2.0.weight"].shape == (4816, 1204) + assert "encoder.station_coords" not in sparse.state_dict() # a non-persistent buffer + + +def test_cell_variants_and_initialisation(): + cell = ConvLEMCell(4, 6, (5, 3), reset_gate=False) + assert not hasattr(cell, "W_z4") and cell.convx.out_channels == 24 and cell.convy.out_channels == 18 + assert all(float(p.detach().abs().sum()) > 0 for p in (cell.W_z1, cell.W_z2)) # xavier, not zero + assert float(cell.convx.bias.detach().abs().sum()) == 0.0 + h, c = cell(torch.randn(2, 4, 5, 3), torch.zeros(2, 6, 5, 3), torch.zeros(2, 6, 5, 3)) + assert h.shape == c.shape == (2, 6, 5, 3) + with pytest.raises(ValueError, match="shape"): + cell(torch.randn(2, 4, 4, 3), torch.zeros(2, 6, 4, 3), torch.zeros(2, 6, 4, 3)) + with pytest.raises(ValueError, match="activation"): + ConvLEMCell(4, 6, (5, 3), activation="gelu") + + +def test_forward_horizon_rollout_and_noise_hooks(): + torch.manual_seed(0) + model = build_model("wavecastnet", task="forecasting", height=16, width=24, future_seq=2).eval() + x = torch.randn(2, 3, 4, 16, 24) + with torch.no_grad(): + assert model(x).shape == (2, 3, 2, 16, 24) + assert model(x, 5).shape == (2, 3, 5, 16, 24) + # The decoder starts from uniform noise even in evaluation mode. + assert not torch.equal(model(x), model(x)) + same = [model(x, generator=torch.Generator().manual_seed(3)) for _ in range(2)] + assert torch.equal(same[0], same[1]) + noise = torch.rand(2, 144, 2, 3, generator=torch.Generator().manual_seed(3)) + assert torch.equal(model(x, decoder_noise=noise), same[0]) + torch.manual_seed(5) + first = model(x) + torch.manual_seed(5) + assert torch.equal(model(x), first) + rolled = model.rollout(x, 5, generator=torch.Generator().manual_seed(1)) + assert rolled.shape == (2, 3, 5, 16, 24) + g = torch.Generator().manual_seed(1) + part1 = model(x, 2, generator=g) + part2 = model(part1, 2, generator=g) + part3 = model(part2, 1, generator=g) + assert torch.equal(rolled, torch.cat([part1, part2, part3], dim=2)) + with pytest.raises(ValueError, match="shape"): + model(x, decoder_noise=torch.rand(2, 144, 3, 3)) + + +def test_input_validation_and_builder_arguments(): + model = WaveCastNet(height=16, width=16) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(1, 3, 2, 16, 24)) + with pytest.raises(ValueError, match="shape"): + model(torch.randn(1, 2, 2, 16, 16)) + with pytest.raises(ValueError, match="multiples of 8"): + WaveCastNet(height=20, width=16) + with pytest.raises(ValueError, match="48"): + WaveCastNet(height=16, width=16, num_kernels=64) + with pytest.raises(TypeError, match="no longer"): + build_model("wavecastnet", task="forecasting", hidden_dim=32) + with pytest.raises(ValueError, match="forecasting"): + build_model("wavecastnet", task="classification") + with pytest.raises(ValueError, match="variant"): + build_model("wavecastnet", task="forecasting", variant="graph", height=16, width=16) + assert isinstance(build_model("wavecastnet", task="regression", height=16, width=16), WaveCastNet) + with pytest.raises(ValueError, match="dense checkpoint"): + build_model("wavecastnet", task="forecasting", height=16, width=16, pretrained="dense") + + +def test_sparse_station_masking(): + coords = _coords(20) + torch.manual_seed(0) + model = build_model("wavecastnet", task="forecasting", variant="sparse", height=32, width=24, station_coords=coords).eval() + assert isinstance(model, WaveCastNetSparse) and model.mask_mode + x = torch.randn(2, 3, 3, 32, 24) + noise = torch.rand(2, 144, 4, 3) + with torch.no_grad(): + everything = model(x, station_mask=torch.ones(20, dtype=torch.bool), decoder_noise=noise) + model.mask_mode = False + assert torch.equal(model(x, decoder_noise=noise), everything) + model.mask_mode = True + # Masked stations are zeroed: changing the wavefield there changes nothing. + keep = torch.arange(20) % 2 == 0 + changed = x.clone() + for row, col in coords[~keep].tolist(): + changed[:, :, :, row, col] += 10.0 + a = model(x, station_mask=keep, decoder_noise=noise) + assert torch.equal(model(changed, station_mask=keep, decoder_noise=noise), a) + assert not torch.equal(model(changed, station_mask=torch.ones(20, dtype=torch.bool), decoder_noise=noise), everything) + # In evaluation the official model still draws a random station mask. + g1, g2 = torch.Generator().manual_seed(1), torch.Generator().manual_seed(2) + assert not torch.equal(model(x, decoder_noise=noise, generator=g1), model(x, decoder_noise=noise, generator=g2)) + with pytest.raises(ValueError, match="shape"): + model(x, station_mask=torch.ones(3, dtype=torch.bool)) + with pytest.raises(ValueError, match="station_coords"): + WaveCastNetSparse(station_coords=torch.tensor([[40, 3]]), height=32, width=24) + + +def test_loss_variants(): + torch.manual_seed(0) + pred, target = torch.randn(4, 3, 2, 8, 8), torch.randn(4, 3, 2, 8, 8) + official = WaveCastNetLoss()(pred, target) + expected = F.smooth_l1_loss(pred, target, beta=0.2) + 0.1 # Huber / delta + delta / 2 + torch.testing.assert_close(official, expected) + torch.testing.assert_close(WaveCastNetLoss(delta=0.5, variant="paper")(pred, target), F.huber_loss(pred, target, delta=0.5)) + with pytest.raises(ValueError, match="variant"): + WaveCastNetLoss(variant="l2") + + +def test_wavefield_metrics_are_per_sample_and_channel(): + target = torch.zeros(2, 3, 2, 2, 2) + target[:, :, 0, 0, 0] = 1.0 + target[:, 2] *= 100.0 # a channel with a much larger scale + pred = target.clone() + pred[:, 0] *= -1.0 # channel x anti-correlated + acc = wavefield_acc(pred, target) + assert acc.shape == (2, 3) + torch.testing.assert_close(acc, torch.tensor([[-1.0, 1.0, 1.0], [-1.0, 1.0, 1.0]])) + torch.testing.assert_close(wavefield_rfne(pred, target), torch.tensor([[2.0, 0.0, 0.0], [2.0, 0.0, 0.0]])) + torch.testing.assert_close(wavefield_rmse(pred, target)[:, 0], torch.full((2,), (4.0 / 8) ** 0.5)) + metrics = wavefield_metrics(pred, target, ["x", "y", "z"]) + assert metrics["acc"] == pytest.approx(1.0 / 3.0) and metrics["acc_x"] == -1.0 and metrics["acc_z"] == 1.0 + assert metrics["rfne"] == pytest.approx(2.0 / 3.0) and metrics["rfne_y"] == 0.0 + assert WavefieldMetrics.compute_all(pred, target)["ACC"] == pytest.approx(1.0 / 3.0) + with pytest.raises(ValueError, match="shape"): + wavefield_acc(pred[0], target[0]) + + +def test_checkpoint_loader_strips_data_parallel_prefix(tmp_path): + source = WaveCastNet(height=16, width=16) + path = tmp_path / "state.pt" + torch.save({f"module.{k}": v for k, v in source.state_dict().items()}, path) + target = load_wavecastnet_checkpoint(WaveCastNet(height=16, width=16), path) + for key, value in source.state_dict().items(): + assert torch.equal(target.state_dict()[key], value) diff --git a/tests/test_wildfire_benchmarks.py b/tests/test_wildfire_benchmarks.py index 0a1dc681..64c7c92a 100644 --- a/tests/test_wildfire_benchmarks.py +++ b/tests/test_wildfire_benchmarks.py @@ -19,16 +19,29 @@ def test_wildfire_spread_vertical_slice(tmp_path): assert summary.hazard_task == "wildfire.spread" assert "iou" in summary.metrics assert "burned_area_mae" in summary.metrics + assert 0.0 <= summary.metrics["average_precision"] <= 1.0 + + +def test_spread_average_precision_matches_sklearn(): + import torch + from sklearn.metrics import average_precision_score + + from pyhazards.benchmarks.wildfire import _spread_metrics + + torch.manual_seed(0) + logits = torch.randn(3, 1, 8, 8) + targets = (torch.rand(3, 1, 8, 8) > 0.8).float() + expected = average_precision_score(targets.flatten().numpy(), torch.sigmoid(logits).flatten().numpy()) + assert abs(_spread_metrics(logits, targets)["average_precision"] - expected) < 1e-9 def test_added_wildfire_breadth_configs(tmp_path): expectations = { - "pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml": "mae", - "pyhazards/configs/wildfire/asufm_smoke.yaml": "mae", + "pyhazards/configs/wildfire/wildfire_forecasting_smoke.yaml": "macro_f1", + "pyhazards/configs/wildfire/asufm_smoke.yaml": "burned_area_mae", "pyhazards/configs/wildfire/wildfirespreadts_smoke.yaml": "burned_area_mae", - "pyhazards/configs/wildfire/forefire_smoke.yaml": "burned_area_mae", - "pyhazards/configs/wildfire/wrf_sfire_smoke.yaml": "burned_area_mae", "pyhazards/configs/wildfire/firecastnet_smoke.yaml": "burned_area_mae", + "pyhazards/configs/wildfire/track_o_convlstm_smoke.yaml": "pr_auc", } for path, metric_name in expectations.items(): summary = BenchmarkRunner().run(load_experiment_config(path), output_dir=str(tmp_path)) diff --git a/tests/test_wildfire_forecasting.py b/tests/test_wildfire_forecasting.py new file mode 100644 index 00000000..ed25879f --- /dev/null +++ b/tests/test_wildfire_forecasting.py @@ -0,0 +1,134 @@ +"""Kondylatos et al. (2022) LSTM / ConvLSTM: configurations, shapes and input validation. + +Numerical equivalence with the official code lives in tests/oracle/test_wildfire_forecasting_oracle.py. +""" + +from __future__ import annotations + +import pytest +import torch + +from pyhazards.datasets import load_dataset +from pyhazards.models import SimpleConvLSTM, SimpleLSTM, WILDFIRE_FORECASTING_VARIANTS, build_model + +# Computed from the official fire_modules.py at the paper configuration (25 input features, +# hidden size 64 for the LSTM and 32 for the ConvLSTM). +EXPECTED_PARAMS = {"lstm": 29_652, "convlstm": 372_212} +EXAMPLE_INPUT = {"lstm": (3, 10, 25), "convlstm": (3, 10, 25, 25, 25)} + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize("variant", WILDFIRE_FORECASTING_VARIANTS) +def test_paper_parameter_counts(variant): + model = build_model("wildfire_forecasting", task="classification", variant=variant) + assert _n_params(model) == EXPECTED_PARAMS[variant] + + +def test_default_variant_is_lstm(): + model = build_model("wildfire_forecasting", task="classification") + assert isinstance(model, SimpleLSTM) + assert model.lstm.hidden_size == 64 + convlstm = build_model("wildfire_forecasting", task="classification", variant="convlstm") + assert isinstance(convlstm, SimpleConvLSTM) + assert convlstm.convlstm.hidden_dim == [32] + assert convlstm.fc1.in_features == 12 * 12 * 32 + + +@pytest.mark.parametrize("variant", WILDFIRE_FORECASTING_VARIANTS) +def test_outputs_are_log_probabilities(variant): + model = build_model("wildfire_forecasting", task="classification", variant=variant).eval() + with torch.no_grad(): + out = model(torch.randn(*EXAMPLE_INPUT[variant])) + assert out.shape == (3, 2) + assert (out <= 0).all() + torch.testing.assert_close(out.exp().sum(dim=1), torch.ones(3)) + + +def test_lstm_keeps_reference_state_dict_layout(): + model = SimpleLSTM() + keys = list(model.state_dict()) + # The reference registers fc1/fc2/fc3 twice (also inside fc_nn), so both key sets exist. + assert keys[:2] == ["ln1.weight", "ln1.bias"] + assert {"fc1.weight", "fc_nn.0.weight", "fc2.weight", "fc_nn.3.weight", "fc3.weight", "fc_nn.6.weight"} <= set(keys) + assert model.fc_nn[0] is model.fc1 + + +def test_convlstm_keeps_reference_state_dict_layout(): + keys = list(SimpleConvLSTM().state_dict()) + assert keys == [ + "ln1.weight", + "ln1.bias", + "convlstm.cell_list.0.conv.weight", + "convlstm.cell_list.0.conv.bias", + "conv1.weight", + "conv1.bias", + "fc1.weight", + "fc1.bias", + "fc2.weight", + "fc2.bias", + "fc3.weight", + "fc3.bias", + ] + + +def test_hyperparameters_are_configurable(): + lstm = build_model("wildfire_forecasting", task="classification", hidden_size=16, lstm_layers=2, input_dim=12) + assert lstm(torch.randn(2, 7, 12)).shape == (2, 2) + convlstm = build_model( + "wildfire_forecasting", task="classification", variant="convlstm", hidden_size=8, patch_size=9, input_dim=4 + ) + assert convlstm.fc1.in_features == 4 * 4 * 8 + assert convlstm(torch.randn(2, 3, 4, 9, 9)).shape == (2, 2) + + +def test_invalid_inputs_raise_value_error(): + lstm = SimpleLSTM() + with pytest.raises(ValueError, match="shape"): + lstm(torch.randn(2, 10, 25, 1)) + with pytest.raises(ValueError, match="features"): + lstm(torch.randn(2, 10, 24)) + convlstm = SimpleConvLSTM() + with pytest.raises(ValueError, match="shape"): + convlstm(torch.randn(2, 10, 25, 25)) + with pytest.raises(ValueError, match="features"): + convlstm(torch.randn(2, 10, 24, 25, 25)) + with pytest.raises(ValueError, match="25x25"): + convlstm(torch.randn(2, 10, 25, 32, 32)) + + +def test_invalid_builder_arguments(): + with pytest.raises(ValueError, match="classification"): + build_model("wildfire_forecasting", task="forecasting") + with pytest.raises(ValueError, match="variant"): + build_model("wildfire_forecasting", task="classification", variant="gru") + with pytest.raises(ValueError, match="dropout"): + build_model("wildfire_forecasting", task="classification", dropout=1.0) + + +@pytest.mark.parametrize( + "variant,access_mode", + [("lstm", "temporal"), ("convlstm", "spatiotemporal")], +) +def test_synthetic_danger_dataset_feeds_each_variant(variant, access_mode): + bundle = load_dataset("wildfire_danger_synthetic", micro=True, access_mode=access_mode).load() + train = bundle.get_split("train") + assert train.inputs.shape[1:] == EXAMPLE_INPUT[variant][1:] + assert train.targets.dtype == torch.long + assert set(train.targets.tolist()) == {0, 1} + assert bundle.label_spec.task_type == "classification" + model = build_model("wildfire_forecasting", task="classification", variant=variant).eval() + with torch.no_grad(): + assert model(train.inputs[:2]).shape == (2, 2) + + +def test_synthetic_danger_dataset_is_deterministic_with_two_to_one_negatives(): + first = load_dataset("wildfire_danger_synthetic", samples=30).load() + second = load_dataset("wildfire_danger_synthetic", samples=30).load() + torch.testing.assert_close(first.get_split("train").inputs, second.get_split("train").inputs) + labels = torch.cat([first.get_split(name).targets for name in ("train", "val", "test")]) + assert int(labels.sum()) == 10 + with pytest.raises(ValueError, match="access_mode"): + load_dataset("wildfire_danger_synthetic", access_mode="spatial") diff --git a/tests/test_wildfire_track_o.py b/tests/test_wildfire_track_o.py new file mode 100644 index 00000000..aabf7ecd --- /dev/null +++ b/tests/test_wildfire_track_o.py @@ -0,0 +1,345 @@ +"""Track-O wildfire occurrence datasets, cache builder and baseline runner (offline, synthetic fixtures).""" + +from __future__ import annotations + +import csv +import importlib.util +import json +from pathlib import Path + +import numpy as np +import pytest +import torch + +from pyhazards.datasets import load_dataset +from pyhazards.datasets.wildfire.track_o_cache import ( + build_track_o_cache, + date_from_name, + grid_bounds, + rasterize_points, + read_daily_weather, + read_firms_detections, +) + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def _load_runner(): + spec = importlib.util.spec_from_file_location( + "run_wildfire_track_o_baselines", REPO_ROOT / "scripts" / "run_wildfire_track_o_baselines.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +# --------------------------------------------------------------------------------------------- +# Synthetic source files +# --------------------------------------------------------------------------------------------- +LAT = np.arange(-10.0, 10.0 + 1e-9, 2.0) # 11 cell centres +LON = np.arange(-20.0, 18.0 + 1e-9, 2.0) # 20 cell centres + + +def _write_weather(directory: Path, day: str, value: float) -> None: + """Two files per day, as MERRA-2 collections: hourly 'slv' (latitude stored north-to-south) and 'lnd'.""" + import xarray as xr + + stamp = day.replace("-", "") + hours = np.arange(3) + t2m = np.stack([np.full((LAT.size, LON.size), value + hour) for hour in hours]) # daily mean = value + 1 + t2m[:, :, 0] += np.arange(LAT.size)[None, :] # a latitude-dependent column to check the orientation + xr.Dataset( + {"T2M": (("time", "lat", "lon"), t2m[:, ::-1, :])}, + coords={"time": hours, "lat": LAT[::-1], "lon": LON}, + ).to_netcdf(directory / f"MERRA2_400.tavg1_2d_slv_Nx.{stamp}.nc4") + gwet = np.full((1, LAT.size, LON.size), 0.5) + gwet[0, :, -2:] = np.nan # undefined over an "ocean" strip + xr.Dataset( + {"GWETROOT": (("time", "lat", "lon"), gwet)}, + coords={"time": [0], "lat": LAT, "lon": LON}, + ).to_netcdf(directory / f"MERRA2_400.tavg1_2d_lnd_Nx.{stamp}.nc4") + + +def _write_firms(path: Path, rows) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.writer(handle) + writer.writerow(["latitude", "longitude", "acq_date", "acq_time", "confidence", "type"]) + writer.writerows(rows) + + +@pytest.fixture() +def track_o_cache(tmp_path: Path) -> Path: + weather = tmp_path / "weather" + weather.mkdir() + days = [f"2024-01-{d:02d}" for d in range(1, 13) if d != 9] # 2024-01-09 has no weather + for index, day in enumerate(days): + _write_weather(weather, day, 280.0 + index) + firms = tmp_path / "firms" + firms.mkdir() + _write_firms( + firms / "fire_archive_M-C61_0001.csv", + [ + [0.4, 0.9, "2024-01-01", "0130", 80, 0], # -> cell (lat 0, lon 0) + [9.9, -20.9, "2024-01-01", "0200", 90, 0], # -> cell (lat 10, lon -20): within half a cell + [3.0, 5.0, "2024-01-01", "0300", 90, 2], # static land source: dropped + [40.0, 0.0, "2024-01-01", "0400", 90, 0], # far outside the grid: dropped + [-4.2, 17.9, "2024-01-02", "1200", 50, 0], + [-4.2, 17.9, "2024-01-12", "1200", 50, 0], + ], + ) + build_track_o_cache( + tmp_path / "cache", + sorted(weather.glob("*.nc4")), + sorted(firms.glob("*.csv")), + weather_vars=["T2M", "GWETROOT"], + splits={"train": ("2024-01-01", "2024-01-06"), "val": ("2024-01-07", "2024-01-09"), "test": ("2024-01-10", "2024-01-12")}, + ) + return tmp_path / "cache" + + +# --------------------------------------------------------------------------------------------- +# Builder +# --------------------------------------------------------------------------------------------- +def test_date_from_name() -> None: + assert date_from_name("pred_20240101_18.nc") == "2024-01-01" + assert date_from_name("MERRA2_sfc_20241231.nc") == "2024-12-31" + assert date_from_name("MERRA2_400.tavg1_2d_slv_Nx.20240229.nc4") == "2024-02-29" + assert date_from_name("2024-03-05.csv") == "2024-03-05" + assert date_from_name("fire_archive_M-C61_123456.csv") is None + assert date_from_name("fire_archive_SV-C2_20241399.csv") is None # not a calendar date + + +def test_rasterize_points_nearest_cell_wrap_and_extent() -> None: + lat = np.array([-1.0, 0.0, 1.0]) + lon = np.arange(0.0, 360.0, 90.0) # global 0..360 grid, 4 columns + grid = rasterize_points(np.array([0.2, 0.9, 5.0]), np.array([-44.0, 179.0, 0.0]), lat, lon) + expected = np.zeros((3, 4), dtype=np.float32) + expected[1, 0] = 1.0 # lon -44 = 316 -> nearest centre 0 (wraps around) + expected[2, 2] = 1.0 # lon 179 -> 180 + np.testing.assert_array_equal(grid, expected) # lat 5.0 is outside the grid and dropped + + regional_lon = np.array([10.0, 11.0, 12.0]) + grid = rasterize_points(np.array([0.0, 0.0, 0.0]), np.array([9.6, 9.4, 12.6]), lat, regional_lon) + assert grid.sum() == 1 and grid[1, 0] == 1 # 9.6 is within half a cell of 10; 9.4 and 12.6 are not + + +def test_read_daily_weather_means_and_orients(tmp_path: Path) -> None: + _write_weather(tmp_path, "2024-05-01", 300.0) + fields, lat, lon = read_daily_weather(sorted(tmp_path.glob("*.nc4")), ["T2M", "GWETROOT"]) + np.testing.assert_allclose(lat, LAT) + np.testing.assert_allclose(lon, LON) + assert fields.shape == (2, LAT.size, LON.size) + np.testing.assert_allclose(fields[0, :, 1], 301.0) # mean over the three hours + np.testing.assert_allclose(fields[0, :, 0], 301.0 + np.arange(LAT.size)) # south-to-north rows + assert np.isnan(fields[1, :, -2:]).all() and np.allclose(fields[1, :, :-2], 0.5) + with pytest.raises(KeyError, match="LAI"): + read_daily_weather(sorted(tmp_path.glob("*.nc4")), ["T2M", "LAI"]) + + +def test_read_firms_detections_filters_type(tmp_path: Path) -> None: + _write_firms(tmp_path / "a.csv", [[1.0, 2.0, "2024-01-01", "0000", 50, 0], [1.0, 2.0, "2024-01-01", "0000", 50, 1]]) + detections, stats = read_firms_detections([tmp_path / "a.csv"]) + assert list(detections) == ["2024-01-01"] and detections["2024-01-01"][0].tolist() == [1.0] + assert stats["dropped_type"] == 1 + detections, _ = read_firms_detections([tmp_path / "a.csv"], firms_types=None) + assert detections["2024-01-01"][0].size == 2 + # one file per day without acq_date: the day comes from the name + (tmp_path / "2024-02-03.csv").write_text("latitude,longitude\n1.5,2.5\n", encoding="utf-8") + detections, stats = read_firms_detections([tmp_path / "2024-02-03.csv"]) + assert list(detections) == ["2024-02-03"] and stats["files_without_type"] == 1 + + +def test_build_cache_layout_labels_and_splits(track_o_cache: Path) -> None: + summary = json.loads((track_o_cache / "cache_summary.json").read_text()) + assert summary["days"] == 11 and summary["splits"] == {"train": 6, "val": 2, "test": 3} + assert summary["firms"]["dropped_type"] == 1 + assert (track_o_cache / "splits" / "val_dates.txt").read_text().split() == ["2024-01-07", "2024-01-08"] + lat, lon = np.load(track_o_cache / "metadata" / "lat.npy"), np.load(track_o_cache / "metadata" / "lon.npy") + np.testing.assert_allclose(lat, LAT) + label = np.load(track_o_cache / "labels" / "2024-01-01.npy") + expected = np.zeros((LAT.size, LON.size), dtype=np.float32) + expected[5, 10] = 1.0 # (0.4, 0.9) -> lat 0, lon 0 + expected[10, 0] = 1.0 # (9.9, -20.9) -> lat 10, lon -20 + np.testing.assert_array_equal(label, expected) + assert np.load(track_o_cache / "labels" / "2024-01-05.npy").sum() == 0 # covered day without fires + met = np.load(track_o_cache / "met" / "2024-01-03.npy") + np.testing.assert_allclose(met[0, :, 1], 283.0) + assert grid_bounds(lat.astype(float), lon.astype(float)) == pytest.approx((-21.0, -11.0, 19.0, 11.0)) + assert not (track_o_cache / "static" / "fuel.npy").exists() + + +# --------------------------------------------------------------------------------------------- +# Datasets +# --------------------------------------------------------------------------------------------- +def test_datasets_read_cache(track_o_cache: Path) -> None: + raster = load_dataset("wildfire_track_o_raster", cache_dir=str(track_o_cache), downsample_factor=1, spatial_multiple=2).load() + train = raster.get_split("train") + assert tuple(train.inputs.shape) == (6, 2, 10, 20) and tuple(train.targets.shape) == (6, 1, 10, 20) + assert torch.isfinite(train.inputs).all() # NaN GWETROOT -> 0 after standardisation + assert raster.metadata["normalization"]["fit_split"] == "train" + assert raster.get_split("test").metadata["dates"] == ["2024-01-10", "2024-01-11", "2024-01-12"] + + temporal = load_dataset( + "wildfire_track_o_temporal", cache_dir=str(track_o_cache), history=2, downsample_factor=1, spatial_multiple=2 + ).load() + # val has 01-07 and 01-08 -> one window; test has 01-10..01-12 -> two (no 01-09 in the cache) + assert temporal.get_split("val").metadata["dates"] == ["2024-01-08"] + assert temporal.get_split("test").metadata["dates"] == ["2024-01-11", "2024-01-12"] + assert tuple(temporal.get_split("test").inputs.shape) == (2, 2, 2, 10, 20) + + tabular = load_dataset("wildfire_track_o_tabular", cache_dir=str(track_o_cache), downsample_factor=2, spatial_multiple=2).load() + split = tabular.get_split("train") + assert split.targets.dtype == torch.int64 and tuple(split.inputs.shape) == (6 * 6 * 10, 6) + assert tabular.feature_spec.extra["feature_names"][-2:] == ["sin_day_of_year", "cos_day_of_year"] + + +def test_dataset_errors(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="cache_dir"): + load_dataset("wildfire_track_o_raster") + with pytest.raises(FileNotFoundError, match="micro=True"): + load_dataset("wildfire_track_o_raster", cache_dir=str(tmp_path / "missing")).load() + with pytest.raises(ValueError, match="spatial_multiple"): + load_dataset("wildfire_track_o_raster", micro=True, downsample_factor=8, spatial_multiple=16).load() + + +@pytest.mark.parametrize( + "name,input_shape,target_shape,target_dtype", + [ + ("wildfire_track_o_raster", (24, 5, 16, 24), (24, 1, 16, 24), torch.float32), + ("wildfire_track_o_temporal", (19, 6, 5, 8, 12), (19, 1, 8, 12), torch.float32), + ("wildfire_track_o_tabular", (24 * 96, 9), (24 * 96,), torch.int64), + ], +) +def test_micro_layouts(name, input_shape, target_shape, target_dtype) -> None: + bundle = load_dataset(name, micro=True).load() + train = bundle.get_split("train") + assert tuple(train.inputs.shape) == input_shape + assert tuple(train.targets.shape) == target_shape and train.targets.dtype == target_dtype + assert torch.isfinite(train.inputs).all() + assert bundle.metadata["source_dataset"] == "micro_synthetic" + + +# --------------------------------------------------------------------------------------------- +# Benchmark and runner +# --------------------------------------------------------------------------------------------- +def test_danger_map_metrics_match_sklearn_and_check_shapes() -> None: + from sklearn.metrics import average_precision_score, f1_score, roc_auc_score + + from pyhazards.benchmarks.wildfire import _binary_map_metrics + + generator = torch.Generator().manual_seed(0) + logits = torch.randn(3, 1, 6, 7, generator=generator) + targets = (torch.rand(3, 1, 6, 7, generator=generator) > 0.8).float() + metrics = _binary_map_metrics(logits, targets) + probs, truth = torch.sigmoid(logits).flatten().numpy(), targets.flatten().numpy() > 0.5 + assert metrics["pr_auc"] == pytest.approx(average_precision_score(truth, probs)) + assert metrics["auc"] == pytest.approx(roc_auc_score(truth, probs)) + assert metrics["macro_f1"] == pytest.approx(f1_score(truth, probs >= 0.5, average="macro")) + + from pyhazards.benchmarks import run_benchmark + from pyhazards.configs import BenchmarkConfig, DatasetRef, ExperimentConfig, ModelRef, ReportConfig + + bundle = load_dataset("wildfire_track_o_raster", micro=True).load() + config = ExperimentConfig( + benchmark=BenchmarkConfig(name="wildfire", hazard_task="wildfire.danger", params={"batch_size": 3}), + dataset=DatasetRef(name="wildfire_track_o_raster"), + model=ModelRef(name="cnn", task="segmentation"), + report=ReportConfig(formats=[]), + ) + two_channel = torch.nn.Conv2d(5, 2, 1) + with pytest.raises(ValueError, match="one logit per cell"): + run_benchmark("wildfire", two_channel, bundle, config, output_dir="unused") + + +def test_probability_diagnostics_and_day_to_day_change() -> None: + from sklearn.metrics import brier_score_loss, log_loss + + runner = _load_runner() + rng = np.random.default_rng(0) + y, p = rng.integers(0, 2, 500), rng.random(500) + scores = runner.probability_diagnostics(y, p) + assert scores["brier"] == pytest.approx(brier_score_loss(y, p)) + assert scores["nll"] == pytest.approx(log_loss(y, p), rel=1e-6) + perfect = runner.probability_diagnostics(np.array([0, 1, 1]), np.array([0.0, 1.0, 1.0])) + assert perfect["ece"] == pytest.approx(0.0) and perfect["brier"] == 0.0 + + maps = np.array([[0.0, 0.0], [0.5, 0.0], [0.5, 1.0], [0.0, 0.0]]) + dates = ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-05"] # the last pair is not consecutive + assert runner.mean_day_to_day_change(maps, dates) == pytest.approx((0.25 + 0.5) / 2) + assert np.isnan(runner.mean_day_to_day_change(maps[:1], dates[:1])) + + +def test_runner_end_to_end_on_micro_data(tmp_path: Path) -> None: + runner = _load_runner() + out = tmp_path / "runs" + code = runner.main( + [ + "--micro", + "--output-dir", + str(out), + "--models", + "logistic_regression,random_forest,convlstm", + "--model-kwargs", + json.dumps({"random_forest": {"n_estimators": 5}, "convlstm": {"hidden_dim": 4}}), + "--max-epochs", + "2", + "--patience", + "1", + "--device", + "cpu", + "--n-jobs", + "1", + ] + ) + assert code == 0 + summary = json.loads((out / "summary.json").read_text()) + assert set(summary["models"]) == {"logistic_regression", "random_forest", "convlstm"} + for name in summary["models"]: + seed_dir = out / name / "seed_42" + metrics = json.loads((seed_dir / "metrics.json").read_text()) + for key in ("accuracy", "macro_f1", "auc", "pr_auc", "brier", "nll", "ece", "mean_day_to_day_change"): + assert np.isfinite(metrics["test"][key]), (name, key) + assert (seed_dir / "history.csv").exists() and (seed_dir / "experiment_setting.json").exists() + assert (seed_dir / "report" / "wildfire.json").exists() + assert json.loads((out / "convlstm" / "seed_42" / "metrics.json").read_text())["train_unit"] == "epoch" + + +# --------------------------------------------------------------------------------------------- +# Fuel alignment (optional rasterio) +# --------------------------------------------------------------------------------------------- +def test_fuel_alignment_keeps_north_up(tmp_path: Path) -> None: + rasterio = pytest.importorskip("rasterio") + from rasterio.transform import from_origin + + from pyhazards.datasets.wildfire.track_o_cache import add_fuel_to_cache, align_fuel_to_grid + + # A projected (CONUS Albers, EPSG:5070) raster: code 7 in the north half, 3 in the south half, + # -9999 fill in the western third under a nodata tag of 32767, as in LANDFIRE's LF2024 GeoTIFFs. + height, width = 200, 300 + data = np.where(np.arange(height)[:, None] < height // 2, 7, 3).astype(np.int16) * np.ones((1, width), np.int16) + data[:, :100] = -9999 + path = tmp_path / "fuel.tif" + with rasterio.open( + path, "w", driver="GTiff", height=height, width=width, count=1, dtype="int16", + crs="EPSG:5070", transform=from_origin(-1_500_000, 2_500_000, 10_000, 10_000), nodata=32767, + ) as dst: + dst.write(data, 1) + lat = np.arange(20.25, 55.0, 0.5) + lon = np.arange(-129.75, -60.0, 0.5) + fuel, mask = align_fuel_to_grid(path, lat, lon) + rows = np.flatnonzero(mask.any(axis=1)) + north_rows = np.flatnonzero((fuel == 7).any(axis=1)) + south_rows = np.flatnonzero((fuel == 3).any(axis=1)) + assert rows.size and north_rows.mean() > south_rows.mean() # rows are stored south-to-north + assert set(np.unique(fuel[mask > 0])) == {3, 7} and (fuel[mask == 0] == 0).all() + # with the file's own nodata tag (32767) the -9999 fill takes part in the mode and wins in the + # western third, where those cells are then marked invalid instead of getting a fuel code + tagged, tagged_mask = align_fuel_to_grid(path, lat, lon, src_nodata=None) + assert tagged_mask.sum() <= mask.sum() and set(np.unique(tagged[tagged_mask > 0])) <= {3, 7} + + cache = tmp_path / "cache" + (cache / "metadata").mkdir(parents=True) + np.save(cache / "metadata" / "lat.npy", lat) + np.save(cache / "metadata" / "lon.npy", lon) + info = add_fuel_to_cache(cache, path) + assert info["codes"] == [3, 7] and np.array_equal(np.load(cache / "static" / "fuel.npy"), fuel) diff --git a/tests/test_wildfirespreadts_baselines.py b/tests/test_wildfirespreadts_baselines.py new file mode 100644 index 00000000..b372bd0a --- /dev/null +++ b/tests/test_wildfirespreadts_baselines.py @@ -0,0 +1,145 @@ +"""WildfireSpreadTS baselines: configurations, shapes and input validation. + +Numerical equivalence with the reference implementations lives in tests/oracle. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import torch + +from pyhazards.model_catalog import REPO_ROOT, load_model_cards +from pyhazards.models import WILDFIRESPREADTS_BASELINES, build_model + +# WildfireSpreadTS paper Table 5 (all features, 40 channels); the U-Net count is smp 0.3.2's. +EXPECTED_PARAMS = { + "logistic_regression": 361, + "resnet18_unet": 14_444_241, + "convlstm": 240_449, + "utae": 1_099_011, +} + + +def _n_params(model: torch.nn.Module) -> int: + return sum(p.numel() for p in model.parameters()) + + +@pytest.mark.parametrize("baseline", WILDFIRESPREADTS_BASELINES) +def test_wildfirespreadts_parameter_counts(baseline): + model = build_model("wildfirespreadts", task="segmentation", baseline=baseline, in_channels=40, history=1) + assert _n_params(model) == EXPECTED_PARAMS[baseline] + + +@pytest.mark.parametrize("baseline", WILDFIRESPREADTS_BASELINES) +def test_wildfirespreadts_forward_shapes(baseline): + model = build_model("wildfirespreadts", task="segmentation", baseline=baseline, in_channels=6, history=3).eval() + with torch.no_grad(): + out = model(torch.randn(2, 3, 6, 32, 32)) + assert out.shape == (2, 1, 32, 32) + + +def test_standalone_builders_match_presets(): + for name, kwargs in { + "logistic_regression": {}, + "resnet18_unet": {}, + "convlstm": {}, + "utae": {}, + }.items(): + model = build_model(name, task="segmentation", in_channels=40, **kwargs) + assert _n_params(model) == EXPECTED_PARAMS[name], name + + +def test_multiday_input_is_flattened_time_major(): + model = build_model("logistic_regression", task="segmentation", in_channels=4, history=2) + x = torch.randn(1, 2, 4, 8, 8) + torch.testing.assert_close(model(x), model.conv(torch.cat([x[:, 0], x[:, 1]], dim=1))) + + +def test_utae_default_positions_are_time_indices(): + model = build_model("utae", task="segmentation", in_channels=3).eval() + x = torch.randn(2, 4, 3, 16, 16) + positions = torch.arange(4, dtype=torch.float32).expand(2, -1) + with torch.no_grad(): + torch.testing.assert_close(model(x), model(x, batch_positions=positions)) + + +def test_utae_handles_padded_dates(): + model = build_model("utae", task="segmentation", in_channels=3).eval() + x = torch.randn(2, 4, 3, 16, 16) + x[0, :2] = 0 + with torch.no_grad(): + out = model(x) + assert torch.isfinite(out).all() + + +@pytest.mark.parametrize( + "name, shape", + [ + ("convlstm", (2, 3, 16, 16)), + ("utae", (2, 3, 16, 16)), + ("utae", (2, 4, 3, 12, 12)), + ("resnet18_unet", (2, 3, 48, 48)), + ("logistic_regression", (2, 16, 16)), + ], +) +def test_bad_input_shapes_raise(name, shape): + model = build_model(name, task="segmentation", in_channels=3) + with pytest.raises(ValueError): + model(torch.randn(*shape)) + + +def test_unknown_baseline_raises(): + with pytest.raises(ValueError): + build_model("wildfirespreadts", task="segmentation", baseline="persistence") + + +def test_reproduction_metadata_points_at_existing_oracle_tests(): + for card in load_model_cards(): + if card.reproduction is None or card.reproduction.oracle_test is None: + continue + assert (REPO_ROOT / card.reproduction.oracle_test).exists(), card.model_name + + +def test_oracle_manifest_pins_full_commits(): + import yaml + + manifest = yaml.safe_load((Path(__file__).parent / "oracle" / "repos.yaml").read_text()) + for name, spec in manifest["repos"].items(): + assert len(spec["commit"]) == 40, name + for name, spec in manifest["assets"].items(): + assert len(spec["sha256"]) == 64, name + + +def test_oracle_workflow_runs_every_oracle_test_once(): + import yaml + + root = Path(__file__).resolve().parents[1] + workflow = yaml.safe_load((root / ".github" / "workflows" / "oracle.yml").read_text()) + entries = workflow["jobs"]["oracle"]["strategy"]["matrix"]["include"] + listed = sorted(path for entry in entries for path in entry["tests"].split()) + expected = sorted(path.relative_to(root).as_posix() for path in (root / "tests" / "oracle").glob("test_*.py")) + assert listed == expected + + manifest = yaml.safe_load((root / "tests" / "oracle" / "repos.yaml").read_text()) + known = set(manifest["repos"]) | set(manifest["assets"]) + for entry in entries: + assert (root / entry["requirements"]).exists(), entry["suite"] + assert set(entry["references"].split()) <= known, entry["suite"] + + +def test_multiday_unet_removes_duplicate_static_features(): + from pyhazards.models.resnet_unet import flatten_and_remove_duplicate_features + from pyhazards.models.wildfirespreadts import WILDFIRESPREADTS_STATIC_FEATURE_IDS + + model = build_model("wildfirespreadts", task="segmentation", baseline="resnet18_unet", in_channels=40, history=5) + assert model.in_channels == 4 * 20 + 40 + assert _n_params(model) == 14_695_121 # paper Table 5: 14.7M for five days + x = torch.randn(1, 5, 40, 32, 32) + flat = flatten_and_remove_duplicate_features(x, WILDFIRESPREADTS_STATIC_FEATURE_IDS) + assert flat.shape == (1, 120, 32, 32) + torch.testing.assert_close(flat[:, -40:], x[:, -1]) + model.eval() + with torch.no_grad(): + torch.testing.assert_close(model(x), model(flat)) diff --git a/tests/test_wrf_sfire_reader.py b/tests/test_wrf_sfire_reader.py new file mode 100644 index 00000000..2e40e19b --- /dev/null +++ b/tests/test_wrf_sfire_reader.py @@ -0,0 +1,216 @@ +"""WRF-SFIRE wrfout reader on small synthetic files with the layout of real WRF-SFIRE history output. + +The synthetic files copy the dimension names, variable dimensions, dtypes and attributes recorded in +tests/fixtures/wrf_sfire_hill_wrfout_header.json, the header of a real history file of the official +WRF-SFIRE W4.4-S0.1 ideal case test/em_fire/hill (fire-grid variables on (Time, south_north_subgrid, +west_east_subgrid), subgrid sizes (south_north + 1) * sr_y by (west_east + 1) * sr_x with the last +sr_y rows / sr_x columns as padding, no sr_x/sr_y global attributes, XTIME in minutes). Their values +follow what that file holds: TIGN_G is the arrival time where LFN < 0 and the frame time plus one fire +step (2 steps at t = 0) elsewhere. +""" + +import json +from pathlib import Path + +import numpy as np +import pytest + +netCDF4 = pytest.importorskip("netCDF4") + +from pyhazards.datasets import load_dataset # noqa: E402 +from pyhazards.datasets.wrf_sfire import ( # noqa: E402 + WRF_SFIRE_FIRE_GRID_VARIABLES, + read_wrf_sfire_fire_grid, +) +from pyhazards.datasets.wrf_sfire.inspection import main as inspection_main # noqa: E402 + +REAL = json.loads((Path(__file__).parent / "fixtures" / "wrf_sfire_hill_wrfout_header.json").read_text()) +NX, NY, SR, DX = 4, 3, 5, 60.0 # atmospheric cells and refinement; fire cells are DX / SR = 12 m +FIRE_DT = REAL["observations"]["fire_dt_s"] +MINUTES = (0.0, 1.0, 2.0, 3.0) +PAD = -777.0 +SIZES = { + "Time": None, + "DateStrLen": 19, + "west_east": NX, + "south_north": NY, + "west_east_subgrid": (NX + 1) * SR, + "south_north_subgrid": (NY + 1) * SR, +} + + +def _truth(): + """Arrival time (s) on the fire grid, south-up, for a fire ignited at t = 30 s in the south-west.""" + rows, cols = NY * SR, NX * SR + y, x = (np.mgrid[0:rows, 0:cols] + 0.5) * (DX / SR) + return 30.0 + np.hypot(x - 40.0, y - 30.0) / 0.5 # 0.5 m/s spread + + +def _write(path, frames, with_sr_attrs=False, variables=("TIGN_G", "LFN", "FIRE_AREA", "FGRNHFX", "ROS", "NFUEL_CAT", "ZSF")): + """A wrfout with the real file's layout (REAL), small sizes and the given fire-grid variables.""" + truth = _truth() + with netCDF4.Dataset(path, "w", format=REAL["file_format"]) as ds: + for name, size in SIZES.items(): + ds.createDimension(name, size) + for key in ("TITLE", "SIMULATION_START_DATE"): + ds.setncattr(key, REAL["global_attributes"][key]) + ds.setncattr("WEST-EAST_GRID_DIMENSION", np.int32(NX + 1)) + ds.setncattr("SOUTH-NORTH_GRID_DIMENSION", np.int32(NY + 1)) + ds.DX = np.float32(DX) + ds.DY = np.float32(DX) + if with_sr_attrs: # accepted too (wrfxpy looks for them), though WRF's own output has none + ds.sr_x = np.int32(SR) + ds.sr_y = np.int32(SR) + out = {} + for name in ("Times", "XTIME", *variables): + spec = REAL["variables"][name] + var = ds.createVariable(name, spec["dtype"], tuple(spec["dimensions"])) + for key, value in spec["attributes"].items(): + var.setncattr(key, np.int32(value) if isinstance(value, int) else value) + out[name] = var + grn = ds.createVariable("GRNHFX", "f4", ("Time", "south_north", "west_east")) # atmospheric grid + grn.description = "heat flux from ground fire" + for i, minute in enumerate(frames): + t = minute * 60.0 + out["Times"][i, :] = np.frombuffer("0001-01-01_00:{:02d}:00".format(int(minute)).encode(), dtype="S1") + out["XTIME"][i] = minute + grn[i] = 0.0 + burned = truth <= t + fields = { + "TIGN_G": np.where(burned, truth, t + (2 * FIRE_DT if t == 0 else FIRE_DT)), + "LFN": truth - t, # negative inside the fire + "FIRE_AREA": burned.astype(float), + "FGRNHFX": np.where(burned, 5e4, 0.0), + "ROS": np.full(truth.shape, 0.5), + "NFUEL_CAT": np.full(truth.shape, 3.0), + "ZSF": np.linspace(0.0, 10.0, truth.shape[1])[None, :].repeat(truth.shape[0], 0), + } + for name in variables: + padded = np.full(((NY + 1) * SR, (NX + 1) * SR), PAD, dtype=np.float32) + padded[: NY * SR, : NX * SR] = fields[name] + out[name][i] = padded + return truth + + +def test_fixture_is_a_real_wrf_sfire_header(): + dims = REAL["dimensions"] + assert dims["west_east_subgrid"] == (dims["west_east"] + 1) * 10 == 420 + assert dims["south_north_subgrid"] == (dims["south_north"] + 1) * 10 == 420 + assert "sr_x" not in REAL["global_attributes"] + for name, (description, units) in WRF_SFIRE_FIRE_GRID_VARIABLES.items(): + spec = REAL["variables"].get(name) + if spec is None: + continue + assert spec["dimensions"] == ["Time", "south_north_subgrid", "west_east_subgrid"] + assert (spec["attributes"]["description"], spec["attributes"]["units"]) == (description, units) + + +@pytest.fixture +def wrfout(tmp_path): + path = tmp_path / "wrfout_d01_0001-01-01_00:00:00" + truth = _write(path, MINUTES) + return path, truth + + +def test_reads_fire_grid_without_padding(wrfout): + path, truth = wrfout + grid = read_wrf_sfire_fire_grid(path, origin="lower") + assert grid.shape == (NY * SR, NX * SR) + assert (grid.sr_x, grid.sr_y) == (SR, SR) + assert grid.fire_dx == grid.fire_dy == DX / SR + np.testing.assert_array_equal(grid.times, np.array(MINUTES) * 60.0) + assert grid.time_strings[1] == "0001-01-01_00:01:00" + assert set(grid.variables) == {"TIGN_G", "LFN", "FIRE_AREA", "FGRNHFX", "ROS"} + for values in grid.variables.values(): + assert values.shape == (len(MINUTES), NY * SR, NX * SR) + assert not np.any(values == PAD) + + masks = grid.burned_masks() + for i, minute in enumerate(MINUTES): + np.testing.assert_array_equal(masks[i], truth <= minute * 60.0) + arrival = grid.arrival_time() + np.testing.assert_allclose(arrival[np.isfinite(arrival)], truth[truth <= 180.0], rtol=1e-6) + assert np.isinf(arrival[truth > 180.0]).all() + + +def test_north_up_is_the_default_and_flips_rows(wrfout): + path, _ = wrfout + lower = read_wrf_sfire_fire_grid(path, origin="lower") + upper = read_wrf_sfire_fire_grid(path) + assert upper.origin == "upper" + np.testing.assert_array_equal(upper.variables["TIGN_G"], lower.variables["TIGN_G"][:, ::-1]) + np.testing.assert_array_equal(upper.burned_masks(), lower.burned_masks()[:, ::-1]) + keep = read_wrf_sfire_fire_grid(path, variables=("LFN",), strip_padding=False, origin="lower") + assert keep.variables["LFN"].shape == (len(MINUTES), (NY + 1) * SR, (NX + 1) * SR) + + +def test_refinement_from_dimensions_and_multiple_files(tmp_path, wrfout): + path, _ = wrfout + single = read_wrf_sfire_fire_grid(path, variables=("TIGN_G", "LFN")) + parts = [] + for minute in reversed(MINUTES): # one frame per file, listed out of order + part = tmp_path / f"wrfout_d01_0001-01-01_00:{int(minute):02d}:00" + _write(part, (minute,), with_sr_attrs=True, variables=("TIGN_G", "LFN")) + parts.append(part) + merged = read_wrf_sfire_fire_grid(parts, variables=("TIGN_G", "LFN")) + assert (merged.sr_x, merged.sr_y) == (SR, SR) + np.testing.assert_array_equal(merged.times, single.times) + np.testing.assert_array_equal(merged.variables["TIGN_G"], single.variables["TIGN_G"]) + globbed = read_wrf_sfire_fire_grid(str(tmp_path / "wrfout_d01_0001-01-01_00:0[0-3]:00"), variables=("LFN",)) + assert globbed.variables["LFN"].shape[0] == len(MINUTES) + + +def test_tign_only_files_use_the_arrival_time(tmp_path): + path = tmp_path / "wrfout_tign_only" + truth = _write(path, MINUTES, variables=("TIGN_G",)) + grid = read_wrf_sfire_fire_grid(path, variables=("TIGN_G",), origin="lower") + masks = grid.burned_masks() + for i, minute in enumerate(MINUTES): + np.testing.assert_array_equal(masks[i], truth <= minute * 60.0) + + +def test_errors(wrfout, tmp_path): + path, _ = wrfout + with pytest.raises(KeyError, match="fire-grid variables in the file"): + read_wrf_sfire_fire_grid(path, variables=("F_ROS",)) + with pytest.raises(ValueError, match="only fire-grid variables"): + read_wrf_sfire_fire_grid(path, variables=("GRNHFX",)) + with pytest.raises(FileNotFoundError): + read_wrf_sfire_fire_grid(tmp_path / "missing_wrfout") + with pytest.raises(ValueError, match="origin"): + read_wrf_sfire_fire_grid(path, origin="north") + grid = read_wrf_sfire_fire_grid(path, variables=("FIRE_AREA",)) + with pytest.raises(KeyError, match="LFN or TIGN_G"): + grid.burned_masks() + + +def test_spread_pairs_and_registered_dataset(wrfout): + path, truth = wrfout + grid = read_wrf_sfire_fire_grid(path, variables=("TIGN_G", "LFN", "NFUEL_CAT"), origin="lower") + inputs, targets, times = grid.spread_pairs(horizon=1, features=("NFUEL_CAT",)) + assert inputs.shape == (3, 2, NY * SR, NX * SR) and targets.shape == (3, 1, NY * SR, NX * SR) + np.testing.assert_array_equal(inputs[:, 0], grid.burned_masks()[:3]) + np.testing.assert_array_equal(targets[:, 0], grid.burned_masks()[1:]) + np.testing.assert_array_equal(inputs[:, 1], 3.0) + np.testing.assert_array_equal(times, [0.0, 60.0, 120.0]) + with pytest.raises(ValueError, match="more than 4"): + grid.spread_pairs(horizon=4) + + bundle = load_dataset("wrf_sfire_spread", paths=str(path), features=("ZSF",), train_fraction=0.34, val_fraction=0.33).load() + assert bundle.metadata["hazard_task"] == "wildfire.spread" + assert bundle.feature_spec.channels == 2 + assert bundle.label_spec.task_type == "segmentation" + sizes = [bundle.get_split(name).inputs.shape[0] for name in ("train", "val", "test")] + assert sizes == [1, 1, 1] + assert bundle.get_split("test").targets.shape == (1, 1, NY * SR, NX * SR) + with pytest.raises(ValueError, match="wrfout"): + load_dataset("wrf_sfire_spread") + + +def test_inspection_cli(wrfout, capsys): + path, _ = wrfout + assert inspection_main([]) == 0 + assert inspection_main(["--path", str(path)]) == 0 + out = capsys.readouterr().out + assert "fire grid: 15 x 20 cells of 12 x 12 m (sr_x=5, sr_y=5)" in out + assert inspection_main(["--path", str(path) + "_missing"]) == 2