Publish causal preprocessing constructors
Browse filesAdd exact route and structure feature builders, normalization statistics, and causal fallbacks for frozen inputs.
README.md
CHANGED
|
@@ -1,63 +1,89 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
library_name: pytorch
|
| 4 |
-
pipeline_tag: time-series-forecasting
|
| 5 |
-
tags:
|
| 6 |
-
- weather
|
| 7 |
-
- tropical-cyclone
|
| 8 |
-
- typhoon
|
| 9 |
-
- causal-forecasting
|
| 10 |
-
- pytorch
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
# Trackformer 1.2
|
| 14 |
|
| 15 |
-
Trackformer 1.2 is an experimental causal western-Pacific tropical-cyclone
|
| 16 |
-
forecasting model. It
|
| 17 |
-
pressure, radius of maximum wind, R34/R50/R64 wind radii
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
The
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
mixed into the 1.2 weights.
|
| 28 |
|
| 29 |
-
##
|
| 30 |
|
| 31 |
-
The model
|
|
|
|
| 32 |
|
| 33 |
- observed IBTrACS history;
|
| 34 |
- current, -12 h, and -24 h atmospheric analysis summaries;
|
| 35 |
-
- current and lagged
|
| 36 |
- causal nearby-storm and basin/global pressure context;
|
| 37 |
- static land/sea, coastline, terrain, land-cover, and location features.
|
| 38 |
|
| 39 |
-
It does not use JMA, JTWC, ECMWF, GFS, GEFS, or another agency's forecast
|
| 40 |
-
track or positive-lead weather field
|
| 41 |
-
only after
|
| 42 |
|
| 43 |
## Inputs
|
| 44 |
|
| 45 |
Trackformer 1.2 keeps the public causal input families used by Trackformer 1.1;
|
| 46 |
-
the route context
|
| 47 |
-
features needed near coastlines.
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
| 51 |
-
|
|
| 52 |
-
|
|
| 53 |
-
|
|
| 54 |
-
|
|
| 55 |
-
|
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
## Outputs
|
| 59 |
|
| 60 |
-
For each six-hour
|
| 61 |
|
| 62 |
| Output | Shape or unit |
|
| 63 |
|---|---|
|
|
@@ -65,21 +91,34 @@ For each six-hour lead, the model returns:
|
|
| 65 |
| Maximum sustained wind | knots, 1-minute estimate |
|
| 66 |
| Central pressure | hPa |
|
| 67 |
| Radius of maximum wind | kilometres |
|
| 68 |
-
| R34
|
| 69 |
-
| Pressure-state route fields | western-Pacific grid with
|
| 70 |
|
| 71 |
-
Radius outputs are non-negative and
|
| 72 |
-
|
| 73 |
|
| 74 |
-
##
|
| 75 |
|
| 76 |
-
|
| 77 |
available test initialization per storm, the same +6 h through +120 h leads,
|
| 78 |
-
and the same issue-time causal boundary.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |

|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|---|---:|---:|---|
|
| 84 |
| Mean track error, all leads (km) | 802.406 | 398.419 | Trackformer 1.2 |
|
| 85 |
| Mean track error, +120 h (km) | 1,604.259 | 808.607 | Trackformer 1.2 |
|
|
@@ -92,83 +131,248 @@ and the same issue-time causal boundary. Lower error is better.
|
|
| 92 |
| RMW MAE, all leads (km) | 26.396 | 26.996 | Trackformer 1.1 |
|
| 93 |
| R34 MAE, all leads (km) | 57.253 | 57.079 | Trackformer 1.2 |
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
|
| 100 |
-
|
| 101 |
-
[`paper/trackformer_1_2_vs_1_1_matched100_metrics.json`](paper/trackformer_1_2_vs_1_1_matched100_metrics.json).
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
|
| 105 |

|
| 106 |
|
| 107 |
-
The
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
- NumPy feature statistics;
|
| 120 |
-
- `manifest.json` with the input boundary, outputs, splits, and metrics.
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
## Python Inference
|
| 126 |
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
```bash
|
| 130 |
python -m pip install -r requirements.txt
|
| 131 |
```
|
| 132 |
|
| 133 |
-
|
| 134 |
|
| 135 |
```python
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
model = Trackformer12.from_pretrained(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
route = model.predict_route(field, context, base_position)
|
| 140 |
intensity = model.predict_intensity(causal_features, anchor_structure)
|
|
|
|
| 141 |
latitude, longitude = local_position_to_latlon(
|
| 142 |
route["position_100km"], issue_latitude, issue_longitude
|
| 143 |
)
|
| 144 |
```
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
`
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
## Limitations
|
| 170 |
|
| 171 |
-
Forecast error varies by storm, basin,
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Trackformer 1.2
|
| 2 |
|
| 3 |
+
Trackformer 1.2 is an experimental, causal western-Pacific tropical-cyclone
|
| 4 |
+
forecasting model. It forecasts storm motion, maximum sustained wind, central
|
| 5 |
+
pressure, radius of maximum wind, and R34/R50/R64 wind radii over six-hour
|
| 6 |
+
leads through +120 h.
|
| 7 |
+
|
| 8 |
+
This is a research release, not an operational warning system. Do not use it
|
| 9 |
+
for evacuation, aviation, maritime, emergency-management, or other
|
| 10 |
+
safety-critical decisions.
|
| 11 |
+
|
| 12 |
+
## Release Highlights
|
| 13 |
+
|
| 14 |
+
- A whole western-Pacific route state with land, coastline, terrain, and
|
| 15 |
+
ocean-context features.
|
| 16 |
+
- A causal intensity and structure head for maximum wind, pressure, RMW, and
|
| 17 |
+
quadrant wind radii.
|
| 18 |
+
- Current and lagged atmospheric analysis plus SST context, nearby-storm
|
| 19 |
+
context, and static geography.
|
| 20 |
+
- Validation-gated calibration and storm-disjoint chronological evaluation.
|
| 21 |
+
- Native PyTorch and joblib artifacts in a GitHub Release and the Hugging Face
|
| 22 |
+
model repository.
|
| 23 |
+
|
| 24 |
+
The public release name is **Trackformer 1.2**. The internal experiment history
|
| 25 |
+
is intentionally not used as the public product name.
|
| 26 |
+
|
| 27 |
+
## Availability
|
| 28 |
|
| 29 |
+
- [GitHub Release: Trackformer 1.2](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.2)
|
| 30 |
+
- [Hugging Face model repository](https://huggingface.co/euler314/typhoon-predict)
|
| 31 |
+
- [Live interactive demo](https://yu314-coder.github.io/typhoon-tracks.html)
|
| 32 |
+
|
| 33 |
+
The main branch contains source and documentation. The model weights are
|
| 34 |
+
distributed as the release archive rather than committed into the Git history.
|
| 35 |
+
|
| 36 |
+
## What Changed
|
| 37 |
|
| 38 |
+
Trackformer 1.2 keeps the causal route design and adds a promoted
|
| 39 |
+
land/ocean-context intensity candidate. The structure head uses pooled
|
| 40 |
+
log-radius groups, lead-wise residual calibration, non-negative radius
|
| 41 |
+
constraints, and a validation-selected ocean-availability gate. The route and
|
| 42 |
+
intensity components are packaged together so the same release can expose the
|
| 43 |
+
forecast track and the surrounding storm structure.
|
| 44 |
|
| 45 |
+
The release deliberately excludes the rejected exploratory multi-variant
|
| 46 |
+
ensemble. It is not used to select a favorable result after looking at the
|
| 47 |
+
test cases.
|
|
|
|
| 48 |
|
| 49 |
+
## Data Boundary
|
| 50 |
|
| 51 |
+
The model input at forecast issue time is limited to information available at
|
| 52 |
+
that time or earlier:
|
| 53 |
|
| 54 |
- observed IBTrACS history;
|
| 55 |
- current, -12 h, and -24 h atmospheric analysis summaries;
|
| 56 |
+
- current and lagged sea-surface-temperature summaries;
|
| 57 |
- causal nearby-storm and basin/global pressure context;
|
| 58 |
- static land/sea, coastline, terrain, land-cover, and location features.
|
| 59 |
|
| 60 |
+
It does **not** use JMA, JTWC, ECMWF, GFS, GEFS, or another agency's forecast
|
| 61 |
+
track or positive-lead weather field as an input. Later observations and
|
| 62 |
+
best-track labels are used only after the forecast is frozen for verification.
|
| 63 |
|
| 64 |
## Inputs
|
| 65 |
|
| 66 |
Trackformer 1.2 keeps the public causal input families used by Trackformer 1.1;
|
| 67 |
+
the route context is expanded across the western Pacific and includes the
|
| 68 |
+
static land/ocean features needed near coastlines. The public tensor contract
|
| 69 |
+
is:
|
| 70 |
+
|
| 71 |
+
| Input | Shape or content | Boundary |
|
| 72 |
+
|---|---|---|
|
| 73 |
+
| Observed track and intensity history | `9 x 54` track window | issue time and earlier |
|
| 74 |
+
| Current storm-centred analysis | `4 x 17 x 17` | issue-time analysis |
|
| 75 |
+
| Older analysis context | `8 x 17 x 17` | -12 h and -24 h analysis |
|
| 76 |
+
| Whole-Pacific route state | `3 snapshots x 7 channels x latitude x longitude` | current and lagged analysis |
|
| 77 |
+
| SST, nearby systems, and pressure context | causal summaries and spatial features | issue time and earlier |
|
| 78 |
+
| Geography | land/sea, coastline, terrain, land-cover, and location features | static |
|
| 79 |
+
|
| 80 |
+
The data families are observations, analyses, reanalysis summaries, and static
|
| 81 |
+
geography. They are not agency forecast products. Missing radius labels are
|
| 82 |
+
masked rather than converted to zero.
|
| 83 |
|
| 84 |
## Outputs
|
| 85 |
|
| 86 |
+
For each of 20 six-hour leads from +6 h through +120 h, the model returns:
|
| 87 |
|
| 88 |
| Output | Shape or unit |
|
| 89 |
|---|---|
|
|
|
|
| 91 |
| Maximum sustained wind | knots, 1-minute estimate |
|
| 92 |
| Central pressure | hPa |
|
| 93 |
| Radius of maximum wind | kilometres |
|
| 94 |
+
| R34, R50, and R64 | four quadrant radii in kilometres |
|
| 95 |
+
| Pressure-state route fields | whole western-Pacific grid with pressure contours and steering context |
|
| 96 |
|
| 97 |
+
Radius outputs are non-negative and the structure head enforces R34 >= R50 >=
|
| 98 |
+
R64 for each quadrant.
|
| 99 |
|
| 100 |
+
## Held-Out Comparison
|
| 101 |
|
| 102 |
+
The canonical comparison uses the same 100 common storms, the same earliest
|
| 103 |
available test initialization per storm, the same +6 h through +120 h leads,
|
| 104 |
+
and the same issue-time causal boundary. The split remains chronological and
|
| 105 |
+
storm-disjoint:
|
| 106 |
+
|
| 107 |
+
- training: storms through 2015;
|
| 108 |
+
- validation: storms from 2016 through 2019;
|
| 109 |
+
- test: storms from 2020 onward, held out until scoring.
|
| 110 |
+
|
| 111 |
+
The earlier README comparison mixed a different release-manifest aggregate with
|
| 112 |
+
this matched-storm benchmark. That is why it appeared to show a win in every
|
| 113 |
+
category. The chart below is now the canonical comparison; lower error is
|
| 114 |
+
better and all values come from the matched 100-storm evaluation.
|
| 115 |
|
| 116 |

|
| 117 |
|
| 118 |
+
The source values and input policy are recorded in
|
| 119 |
+
[paper/trackformer_1_2_vs_1_1_matched100_metrics.json](paper/trackformer_1_2_vs_1_1_matched100_metrics.json).
|
| 120 |
+
|
| 121 |
+
| Metric | Trackformer 1.1 | Trackformer 1.2 | Better in this benchmark |
|
| 122 |
|---|---:|---:|---|
|
| 123 |
| Mean track error, all leads (km) | 802.406 | 398.419 | Trackformer 1.2 |
|
| 124 |
| Mean track error, +120 h (km) | 1,604.259 | 808.607 | Trackformer 1.2 |
|
|
|
|
| 131 |
| RMW MAE, all leads (km) | 26.396 | 26.996 | Trackformer 1.1 |
|
| 132 |
| R34 MAE, all leads (km) | 57.253 | 57.079 | Trackformer 1.2 |
|
| 133 |
|
| 134 |
+
This benchmark supports a strong track improvement and lower wind/pressure
|
| 135 |
+
error. It does **not** support the claim that Trackformer 1.2 is better on
|
| 136 |
+
every radius metric; RMW remains slightly worse and +120 h R34 is worse. Those
|
| 137 |
+
limitations are kept visible instead of selecting a more favorable cohort.
|
| 138 |
|
| 139 |
+
## Pressure-Map Diagnostic
|
|
|
|
| 140 |
|
| 141 |
+
The route output is a whole-western-Pacific pressure-state diagnostic with
|
| 142 |
+
MSLP contours, 500-hPa height, wind context, and the causal route. It is a
|
| 143 |
+
model diagnostic, not an official forecast overlay.
|
| 144 |
|
| 145 |

|
| 146 |
|
| 147 |
+
The image is included to show the spatial output format. The quantitative
|
| 148 |
+
comparison above, not a single case map, is the model benchmark.
|
| 149 |
+
|
| 150 |
+
## Release-Candidate Metrics
|
| 151 |
+
|
| 152 |
+
For completeness, the released land/ocean-context head was also compared with
|
| 153 |
+
its frozen causal baseline on 9,994 untouched test windows at +120 h. Lower is
|
| 154 |
+
better.
|
| 155 |
+
|
| 156 |
+
| Metric at +120 h | Frozen baseline | Trackformer 1.2 candidate |
|
| 157 |
+
|---|---:|---:|
|
| 158 |
+
| Maximum wind MAE (kt) | 19.876 | 19.618 |
|
| 159 |
+
| Central pressure MAE (hPa) | 13.634 | 13.519 |
|
| 160 |
+
| Mean radius MAE (km) | 28.952 | 28.944 |
|
| 161 |
+
| R34 MAE (km) | 46.672 | 46.672 |
|
| 162 |
+
| R50 MAE (km) | 25.417 | 25.417 |
|
| 163 |
+
| R64 MAE (km) | 14.767 | 14.742 |
|
| 164 |
+
|
| 165 |
+
The candidate improves maximum wind, pressure, mean radius, and R64 at +120 h,
|
| 166 |
+
while R34 and R50 are unchanged at the displayed precision. This is a separate
|
| 167 |
+
candidate-versus-baseline diagnostic and must not be substituted for the
|
| 168 |
+
matched 1.1 comparison above.
|
| 169 |
+
|
| 170 |
+
## Weight Bundle
|
| 171 |
+
|
| 172 |
+
The release archive contains:
|
| 173 |
+
|
| 174 |
+
```text
|
| 175 |
+
models/trackformer_1_2/
|
| 176 |
+
manifest.json
|
| 177 |
+
trackformer_1_2_route_seed0.pt
|
| 178 |
+
trackformer_1_2_route_seed1.pt
|
| 179 |
+
trackformer_1_2_intensity_seed0.pt
|
| 180 |
+
trackformer_1_2_intensity_seed1.pt
|
| 181 |
+
trackformer_1_2_ocean_structure.joblib
|
| 182 |
+
trackformer_1_2_feature_stats.npz
|
| 183 |
+
trackformer_1_2_route_context_stats.npz
|
| 184 |
+
trackformer_1_2_track_stats.npz
|
| 185 |
+
trackformer_1_2_system_context_stats.npz
|
| 186 |
+
```
|
| 187 |
|
| 188 |
+
The bundle uses native PyTorch checkpoints, NumPy statistics, and a joblib
|
| 189 |
+
calibration artifact. GGUF is not an appropriate interchange format for this
|
| 190 |
+
CNN/Transformer weather model.
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
Download the archive from the [Trackformer 1.2 release](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.2),
|
| 193 |
+
verify its SHA-256 value shown in the release notes, and extract it outside the
|
| 194 |
+
Git checkout.
|
| 195 |
|
| 196 |
## Python Inference
|
| 197 |
|
| 198 |
+
The repository includes a checkpoint-compatible inference module in
|
| 199 |
+
[`trackformer_1_2.py`](trackformer_1_2.py). It loads both released neural
|
| 200 |
+
seeds and averages them as one Trackformer 1.2 model. The same module now
|
| 201 |
+
publishes the feature constructors used to build the tensor contracts, rather
|
| 202 |
+
than requiring callers to reverse-engineer the training code. Install the
|
| 203 |
+
runtime dependencies with:
|
| 204 |
|
| 205 |
```bash
|
| 206 |
python -m pip install -r requirements.txt
|
| 207 |
```
|
| 208 |
|
| 209 |
+
Load from an extracted GitHub Release bundle:
|
| 210 |
|
| 211 |
```python
|
| 212 |
+
import numpy as np
|
| 213 |
+
from trackformer_1_2 import (
|
| 214 |
+
Trackformer12, build_base_position, build_route_context,
|
| 215 |
+
build_nearby_interaction_features, build_route_geography_features,
|
| 216 |
+
build_route_kinematic_features, build_route_system_features,
|
| 217 |
+
build_synoptic_features, local_position_to_latlon, prepare_route_field,
|
| 218 |
+
)
|
| 219 |
|
| 220 |
+
model = Trackformer12.from_pretrained(
|
| 221 |
+
"/path/to/trackformer_1_2/models/trackformer_1_2",
|
| 222 |
+
device="cpu", # use "mps" on Apple Silicon or "cuda" on NVIDIA
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# These arrays must be constructed from issue-time/current and earlier data.
|
| 226 |
+
# build_route_context returns the raw 647-feature vector; the loader applies
|
| 227 |
+
# the released train-only route normalization automatically.
|
| 228 |
+
context = build_route_context(
|
| 229 |
+
synoptic_features, system_features, interaction_features,
|
| 230 |
+
geography_features, kinematic_features, base_route_100km,
|
| 231 |
+
)
|
| 232 |
+
base_position = build_base_position(base_route_100km)
|
| 233 |
route = model.predict_route(field, context, base_position)
|
| 234 |
intensity = model.predict_intensity(causal_features, anchor_structure)
|
| 235 |
+
|
| 236 |
latitude, longitude = local_position_to_latlon(
|
| 237 |
route["position_100km"], issue_latitude, issue_longitude
|
| 238 |
)
|
| 239 |
```
|
| 240 |
|
| 241 |
+
`Trackformer12.from_pretrained()` can also download the same files from the
|
| 242 |
+
[Hugging Face model repository](https://huggingface.co/euler314/typhoon-predict)
|
| 243 |
+
when `model_root` is omitted:
|
| 244 |
+
|
| 245 |
+
```python
|
| 246 |
+
from trackformer_1_2 import Trackformer12
|
| 247 |
+
model = Trackformer12.from_pretrained(device="cuda")
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
The exact public tensor contract is:
|
| 251 |
+
|
| 252 |
+
| API input | Shape | Meaning |
|
| 253 |
+
|---|---:|---|
|
| 254 |
+
| `field` | `[B, 6, 25, 61]` | normalized SLP/H500 grids ordered as current, -12 h, -24 h pairs |
|
| 255 |
+
| `context` | `[B, 647]` | causal whole-Pacific context used by the released route checkpoint |
|
| 256 |
+
| `base_position` | `[B, 20, 2]` | cumulative local 100-km displacement before route correction |
|
| 257 |
+
| `causal_features` | `[B, 1020]` | exact pre-residual causal structure features |
|
| 258 |
+
| `anchor_structure` | `[B, 20, 15]` | frozen causal anchor: vmax, pressure, RMW, R34/R50/R64 quadrants |
|
| 259 |
+
| `ocean_features` | `[B, 66]` | current/-12 h/-24 h OHC/D26/D20 summary for the optional calibration |
|
| 260 |
+
|
| 261 |
+
### Published Feature Constructors
|
| 262 |
+
|
| 263 |
+
The constructors below are the supported bridge from causal source arrays to
|
| 264 |
+
the tensor contract. Every time axis is explicitly retrospective: route
|
| 265 |
+
analysis frames are `t0, t-6 h, t-12 h`; structure patches are `t0, t-12 h,
|
| 266 |
+
t-24 h`; and labels after the issue time are never accepted as inputs.
|
| 267 |
+
|
| 268 |
+
| Constructor | Output | Purpose |
|
| 269 |
+
|---|---:|---|
|
| 270 |
+
| `prepare_route_field(slp, hgt500)` | `[B,6,25,61]` | normalize physical PRMSL/H500 analysis grids |
|
| 271 |
+
| `build_synoptic_features(...)` | `[B,270]` | causal low-center and 500-hPa ridge descriptors |
|
| 272 |
+
| `build_route_system_features(...)` | `[B,46]` | causal Pacific-High, steering, and local analysis context |
|
| 273 |
+
| `build_nearby_interaction_features(...)` | `[B,16]` | causal nearby observed-storm interaction context |
|
| 274 |
+
| `build_route_geography_features(...)` | `[B,224]` | land, coast, buffer, and terrain values along a route |
|
| 275 |
+
| `build_route_kinematic_features(...)` | `[B,11]` | issue-time position, heading, speed, turn, and acceleration |
|
| 276 |
+
| `build_route_context(...)` | `[B,647]` | concatenate the exact route context |
|
| 277 |
+
| `build_causal_structure_features(...)` | `[B,1020]` | construct the full wind/pressure/RMW/radius feature vector |
|
| 278 |
+
| `build_intensity_context_features(...)` | `[B,183]` | concatenate basin, nearby-system, and global context |
|
| 279 |
+
| `build_ocean_features(summary)` | `[B,66]` | flatten current/-12 h/-24 h 22-value ocean summaries |
|
| 280 |
+
| `build_terrain_samples(...)` | `[B,168]` | six causal land/sea samples used by structure |
|
| 281 |
+
|
| 282 |
+
The model bundle also contains `trackformer_1_2_route_context_stats.npz`,
|
| 283 |
+
`trackformer_1_2_track_stats.npz`, and
|
| 284 |
+
`trackformer_1_2_system_context_stats.npz`. `Trackformer12.predict_route`
|
| 285 |
+
applies the route normalization automatically when passed the raw output of
|
| 286 |
+
`build_route_context`.
|
| 287 |
+
|
| 288 |
+
For example, the route-side construction is:
|
| 289 |
+
|
| 290 |
+
```python
|
| 291 |
+
stats = model.system_context_stats
|
| 292 |
+
system = build_route_system_features(
|
| 293 |
+
ncep_current_7ch, ncep_previous_7ch, ncep_lat, ncep_lon,
|
| 294 |
+
issue_latitude, issue_longitude, feature_mean=stats["system_mean"],
|
| 295 |
+
feature_std=stats["system_std"],
|
| 296 |
+
)
|
| 297 |
+
interaction = build_nearby_interaction_features(
|
| 298 |
+
nearby_latitude, nearby_longitude, nearby_vmax, nearby_age_hours,
|
| 299 |
+
issue_latitude, issue_longitude,
|
| 300 |
+
feature_mean=stats["interaction_mean"],
|
| 301 |
+
feature_std=stats["interaction_std"],
|
| 302 |
+
)
|
| 303 |
+
base_position = build_base_position(base_route_100km)
|
| 304 |
+
synoptic = build_synoptic_features(
|
| 305 |
+
slp_t0_tminus6_tminus12, h500_t0_tminus6_tminus12,
|
| 306 |
+
pressure_lat, pressure_lon, issue_latitude, issue_longitude,
|
| 307 |
+
)
|
| 308 |
+
geography = build_route_geography_features(
|
| 309 |
+
base_position, issue_latitude, issue_longitude,
|
| 310 |
+
terrain_lat, terrain_lon, terrain_features, terrain_feature_names,
|
| 311 |
+
)
|
| 312 |
+
kinematic = build_route_kinematic_features(
|
| 313 |
+
current_motion_100km, previous_motion_100km,
|
| 314 |
+
issue_latitude, issue_longitude,
|
| 315 |
+
)
|
| 316 |
+
context = build_route_context(
|
| 317 |
+
synoptic, system, interaction, geography, kinematic, base_route_100km,
|
| 318 |
+
)
|
| 319 |
+
route = model.predict_route(field, context, base_position)
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
For intensity, call `build_causal_structure_features(...)` with the three
|
| 323 |
+
decoded DLM4 analysis patches, three SST patches, the six-point terrain sample,
|
| 324 |
+
and the 183-feature result of `build_intensity_context_features(...)`. Pass
|
| 325 |
+
`model.track_mean` and `model.track_std` so the physical observed track is
|
| 326 |
+
encoded exactly. Then call `model.predict_intensity(features, anchor)`. The
|
| 327 |
+
`build_causal_anchor_structure(observed_structure)` helper is a causal
|
| 328 |
+
persistence/trend fallback only; it is not the frozen incumbent anchor and
|
| 329 |
+
must be labeled as such in a benchmark.
|
| 330 |
+
|
| 331 |
+
Two trained inputs are frozen upstream members rather than standalone public
|
| 332 |
+
neural heads: the route model's incumbent route and the intensity model's
|
| 333 |
+
20-lead structure anchor. If those exact causal arrays are available, pass
|
| 334 |
+
them directly. For a fully causal smoke run without them,
|
| 335 |
+
`build_kinematic_base_position` and `build_causal_anchor_structure` provide
|
| 336 |
+
explicit persistence/trend fallbacks. They are not presented as reproducing
|
| 337 |
+
the hidden incumbent members and should be labeled as fallback inputs in any
|
| 338 |
+
benchmark.
|
| 339 |
+
|
| 340 |
+
Use `prepare_route_field(slp, hgt500, ...)` when the three SLP and 500-hPa
|
| 341 |
+
height grids are still in physical units. Use
|
| 342 |
+
`examples/predict_trackformer_1_2.py` to run an `.npz` issue packet:
|
| 343 |
+
|
| 344 |
+
```bash
|
| 345 |
+
python examples/predict_trackformer_1_2.py \
|
| 346 |
+
--input issue_packet.npz \
|
| 347 |
+
--output forecast.npz \
|
| 348 |
+
--model-root /path/to/models/trackformer_1_2
|
| 349 |
+
```
|
| 350 |
+
|
| 351 |
+
The optional `predict_ocean_structure(...)` method returns the separately
|
| 352 |
+
validated causal OHC/D26/D20 calibration around the frozen 1.2.26 anchor. It
|
| 353 |
+
is intentionally returned as a separate result and is not silently stacked
|
| 354 |
+
on the neural intensity residual head; stacking them would be a new,
|
| 355 |
+
unvalidated model. The wrapper does not include a raw-data downloader because
|
| 356 |
+
the released feature tensors require source-specific preprocessing and
|
| 357 |
+
quality/availability masks. This keeps the issue-time boundary auditable and
|
| 358 |
+
prevents future or official forecast fields from entering by accident.
|
| 359 |
+
|
| 360 |
+
## Historical Releases
|
| 361 |
+
|
| 362 |
+
[Trackformer 1.1](https://github.com/yu314-coder/typhoon-predict/releases/tag/trackformer-1.1)
|
| 363 |
+
remains available as a historical baseline. It is not mixed into the
|
| 364 |
+
Trackformer 1.2 weights or ensemble.
|
| 365 |
|
| 366 |
## Limitations
|
| 367 |
|
| 368 |
+
Forecast error varies by storm, basin, analysis source, storm structure, land
|
| 369 |
+
interaction, and missing-data pattern. Radius labels are incomplete for some
|
| 370 |
+
historical storms and are masked during training. The model does not provide
|
| 371 |
+
calibrated operational warnings. Use official meteorological agencies for
|
| 372 |
+
real-world forecasts and warnings.
|
| 373 |
+
|
| 374 |
+
## License
|
| 375 |
+
|
| 376 |
+
Code and compact artifacts are released under the repository MIT license.
|
| 377 |
+
Upstream datasets remain subject to their own terms and attribution
|
| 378 |
+
requirements.
|
models/trackformer_1_2/manifest.json
CHANGED
|
@@ -54,7 +54,10 @@
|
|
| 54 |
"trackformer_1_2_intensity_seed0.pt",
|
| 55 |
"trackformer_1_2_intensity_seed1.pt",
|
| 56 |
"trackformer_1_2_ocean_structure.joblib",
|
| 57 |
-
"trackformer_1_2_feature_stats.npz"
|
|
|
|
|
|
|
|
|
|
| 58 |
],
|
| 59 |
"formats": {
|
| 60 |
"neural_checkpoints": "native PyTorch state dictionaries",
|
|
|
|
| 54 |
"trackformer_1_2_intensity_seed0.pt",
|
| 55 |
"trackformer_1_2_intensity_seed1.pt",
|
| 56 |
"trackformer_1_2_ocean_structure.joblib",
|
| 57 |
+
"trackformer_1_2_feature_stats.npz",
|
| 58 |
+
"trackformer_1_2_route_context_stats.npz",
|
| 59 |
+
"trackformer_1_2_track_stats.npz",
|
| 60 |
+
"trackformer_1_2_system_context_stats.npz"
|
| 61 |
],
|
| 62 |
"formats": {
|
| 63 |
"neural_checkpoints": "native PyTorch state dictionaries",
|
models/trackformer_1_2/trackformer_1_2_route_context_stats.npz
ADDED
|
Binary file (5.42 kB). View file
|
|
|
models/trackformer_1_2/trackformer_1_2_system_context_stats.npz
ADDED
|
Binary file (1.34 kB). View file
|
|
|
models/trackformer_1_2/trackformer_1_2_track_stats.npz
ADDED
|
Binary file (856 Bytes). View file
|
|
|
trackformer_1_2.py
CHANGED
|
@@ -26,6 +26,7 @@ from typing import Any, Iterable
|
|
| 26 |
import numpy as np
|
| 27 |
import torch
|
| 28 |
import torch.nn as nn
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
LEADS = 20
|
|
@@ -37,6 +38,13 @@ INTENSITY_INPUT_DIM = 1320
|
|
| 37 |
OCEAN_FEATURE_DIM = 66
|
| 38 |
FIELD_HEIGHT = 25
|
| 39 |
FIELD_WIDTH = 61
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def _select_device(value: str | torch.device | None) -> torch.device:
|
|
@@ -100,6 +108,535 @@ def prepare_route_field(
|
|
| 100 |
return field
|
| 101 |
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
def local_position_to_latlon(
|
| 104 |
position_100km: np.ndarray,
|
| 105 |
issue_latitude: np.ndarray | float,
|
|
@@ -123,6 +660,217 @@ def local_position_to_latlon(
|
|
| 123 |
return latitude.astype("float32"), np.mod(longitude, 360.0).astype("float32")
|
| 124 |
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
def _structure_transform(value: np.ndarray) -> np.ndarray:
|
| 127 |
value = np.asarray(value, dtype="float32")
|
| 128 |
result = np.zeros_like(value, dtype="float32")
|
|
@@ -239,6 +987,28 @@ class Trackformer12:
|
|
| 239 |
with np.load(stats_path, allow_pickle=False) as stats:
|
| 240 |
self.feature_mean = stats["feature_mean"].astype("float32")
|
| 241 |
self.feature_std = np.maximum(stats["feature_std"].astype("float32"), 1.0e-4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
self.route_members = self._load_route_members()
|
| 243 |
self.intensity_members = self._load_intensity_members()
|
| 244 |
ocean_path = self.model_root / "trackformer_1_2_ocean_structure.joblib"
|
|
@@ -298,12 +1068,20 @@ class Trackformer12:
|
|
| 298 |
return members
|
| 299 |
|
| 300 |
@torch.no_grad()
|
| 301 |
-
def predict_route(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
"""Predict the 20-lead route from issue-time causal route tensors.
|
| 303 |
|
| 304 |
``field`` is normalized by :func:`prepare_route_field` and has shape
|
| 305 |
-
``[B, 6, H, W]``; ``context`` is ``[B, 647]``
|
| 306 |
-
is ``[B, 20, 2]``
|
|
|
|
| 307 |
"""
|
| 308 |
field = _batch(field, (6, np.asarray(field).shape[-2], np.asarray(field).shape[-1]), "field")
|
| 309 |
context = _batch(context, (ROUTE_CONTEXT_DIM,), "context")
|
|
@@ -311,6 +1089,10 @@ class Trackformer12:
|
|
| 311 |
if field.shape[-2:] != (FIELD_HEIGHT, FIELD_WIDTH):
|
| 312 |
raise ValueError(f"field must be the released [25, 61] Pacific grid, got {field.shape[-2:]}")
|
| 313 |
_same_batch(field, context, base_position)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
positions: list[np.ndarray] = []
|
| 315 |
land: list[np.ndarray] = []
|
| 316 |
for start in range(0, len(field), batch_size):
|
|
@@ -401,7 +1183,10 @@ class Trackformer12:
|
|
| 401 |
"""
|
| 402 |
result: dict[str, Any] = {}
|
| 403 |
if {"field", "context", "base_position"}.issubset(packet):
|
| 404 |
-
result["route"] = self.predict_route(
|
|
|
|
|
|
|
|
|
|
| 405 |
if {"causal_features", "anchor_structure"}.issubset(packet):
|
| 406 |
result["intensity"] = self.predict_intensity(packet["causal_features"], packet["anchor_structure"])
|
| 407 |
if "ocean_features" in packet:
|
|
@@ -414,5 +1199,10 @@ class Trackformer12:
|
|
| 414 |
__all__ = [
|
| 415 |
"FIELD_HEIGHT", "FIELD_WIDTH", "INTENSITY_FEATURE_DIM", "INTENSITY_INPUT_DIM", "LEADS", "LEAD_HOURS",
|
| 416 |
"OCEAN_FEATURE_DIM", "ROUTE_CONTEXT_DIM", "STRUCTURE_DIM", "Trackformer12",
|
| 417 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
]
|
|
|
|
| 26 |
import numpy as np
|
| 27 |
import torch
|
| 28 |
import torch.nn as nn
|
| 29 |
+
from scipy.ndimage import maximum_filter, minimum_filter
|
| 30 |
|
| 31 |
|
| 32 |
LEADS = 20
|
|
|
|
| 38 |
OCEAN_FEATURE_DIM = 66
|
| 39 |
FIELD_HEIGHT = 25
|
| 40 |
FIELD_WIDTH = 61
|
| 41 |
+
ROUTE_SYNOPTIC_DIM = 270
|
| 42 |
+
ROUTE_SYSTEM_DIM = 46
|
| 43 |
+
ROUTE_INTERACTION_DIM = 16
|
| 44 |
+
ROUTE_GEOGRAPHY_DIM = 224
|
| 45 |
+
ROUTE_KINEMATIC_DIM = 11
|
| 46 |
+
TRACK_WINDOW_LENGTH = 9
|
| 47 |
+
TRACK_FEATURE_DIM = 54
|
| 48 |
|
| 49 |
|
| 50 |
def _select_device(value: str | torch.device | None) -> torch.device:
|
|
|
|
| 108 |
return field
|
| 109 |
|
| 110 |
|
| 111 |
+
def build_base_position(base_route_100km: np.ndarray) -> np.ndarray:
|
| 112 |
+
"""Convert per-lead local route increments to cumulative positions.
|
| 113 |
+
|
| 114 |
+
The released route checkpoint was trained around a frozen incumbent route.
|
| 115 |
+
Pass those causal per-lead increments here when reproducing that exact
|
| 116 |
+
route pipeline; the function does not infer a route from future labels.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
route = _batch(base_route_100km, (LEADS, 2), "base_route_100km")
|
| 120 |
+
return np.cumsum(route, axis=1).astype("float32")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def build_kinematic_base_position(
|
| 124 |
+
current_motion_100km: np.ndarray,
|
| 125 |
+
previous_motion_100km: np.ndarray | None = None,
|
| 126 |
+
) -> np.ndarray:
|
| 127 |
+
"""Build a causal persistence base route when no incumbent route is available.
|
| 128 |
+
|
| 129 |
+
``current_motion_100km`` is the observed six-hour local displacement. The
|
| 130 |
+
optional previous displacement is accepted for auditability, but the
|
| 131 |
+
fallback deliberately persists the current motion rather than pretending
|
| 132 |
+
to reproduce the private incumbent route used during training.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
current = _batch(current_motion_100km, (2,), "current_motion_100km")
|
| 136 |
+
if previous_motion_100km is not None:
|
| 137 |
+
previous = _batch(previous_motion_100km, (2,), "previous_motion_100km")
|
| 138 |
+
_same_batch(current, previous)
|
| 139 |
+
increments = np.repeat(current[:, None, :], LEADS, axis=1)
|
| 140 |
+
return build_base_position(increments)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def normalize_route_context(
|
| 144 |
+
context: np.ndarray,
|
| 145 |
+
feature_mean: np.ndarray,
|
| 146 |
+
feature_std: np.ndarray,
|
| 147 |
+
) -> np.ndarray:
|
| 148 |
+
"""Apply the train-only normalization used by the route checkpoint."""
|
| 149 |
+
|
| 150 |
+
value = _batch(context, (ROUTE_CONTEXT_DIM,), "context")
|
| 151 |
+
mean = np.asarray(feature_mean, dtype="float32").reshape(-1)
|
| 152 |
+
std = np.maximum(np.asarray(feature_std, dtype="float32").reshape(-1), 1.0e-4)
|
| 153 |
+
if mean.shape != (ROUTE_CONTEXT_DIM,) or std.shape != (ROUTE_CONTEXT_DIM,):
|
| 154 |
+
raise ValueError("route context statistics must each have shape [647]")
|
| 155 |
+
return ((value - mean[None, :]) / std[None, :]).astype("float32")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _nearest_static(
|
| 159 |
+
static_map: np.ndarray,
|
| 160 |
+
latitude_grid: np.ndarray,
|
| 161 |
+
longitude_grid: np.ndarray,
|
| 162 |
+
latitude: np.ndarray,
|
| 163 |
+
longitude: np.ndarray,
|
| 164 |
+
) -> np.ndarray:
|
| 165 |
+
fields = np.asarray(static_map, dtype="float32")
|
| 166 |
+
lat_grid = np.asarray(latitude_grid, dtype="float32").reshape(-1)
|
| 167 |
+
lon_grid = np.asarray(longitude_grid, dtype="float32").reshape(-1)
|
| 168 |
+
lat = np.asarray(latitude, dtype="float32").reshape(-1)
|
| 169 |
+
lon = np.mod(np.asarray(longitude, dtype="float32").reshape(-1), 360.0)
|
| 170 |
+
iy = np.clip(np.searchsorted(lat_grid, lat), 1, len(lat_grid) - 1)
|
| 171 |
+
iy = np.where(np.abs(lat_grid[iy - 1] - lat) <= np.abs(lat_grid[iy] - lat), iy - 1, iy)
|
| 172 |
+
ix = np.clip(np.searchsorted(lon_grid, lon), 1, len(lon_grid) - 1)
|
| 173 |
+
ix = np.where(np.abs(lon_grid[ix - 1] - lon) <= np.abs(lon_grid[ix] - lon), ix - 1, ix)
|
| 174 |
+
return fields[:, iy, ix].T.astype("float32")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def build_route_geography_features(
|
| 178 |
+
route_position_100km: np.ndarray,
|
| 179 |
+
issue_latitude: np.ndarray | float,
|
| 180 |
+
issue_longitude: np.ndarray | float,
|
| 181 |
+
latitude_grid: np.ndarray,
|
| 182 |
+
longitude_grid: np.ndarray,
|
| 183 |
+
static_map: np.ndarray,
|
| 184 |
+
feature_names: Iterable[str] | None = None,
|
| 185 |
+
) -> np.ndarray:
|
| 186 |
+
"""Construct the exact 224-feature static route geography block.
|
| 187 |
+
|
| 188 |
+
``static_map`` is ``[C,H,W]``. When all 28 release channels are passed,
|
| 189 |
+
``feature_names`` must name them; an eight-channel map may be passed in
|
| 190 |
+
the trained order listed in ``ROUTE_GEOGRAPHY_CHANNELS``.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
position = _batch(route_position_100km, (LEADS, 2), "route_position_100km")
|
| 194 |
+
lat0 = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 195 |
+
lon0 = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 196 |
+
if len(lat0) == 1 and len(position) > 1:
|
| 197 |
+
lat0 = np.repeat(lat0, len(position))
|
| 198 |
+
if len(lon0) == 1 and len(position) > 1:
|
| 199 |
+
lon0 = np.repeat(lon0, len(position))
|
| 200 |
+
_same_batch(position, lat0[:, None], lon0[:, None])
|
| 201 |
+
names = list(feature_names) if feature_names is not None else None
|
| 202 |
+
selected_names = (
|
| 203 |
+
"land_fraction", "coast_proximity", "land_fraction_75km",
|
| 204 |
+
"land_fraction_150km", "land_fraction_300km", "land_buffer_25km",
|
| 205 |
+
"land_buffer_50km", "land_local_std_150km",
|
| 206 |
+
)
|
| 207 |
+
static = np.asarray(static_map, dtype="float32")
|
| 208 |
+
if static.ndim != 3:
|
| 209 |
+
raise ValueError("static_map must have shape [channels, latitude, longitude]")
|
| 210 |
+
if names is None:
|
| 211 |
+
if static.shape[0] != len(selected_names):
|
| 212 |
+
raise ValueError("feature_names is required when static_map is not the eight-channel trained subset")
|
| 213 |
+
selected = static
|
| 214 |
+
else:
|
| 215 |
+
indices = []
|
| 216 |
+
for name in selected_names:
|
| 217 |
+
if name not in names:
|
| 218 |
+
raise ValueError(f"static_map is missing required channel {name!r}")
|
| 219 |
+
indices.append(names.index(name))
|
| 220 |
+
selected = static[np.asarray(indices, dtype="int64")]
|
| 221 |
+
route_lat = lat0[:, None] + position[..., 1] * 100.0 / 111.0
|
| 222 |
+
route_lon = lon0[:, None] + position[..., 0] * 100.0 / (
|
| 223 |
+
111.0 * np.maximum(np.cos(np.deg2rad(route_lat)), 0.2)
|
| 224 |
+
)
|
| 225 |
+
route = _nearest_static(
|
| 226 |
+
selected, latitude_grid, longitude_grid,
|
| 227 |
+
route_lat.reshape(-1), route_lon.reshape(-1),
|
| 228 |
+
).reshape(len(position), LEADS, len(selected_names))
|
| 229 |
+
delta = np.diff(route, axis=1)
|
| 230 |
+
summary = np.concatenate([
|
| 231 |
+
route[:, 0], route[:, -1], route.mean(axis=1), route.max(axis=1),
|
| 232 |
+
route.min(axis=1), route[:, -1] - route[:, 0],
|
| 233 |
+
delta.mean(axis=1), delta[:, -1],
|
| 234 |
+
], axis=1)
|
| 235 |
+
output = np.concatenate([route.reshape(len(position), -1), summary], axis=1)
|
| 236 |
+
if output.shape[1] != ROUTE_GEOGRAPHY_DIM:
|
| 237 |
+
raise RuntimeError(f"route geography builder produced {output.shape[1]} features, expected 224")
|
| 238 |
+
return np.nan_to_num(output, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def build_route_kinematic_features(
|
| 242 |
+
current_motion_100km: np.ndarray,
|
| 243 |
+
previous_motion_100km: np.ndarray,
|
| 244 |
+
issue_latitude: np.ndarray | float,
|
| 245 |
+
issue_longitude: np.ndarray | float,
|
| 246 |
+
) -> np.ndarray:
|
| 247 |
+
"""Construct the exact 11-feature issue-time motion block."""
|
| 248 |
+
|
| 249 |
+
current = _batch(current_motion_100km, (2,), "current_motion_100km")
|
| 250 |
+
previous = _batch(previous_motion_100km, (2,), "previous_motion_100km")
|
| 251 |
+
lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 252 |
+
lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 253 |
+
if len(lat) == 1 and len(current) > 1:
|
| 254 |
+
lat = np.repeat(lat, len(current))
|
| 255 |
+
if len(lon) == 1 and len(current) > 1:
|
| 256 |
+
lon = np.repeat(lon, len(current))
|
| 257 |
+
_same_batch(current, previous, lat[:, None], lon[:, None])
|
| 258 |
+
speed = np.linalg.norm(current, axis=1)
|
| 259 |
+
turn = np.arctan2(
|
| 260 |
+
current[:, 0] * previous[:, 1] - current[:, 1] * previous[:, 0],
|
| 261 |
+
(current * previous).sum(axis=1) + 1.0e-4,
|
| 262 |
+
)
|
| 263 |
+
return np.stack([
|
| 264 |
+
lat / 30.0, np.mod(lon, 360.0) / 180.0,
|
| 265 |
+
np.sin(np.deg2rad(lat)), np.cos(np.deg2rad(lat)),
|
| 266 |
+
current[:, 0] / 30.0, current[:, 1] / 30.0, speed / 30.0,
|
| 267 |
+
np.sin(turn), np.cos(turn),
|
| 268 |
+
(current[:, 0] - previous[:, 0]) / 30.0,
|
| 269 |
+
(current[:, 1] - previous[:, 1]) / 30.0,
|
| 270 |
+
], axis=1).astype("float32")
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def build_route_context(
|
| 274 |
+
synoptic_features: np.ndarray,
|
| 275 |
+
system_features: np.ndarray,
|
| 276 |
+
interaction_features: np.ndarray,
|
| 277 |
+
geography_features: np.ndarray,
|
| 278 |
+
kinematic_features: np.ndarray,
|
| 279 |
+
base_route_100km: np.ndarray,
|
| 280 |
+
base_position_100km: np.ndarray | None = None,
|
| 281 |
+
) -> np.ndarray:
|
| 282 |
+
"""Concatenate the exact causal 647-feature route context.
|
| 283 |
+
|
| 284 |
+
All components are issue-time features. ``base_route_100km`` is the
|
| 285 |
+
causal incumbent-route input; it is not an official forecast product.
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
synoptic = _batch(synoptic_features, (ROUTE_SYNOPTIC_DIM,), "synoptic_features")
|
| 289 |
+
system = _batch(system_features, (ROUTE_SYSTEM_DIM,), "system_features")
|
| 290 |
+
interaction = _batch(interaction_features, (ROUTE_INTERACTION_DIM,), "interaction_features")
|
| 291 |
+
geography = _batch(geography_features, (ROUTE_GEOGRAPHY_DIM,), "geography_features")
|
| 292 |
+
kinematic = _batch(kinematic_features, (ROUTE_KINEMATIC_DIM,), "kinematic_features")
|
| 293 |
+
route = _batch(base_route_100km, (LEADS, 2), "base_route_100km")
|
| 294 |
+
position = build_base_position(route) if base_position_100km is None else _batch(base_position_100km, (LEADS, 2), "base_position_100km")
|
| 295 |
+
_same_batch(synoptic, system, interaction, geography, kinematic, route, position)
|
| 296 |
+
context = np.concatenate([
|
| 297 |
+
synoptic, system, interaction, geography, kinematic,
|
| 298 |
+
route.reshape(len(route), -1), position.reshape(len(position), -1),
|
| 299 |
+
], axis=1)
|
| 300 |
+
if context.shape[1] != ROUTE_CONTEXT_DIM:
|
| 301 |
+
raise RuntimeError(f"route context builder produced {context.shape[1]} features, expected 647")
|
| 302 |
+
return np.nan_to_num(context, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _grid_distance(
|
| 306 |
+
base_latitude: np.ndarray,
|
| 307 |
+
base_longitude: np.ndarray,
|
| 308 |
+
latitude: np.ndarray,
|
| 309 |
+
longitude: np.ndarray,
|
| 310 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 311 |
+
lat = np.asarray(latitude, dtype="float32")[None, :, None]
|
| 312 |
+
lon = np.asarray(longitude, dtype="float32")[None, None, :]
|
| 313 |
+
center_lat = np.asarray(base_latitude, dtype="float32")[:, None, None]
|
| 314 |
+
center_lon = np.asarray(base_longitude, dtype="float32")[:, None, None]
|
| 315 |
+
dy = np.broadcast_to((lat - center_lat) * 111.2, (len(center_lat), len(latitude), len(longitude)))
|
| 316 |
+
delta_lon = (lon - center_lon + 180.0) % 360.0 - 180.0
|
| 317 |
+
dx = delta_lon * 111.2 * np.cos(np.deg2rad((lat + center_lat) * 0.5))
|
| 318 |
+
return dx.astype("float32"), dy.astype("float32"), np.hypot(dx, dy).astype("float32")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _synoptic_extrema(
|
| 322 |
+
field: np.ndarray,
|
| 323 |
+
base_latitude: np.ndarray,
|
| 324 |
+
base_longitude: np.ndarray,
|
| 325 |
+
latitude: np.ndarray,
|
| 326 |
+
longitude: np.ndarray,
|
| 327 |
+
kind: str,
|
| 328 |
+
) -> np.ndarray:
|
| 329 |
+
dx, dy, distance = _grid_distance(base_latitude, base_longitude, latitude, longitude)
|
| 330 |
+
if kind == "low":
|
| 331 |
+
local = minimum_filter(field, size=(1, 5, 5), mode="nearest")
|
| 332 |
+
background = maximum_filter(field, size=(1, 9, 9), mode="nearest")
|
| 333 |
+
strength = background - field
|
| 334 |
+
candidate = (
|
| 335 |
+
(np.abs(field - local) <= 0.26) & (strength >= 0.75)
|
| 336 |
+
& (distance >= 450.0) & (distance <= 2200.0)
|
| 337 |
+
& (np.asarray(latitude)[None, :, None] >= 0.0)
|
| 338 |
+
& (np.asarray(latitude)[None, :, None] <= 60.0)
|
| 339 |
+
)
|
| 340 |
+
value_scale, strength_scale = 1000.0, 10.0
|
| 341 |
+
elif kind == "ridge":
|
| 342 |
+
local = maximum_filter(field, size=(1, 7, 7), mode="nearest")
|
| 343 |
+
background = minimum_filter(field, size=(1, 11, 11), mode="nearest")
|
| 344 |
+
strength = field - background
|
| 345 |
+
candidate = (
|
| 346 |
+
(np.abs(field - local) <= 10.0) & (strength >= 18.0)
|
| 347 |
+
& (distance >= 450.0) & (distance <= 2600.0)
|
| 348 |
+
& (np.asarray(latitude)[None, :, None] >= 10.0)
|
| 349 |
+
& (np.asarray(latitude)[None, :, None] <= 45.0)
|
| 350 |
+
& (np.asarray(longitude)[None, None, :] >= 115.0)
|
| 351 |
+
& (np.asarray(longitude)[None, None, :] <= 205.0)
|
| 352 |
+
)
|
| 353 |
+
value_scale, strength_scale = 1000.0, 1000.0
|
| 354 |
+
else:
|
| 355 |
+
raise ValueError("kind must be 'low' or 'ridge'")
|
| 356 |
+
score = np.where(candidate, strength, -np.inf).reshape(len(field), -1)
|
| 357 |
+
top_index = np.argpartition(score, -3, axis=1)[:, -3:]
|
| 358 |
+
top_score = np.take_along_axis(score, top_index, axis=1)
|
| 359 |
+
order = np.argsort(-top_score, axis=1)
|
| 360 |
+
top_index = np.take_along_axis(top_index, order, axis=1)
|
| 361 |
+
top_score = np.take_along_axis(top_score, order, axis=1)
|
| 362 |
+
row = np.arange(len(field))[:, None]
|
| 363 |
+
iy, ix = np.divmod(top_index, field.shape[-1])
|
| 364 |
+
picked_dx = dx[row, iy, ix]
|
| 365 |
+
picked_dy = dy[row, iy, ix]
|
| 366 |
+
picked_distance = distance[row, iy, ix]
|
| 367 |
+
picked_value = field[row, iy, ix]
|
| 368 |
+
valid = np.isfinite(top_score).astype("float32")
|
| 369 |
+
angle = np.arctan2(picked_dy, picked_dx)
|
| 370 |
+
counts = np.stack([
|
| 371 |
+
np.sum(candidate & (distance <= 750.0), axis=(1, 2)),
|
| 372 |
+
np.sum(candidate & (distance <= 1250.0), axis=(1, 2)),
|
| 373 |
+
np.sum(candidate & (distance <= 1750.0), axis=(1, 2)),
|
| 374 |
+
], axis=1).astype("float32")
|
| 375 |
+
values = np.stack([
|
| 376 |
+
valid, picked_dx / 1000.0, picked_dy / 1000.0,
|
| 377 |
+
picked_distance / 1000.0,
|
| 378 |
+
np.nan_to_num(top_score, nan=0.0, posinf=0.0, neginf=0.0) / strength_scale,
|
| 379 |
+
picked_value / value_scale,
|
| 380 |
+
np.sin(angle) * valid, np.cos(angle) * valid,
|
| 381 |
+
], axis=-1)
|
| 382 |
+
return np.concatenate([values.reshape(len(field), -1), counts], axis=1).astype("float32")
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def build_synoptic_features(
|
| 386 |
+
slp: np.ndarray,
|
| 387 |
+
hgt500: np.ndarray,
|
| 388 |
+
latitude: np.ndarray,
|
| 389 |
+
longitude: np.ndarray,
|
| 390 |
+
issue_latitude: np.ndarray | float,
|
| 391 |
+
issue_longitude: np.ndarray | float,
|
| 392 |
+
valid: np.ndarray | None = None,
|
| 393 |
+
) -> np.ndarray:
|
| 394 |
+
"""Build the exact 270-feature causal low/ridge catalog.
|
| 395 |
+
|
| 396 |
+
The three frames must be ordered ``t0, t-6h, t-12h``. The function uses
|
| 397 |
+
only the supplied analysis fields and never reads a positive-lead product.
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
slp = np.asarray(slp, dtype="float32")
|
| 401 |
+
hgt500 = np.asarray(hgt500, dtype="float32")
|
| 402 |
+
if slp.ndim == 3:
|
| 403 |
+
slp = slp[None, ...]
|
| 404 |
+
if hgt500.ndim == 3:
|
| 405 |
+
hgt500 = hgt500[None, ...]
|
| 406 |
+
if slp.ndim != 4 or hgt500.shape != slp.shape or slp.shape[1] != 3:
|
| 407 |
+
raise ValueError("slp and hgt500 must both have shape [B, 3, H, W]")
|
| 408 |
+
lat = np.asarray(latitude, dtype="float32").reshape(-1)
|
| 409 |
+
lon = np.asarray(longitude, dtype="float32").reshape(-1)
|
| 410 |
+
if slp.shape[-2:] != (len(lat), len(lon)):
|
| 411 |
+
raise ValueError("analysis field shape does not match latitude/longitude grids")
|
| 412 |
+
base_lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 413 |
+
base_lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 414 |
+
if len(base_lat) == 1 and len(slp) > 1:
|
| 415 |
+
base_lat = np.repeat(base_lat, len(slp))
|
| 416 |
+
if len(base_lon) == 1 and len(slp) > 1:
|
| 417 |
+
base_lon = np.repeat(base_lon, len(slp))
|
| 418 |
+
_same_batch(slp, hgt500, base_lat[:, None], base_lon[:, None])
|
| 419 |
+
frame_valid = np.ones((len(slp), 3), dtype="float32") if valid is None else np.asarray(valid, dtype="float32").reshape(len(slp), 3)
|
| 420 |
+
parts: list[np.ndarray] = []
|
| 421 |
+
for values, kind in ((slp, "low"), (hgt500, "ridge")):
|
| 422 |
+
frames = []
|
| 423 |
+
for frame in range(3):
|
| 424 |
+
item = _synoptic_extrema(values[:, frame], base_lat, base_lon, lat, lon, kind)
|
| 425 |
+
frames.append(item * frame_valid[:, frame, None])
|
| 426 |
+
stacked = np.stack(frames, axis=1)
|
| 427 |
+
parts.extend([
|
| 428 |
+
stacked.reshape(len(stacked), -1),
|
| 429 |
+
stacked[:, 0] - stacked[:, 1],
|
| 430 |
+
stacked[:, 1] - stacked[:, 2],
|
| 431 |
+
])
|
| 432 |
+
output = np.concatenate(parts, axis=1)
|
| 433 |
+
if output.shape[1] != ROUTE_SYNOPTIC_DIM:
|
| 434 |
+
raise RuntimeError(f"synoptic builder produced {output.shape[1]} features, expected 270")
|
| 435 |
+
return np.nan_to_num(output, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _system_frame_summary(field: np.ndarray, latitude: np.ndarray, longitude: np.ndarray) -> np.ndarray:
|
| 439 |
+
ridge = (latitude[:, None] >= 15.0) & (latitude[:, None] <= 35.0)
|
| 440 |
+
ridge = ridge & (longitude[None, :] >= 130.0) & (longitude[None, :] <= 180.0)
|
| 441 |
+
broad = (latitude[:, None] >= 5.0) & (latitude[:, None] <= 40.0)
|
| 442 |
+
broad = broad & (longitude[None, :] >= 115.0) & (longitude[None, :] <= 180.0)
|
| 443 |
+
hgt = field[0]
|
| 444 |
+
ridge_values = hgt[ridge]
|
| 445 |
+
broad_values = hgt[broad]
|
| 446 |
+
if ridge_values.size:
|
| 447 |
+
baseline = float(np.percentile(ridge_values, 60.0))
|
| 448 |
+
weights = np.maximum(ridge_values - baseline, 0.0) + 1.0e-3
|
| 449 |
+
lat_grid, lon_grid = np.broadcast_arrays(latitude[:, None], longitude[None, :])
|
| 450 |
+
ridge_lat = float(np.average(lat_grid[ridge], weights=weights))
|
| 451 |
+
ridge_lon = float(np.average(lon_grid[ridge], weights=weights))
|
| 452 |
+
else:
|
| 453 |
+
ridge_lat, ridge_lon = 25.0, 155.0
|
| 454 |
+
grad_lat, grad_lon = np.gradient(hgt)
|
| 455 |
+
mean = lambda values, mask: float(values[mask].mean()) if np.any(mask) else 0.0
|
| 456 |
+
std = lambda values, mask: float(values[mask].std()) if np.any(mask) else 0.0
|
| 457 |
+
return np.asarray([
|
| 458 |
+
mean(hgt, ridge), std(hgt, ridge), float(hgt[ridge].max()) if ridge_values.size else 0.0,
|
| 459 |
+
float(hgt[ridge].min()) if ridge_values.size else 0.0, ridge_lat, ridge_lon,
|
| 460 |
+
mean(grad_lat, ridge), mean(grad_lon, ridge),
|
| 461 |
+
mean(field[1], broad), mean(field[2], broad), mean(field[3], broad),
|
| 462 |
+
mean(field[4], broad), mean(field[5], broad), mean(field[6], broad),
|
| 463 |
+
mean(field[3], ridge), mean(field[4], ridge), mean(field[1], ridge),
|
| 464 |
+
mean(field[2], ridge), mean(field[5], ridge), mean(field[6], ridge),
|
| 465 |
+
mean(hgt, broad), std(hgt, broad), float(hgt[broad].max()) if broad_values.size else 0.0,
|
| 466 |
+
float(hgt[broad].min()) if broad_values.size else 0.0,
|
| 467 |
+
], dtype="float32")
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def _normalize_context_block(value: np.ndarray, mean: np.ndarray | None, std: np.ndarray | None) -> np.ndarray:
|
| 471 |
+
output = np.asarray(value, dtype="float32")
|
| 472 |
+
if mean is None and std is None:
|
| 473 |
+
return output
|
| 474 |
+
if mean is None or std is None:
|
| 475 |
+
raise ValueError("context mean and std must be supplied together")
|
| 476 |
+
mean_value = np.asarray(mean, dtype="float32").reshape(1, -1)
|
| 477 |
+
std_value = np.maximum(np.asarray(std, dtype="float32").reshape(1, -1), 1.0e-5)
|
| 478 |
+
if output.shape[1] != mean_value.shape[1]:
|
| 479 |
+
raise ValueError("context statistics do not match the feature block")
|
| 480 |
+
return np.clip((output - mean_value) / std_value, -5.0, 5.0).astype("float32")
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def build_route_system_features(
|
| 484 |
+
analysis_field: np.ndarray,
|
| 485 |
+
previous_analysis_field: np.ndarray,
|
| 486 |
+
latitude: np.ndarray,
|
| 487 |
+
longitude: np.ndarray,
|
| 488 |
+
issue_latitude: np.ndarray | float,
|
| 489 |
+
issue_longitude: np.ndarray | float,
|
| 490 |
+
analysis_age_hours: np.ndarray | float = 0.0,
|
| 491 |
+
valid: np.ndarray | float = 1.0,
|
| 492 |
+
feature_mean: np.ndarray | None = None,
|
| 493 |
+
feature_std: np.ndarray | None = None,
|
| 494 |
+
) -> np.ndarray:
|
| 495 |
+
"""Build the 46-feature causal Pacific-High/system context block."""
|
| 496 |
+
|
| 497 |
+
current = np.asarray(analysis_field, dtype="float32")
|
| 498 |
+
previous = np.asarray(previous_analysis_field, dtype="float32")
|
| 499 |
+
if current.ndim == 3:
|
| 500 |
+
current = current[None, ...]
|
| 501 |
+
if previous.ndim == 3:
|
| 502 |
+
previous = previous[None, ...]
|
| 503 |
+
if current.ndim != 4 or current.shape[1] != 7 or previous.shape != current.shape:
|
| 504 |
+
raise ValueError("analysis fields must both have shape [B, 7, H, W]")
|
| 505 |
+
lat_grid = np.asarray(latitude, dtype="float32").reshape(-1)
|
| 506 |
+
lon_grid = np.asarray(longitude, dtype="float32").reshape(-1)
|
| 507 |
+
if current.shape[-2:] != (len(lat_grid), len(lon_grid)):
|
| 508 |
+
raise ValueError("analysis field shape does not match latitude/longitude grids")
|
| 509 |
+
lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 510 |
+
lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 511 |
+
if len(lat) == 1 and len(current) > 1:
|
| 512 |
+
lat = np.repeat(lat, len(current))
|
| 513 |
+
if len(lon) == 1 and len(current) > 1:
|
| 514 |
+
lon = np.repeat(lon, len(current))
|
| 515 |
+
_same_batch(current, previous, lat[:, None], lon[:, None])
|
| 516 |
+
ages = np.asarray(analysis_age_hours, dtype="float32").reshape(-1)
|
| 517 |
+
flags = np.asarray(valid, dtype="float32").reshape(-1)
|
| 518 |
+
if len(ages) == 1 and len(current) > 1:
|
| 519 |
+
ages = np.repeat(ages, len(current))
|
| 520 |
+
if len(flags) == 1 and len(current) > 1:
|
| 521 |
+
flags = np.repeat(flags, len(current))
|
| 522 |
+
summaries = np.stack([_system_frame_summary(item, lat_grid, lon_grid) for item in current], axis=0)
|
| 523 |
+
previous_summary = np.stack([_system_frame_summary(item, lat_grid, lon_grid) for item in previous], axis=0)
|
| 524 |
+
delta_columns = np.asarray([0, 2, 4, 5, 10, 11, 12, 13], dtype="int64")
|
| 525 |
+
deltas = summaries[:, delta_columns] - previous_summary[:, delta_columns]
|
| 526 |
+
local = []
|
| 527 |
+
for index, item in enumerate(current):
|
| 528 |
+
iy = int(np.argmin(np.abs(lat_grid - lat[index])))
|
| 529 |
+
ix = int(np.argmin(np.abs(lon_grid - lon[index])))
|
| 530 |
+
ridge_lat, ridge_lon = summaries[index, 4], summaries[index, 5]
|
| 531 |
+
grad_lat, grad_lon = np.gradient(item[0])
|
| 532 |
+
local.append(np.asarray([
|
| 533 |
+
*item[:, iy, ix],
|
| 534 |
+
(ridge_lat - lat[index]) * 111.2,
|
| 535 |
+
((ridge_lon - lon[index] + 180.0) % 360.0 - 180.0) * 111.2 * np.cos(np.deg2rad(lat[index])),
|
| 536 |
+
item[0, iy, ix] - summaries[index, 0], grad_lat[iy, ix], grad_lon[iy, ix],
|
| 537 |
+
], dtype="float32"))
|
| 538 |
+
raw = np.concatenate([summaries, deltas, np.stack(local), flags[:, None], np.clip(ages, -1.0, 3.0)[:, None]], axis=1)
|
| 539 |
+
if raw.shape[1] != ROUTE_SYSTEM_DIM:
|
| 540 |
+
raise RuntimeError(f"system builder produced {raw.shape[1]} features, expected 46")
|
| 541 |
+
raw[flags <= 0.0] = 0.0
|
| 542 |
+
return _normalize_context_block(np.nan_to_num(raw, nan=0.0, posinf=0.0, neginf=0.0), feature_mean, feature_std)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def build_nearby_interaction_features(
|
| 546 |
+
nearby_latitude: np.ndarray,
|
| 547 |
+
nearby_longitude: np.ndarray,
|
| 548 |
+
nearby_vmax: np.ndarray,
|
| 549 |
+
nearby_age_hours: np.ndarray,
|
| 550 |
+
issue_latitude: np.ndarray | float,
|
| 551 |
+
issue_longitude: np.ndarray | float,
|
| 552 |
+
feature_mean: np.ndarray | None = None,
|
| 553 |
+
feature_std: np.ndarray | None = None,
|
| 554 |
+
) -> np.ndarray:
|
| 555 |
+
"""Build the 16-feature causal interaction block from other observed storms.
|
| 556 |
+
|
| 557 |
+
The nearby arrays are ``[B,N]`` and must exclude the target storm. Points
|
| 558 |
+
older than six hours or later than the issue time are ignored.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
lat_values = np.asarray(nearby_latitude, dtype="float32")
|
| 562 |
+
lon_values = np.asarray(nearby_longitude, dtype="float32")
|
| 563 |
+
wind_values = np.asarray(nearby_vmax, dtype="float32")
|
| 564 |
+
age_values = np.asarray(nearby_age_hours, dtype="float32")
|
| 565 |
+
if lat_values.ndim == 1:
|
| 566 |
+
lat_values = lat_values[None, :]
|
| 567 |
+
if lon_values.ndim == 1:
|
| 568 |
+
lon_values = lon_values[None, :]
|
| 569 |
+
if wind_values.ndim == 1:
|
| 570 |
+
wind_values = wind_values[None, :]
|
| 571 |
+
if age_values.ndim == 1:
|
| 572 |
+
age_values = age_values[None, :]
|
| 573 |
+
if not (lat_values.shape == lon_values.shape == wind_values.shape == age_values.shape):
|
| 574 |
+
raise ValueError("nearby arrays must have matching shape [B, N]")
|
| 575 |
+
lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 576 |
+
lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 577 |
+
if len(lat) == 1 and len(lat_values) > 1:
|
| 578 |
+
lat = np.repeat(lat, len(lat_values))
|
| 579 |
+
if len(lon) == 1 and len(lon_values) > 1:
|
| 580 |
+
lon = np.repeat(lon, len(lon_values))
|
| 581 |
+
result = np.zeros((len(lat_values), ROUTE_INTERACTION_DIM), dtype="float32")
|
| 582 |
+
for index in range(len(result)):
|
| 583 |
+
active = np.isfinite(lat_values[index]) & np.isfinite(lon_values[index]) & np.isfinite(wind_values[index])
|
| 584 |
+
active &= np.isfinite(age_values[index]) & (age_values[index] >= 0.0) & (age_values[index] <= 6.0)
|
| 585 |
+
if not np.any(active):
|
| 586 |
+
continue
|
| 587 |
+
other_lat = lat_values[index, active].astype("float64")
|
| 588 |
+
other_lon = lon_values[index, active].astype("float64")
|
| 589 |
+
dx = ((other_lon - lon[index] + 180.0) % 360.0 - 180.0) * 111.2 * np.cos(np.deg2rad(lat[index]))
|
| 590 |
+
dy = (other_lat - lat[index]) * 111.2
|
| 591 |
+
distance = np.hypot(dx, dy)
|
| 592 |
+
wind = np.clip(wind_values[index, active], 0.0, 180.0)
|
| 593 |
+
result[index, :4] = [np.count_nonzero(distance <= 200.0), np.count_nonzero(distance <= 500.0), np.count_nonzero(distance <= 1000.0), np.count_nonzero(distance <= 1500.0)]
|
| 594 |
+
nearest = int(np.argmin(distance))
|
| 595 |
+
result[index, 4:8] = [distance[nearest], dx[nearest], dy[nearest], wind[nearest]]
|
| 596 |
+
result[index, 8] = float(wind.max())
|
| 597 |
+
weights = (wind + 10.0) * np.exp(-distance / 600.0)
|
| 598 |
+
total = float(weights.sum())
|
| 599 |
+
if total > 0.0:
|
| 600 |
+
result[index, 9:12] = [(weights * wind).sum() / total, (weights * dx).sum() / total, (weights * dy).sum() / total]
|
| 601 |
+
result[index, 12:14] = [(wind * dx / (distance + 150.0)).sum(), (wind * dy / (distance + 150.0)).sum()]
|
| 602 |
+
result[index, 14] = float(age_values[index, active].min())
|
| 603 |
+
result[index, 15] = float(active.sum())
|
| 604 |
+
return _normalize_context_block(result, feature_mean, feature_std)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def build_intensity_context_features(
|
| 608 |
+
basin_features: np.ndarray,
|
| 609 |
+
basin_valid: np.ndarray,
|
| 610 |
+
basin_age_hours: np.ndarray,
|
| 611 |
+
system_features: np.ndarray,
|
| 612 |
+
interaction_features: np.ndarray,
|
| 613 |
+
system_valid: np.ndarray,
|
| 614 |
+
system_age_hours: np.ndarray,
|
| 615 |
+
global_features: np.ndarray,
|
| 616 |
+
global_valid: np.ndarray,
|
| 617 |
+
global_age_hours: np.ndarray,
|
| 618 |
+
) -> np.ndarray:
|
| 619 |
+
"""Concatenate the exact 183-feature causal intensity context block."""
|
| 620 |
+
|
| 621 |
+
parts = [
|
| 622 |
+
_batch(basin_features, (42,), "basin_features"),
|
| 623 |
+
np.asarray(basin_valid, dtype="float32").reshape(-1, 1),
|
| 624 |
+
np.clip(np.asarray(basin_age_hours, dtype="float32").reshape(-1, 1), -1.0, 6.0) / 6.0,
|
| 625 |
+
_batch(system_features, (46,), "system_features"),
|
| 626 |
+
_batch(interaction_features, (16,), "interaction_features"),
|
| 627 |
+
np.asarray(system_valid, dtype="float32").reshape(-1, 1),
|
| 628 |
+
np.clip(np.asarray(system_age_hours, dtype="float32").reshape(-1, 1), -1.0, 6.0) / 6.0,
|
| 629 |
+
_batch(global_features, (73,), "global_features"),
|
| 630 |
+
np.asarray(global_valid, dtype="float32").reshape(-1, 1),
|
| 631 |
+
np.clip(np.asarray(global_age_hours, dtype="float32").reshape(-1, 1), -1.0, 6.0) / 6.0,
|
| 632 |
+
]
|
| 633 |
+
_same_batch(*parts)
|
| 634 |
+
context = np.concatenate(parts, axis=1)
|
| 635 |
+
if context.shape[1] != 183:
|
| 636 |
+
raise RuntimeError(f"intensity context builder produced {context.shape[1]} features, expected 183")
|
| 637 |
+
return np.nan_to_num(context, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 638 |
+
|
| 639 |
+
|
| 640 |
def local_position_to_latlon(
|
| 641 |
position_100km: np.ndarray,
|
| 642 |
issue_latitude: np.ndarray | float,
|
|
|
|
| 660 |
return latitude.astype("float32"), np.mod(longitude, 360.0).astype("float32")
|
| 661 |
|
| 662 |
|
| 663 |
+
def build_patch_summary(patch: np.ndarray, available: np.ndarray | float = 1.0) -> np.ndarray:
|
| 664 |
+
"""Build the causal 8-statistics-plus-availability patch summary."""
|
| 665 |
+
|
| 666 |
+
value = np.asarray(patch, dtype="float32")
|
| 667 |
+
if value.ndim == 3:
|
| 668 |
+
value = value[:, None]
|
| 669 |
+
if value.ndim != 4:
|
| 670 |
+
raise ValueError("patch must have shape [B, channels, height, width]")
|
| 671 |
+
count, channels, height, width = value.shape
|
| 672 |
+
cy, cx = height // 2, width // 2
|
| 673 |
+
inner = value[..., max(0, cy - 2):cy + 3, max(0, cx - 2):cx + 3]
|
| 674 |
+
broad = value[..., max(0, cy - 4):cy + 5, max(0, cx - 4):cx + 5]
|
| 675 |
+
ring = value[..., max(0, cy - 6):min(height, cy + 7), max(0, cx - 6):min(width, cx + 7)]
|
| 676 |
+
north = value[..., max(0, cy - 4):max(1, cy - 1), max(0, cx - 1):cx + 2].mean(axis=(-2, -1))
|
| 677 |
+
south = value[..., cy + 2:min(height, cy + 5), max(0, cx - 1):cx + 2].mean(axis=(-2, -1))
|
| 678 |
+
west = value[..., max(0, cy - 1):cy + 2, max(0, cx - 4):max(1, cx - 1)].mean(axis=(-2, -1))
|
| 679 |
+
east = value[..., max(0, cy - 1):cy + 2, cx + 2:min(width, cx + 5)].mean(axis=(-2, -1))
|
| 680 |
+
available_value = np.asarray(available, dtype="float32")
|
| 681 |
+
if available_value.ndim == 0:
|
| 682 |
+
available_value = np.full((count, 1), float(available_value), dtype="float32")
|
| 683 |
+
else:
|
| 684 |
+
available_value = available_value.reshape(count, -1)
|
| 685 |
+
features = np.concatenate([
|
| 686 |
+
value[..., cy, cx].reshape(count, -1),
|
| 687 |
+
inner.mean(axis=(-2, -1)).reshape(count, -1),
|
| 688 |
+
inner.std(axis=(-2, -1)).reshape(count, -1),
|
| 689 |
+
broad.mean(axis=(-2, -1)).reshape(count, -1),
|
| 690 |
+
ring.mean(axis=(-2, -1)).reshape(count, -1),
|
| 691 |
+
ring.std(axis=(-2, -1)).reshape(count, -1),
|
| 692 |
+
(north - south).reshape(count, -1),
|
| 693 |
+
(east - west).reshape(count, -1),
|
| 694 |
+
available_value,
|
| 695 |
+
], axis=1)
|
| 696 |
+
return np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def build_terrain_samples(
|
| 700 |
+
issue_latitude: np.ndarray | float,
|
| 701 |
+
issue_longitude: np.ndarray | float,
|
| 702 |
+
latitude_grid: np.ndarray,
|
| 703 |
+
longitude_grid: np.ndarray,
|
| 704 |
+
static_map: np.ndarray,
|
| 705 |
+
) -> np.ndarray:
|
| 706 |
+
"""Sample the six causal land/sea points used by the structure head."""
|
| 707 |
+
|
| 708 |
+
lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 709 |
+
lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 710 |
+
if len(lat) == 1 and len(lon) > 1:
|
| 711 |
+
lat = np.repeat(lat, len(lon))
|
| 712 |
+
if len(lon) == 1 and len(lat) > 1:
|
| 713 |
+
lon = np.repeat(lon, len(lat))
|
| 714 |
+
if len(lat) != len(lon):
|
| 715 |
+
raise ValueError("issue latitude/longitude must have one value per batch item")
|
| 716 |
+
fields = np.asarray(static_map, dtype="float32")
|
| 717 |
+
if fields.ndim != 3:
|
| 718 |
+
raise ValueError("static_map must have shape [channels, latitude, longitude]")
|
| 719 |
+
grid_lat = np.asarray(latitude_grid, dtype="float32").reshape(-1)
|
| 720 |
+
grid_lon = np.asarray(longitude_grid, dtype="float32").reshape(-1)
|
| 721 |
+
offsets_lat = np.asarray([0.0, 150.0 / 111.0, -150.0 / 111.0, 0.0, 0.0, 500.0 / 111.0], dtype="float32")
|
| 722 |
+
cos_lat = np.maximum(np.cos(np.deg2rad(lat)), 0.2)
|
| 723 |
+
offsets_lon = np.asarray([0.0, 0.0, 0.0, 150.0, -150.0, 0.0], dtype="float32")[None, :] / (111.0 * cos_lat[:, None])
|
| 724 |
+
sample_lat = np.clip(lat[:, None] + offsets_lat[None, :], grid_lat[0], grid_lat[-1])
|
| 725 |
+
sample_lon = np.mod(lon[:, None] + offsets_lon, 360.0)
|
| 726 |
+
lat_index = np.clip(np.rint((sample_lat - grid_lat[0]) / (grid_lat[1] - grid_lat[0])).astype("int64"), 0, len(grid_lat) - 1)
|
| 727 |
+
lon_index = np.clip(np.rint((sample_lon - grid_lon[0]) / (grid_lon[1] - grid_lon[0])).astype("int64"), 0, len(grid_lon) - 1)
|
| 728 |
+
result = fields[:, lat_index, lon_index].transpose(1, 2, 0)
|
| 729 |
+
return np.nan_to_num(result.reshape(len(lat), -1), nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def build_ocean_features(ocean_summary: np.ndarray) -> np.ndarray:
|
| 733 |
+
"""Flatten current, -12 h, and -24 h 22-value ocean summaries to 66."""
|
| 734 |
+
|
| 735 |
+
summary = np.asarray(ocean_summary, dtype="float32")
|
| 736 |
+
if summary.ndim == 2 and summary.shape == (3, 22):
|
| 737 |
+
summary = summary[None, ...]
|
| 738 |
+
if summary.ndim != 3 or summary.shape[1:] != (3, 22):
|
| 739 |
+
raise ValueError("ocean_summary must have shape [B, 3, 22]")
|
| 740 |
+
return np.nan_to_num(summary.reshape(len(summary), OCEAN_FEATURE_DIM), nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _season_features(issue_time_ns: np.ndarray) -> np.ndarray:
|
| 744 |
+
value = np.asarray(issue_time_ns, dtype="int64").reshape(-1)
|
| 745 |
+
dates = value.astype("datetime64[ns]").astype("datetime64[D]")
|
| 746 |
+
years = dates.astype("datetime64[Y]").astype("datetime64[D]")
|
| 747 |
+
day = (dates - years).astype("timedelta64[D]").astype("float32")
|
| 748 |
+
hour = ((value // (3_600 * 1_000_000_000)) % 24).astype("float32")
|
| 749 |
+
phase = 2.0 * np.pi * (day + hour / 24.0) / 365.25
|
| 750 |
+
return np.stack([
|
| 751 |
+
np.sin(phase), np.cos(phase), np.sin(2.0 * phase), np.cos(2.0 * phase),
|
| 752 |
+
], axis=1).astype("float32")
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
def build_causal_structure_features(
|
| 756 |
+
track_window: np.ndarray,
|
| 757 |
+
analysis_patches: np.ndarray,
|
| 758 |
+
analysis_valid: np.ndarray,
|
| 759 |
+
sst_patches: np.ndarray,
|
| 760 |
+
sst_valid: np.ndarray,
|
| 761 |
+
terrain_features: np.ndarray,
|
| 762 |
+
context_features: np.ndarray,
|
| 763 |
+
issue_latitude: np.ndarray | float,
|
| 764 |
+
issue_longitude: np.ndarray | float,
|
| 765 |
+
issue_time_ns: np.ndarray,
|
| 766 |
+
track_mean: np.ndarray | None = None,
|
| 767 |
+
track_std: np.ndarray | None = None,
|
| 768 |
+
history_available: np.ndarray | None = None,
|
| 769 |
+
track_normalized: bool = True,
|
| 770 |
+
) -> np.ndarray:
|
| 771 |
+
"""Build the exact 1,020-dimensional causal structure feature vector.
|
| 772 |
+
|
| 773 |
+
``track_window`` is the normalized ``9 x 54`` archive representation by
|
| 774 |
+
default. Supply ``track_mean`` and ``track_std`` to reconstruct the raw
|
| 775 |
+
physical rows needed for the current-state block; set ``track_normalized``
|
| 776 |
+
to ``False`` when the passed rows are physical and should be normalized.
|
| 777 |
+
Analysis patches
|
| 778 |
+
must already be in the released DLM4 representation (decoded ``q / 31.75``)
|
| 779 |
+
and ordered ``t0, t-12 h, t-24 h``. No future observations are accepted.
|
| 780 |
+
"""
|
| 781 |
+
|
| 782 |
+
track = np.asarray(track_window, dtype="float32")
|
| 783 |
+
if track.ndim == 2 and track.shape == (TRACK_WINDOW_LENGTH, TRACK_FEATURE_DIM):
|
| 784 |
+
track = track[None, ...]
|
| 785 |
+
if track.ndim != 3 or track.shape[1:] != (TRACK_WINDOW_LENGTH, TRACK_FEATURE_DIM):
|
| 786 |
+
raise ValueError("track_window must have shape [B, 9, 54]")
|
| 787 |
+
if track_mean is not None or track_std is not None:
|
| 788 |
+
if track_mean is None or track_std is None:
|
| 789 |
+
raise ValueError("track_mean and track_std must be supplied together")
|
| 790 |
+
mean = np.asarray(track_mean, dtype="float32").reshape(1, 1, TRACK_FEATURE_DIM)
|
| 791 |
+
std = np.asarray(track_std, dtype="float32").reshape(1, 1, TRACK_FEATURE_DIM)
|
| 792 |
+
if track_normalized:
|
| 793 |
+
raw_track = track * std + mean
|
| 794 |
+
else:
|
| 795 |
+
raw_track = track.copy()
|
| 796 |
+
track = (track - mean) / np.maximum(std, 1.0e-6)
|
| 797 |
+
else:
|
| 798 |
+
raw_track = None
|
| 799 |
+
analysis = np.asarray(analysis_patches, dtype="float32")
|
| 800 |
+
if analysis.ndim == 4 and analysis.shape[:2] == (3, 4):
|
| 801 |
+
analysis = analysis[None, ...]
|
| 802 |
+
if analysis.ndim != 5 or analysis.shape[1:3] != (3, 4) or analysis.shape[-2:] != (17, 17):
|
| 803 |
+
raise ValueError("analysis_patches must have shape [B, 3, 4, 17, 17]")
|
| 804 |
+
valid = np.asarray(analysis_valid, dtype="float32").reshape(len(track), 3)
|
| 805 |
+
history = valid[:, 1:] if history_available is None else np.asarray(history_available, dtype="float32").reshape(len(track), 2)
|
| 806 |
+
field_features = build_patch_summary(analysis.reshape(-1, 4, 17, 17), 1.0).reshape(len(track), 3, -1).reshape(len(track), -1)
|
| 807 |
+
field_availability = np.concatenate([valid[:, :1], valid[:, 1:], history], axis=1)
|
| 808 |
+
sst = np.asarray(sst_patches, dtype="float32")
|
| 809 |
+
if sst.ndim == 4 and sst.shape[:2] == (3, 1):
|
| 810 |
+
sst = sst[None, ...]
|
| 811 |
+
if sst.ndim != 5 or sst.shape[1:3] != (3, 1) or sst.shape[-2:] != (17, 17):
|
| 812 |
+
raise ValueError("sst_patches must have shape [B, 3, 1, 17, 17]")
|
| 813 |
+
sst_ok = np.asarray(sst_valid, dtype="float32").reshape(len(track), 3)
|
| 814 |
+
sst_features = build_patch_summary(sst.reshape(-1, 1, 17, 17), sst_ok.reshape(-1, 1)).reshape(len(track), 3, -1).reshape(len(track), -1)
|
| 815 |
+
terrain = _batch(terrain_features, (168,), "terrain_features")
|
| 816 |
+
context = _batch(context_features, (183,), "context_features")
|
| 817 |
+
lat = np.asarray(issue_latitude, dtype="float32").reshape(-1)
|
| 818 |
+
lon = np.asarray(issue_longitude, dtype="float32").reshape(-1)
|
| 819 |
+
time_value = np.asarray(issue_time_ns, dtype="int64").reshape(-1)
|
| 820 |
+
if len(lat) == 1 and len(track) > 1:
|
| 821 |
+
lat = np.repeat(lat, len(track))
|
| 822 |
+
if len(lon) == 1 and len(track) > 1:
|
| 823 |
+
lon = np.repeat(lon, len(track))
|
| 824 |
+
if len(time_value) == 1 and len(track) > 1:
|
| 825 |
+
time_value = np.repeat(time_value, len(track))
|
| 826 |
+
_same_batch(track, analysis, sst, terrain, context, lat[:, None], lon[:, None], time_value[:, None])
|
| 827 |
+
if raw_track is None:
|
| 828 |
+
raise ValueError("track_mean and track_std are required to reconstruct physical current-state features")
|
| 829 |
+
raw_last = raw_track[:, -1]
|
| 830 |
+
raw_prev = raw_track[:, -2]
|
| 831 |
+
current_state = np.concatenate([
|
| 832 |
+
raw_last[:, 4:20] / np.asarray([80.0, 1000.0, 300.0] + [300.0] * 13, dtype="float32"),
|
| 833 |
+
(raw_last[:, 4:20] - raw_prev[:, 4:20]) / np.asarray([40.0, 20.0, 100.0] + [100.0] * 13, dtype="float32"),
|
| 834 |
+
raw_last[:, 28:40],
|
| 835 |
+
], axis=1).astype("float32")
|
| 836 |
+
location = np.stack([lat / 90.0, np.mod(lon, 360.0) / 180.0, np.sin(np.deg2rad(lat)), np.cos(np.deg2rad(lat))], axis=1).astype("float32")
|
| 837 |
+
output = np.concatenate([
|
| 838 |
+
track.reshape(len(track), -1), current_state, field_features, field_availability,
|
| 839 |
+
sst_features, terrain, context, location, _season_features(time_value),
|
| 840 |
+
], axis=1)
|
| 841 |
+
if output.shape[1] != INTENSITY_FEATURE_DIM:
|
| 842 |
+
raise RuntimeError(f"causal structure builder produced {output.shape[1]} features, expected 1020")
|
| 843 |
+
return np.nan_to_num(output, nan=0.0, posinf=0.0, neginf=0.0).astype("float32")
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def build_causal_anchor_structure(observed_structure: np.ndarray) -> np.ndarray:
|
| 847 |
+
"""Build a causal persistence/trend anchor when no incumbent is supplied.
|
| 848 |
+
|
| 849 |
+
This is a documented fallback, not the private frozen Trackformer 1.2.26
|
| 850 |
+
anchor used to train the released residual head. Supply the real anchor
|
| 851 |
+
to ``predict_intensity`` when reproducing the trained residual pipeline.
|
| 852 |
+
``observed_structure`` is physical ``[B, 3, 15]`` history ordered oldest to
|
| 853 |
+
newest, with columns ``vmax, pressure, RMW, R34/R50/R64``.
|
| 854 |
+
"""
|
| 855 |
+
|
| 856 |
+
history = np.asarray(observed_structure, dtype="float32")
|
| 857 |
+
if history.ndim == 2 and history.shape == (3, STRUCTURE_DIM):
|
| 858 |
+
history = history[None, ...]
|
| 859 |
+
if history.ndim == 2 and history.shape == (STRUCTURE_DIM,):
|
| 860 |
+
history = history[None, None, ...]
|
| 861 |
+
if history.ndim != 3 or history.shape[-1] != STRUCTURE_DIM or history.shape[1] not in (1, 2, 3):
|
| 862 |
+
raise ValueError("observed_structure must have shape [B, 1|2|3, 15]")
|
| 863 |
+
latest = history[:, -1]
|
| 864 |
+
if history.shape[1] >= 2:
|
| 865 |
+
delta = latest - history[:, -2]
|
| 866 |
+
else:
|
| 867 |
+
delta = np.zeros_like(latest)
|
| 868 |
+
lead = np.arange(1, LEADS + 1, dtype="float32")[None, :, None]
|
| 869 |
+
trend = (1.0 - np.exp(-lead / 6.0)) * delta[:, None, :]
|
| 870 |
+
output = latest[:, None, :] + trend
|
| 871 |
+
return _project_structure(output).astype("float32")
|
| 872 |
+
|
| 873 |
+
|
| 874 |
def _structure_transform(value: np.ndarray) -> np.ndarray:
|
| 875 |
value = np.asarray(value, dtype="float32")
|
| 876 |
result = np.zeros_like(value, dtype="float32")
|
|
|
|
| 987 |
with np.load(stats_path, allow_pickle=False) as stats:
|
| 988 |
self.feature_mean = stats["feature_mean"].astype("float32")
|
| 989 |
self.feature_std = np.maximum(stats["feature_std"].astype("float32"), 1.0e-4)
|
| 990 |
+
route_stats_path = self.model_root / "trackformer_1_2_route_context_stats.npz"
|
| 991 |
+
self.route_context_mean: np.ndarray | None = None
|
| 992 |
+
self.route_context_std: np.ndarray | None = None
|
| 993 |
+
if route_stats_path.exists():
|
| 994 |
+
with np.load(route_stats_path, allow_pickle=False) as route_stats:
|
| 995 |
+
self.route_context_mean = route_stats["feature_mean"].astype("float32")
|
| 996 |
+
self.route_context_std = np.maximum(route_stats["feature_std"].astype("float32"), 1.0e-4)
|
| 997 |
+
track_stats_path = self.model_root / "trackformer_1_2_track_stats.npz"
|
| 998 |
+
self.track_mean: np.ndarray | None = None
|
| 999 |
+
self.track_std: np.ndarray | None = None
|
| 1000 |
+
if track_stats_path.exists():
|
| 1001 |
+
with np.load(track_stats_path, allow_pickle=False) as track_stats:
|
| 1002 |
+
self.track_mean = track_stats["track_mean"].astype("float32")
|
| 1003 |
+
self.track_std = np.maximum(track_stats["track_std"].astype("float32"), 1.0e-6)
|
| 1004 |
+
system_stats_path = self.model_root / "trackformer_1_2_system_context_stats.npz"
|
| 1005 |
+
self.system_context_stats: dict[str, np.ndarray] | None = None
|
| 1006 |
+
if system_stats_path.exists():
|
| 1007 |
+
with np.load(system_stats_path, allow_pickle=False) as system_stats:
|
| 1008 |
+
self.system_context_stats = {
|
| 1009 |
+
key: system_stats[key].astype("float32")
|
| 1010 |
+
for key in ("system_mean", "system_std", "interaction_mean", "interaction_std")
|
| 1011 |
+
}
|
| 1012 |
self.route_members = self._load_route_members()
|
| 1013 |
self.intensity_members = self._load_intensity_members()
|
| 1014 |
ocean_path = self.model_root / "trackformer_1_2_ocean_structure.joblib"
|
|
|
|
| 1068 |
return members
|
| 1069 |
|
| 1070 |
@torch.no_grad()
|
| 1071 |
+
def predict_route(
|
| 1072 |
+
self,
|
| 1073 |
+
field: np.ndarray,
|
| 1074 |
+
context: np.ndarray,
|
| 1075 |
+
base_position: np.ndarray,
|
| 1076 |
+
batch_size: int = 64,
|
| 1077 |
+
context_is_normalized: bool = False,
|
| 1078 |
+
) -> dict[str, np.ndarray]:
|
| 1079 |
"""Predict the 20-lead route from issue-time causal route tensors.
|
| 1080 |
|
| 1081 |
``field`` is normalized by :func:`prepare_route_field` and has shape
|
| 1082 |
+
``[B, 6, H, W]``; ``context`` is raw ``[B, 647]`` unless
|
| 1083 |
+
``context_is_normalized=True``; and ``base_position`` is ``[B, 20, 2]``
|
| 1084 |
+
in cumulative 100-km local displacement units.
|
| 1085 |
"""
|
| 1086 |
field = _batch(field, (6, np.asarray(field).shape[-2], np.asarray(field).shape[-1]), "field")
|
| 1087 |
context = _batch(context, (ROUTE_CONTEXT_DIM,), "context")
|
|
|
|
| 1089 |
if field.shape[-2:] != (FIELD_HEIGHT, FIELD_WIDTH):
|
| 1090 |
raise ValueError(f"field must be the released [25, 61] Pacific grid, got {field.shape[-2:]}")
|
| 1091 |
_same_batch(field, context, base_position)
|
| 1092 |
+
if not context_is_normalized:
|
| 1093 |
+
if self.route_context_mean is None or self.route_context_std is None:
|
| 1094 |
+
raise FileNotFoundError("route context normalization stats are not present in this model bundle")
|
| 1095 |
+
context = normalize_route_context(context, self.route_context_mean, self.route_context_std)
|
| 1096 |
positions: list[np.ndarray] = []
|
| 1097 |
land: list[np.ndarray] = []
|
| 1098 |
for start in range(0, len(field), batch_size):
|
|
|
|
| 1183 |
"""
|
| 1184 |
result: dict[str, Any] = {}
|
| 1185 |
if {"field", "context", "base_position"}.issubset(packet):
|
| 1186 |
+
result["route"] = self.predict_route(
|
| 1187 |
+
packet["field"], packet["context"], packet["base_position"],
|
| 1188 |
+
context_is_normalized=bool(packet.get("context_is_normalized", False)),
|
| 1189 |
+
)
|
| 1190 |
if {"causal_features", "anchor_structure"}.issubset(packet):
|
| 1191 |
result["intensity"] = self.predict_intensity(packet["causal_features"], packet["anchor_structure"])
|
| 1192 |
if "ocean_features" in packet:
|
|
|
|
| 1199 |
__all__ = [
|
| 1200 |
"FIELD_HEIGHT", "FIELD_WIDTH", "INTENSITY_FEATURE_DIM", "INTENSITY_INPUT_DIM", "LEADS", "LEAD_HOURS",
|
| 1201 |
"OCEAN_FEATURE_DIM", "ROUTE_CONTEXT_DIM", "STRUCTURE_DIM", "Trackformer12",
|
| 1202 |
+
"build_base_position", "build_causal_anchor_structure", "build_causal_structure_features",
|
| 1203 |
+
"build_intensity_context_features", "build_kinematic_base_position", "build_ocean_features",
|
| 1204 |
+
"build_nearby_interaction_features", "build_patch_summary", "build_route_context",
|
| 1205 |
+
"build_route_geography_features", "build_route_kinematic_features",
|
| 1206 |
+
"build_route_system_features", "build_synoptic_features", "build_terrain_samples",
|
| 1207 |
+
"local_position_to_latlon", "normalize_route_context", "prepare_route_field",
|
| 1208 |
]
|