Anlea commited on
Commit
3656aff
·
verified ·
1 Parent(s): 85f2567

fix: upload synced space/bundle to Space root

Browse files
config/config.yaml CHANGED
@@ -1,233 +1,233 @@
1
- project:
2
- name: cyclone-intensity-estimation
3
- seed: 42
4
- honesty: >
5
- No trained weights are shipped. Smoke images are synthetic.
6
- This is not an operational forecast or warning system.
7
- Best-track labels are noisy, and agreement with them is not ground truth.
8
- No survey or smoke number is a result of this project.
9
- paths:
10
- manifest: data/manifest.csv
11
- artifacts: artifacts
12
- reports: reports
13
- checkpoint_name: checkpoint.pt
14
- run_records: artifacts/run_records
15
- runs: artifacts/runs
16
- nasa_root: data/nasa_tc
17
- tcir_files: []
18
- tcir_manifest_dir: data/tcir
19
- frame_cache: artifacts/frame_cache
20
- # Extracted Cropped_cyclone_data directory. This file does not download it.
21
- incyde_root: data/incyde
22
- # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
23
- run_id: null
24
- hf_model_repo: null
25
- data:
26
- dataset: nasa
27
- # null or native keeps each chip's height and width. NASA TorchGeo chips
28
- # are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
29
- # resizes the deep model to that square. Classical features stay native.
30
- image_size: native
31
- channels: 1
32
- normalize: zscore
33
- max_missing_fraction: 0.30
34
- plausible_wind_kt: [0, 200]
35
- # NASA TropicalCyclone labels are HURDAT2 maximum sustained wind, a
36
- # 1-minute average. Do not mix this with 10-minute winds.
37
- wind_averaging: 1min
38
- # Project bins for error tables. Not an IMD warning, and not the IMD
39
- # 3-minute scale. IMD uses 3-minute winds. These edges are this project's
40
- # own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
41
- # and 91 kt and above ESCS_SUCS.
42
- imd5_edges_kt: [17, 34, 48, 64, 91]
43
- imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
44
- # International knot. Used only to display a second unit.
45
- kt_to_kmh: 1.852
46
- # letterbox pads to a square before the checkpoint resize. stretch is the old path.
47
- resize: letterbox
48
- pad: median
49
- grouping_note: >
50
- Intensity category is this project's grouping on the configured knot bins.
51
- It is not an official IMD class.
52
- labels:
53
- # Training target for TCIR, NASA, and INCYDE. Raw knots stay on wind_speed_kt.
54
- label_column: wind_kt_3min
55
- # Derived at-sea factor, not a WMO constant. See docs/TRAINING.md.
56
- wind_1min_to_3min: 0.93
57
- # flag: still multiply near-land 1-minute rows and set conversion_exposure_flag.
58
- # raw: leave those rows at the 1-minute label.
59
- near_land_policy: flag
60
- # The factor is for open water farther offshore than this, in kilometres.
61
- open_water_km: 20
62
- incyde:
63
- # null uses incyde/audit/storm_split.csv and exclusions.csv.
64
- manifest_csv: null
65
- storm_split_csv: null
66
- exclusions_csv: null
67
- archive: null
68
- drop_qc_flags: []
69
- n_folds: 5
70
- cv_val_fold: 0
71
- cv_seed: 42
72
- # Optional storm_id,fold file. When set, it replaces the seeded folds.
73
- cv_folds_csv: null
74
- # null uses incyde/audit/frame_flags.csv. Unknown cells stay unknown.
75
- frame_flags_csv: null
76
- # When true, also report validation metrics on explicit on_fix frames.
77
- # The overall validation metrics stay the full validation split.
78
- on_fix_only_eval: false
79
- split:
80
- strategy: storm_wise
81
- test_fraction: 0.2
82
- val_fraction: 0.2
83
- holdout_years: []
84
- holdout_basin: null
85
- seed: 42
86
- model:
87
- name: simple_cnn
88
- pretrained: false
89
- dropout: 0.3
90
- mc_samples: 20
91
- # Used when model.name is convlstm. The sequence length stays 4.
92
- n_frames: 4
93
- hidden: 16
94
- train:
95
- batch_size: 16
96
- epochs: 20
97
- lr: 0.001
98
- weight_decay: 0.0001
99
- patience: 5
100
- # auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
101
- device: auto
102
- max_steps: null
103
- grad_accum_steps: 1
104
- num_workers: 2
105
- # Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
106
- device_parity_tol: 0.05
107
- class_loss_weight: 0.1
108
- # Applied only when r34_nmi and rmw_nmi exist on the train split.
109
- size_loss_weight: 0.1
110
- # none leaves Smooth L1 unweighted. The other modes reweight the five
111
- # project bins on the 3-minute target, using train originals only.
112
- loss_weighting: none
113
- # Draw train rows with inverse-frequency weights so each occurring bin
114
- # has the same expected count. Off by default.
115
- balanced_sampling: false
116
- predict:
117
- # Review flag, not a warning threshold.
118
- advisory_jump_kt: 20
119
- operational_disclaimer: "This is not an operational forecast."
120
- no_run_record_review: "no matching real-data run record"
121
- no_run_record_refusal: >
122
- This checkpoint has no matching real-data run record.
123
- There is no model output. This is not a forecast.
124
- held_out_refusal: >
125
- This checkpoint's real-data run record has not passed the held-out
126
- storm check. There is no model output. This is not a forecast.
127
- landfall_note: "not a landfall forecast"
128
- coast_reference_note: >
129
- Reference points are approximate coastal coordinates, not a shoreline
130
- survey and not a landfall forecast.
131
- coastal_heading: "nearest Indian coastal states to the current position"
132
- coastal_count: 3
133
- earth_radius_km: 6371.0
134
- latitude_keys: [latitude, lat]
135
- longitude_keys: [longitude, lon]
136
- # Image mean must sit within this many training standard deviations.
137
- training_mean_width: 3
138
- # Same storm, resized, should stay inside this knot span.
139
- scale_tolerance_kt: 1.0
140
- sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
141
- confidence:
142
- uncalibrated_label: uncalibrated
143
- coverage_label: "real-data coverage recorded"
144
- gate_weight: 0.4
145
- mc_weight: 0.4
146
- interval_weight: 0.2
147
- mc_std_scale_kt: 15
148
- interval_scale_kt: 30
149
- gate:
150
- refusal: "not a tropical cyclone IR image"
151
- grayscale_tolerance: 0.08
152
- min_std: 0.02
153
- min_symmetry: 0.45
154
- min_cold_concentration: 0.36
155
- cold_radius_fraction: 0.45
156
- cold_tail_fraction: 0.25
157
- eye_radius_fraction: 0.12
158
- eyewall_outer_fraction: 0.32
159
- outer_inner_fraction: 0.55
160
- outer_outer_fraction: 0.95
161
- min_wall_contrast: 0.45
162
- radial_bins: 8
163
- cold_value: auto
164
- max_dropout_std_kt: 50
165
- concentration_reference: 0.75
166
- # Approximate public reference points, not Survey of India boundaries.
167
- coast:
168
- - {name: Gujarat, lat: 21.64, lon: 69.61}
169
- - {name: Maharashtra, lat: 18.94, lon: 72.84}
170
- - {name: Goa, lat: 15.49, lon: 73.83}
171
- - {name: Karnataka, lat: 12.91, lon: 74.86}
172
- - {name: Kerala, lat: 9.93, lon: 76.26}
173
- - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
174
- - {name: Puducherry, lat: 11.94, lon: 79.83}
175
- - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
176
- - {name: Odisha, lat: 19.81, lon: 85.83}
177
- - {name: West Bengal, lat: 21.63, lon: 87.51}
178
- - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
179
- - {name: Lakshadweep, lat: 10.57, lon: 72.64}
180
- - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
181
- forbidden_features:
182
- - wind_speed_kt
183
- - r34_nmi
184
- - rmw_nmi
185
- - imd5_class
186
- - intensity_bin
187
- features:
188
- # Name distributional stats tb_* only when a calibration table was applied.
189
- calibrated: false
190
- cold_thresholds: [200, 210, 220, 230, 240]
191
- radial_bins: 8
192
- eye_radius_fraction: 0.12
193
- cdo_outer_fraction: 0.35
194
- eye_contrast_min: 2.0
195
- dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
196
- dav_annulus_width_fraction: 0.08
197
- glcm_levels: 16
198
- glcm_distance: 1
199
- selection:
200
- correlation_threshold: 0.95
201
- max_features: 25
202
- method: correlation_rf
203
- n_estimators: 80
204
- seed: 42
205
- baselines:
206
- n_splits: 3
207
- seed: 42
208
- # Validation per-class intervals. Each resample draws storms with replacement.
209
- # The generator seed is baselines.seed. Rows are not resampled.
210
- bootstrap_resamples: 1000
211
- # List each storm inside a class that has fewer than 3 storms.
212
- per_storm_breakdown: true
213
- regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
214
- classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
215
- use_smote: true
216
- ridge_alpha: 1.0
217
- knn_neighbors: 5
218
- svr_c: 1.0
219
- svc_c: 1.0
220
- rf_estimators: 200
221
- rf_max_depth: 6
222
- xgb_estimators: 80
223
- xgb_max_depth: 3
224
- xgb_learning_rate: 0.1
225
- max_iter: 1000
226
- # Grouped CV. train folds the training storms only. train_val folds
227
- # train and val together and never includes test. The group column stays
228
- # intact inside a fold. cv_collapse_rare remaps a stratify label that
229
- # sits in fewer groups than n_splits, for fold assignment only.
230
- cv_pool: train
231
- cv_group_column: storm_id
232
- cv_collapse_rare: false
233
- cv_assign: stratified
 
1
+ project:
2
+ name: cyclone-intensity-estimation
3
+ seed: 42
4
+ honesty: >
5
+ No trained weights are shipped. Smoke images are synthetic.
6
+ This is not an operational forecast or warning system.
7
+ Best-track labels are noisy, and agreement with them is not ground truth.
8
+ No survey or smoke number is a result of this project.
9
+ paths:
10
+ manifest: data/manifest.csv
11
+ artifacts: artifacts
12
+ reports: reports
13
+ checkpoint_name: checkpoint.pt
14
+ run_records: artifacts/run_records
15
+ runs: artifacts/runs
16
+ nasa_root: data/nasa_tc
17
+ tcir_files: []
18
+ tcir_manifest_dir: data/tcir
19
+ frame_cache: artifacts/frame_cache
20
+ # Extracted Cropped_cyclone_data directory. This file does not download it.
21
+ incyde_root: data/incyde
22
+ # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
23
+ run_id: null
24
+ hf_model_repo: null
25
+ data:
26
+ dataset: nasa
27
+ # null or native keeps each chip's height and width. NASA TorchGeo chips
28
+ # are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
29
+ # resizes the deep model to that square. Classical features stay native.
30
+ image_size: native
31
+ channels: 1
32
+ normalize: zscore
33
+ max_missing_fraction: 0.30
34
+ plausible_wind_kt: [0, 200]
35
+ # NASA TropicalCyclone labels are HURDAT2 maximum sustained wind, a
36
+ # 1-minute average. Do not mix this with 10-minute winds.
37
+ wind_averaging: 1min
38
+ # Project bins for error tables. Not an IMD warning, and not the IMD
39
+ # 3-minute scale. IMD uses 3-minute winds. These edges are this project's
40
+ # own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
41
+ # and 91 kt and above ESCS_SUCS.
42
+ imd5_edges_kt: [17, 34, 48, 64, 91]
43
+ imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
44
+ # International knot. Used only to display a second unit.
45
+ kt_to_kmh: 1.852
46
+ # letterbox pads to a square before the checkpoint resize. stretch is the old path.
47
+ resize: letterbox
48
+ pad: median
49
+ grouping_note: >
50
+ Intensity category is this project's grouping on the configured knot bins.
51
+ It is not an official IMD class.
52
+ labels:
53
+ # Training target for TCIR, NASA, and INCYDE. Raw knots stay on wind_speed_kt.
54
+ label_column: wind_kt_3min
55
+ # Derived at-sea factor, not a WMO constant. See docs/TRAINING.md.
56
+ wind_1min_to_3min: 0.93
57
+ # flag: still multiply near-land 1-minute rows and set conversion_exposure_flag.
58
+ # raw: leave those rows at the 1-minute label.
59
+ near_land_policy: flag
60
+ # The factor is for open water farther offshore than this, in kilometres.
61
+ open_water_km: 20
62
+ incyde:
63
+ # null uses incyde/audit/storm_split.csv and exclusions.csv.
64
+ manifest_csv: null
65
+ storm_split_csv: null
66
+ exclusions_csv: null
67
+ archive: null
68
+ drop_qc_flags: []
69
+ n_folds: 5
70
+ cv_val_fold: 0
71
+ cv_seed: 42
72
+ # Optional storm_id,fold file. When set, it replaces the seeded folds.
73
+ cv_folds_csv: null
74
+ # null uses incyde/audit/frame_flags.csv. Unknown cells stay unknown.
75
+ frame_flags_csv: null
76
+ # When true, also report validation metrics on explicit on_fix frames.
77
+ # The overall validation metrics stay the full validation split.
78
+ on_fix_only_eval: false
79
+ split:
80
+ strategy: storm_wise
81
+ test_fraction: 0.2
82
+ val_fraction: 0.2
83
+ holdout_years: []
84
+ holdout_basin: null
85
+ seed: 42
86
+ model:
87
+ name: simple_cnn
88
+ pretrained: false
89
+ dropout: 0.3
90
+ mc_samples: 20
91
+ # Used when model.name is convlstm. The sequence length stays 4.
92
+ n_frames: 4
93
+ hidden: 16
94
+ train:
95
+ batch_size: 16
96
+ epochs: 20
97
+ lr: 0.001
98
+ weight_decay: 0.0001
99
+ patience: 5
100
+ # auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
101
+ device: auto
102
+ max_steps: null
103
+ grad_accum_steps: 1
104
+ num_workers: 2
105
+ # Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
106
+ device_parity_tol: 0.05
107
+ class_loss_weight: 0.1
108
+ # Applied only when r34_nmi and rmw_nmi exist on the train split.
109
+ size_loss_weight: 0.1
110
+ # none leaves Smooth L1 unweighted. The other modes reweight the five
111
+ # project bins on the 3-minute target, using train originals only.
112
+ loss_weighting: none
113
+ # Draw train rows with inverse-frequency weights so each occurring bin
114
+ # has the same expected count. Off by default.
115
+ balanced_sampling: false
116
+ predict:
117
+ # Review flag, not a warning threshold.
118
+ advisory_jump_kt: 20
119
+ operational_disclaimer: "This is not an operational forecast."
120
+ no_run_record_review: "no matching real-data run record"
121
+ no_run_record_refusal: >
122
+ This checkpoint has no matching real-data run record.
123
+ There is no model output. This is not a forecast.
124
+ held_out_refusal: >
125
+ This checkpoint's real-data run record has not passed the held-out
126
+ storm check. There is no model output. This is not a forecast.
127
+ landfall_note: "not a landfall forecast"
128
+ coast_reference_note: >
129
+ Reference points are approximate coastal coordinates, not a shoreline
130
+ survey and not a landfall forecast.
131
+ coastal_heading: "nearest Indian coastal states to the current position"
132
+ coastal_count: 3
133
+ earth_radius_km: 6371.0
134
+ latitude_keys: [latitude, lat]
135
+ longitude_keys: [longitude, lon]
136
+ # Image mean must sit within this many training standard deviations.
137
+ training_mean_width: 3
138
+ # Same storm, resized, should stay inside this knot span.
139
+ scale_tolerance_kt: 1.0
140
+ sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
141
+ confidence:
142
+ uncalibrated_label: uncalibrated
143
+ coverage_label: "real-data coverage recorded"
144
+ gate_weight: 0.4
145
+ mc_weight: 0.4
146
+ interval_weight: 0.2
147
+ mc_std_scale_kt: 15
148
+ interval_scale_kt: 30
149
+ gate:
150
+ refusal: "not a tropical cyclone IR image"
151
+ grayscale_tolerance: 0.08
152
+ min_std: 0.02
153
+ min_symmetry: 0.45
154
+ min_cold_concentration: 0.36
155
+ cold_radius_fraction: 0.45
156
+ cold_tail_fraction: 0.25
157
+ eye_radius_fraction: 0.12
158
+ eyewall_outer_fraction: 0.32
159
+ outer_inner_fraction: 0.55
160
+ outer_outer_fraction: 0.95
161
+ min_wall_contrast: 0.45
162
+ radial_bins: 8
163
+ cold_value: auto
164
+ max_dropout_std_kt: 50
165
+ concentration_reference: 0.75
166
+ # Approximate public reference points, not Survey of India boundaries.
167
+ coast:
168
+ - {name: Gujarat, lat: 21.64, lon: 69.61}
169
+ - {name: Maharashtra, lat: 18.94, lon: 72.84}
170
+ - {name: Goa, lat: 15.49, lon: 73.83}
171
+ - {name: Karnataka, lat: 12.91, lon: 74.86}
172
+ - {name: Kerala, lat: 9.93, lon: 76.26}
173
+ - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
174
+ - {name: Puducherry, lat: 11.94, lon: 79.83}
175
+ - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
176
+ - {name: Odisha, lat: 19.81, lon: 85.83}
177
+ - {name: West Bengal, lat: 21.63, lon: 87.51}
178
+ - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
179
+ - {name: Lakshadweep, lat: 10.57, lon: 72.64}
180
+ - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
181
+ forbidden_features:
182
+ - wind_speed_kt
183
+ - r34_nmi
184
+ - rmw_nmi
185
+ - imd5_class
186
+ - intensity_bin
187
+ features:
188
+ # Name distributional stats tb_* only when a calibration table was applied.
189
+ calibrated: false
190
+ cold_thresholds: [200, 210, 220, 230, 240]
191
+ radial_bins: 8
192
+ eye_radius_fraction: 0.12
193
+ cdo_outer_fraction: 0.35
194
+ eye_contrast_min: 2.0
195
+ dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
196
+ dav_annulus_width_fraction: 0.08
197
+ glcm_levels: 16
198
+ glcm_distance: 1
199
+ selection:
200
+ correlation_threshold: 0.95
201
+ max_features: 25
202
+ method: correlation_rf
203
+ n_estimators: 80
204
+ seed: 42
205
+ baselines:
206
+ n_splits: 3
207
+ seed: 42
208
+ # Validation per-class intervals. Each resample draws storms with replacement.
209
+ # The generator seed is baselines.seed. Rows are not resampled.
210
+ bootstrap_resamples: 1000
211
+ # List each storm inside a class that has fewer than 3 storms.
212
+ per_storm_breakdown: true
213
+ regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
214
+ classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
215
+ use_smote: true
216
+ ridge_alpha: 1.0
217
+ knn_neighbors: 5
218
+ svr_c: 1.0
219
+ svc_c: 1.0
220
+ rf_estimators: 200
221
+ rf_max_depth: 6
222
+ xgb_estimators: 80
223
+ xgb_max_depth: 3
224
+ xgb_learning_rate: 0.1
225
+ max_iter: 1000
226
+ # Grouped CV. train folds the training storms only. train_val folds
227
+ # train and val together and never includes test. The group column stays
228
+ # intact inside a fold. cv_collapse_rare remaps a stratify label that
229
+ # sits in fewer groups than n_splits, for fold assignment only.
230
+ cv_pool: train
231
+ cv_group_column: storm_id
232
+ cv_collapse_rare: false
233
+ cv_assign: stratified
config/config_incyde.yaml CHANGED
@@ -1,201 +1,201 @@
1
- project:
2
- name: cyclone-intensity-estimation
3
- seed: 42
4
- honesty: >
5
- No trained weights are shipped. Smoke images are synthetic.
6
- This is not an operational forecast or warning system.
7
- Best-track labels are noisy, and agreement with them is not ground truth.
8
- No survey or smoke number is a result of this project.
9
- paths:
10
- manifest: data/incyde/manifest.csv
11
- artifacts: artifacts
12
- reports: reports
13
- checkpoint_name: checkpoint.pt
14
- run_records: artifacts/run_records
15
- runs: artifacts/runs
16
- nasa_root: data/nasa_tc
17
- tcir_files: []
18
- tcir_manifest_dir: data/tcir
19
- frame_cache: artifacts/frame_cache
20
- # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
21
- run_id: null
22
- hf_model_repo: null
23
- data:
24
- dataset: incyde
25
- # null or native keeps each chip's height and width. NASA TorchGeo chips
26
- # are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
27
- # resizes the deep model to that square. Classical features stay native.
28
- image_size: native
29
- channels: 1
30
- normalize: zscore
31
- max_missing_fraction: 0.30
32
- plausible_wind_kt: [0, 200]
33
- # Raw IMD 3-minute sustained winds from the INCYDE labels CSV.
34
- # Do not convert them to 1-minute. wind_averaging_s is 180 on every row.
35
- wind_averaging: 3-min
36
- # Project bins for error tables. Not an IMD warning, and not the IMD
37
- # 3-minute scale. IMD uses 3-minute winds. These edges are this project's
38
- # own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
39
- # and 91 kt and above ESCS_SUCS.
40
- imd5_edges_kt: [17, 34, 48, 64, 91]
41
- imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
42
- # International knot. Used only to display a second unit.
43
- kt_to_kmh: 1.852
44
- # letterbox pads to a square before the checkpoint resize. stretch is the old path.
45
- resize: letterbox
46
- pad: median
47
- grouping_note: >
48
- Intensity category is this project's grouping on the configured knot bins.
49
- It is not an official IMD class.
50
- split:
51
- strategy: recorded
52
- test_fraction: 0.2
53
- val_fraction: 0.2
54
- holdout_years: []
55
- holdout_basin: null
56
- seed: 42
57
- model:
58
- name: simple_cnn
59
- pretrained: false
60
- dropout: 0.3
61
- mc_samples: 20
62
- # Used when model.name is convlstm. The sequence length stays 4.
63
- n_frames: 4
64
- hidden: 16
65
- train:
66
- batch_size: 16
67
- epochs: 20
68
- lr: 0.001
69
- weight_decay: 0.0001
70
- patience: 5
71
- # auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
72
- device: auto
73
- max_steps: null
74
- grad_accum_steps: 1
75
- num_workers: 2
76
- # Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
77
- device_parity_tol: 0.05
78
- class_loss_weight: 0.1
79
- # Applied only when r34_nmi and rmw_nmi exist on the train split.
80
- size_loss_weight: 0.1
81
- predict:
82
- # Review flag, not a warning threshold.
83
- advisory_jump_kt: 20
84
- operational_disclaimer: "This is not an operational forecast."
85
- no_run_record_review: "no matching real-data run record"
86
- no_run_record_refusal: >
87
- This checkpoint has no matching real-data run record.
88
- There is no model output. This is not a forecast.
89
- held_out_refusal: >
90
- This checkpoint's real-data run record has not passed the held-out
91
- storm check. There is no model output. This is not a forecast.
92
- landfall_note: "not a landfall forecast"
93
- coast_reference_note: >
94
- Reference points are approximate coastal coordinates, not a shoreline
95
- survey and not a landfall forecast.
96
- coastal_heading: "nearest Indian coastal states to the current position"
97
- coastal_count: 3
98
- earth_radius_km: 6371.0
99
- latitude_keys: [latitude, lat]
100
- longitude_keys: [longitude, lon]
101
- # Image mean must sit within this many training standard deviations.
102
- training_mean_width: 3
103
- # Same storm, resized, should stay inside this knot span.
104
- scale_tolerance_kt: 1.0
105
- sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
106
- confidence:
107
- uncalibrated_label: uncalibrated
108
- coverage_label: "real-data coverage recorded"
109
- gate_weight: 0.4
110
- mc_weight: 0.4
111
- interval_weight: 0.2
112
- mc_std_scale_kt: 15
113
- interval_scale_kt: 30
114
- gate:
115
- refusal: "not a tropical cyclone IR image"
116
- grayscale_tolerance: 0.08
117
- min_std: 0.02
118
- min_symmetry: 0.45
119
- min_cold_concentration: 0.36
120
- cold_radius_fraction: 0.45
121
- cold_tail_fraction: 0.25
122
- eye_radius_fraction: 0.12
123
- eyewall_outer_fraction: 0.32
124
- outer_inner_fraction: 0.55
125
- outer_outer_fraction: 0.95
126
- min_wall_contrast: 0.45
127
- radial_bins: 8
128
- cold_value: auto
129
- max_dropout_std_kt: 50
130
- concentration_reference: 0.75
131
- # Approximate public reference points, not Survey of India boundaries.
132
- coast:
133
- - {name: Gujarat, lat: 21.64, lon: 69.61}
134
- - {name: Maharashtra, lat: 18.94, lon: 72.84}
135
- - {name: Goa, lat: 15.49, lon: 73.83}
136
- - {name: Karnataka, lat: 12.91, lon: 74.86}
137
- - {name: Kerala, lat: 9.93, lon: 76.26}
138
- - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
139
- - {name: Puducherry, lat: 11.94, lon: 79.83}
140
- - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
141
- - {name: Odisha, lat: 19.81, lon: 85.83}
142
- - {name: West Bengal, lat: 21.63, lon: 87.51}
143
- - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
144
- - {name: Lakshadweep, lat: 10.57, lon: 72.64}
145
- - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
146
- forbidden_features:
147
- - wind_speed_kt
148
- - r34_nmi
149
- - rmw_nmi
150
- - imd5_class
151
- - intensity_bin
152
- features:
153
- # Name distributional stats tb_* only when a calibration table was applied.
154
- calibrated: false
155
- cold_thresholds: [200, 210, 220, 230, 240]
156
- radial_bins: 8
157
- eye_radius_fraction: 0.12
158
- cdo_outer_fraction: 0.35
159
- eye_contrast_min: 2.0
160
- dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
161
- dav_annulus_width_fraction: 0.08
162
- glcm_levels: 16
163
- glcm_distance: 1
164
- selection:
165
- correlation_threshold: 0.95
166
- max_features: 25
167
- method: correlation_rf
168
- n_estimators: 80
169
- seed: 42
170
- baselines:
171
- # Five folds, seed 42, groups dealt round-robin. The file
172
- # results/incyde_baselines/cv_folds.csv is storm_id,fold for train+val
173
- # only, and each cooccurrence_group stays in one fold.
174
- n_splits: 5
175
- seed: 42
176
- # Validation per-class intervals. Each resample draws storms with replacement.
177
- # The generator seed is baselines.seed. Rows are not resampled.
178
- bootstrap_resamples: 1000
179
- # List each storm inside a class that has fewer than 3 storms.
180
- per_storm_breakdown: true
181
- regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
182
- classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
183
- use_smote: true
184
- ridge_alpha: 1.0
185
- knn_neighbors: 5
186
- svr_c: 1.0
187
- svc_c: 1.0
188
- rf_estimators: 200
189
- rf_max_depth: 6
190
- xgb_estimators: 80
191
- xgb_max_depth: 3
192
- xgb_learning_rate: 0.1
193
- max_iter: 1000
194
- # Grouped CV. train folds the training storms only. train_val folds
195
- # train and val together and never includes test. The group column stays
196
- # intact inside a fold. cv_collapse_rare remaps a stratify label that
197
- # sits in fewer groups than n_splits, for fold assignment only.
198
- cv_pool: train_val
199
- cv_group_column: cv_group
200
- cv_collapse_rare: false
201
- cv_assign: round_robin
 
1
+ project:
2
+ name: cyclone-intensity-estimation
3
+ seed: 42
4
+ honesty: >
5
+ No trained weights are shipped. Smoke images are synthetic.
6
+ This is not an operational forecast or warning system.
7
+ Best-track labels are noisy, and agreement with them is not ground truth.
8
+ No survey or smoke number is a result of this project.
9
+ paths:
10
+ manifest: data/incyde/manifest.csv
11
+ artifacts: artifacts
12
+ reports: reports
13
+ checkpoint_name: checkpoint.pt
14
+ run_records: artifacts/run_records
15
+ runs: artifacts/runs
16
+ nasa_root: data/nasa_tc
17
+ tcir_files: []
18
+ tcir_manifest_dir: data/tcir
19
+ frame_cache: artifacts/frame_cache
20
+ # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
21
+ run_id: null
22
+ hf_model_repo: null
23
+ data:
24
+ dataset: incyde
25
+ # null or native keeps each chip's height and width. NASA TorchGeo chips
26
+ # are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
27
+ # resizes the deep model to that square. Classical features stay native.
28
+ image_size: native
29
+ channels: 1
30
+ normalize: zscore
31
+ max_missing_fraction: 0.30
32
+ plausible_wind_kt: [0, 200]
33
+ # Raw IMD 3-minute sustained winds from the INCYDE labels CSV.
34
+ # Do not convert them to 1-minute. wind_averaging_s is 180 on every row.
35
+ wind_averaging: 3-min
36
+ # Project bins for error tables. Not an IMD warning, and not the IMD
37
+ # 3-minute scale. IMD uses 3-minute winds. These edges are this project's
38
+ # own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
39
+ # and 91 kt and above ESCS_SUCS.
40
+ imd5_edges_kt: [17, 34, 48, 64, 91]
41
+ imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
42
+ # International knot. Used only to display a second unit.
43
+ kt_to_kmh: 1.852
44
+ # letterbox pads to a square before the checkpoint resize. stretch is the old path.
45
+ resize: letterbox
46
+ pad: median
47
+ grouping_note: >
48
+ Intensity category is this project's grouping on the configured knot bins.
49
+ It is not an official IMD class.
50
+ split:
51
+ strategy: recorded
52
+ test_fraction: 0.2
53
+ val_fraction: 0.2
54
+ holdout_years: []
55
+ holdout_basin: null
56
+ seed: 42
57
+ model:
58
+ name: simple_cnn
59
+ pretrained: false
60
+ dropout: 0.3
61
+ mc_samples: 20
62
+ # Used when model.name is convlstm. The sequence length stays 4.
63
+ n_frames: 4
64
+ hidden: 16
65
+ train:
66
+ batch_size: 16
67
+ epochs: 20
68
+ lr: 0.001
69
+ weight_decay: 0.0001
70
+ patience: 5
71
+ # auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
72
+ device: auto
73
+ max_steps: null
74
+ grad_accum_steps: 1
75
+ num_workers: 2
76
+ # Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
77
+ device_parity_tol: 0.05
78
+ class_loss_weight: 0.1
79
+ # Applied only when r34_nmi and rmw_nmi exist on the train split.
80
+ size_loss_weight: 0.1
81
+ predict:
82
+ # Review flag, not a warning threshold.
83
+ advisory_jump_kt: 20
84
+ operational_disclaimer: "This is not an operational forecast."
85
+ no_run_record_review: "no matching real-data run record"
86
+ no_run_record_refusal: >
87
+ This checkpoint has no matching real-data run record.
88
+ There is no model output. This is not a forecast.
89
+ held_out_refusal: >
90
+ This checkpoint's real-data run record has not passed the held-out
91
+ storm check. There is no model output. This is not a forecast.
92
+ landfall_note: "not a landfall forecast"
93
+ coast_reference_note: >
94
+ Reference points are approximate coastal coordinates, not a shoreline
95
+ survey and not a landfall forecast.
96
+ coastal_heading: "nearest Indian coastal states to the current position"
97
+ coastal_count: 3
98
+ earth_radius_km: 6371.0
99
+ latitude_keys: [latitude, lat]
100
+ longitude_keys: [longitude, lon]
101
+ # Image mean must sit within this many training standard deviations.
102
+ training_mean_width: 3
103
+ # Same storm, resized, should stay inside this knot span.
104
+ scale_tolerance_kt: 1.0
105
+ sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
106
+ confidence:
107
+ uncalibrated_label: uncalibrated
108
+ coverage_label: "real-data coverage recorded"
109
+ gate_weight: 0.4
110
+ mc_weight: 0.4
111
+ interval_weight: 0.2
112
+ mc_std_scale_kt: 15
113
+ interval_scale_kt: 30
114
+ gate:
115
+ refusal: "not a tropical cyclone IR image"
116
+ grayscale_tolerance: 0.08
117
+ min_std: 0.02
118
+ min_symmetry: 0.45
119
+ min_cold_concentration: 0.36
120
+ cold_radius_fraction: 0.45
121
+ cold_tail_fraction: 0.25
122
+ eye_radius_fraction: 0.12
123
+ eyewall_outer_fraction: 0.32
124
+ outer_inner_fraction: 0.55
125
+ outer_outer_fraction: 0.95
126
+ min_wall_contrast: 0.45
127
+ radial_bins: 8
128
+ cold_value: auto
129
+ max_dropout_std_kt: 50
130
+ concentration_reference: 0.75
131
+ # Approximate public reference points, not Survey of India boundaries.
132
+ coast:
133
+ - {name: Gujarat, lat: 21.64, lon: 69.61}
134
+ - {name: Maharashtra, lat: 18.94, lon: 72.84}
135
+ - {name: Goa, lat: 15.49, lon: 73.83}
136
+ - {name: Karnataka, lat: 12.91, lon: 74.86}
137
+ - {name: Kerala, lat: 9.93, lon: 76.26}
138
+ - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
139
+ - {name: Puducherry, lat: 11.94, lon: 79.83}
140
+ - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
141
+ - {name: Odisha, lat: 19.81, lon: 85.83}
142
+ - {name: West Bengal, lat: 21.63, lon: 87.51}
143
+ - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
144
+ - {name: Lakshadweep, lat: 10.57, lon: 72.64}
145
+ - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
146
+ forbidden_features:
147
+ - wind_speed_kt
148
+ - r34_nmi
149
+ - rmw_nmi
150
+ - imd5_class
151
+ - intensity_bin
152
+ features:
153
+ # Name distributional stats tb_* only when a calibration table was applied.
154
+ calibrated: false
155
+ cold_thresholds: [200, 210, 220, 230, 240]
156
+ radial_bins: 8
157
+ eye_radius_fraction: 0.12
158
+ cdo_outer_fraction: 0.35
159
+ eye_contrast_min: 2.0
160
+ dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
161
+ dav_annulus_width_fraction: 0.08
162
+ glcm_levels: 16
163
+ glcm_distance: 1
164
+ selection:
165
+ correlation_threshold: 0.95
166
+ max_features: 25
167
+ method: correlation_rf
168
+ n_estimators: 80
169
+ seed: 42
170
+ baselines:
171
+ # Five folds, seed 42, groups dealt round-robin. The file
172
+ # results/incyde_baselines/cv_folds.csv is storm_id,fold for train+val
173
+ # only, and each cooccurrence_group stays in one fold.
174
+ n_splits: 5
175
+ seed: 42
176
+ # Validation per-class intervals. Each resample draws storms with replacement.
177
+ # The generator seed is baselines.seed. Rows are not resampled.
178
+ bootstrap_resamples: 1000
179
+ # List each storm inside a class that has fewer than 3 storms.
180
+ per_storm_breakdown: true
181
+ regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
182
+ classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
183
+ use_smote: true
184
+ ridge_alpha: 1.0
185
+ knn_neighbors: 5
186
+ svr_c: 1.0
187
+ svc_c: 1.0
188
+ rf_estimators: 200
189
+ rf_max_depth: 6
190
+ xgb_estimators: 80
191
+ xgb_max_depth: 3
192
+ xgb_learning_rate: 0.1
193
+ max_iter: 1000
194
+ # Grouped CV. train folds the training storms only. train_val folds
195
+ # train and val together and never includes test. The group column stays
196
+ # intact inside a fold. cv_collapse_rare remaps a stratify label that
197
+ # sits in fewer groups than n_splits, for fold assignment only.
198
+ cv_pool: train_val
199
+ cv_group_column: cv_group
200
+ cv_collapse_rare: false
201
+ cv_assign: round_robin
config/config_incyde_224.yaml ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ baselines:
2
+ bootstrap_resamples: 1000
3
+ classification_models:
4
+ - mean
5
+ - persistence
6
+ - logreg
7
+ - knn
8
+ - rf
9
+ - xgboost
10
+ - svc
11
+ cv_assign: stratified
12
+ cv_collapse_rare: false
13
+ cv_group_column: storm_id
14
+ cv_pool: train
15
+ knn_neighbors: 5
16
+ max_iter: 1000
17
+ n_splits: 3
18
+ per_storm_breakdown: true
19
+ regression_models:
20
+ - mean
21
+ - persistence
22
+ - ridge
23
+ - lr
24
+ - knn
25
+ - rf
26
+ - xgboost
27
+ - svr
28
+ rf_estimators: 200
29
+ rf_max_depth: 6
30
+ ridge_alpha: 1.0
31
+ seed: 42
32
+ svc_c: 1.0
33
+ svr_c: 1.0
34
+ use_smote: true
35
+ xgb_estimators: 80
36
+ xgb_learning_rate: 0.1
37
+ xgb_max_depth: 3
38
+ data:
39
+ channels: 1
40
+ dataset: nasa
41
+ grouping_note: 'Intensity category is this project''s grouping on the configured
42
+ knot bins. It is not an official IMD class.
43
+
44
+ '
45
+ image_size: 224
46
+ imd5_edges_kt:
47
+ - 17
48
+ - 34
49
+ - 48
50
+ - 64
51
+ - 91
52
+ imd5_names:
53
+ - D_DD
54
+ - CS
55
+ - SCS
56
+ - VSCS
57
+ - ESCS_SUCS
58
+ kt_to_kmh: 1.852
59
+ max_missing_fraction: 0.3
60
+ normalize: zscore
61
+ pad: median
62
+ plausible_wind_kt:
63
+ - 0
64
+ - 200
65
+ resize: letterbox
66
+ wind_averaging: 1min
67
+ features:
68
+ calibrated: false
69
+ cdo_outer_fraction: 0.35
70
+ cold_thresholds:
71
+ - 200
72
+ - 210
73
+ - 220
74
+ - 230
75
+ - 240
76
+ dav_annulus_width_fraction: 0.08
77
+ dav_radii_fractions:
78
+ - 0.15
79
+ - 0.3
80
+ - 0.45
81
+ - 0.6
82
+ eye_contrast_min: 2.0
83
+ eye_radius_fraction: 0.12
84
+ glcm_distance: 1
85
+ glcm_levels: 16
86
+ radial_bins: 8
87
+ selection:
88
+ correlation_threshold: 0.95
89
+ max_features: 25
90
+ method: correlation_rf
91
+ n_estimators: 80
92
+ seed: 42
93
+ forbidden_features:
94
+ - wind_speed_kt
95
+ - r34_nmi
96
+ - rmw_nmi
97
+ - imd5_class
98
+ - intensity_bin
99
+ incyde:
100
+ archive: null
101
+ cv_folds_csv: null
102
+ cv_seed: 42
103
+ cv_val_fold: 0
104
+ drop_qc_flags: []
105
+ exclusions_csv: null
106
+ frame_flags_csv: null
107
+ manifest_csv: null
108
+ n_folds: 5
109
+ on_fix_only_eval: false
110
+ storm_split_csv: null
111
+ labels:
112
+ label_column: wind_kt_3min
113
+ near_land_policy: flag
114
+ open_water_km: 20
115
+ wind_1min_to_3min: 0.93
116
+ model:
117
+ dropout: 0.3
118
+ hidden: 16
119
+ mc_samples: 20
120
+ n_frames: 4
121
+ name: simple_cnn
122
+ pretrained: false
123
+ paths:
124
+ artifacts: artifacts
125
+ checkpoint_name: checkpoint.pt
126
+ frame_cache: artifacts/frame_cache
127
+ hf_model_repo: null
128
+ incyde_root: data/incyde
129
+ manifest: data/manifest.csv
130
+ nasa_root: data/nasa_tc
131
+ reports: reports
132
+ run_id: null
133
+ run_records: artifacts/run_records
134
+ runs: artifacts/runs
135
+ tcir_files: []
136
+ tcir_manifest_dir: data/tcir
137
+ predict:
138
+ advisory_jump_kt: 20
139
+ coast:
140
+ - lat: 21.64
141
+ lon: 69.61
142
+ name: Gujarat
143
+ - lat: 18.94
144
+ lon: 72.84
145
+ name: Maharashtra
146
+ - lat: 15.49
147
+ lon: 73.83
148
+ name: Goa
149
+ - lat: 12.91
150
+ lon: 74.86
151
+ name: Karnataka
152
+ - lat: 9.93
153
+ lon: 76.26
154
+ name: Kerala
155
+ - lat: 13.08
156
+ lon: 80.27
157
+ name: Tamil Nadu
158
+ - lat: 11.94
159
+ lon: 79.83
160
+ name: Puducherry
161
+ - lat: 17.69
162
+ lon: 83.22
163
+ name: Andhra Pradesh
164
+ - lat: 19.81
165
+ lon: 85.83
166
+ name: Odisha
167
+ - lat: 21.63
168
+ lon: 87.51
169
+ name: West Bengal
170
+ - lat: 11.67
171
+ lon: 92.74
172
+ name: Andaman and Nicobar Islands
173
+ - lat: 10.57
174
+ lon: 72.64
175
+ name: Lakshadweep
176
+ - lat: 20.42
177
+ lon: 72.83
178
+ name: Dadra and Nagar Haveli and Daman and Diu
179
+ coast_reference_note: 'Reference points are approximate coastal coordinates, not
180
+ a shoreline survey and not a landfall forecast.
181
+
182
+ '
183
+ coastal_count: 3
184
+ coastal_heading: nearest Indian coastal states to the current position
185
+ confidence:
186
+ coverage_label: real-data coverage recorded
187
+ gate_weight: 0.4
188
+ interval_scale_kt: 30
189
+ interval_weight: 0.2
190
+ mc_std_scale_kt: 15
191
+ mc_weight: 0.4
192
+ uncalibrated_label: uncalibrated
193
+ earth_radius_km: 6371.0
194
+ gate:
195
+ cold_radius_fraction: 0.45
196
+ cold_tail_fraction: 0.25
197
+ cold_value: auto
198
+ concentration_reference: 0.75
199
+ eye_radius_fraction: 0.12
200
+ eyewall_outer_fraction: 0.32
201
+ grayscale_tolerance: 0.08
202
+ max_dropout_std_kt: 50
203
+ min_cold_concentration: 0.36
204
+ min_std: 0.02
205
+ min_symmetry: 0.45
206
+ min_wall_contrast: 0.45
207
+ outer_inner_fraction: 0.55
208
+ outer_outer_fraction: 0.95
209
+ radial_bins: 8
210
+ refusal: not a tropical cyclone IR image
211
+ held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out
212
+ storm check. There is no model output. This is not a forecast.
213
+
214
+ '
215
+ landfall_note: not a landfall forecast
216
+ latitude_keys:
217
+ - latitude
218
+ - lat
219
+ longitude_keys:
220
+ - longitude
221
+ - lon
222
+ no_run_record_refusal: 'This checkpoint has no matching real-data run record. There
223
+ is no model output. This is not a forecast.
224
+
225
+ '
226
+ no_run_record_review: no matching real-data run record
227
+ operational_disclaimer: This is not an operational forecast.
228
+ scale_tolerance_kt: 1.0
229
+ sklearn_features:
230
+ - symmetry
231
+ - cold_concentration
232
+ - wall_contrast
233
+ - eye_contrast
234
+ training_mean_width: 3
235
+ project:
236
+ honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not
237
+ an operational forecast or warning system. Best-track labels are noisy, and agreement
238
+ with them is not ground truth. No survey or smoke number is a result of this project.
239
+
240
+ '
241
+ name: cyclone-intensity-estimation
242
+ seed: 42
243
+ split:
244
+ holdout_basin: null
245
+ holdout_years: []
246
+ seed: 42
247
+ strategy: storm_wise
248
+ test_fraction: 0.2
249
+ val_fraction: 0.2
250
+ train:
251
+ balanced_sampling: false
252
+ batch_size: 16
253
+ class_loss_weight: 0.1
254
+ device: auto
255
+ device_parity_tol: 0.05
256
+ epochs: 20
257
+ grad_accum_steps: 1
258
+ loss_weighting: none
259
+ lr: 0.001
260
+ max_steps: null
261
+ num_workers: 2
262
+ patience: 5
263
+ size_loss_weight: 0.1
264
+ weight_decay: 0.0001
config/config_incyde_safe.yaml ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ baselines:
2
+ bootstrap_resamples: 1000
3
+ classification_models:
4
+ - mean
5
+ - persistence
6
+ - logreg
7
+ - knn
8
+ - rf
9
+ - xgboost
10
+ - svc
11
+ cv_assign: stratified
12
+ cv_collapse_rare: false
13
+ cv_group_column: storm_id
14
+ cv_pool: train
15
+ knn_neighbors: 5
16
+ max_iter: 1000
17
+ n_splits: 3
18
+ per_storm_breakdown: true
19
+ regression_models:
20
+ - mean
21
+ - persistence
22
+ - ridge
23
+ - lr
24
+ - knn
25
+ - rf
26
+ - xgboost
27
+ - svr
28
+ rf_estimators: 200
29
+ rf_max_depth: 6
30
+ ridge_alpha: 1.0
31
+ seed: 42
32
+ svc_c: 1.0
33
+ svr_c: 1.0
34
+ use_smote: true
35
+ xgb_estimators: 80
36
+ xgb_learning_rate: 0.1
37
+ xgb_max_depth: 3
38
+ data:
39
+ channels: 1
40
+ dataset: nasa
41
+ grouping_note: 'Intensity category is this project''s grouping on the configured
42
+ knot bins. It is not an official IMD class.
43
+
44
+ '
45
+ image_size: 224
46
+ imd5_edges_kt:
47
+ - 17
48
+ - 34
49
+ - 48
50
+ - 64
51
+ - 91
52
+ imd5_names:
53
+ - D_DD
54
+ - CS
55
+ - SCS
56
+ - VSCS
57
+ - ESCS_SUCS
58
+ kt_to_kmh: 1.852
59
+ max_missing_fraction: 0.3
60
+ normalize: zscore
61
+ pad: median
62
+ plausible_wind_kt:
63
+ - 0
64
+ - 200
65
+ resize: letterbox
66
+ wind_averaging: 1min
67
+ features:
68
+ calibrated: false
69
+ cdo_outer_fraction: 0.35
70
+ cold_thresholds:
71
+ - 200
72
+ - 210
73
+ - 220
74
+ - 230
75
+ - 240
76
+ dav_annulus_width_fraction: 0.08
77
+ dav_radii_fractions:
78
+ - 0.15
79
+ - 0.3
80
+ - 0.45
81
+ - 0.6
82
+ eye_contrast_min: 2.0
83
+ eye_radius_fraction: 0.12
84
+ glcm_distance: 1
85
+ glcm_levels: 16
86
+ radial_bins: 8
87
+ selection:
88
+ correlation_threshold: 0.95
89
+ max_features: 25
90
+ method: correlation_rf
91
+ n_estimators: 80
92
+ seed: 42
93
+ forbidden_features:
94
+ - wind_speed_kt
95
+ - r34_nmi
96
+ - rmw_nmi
97
+ - imd5_class
98
+ - intensity_bin
99
+ incyde:
100
+ archive: null
101
+ cv_folds_csv: null
102
+ cv_seed: 42
103
+ cv_val_fold: 0
104
+ drop_qc_flags: []
105
+ exclusions_csv: null
106
+ frame_flags_csv: null
107
+ manifest_csv: null
108
+ n_folds: 5
109
+ on_fix_only_eval: false
110
+ storm_split_csv: null
111
+ labels:
112
+ label_column: wind_kt_3min
113
+ near_land_policy: flag
114
+ open_water_km: 20
115
+ wind_1min_to_3min: 0.93
116
+ model:
117
+ dropout: 0.3
118
+ hidden: 16
119
+ mc_samples: 20
120
+ n_frames: 4
121
+ name: simple_cnn
122
+ pretrained: false
123
+ paths:
124
+ artifacts: artifacts
125
+ checkpoint_name: checkpoint.pt
126
+ frame_cache: artifacts/frame_cache
127
+ hf_model_repo: null
128
+ incyde_root: data/incyde/Cropped_cyclone_data
129
+ manifest: data/manifest.csv
130
+ nasa_root: data/nasa_tc
131
+ reports: reports
132
+ run_id: null
133
+ run_records: artifacts/run_records
134
+ runs: artifacts/runs
135
+ tcir_files: []
136
+ tcir_manifest_dir: data/tcir
137
+ predict:
138
+ advisory_jump_kt: 20
139
+ coast:
140
+ - lat: 21.64
141
+ lon: 69.61
142
+ name: Gujarat
143
+ - lat: 18.94
144
+ lon: 72.84
145
+ name: Maharashtra
146
+ - lat: 15.49
147
+ lon: 73.83
148
+ name: Goa
149
+ - lat: 12.91
150
+ lon: 74.86
151
+ name: Karnataka
152
+ - lat: 9.93
153
+ lon: 76.26
154
+ name: Kerala
155
+ - lat: 13.08
156
+ lon: 80.27
157
+ name: Tamil Nadu
158
+ - lat: 11.94
159
+ lon: 79.83
160
+ name: Puducherry
161
+ - lat: 17.69
162
+ lon: 83.22
163
+ name: Andhra Pradesh
164
+ - lat: 19.81
165
+ lon: 85.83
166
+ name: Odisha
167
+ - lat: 21.63
168
+ lon: 87.51
169
+ name: West Bengal
170
+ - lat: 11.67
171
+ lon: 92.74
172
+ name: Andaman and Nicobar Islands
173
+ - lat: 10.57
174
+ lon: 72.64
175
+ name: Lakshadweep
176
+ - lat: 20.42
177
+ lon: 72.83
178
+ name: Dadra and Nagar Haveli and Daman and Diu
179
+ coast_reference_note: 'Reference points are approximate coastal coordinates, not
180
+ a shoreline survey and not a landfall forecast.
181
+
182
+ '
183
+ coastal_count: 3
184
+ coastal_heading: nearest Indian coastal states to the current position
185
+ confidence:
186
+ coverage_label: real-data coverage recorded
187
+ gate_weight: 0.4
188
+ interval_scale_kt: 30
189
+ interval_weight: 0.2
190
+ mc_std_scale_kt: 15
191
+ mc_weight: 0.4
192
+ uncalibrated_label: uncalibrated
193
+ earth_radius_km: 6371.0
194
+ gate:
195
+ cold_radius_fraction: 0.45
196
+ cold_tail_fraction: 0.25
197
+ cold_value: auto
198
+ concentration_reference: 0.75
199
+ eye_radius_fraction: 0.12
200
+ eyewall_outer_fraction: 0.32
201
+ grayscale_tolerance: 0.08
202
+ max_dropout_std_kt: 50
203
+ min_cold_concentration: 0.36
204
+ min_std: 0.02
205
+ min_symmetry: 0.45
206
+ min_wall_contrast: 0.45
207
+ outer_inner_fraction: 0.55
208
+ outer_outer_fraction: 0.95
209
+ radial_bins: 8
210
+ refusal: not a tropical cyclone IR image
211
+ held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out
212
+ storm check. There is no model output. This is not a forecast.
213
+
214
+ '
215
+ landfall_note: not a landfall forecast
216
+ latitude_keys:
217
+ - latitude
218
+ - lat
219
+ longitude_keys:
220
+ - longitude
221
+ - lon
222
+ no_run_record_refusal: 'This checkpoint has no matching real-data run record. There
223
+ is no model output. This is not a forecast.
224
+
225
+ '
226
+ no_run_record_review: no matching real-data run record
227
+ operational_disclaimer: This is not an operational forecast.
228
+ scale_tolerance_kt: 1.0
229
+ sklearn_features:
230
+ - symmetry
231
+ - cold_concentration
232
+ - wall_contrast
233
+ - eye_contrast
234
+ training_mean_width: 3
235
+ project:
236
+ honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not
237
+ an operational forecast or warning system. Best-track labels are noisy, and agreement
238
+ with them is not ground truth. No survey or smoke number is a result of this project.
239
+
240
+ '
241
+ name: cyclone-intensity-estimation
242
+ seed: 42
243
+ split:
244
+ holdout_basin: null
245
+ holdout_years: []
246
+ seed: 42
247
+ strategy: storm_wise
248
+ test_fraction: 0.2
249
+ val_fraction: 0.2
250
+ train:
251
+ balanced_sampling: false
252
+ batch_size: 8
253
+ class_loss_weight: 0.1
254
+ device: auto
255
+ device_parity_tol: 0.05
256
+ epochs: 20
257
+ grad_accum_steps: 2
258
+ loss_weighting: none
259
+ lr: 0.001
260
+ max_steps: null
261
+ num_workers: 0
262
+ patience: 5
263
+ size_loss_weight: 0.1
264
+ weight_decay: 0.0001
config/config_nasa_safe.yaml ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ baselines:
2
+ bootstrap_resamples: 1000
3
+ classification_models:
4
+ - mean
5
+ - persistence
6
+ - logreg
7
+ - knn
8
+ - rf
9
+ - xgboost
10
+ - svc
11
+ cv_assign: stratified
12
+ cv_collapse_rare: false
13
+ cv_group_column: storm_id
14
+ cv_pool: train
15
+ knn_neighbors: 5
16
+ max_iter: 1000
17
+ n_splits: 3
18
+ per_storm_breakdown: true
19
+ regression_models:
20
+ - mean
21
+ - persistence
22
+ - ridge
23
+ - lr
24
+ - knn
25
+ - rf
26
+ - xgboost
27
+ - svr
28
+ rf_estimators: 200
29
+ rf_max_depth: 6
30
+ ridge_alpha: 1.0
31
+ seed: 42
32
+ svc_c: 1.0
33
+ svr_c: 1.0
34
+ use_smote: true
35
+ xgb_estimators: 80
36
+ xgb_learning_rate: 0.1
37
+ xgb_max_depth: 3
38
+ data:
39
+ channels: 1
40
+ dataset: nasa
41
+ grouping_note: 'Intensity category is this project''s grouping on the configured
42
+ knot bins. It is not an official IMD class.
43
+
44
+ '
45
+ image_size: native
46
+ imd5_edges_kt:
47
+ - 17
48
+ - 34
49
+ - 48
50
+ - 64
51
+ - 91
52
+ imd5_names:
53
+ - D_DD
54
+ - CS
55
+ - SCS
56
+ - VSCS
57
+ - ESCS_SUCS
58
+ kt_to_kmh: 1.852
59
+ max_missing_fraction: 0.3
60
+ normalize: zscore
61
+ pad: median
62
+ plausible_wind_kt:
63
+ - 0
64
+ - 200
65
+ resize: letterbox
66
+ wind_averaging: 1min
67
+ features:
68
+ calibrated: false
69
+ cdo_outer_fraction: 0.35
70
+ cold_thresholds:
71
+ - 200
72
+ - 210
73
+ - 220
74
+ - 230
75
+ - 240
76
+ dav_annulus_width_fraction: 0.08
77
+ dav_radii_fractions:
78
+ - 0.15
79
+ - 0.3
80
+ - 0.45
81
+ - 0.6
82
+ eye_contrast_min: 2.0
83
+ eye_radius_fraction: 0.12
84
+ glcm_distance: 1
85
+ glcm_levels: 16
86
+ radial_bins: 8
87
+ selection:
88
+ correlation_threshold: 0.95
89
+ max_features: 25
90
+ method: correlation_rf
91
+ n_estimators: 80
92
+ seed: 42
93
+ forbidden_features:
94
+ - wind_speed_kt
95
+ - r34_nmi
96
+ - rmw_nmi
97
+ - imd5_class
98
+ - intensity_bin
99
+ incyde:
100
+ archive: null
101
+ cv_folds_csv: null
102
+ cv_seed: 42
103
+ cv_val_fold: 0
104
+ drop_qc_flags: []
105
+ exclusions_csv: null
106
+ frame_flags_csv: null
107
+ manifest_csv: null
108
+ n_folds: 5
109
+ on_fix_only_eval: false
110
+ storm_split_csv: null
111
+ labels:
112
+ label_column: wind_kt_3min
113
+ near_land_policy: flag
114
+ open_water_km: 20
115
+ wind_1min_to_3min: 0.93
116
+ model:
117
+ dropout: 0.3
118
+ hidden: 16
119
+ mc_samples: 20
120
+ n_frames: 4
121
+ name: simple_cnn
122
+ pretrained: false
123
+ paths:
124
+ artifacts: artifacts
125
+ checkpoint_name: checkpoint.pt
126
+ frame_cache: artifacts/frame_cache
127
+ hf_model_repo: null
128
+ incyde_root: data/incyde
129
+ manifest: data/manifest.csv
130
+ nasa_root: data/nasa_tc
131
+ reports: reports
132
+ run_id: null
133
+ run_records: artifacts/run_records
134
+ runs: artifacts/runs
135
+ tcir_files: []
136
+ tcir_manifest_dir: data/tcir
137
+ predict:
138
+ advisory_jump_kt: 20
139
+ coast:
140
+ - lat: 21.64
141
+ lon: 69.61
142
+ name: Gujarat
143
+ - lat: 18.94
144
+ lon: 72.84
145
+ name: Maharashtra
146
+ - lat: 15.49
147
+ lon: 73.83
148
+ name: Goa
149
+ - lat: 12.91
150
+ lon: 74.86
151
+ name: Karnataka
152
+ - lat: 9.93
153
+ lon: 76.26
154
+ name: Kerala
155
+ - lat: 13.08
156
+ lon: 80.27
157
+ name: Tamil Nadu
158
+ - lat: 11.94
159
+ lon: 79.83
160
+ name: Puducherry
161
+ - lat: 17.69
162
+ lon: 83.22
163
+ name: Andhra Pradesh
164
+ - lat: 19.81
165
+ lon: 85.83
166
+ name: Odisha
167
+ - lat: 21.63
168
+ lon: 87.51
169
+ name: West Bengal
170
+ - lat: 11.67
171
+ lon: 92.74
172
+ name: Andaman and Nicobar Islands
173
+ - lat: 10.57
174
+ lon: 72.64
175
+ name: Lakshadweep
176
+ - lat: 20.42
177
+ lon: 72.83
178
+ name: Dadra and Nagar Haveli and Daman and Diu
179
+ coast_reference_note: 'Reference points are approximate coastal coordinates, not
180
+ a shoreline survey and not a landfall forecast.
181
+
182
+ '
183
+ coastal_count: 3
184
+ coastal_heading: nearest Indian coastal states to the current position
185
+ confidence:
186
+ coverage_label: real-data coverage recorded
187
+ gate_weight: 0.4
188
+ interval_scale_kt: 30
189
+ interval_weight: 0.2
190
+ mc_std_scale_kt: 15
191
+ mc_weight: 0.4
192
+ uncalibrated_label: uncalibrated
193
+ earth_radius_km: 6371.0
194
+ gate:
195
+ cold_radius_fraction: 0.45
196
+ cold_tail_fraction: 0.25
197
+ cold_value: auto
198
+ concentration_reference: 0.75
199
+ eye_radius_fraction: 0.12
200
+ eyewall_outer_fraction: 0.32
201
+ grayscale_tolerance: 0.08
202
+ max_dropout_std_kt: 50
203
+ min_cold_concentration: 0.36
204
+ min_std: 0.02
205
+ min_symmetry: 0.45
206
+ min_wall_contrast: 0.45
207
+ outer_inner_fraction: 0.55
208
+ outer_outer_fraction: 0.95
209
+ radial_bins: 8
210
+ refusal: not a tropical cyclone IR image
211
+ held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out
212
+ storm check. There is no model output. This is not a forecast.
213
+
214
+ '
215
+ landfall_note: not a landfall forecast
216
+ latitude_keys:
217
+ - latitude
218
+ - lat
219
+ longitude_keys:
220
+ - longitude
221
+ - lon
222
+ no_run_record_refusal: 'This checkpoint has no matching real-data run record. There
223
+ is no model output. This is not a forecast.
224
+
225
+ '
226
+ no_run_record_review: no matching real-data run record
227
+ operational_disclaimer: This is not an operational forecast.
228
+ scale_tolerance_kt: 1.0
229
+ sklearn_features:
230
+ - symmetry
231
+ - cold_concentration
232
+ - wall_contrast
233
+ - eye_contrast
234
+ training_mean_width: 3
235
+ project:
236
+ honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not
237
+ an operational forecast or warning system. Best-track labels are noisy, and agreement
238
+ with them is not ground truth. No survey or smoke number is a result of this project.
239
+
240
+ '
241
+ name: cyclone-intensity-estimation
242
+ seed: 42
243
+ split:
244
+ holdout_basin: null
245
+ holdout_years: []
246
+ seed: 42
247
+ strategy: storm_wise
248
+ test_fraction: 0.2
249
+ val_fraction: 0.2
250
+ train:
251
+ balanced_sampling: false
252
+ batch_size: 8
253
+ class_loss_weight: 0.1
254
+ device: auto
255
+ device_parity_tol: 0.05
256
+ epochs: 20
257
+ grad_accum_steps: 2
258
+ loss_weighting: none
259
+ lr: 0.001
260
+ max_steps: null
261
+ num_workers: 0
262
+ patience: 5
263
+ size_loss_weight: 0.1
264
+ weight_decay: 0.0001
config/config_smoke.yaml CHANGED
@@ -1,196 +1,196 @@
1
- project:
2
- name: cyclone-intensity-estimation-smoke
3
- seed: 7
4
- honesty: >
5
- Smoke images are synthetic. Metrics from this config are a software
6
- check, not a scientific result and not a forecast.
7
- paths:
8
- manifest: data/smoke/manifest.csv
9
- artifacts: artifacts/smoke
10
- reports: reports/smoke
11
- checkpoint_name: checkpoint.pt
12
- run_records: artifacts/run_records
13
- runs: artifacts/runs
14
- nasa_root: data/nasa_tc
15
- tcir_files: []
16
- tcir_manifest_dir: data/tcir
17
- frame_cache: artifacts/frame_cache
18
- incyde_root: data/incyde
19
- # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
20
- run_id: null
21
- hf_model_repo: null
22
- data:
23
- dataset: smoke
24
- # Small square so the software check stays fast. The NASA config uses native.
25
- image_size: 64
26
- channels: 1
27
- normalize: zscore
28
- max_missing_fraction: 0.30
29
- plausible_wind_kt: [0, 200]
30
- # Smoke labels are synthetic. They are not HURDAT2 1-minute winds.
31
- wind_averaging: synthetic
32
- # Same project bins as config.yaml. IMD itself uses 3-minute winds.
33
- # 17/34/48/64/91 kt is this project's grouping, not that IMD scale.
34
- imd5_edges_kt: [17, 34, 48, 64, 91]
35
- imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
36
- kt_to_kmh: 1.852
37
- resize: letterbox
38
- pad: median
39
- grouping_note: >
40
- Intensity category is this project's grouping on the configured knot bins.
41
- It is not an official IMD class.
42
- labels:
43
- label_column: wind_kt_3min
44
- wind_1min_to_3min: 0.93
45
- near_land_policy: flag
46
- open_water_km: 20
47
- incyde:
48
- manifest_csv: null
49
- storm_split_csv: null
50
- exclusions_csv: null
51
- archive: null
52
- drop_qc_flags: []
53
- n_folds: 5
54
- cv_val_fold: 0
55
- cv_seed: 42
56
- cv_folds_csv: null
57
- frame_flags_csv: null
58
- on_fix_only_eval: false
59
- split:
60
- strategy: storm_wise
61
- test_fraction: 0.2
62
- val_fraction: 0.2
63
- holdout_years: [2021]
64
- holdout_basin: NIO
65
- seed: 7
66
- model:
67
- name: simple_cnn
68
- pretrained: false
69
- dropout: 0.3
70
- mc_samples: 20
71
- n_frames: 4
72
- hidden: 8
73
- train:
74
- batch_size: 8
75
- epochs: 2
76
- lr: 0.001
77
- weight_decay: 0.0001
78
- patience: 1
79
- device: auto
80
- max_steps: null
81
- grad_accum_steps: 1
82
- num_workers: 2
83
- device_parity_tol: 0.05
84
- class_loss_weight: 0.1
85
- size_loss_weight: 0.1
86
- loss_weighting: none
87
- balanced_sampling: false
88
- predict:
89
- advisory_jump_kt: 20
90
- operational_disclaimer: "This is not an operational forecast."
91
- no_run_record_review: "no matching real-data run record"
92
- no_run_record_refusal: >
93
- This checkpoint has no matching real-data run record.
94
- There is no model output. This is not a forecast.
95
- held_out_refusal: >
96
- This checkpoint's real-data run record has not passed the held-out
97
- storm check. There is no model output. This is not a forecast.
98
- landfall_note: "not a landfall forecast"
99
- coast_reference_note: >
100
- Reference points are approximate coastal coordinates, not a shoreline
101
- survey and not a landfall forecast.
102
- coastal_heading: "nearest Indian coastal states to the current position"
103
- coastal_count: 3
104
- earth_radius_km: 6371.0
105
- latitude_keys: [latitude, lat]
106
- longitude_keys: [longitude, lon]
107
- training_mean_width: 3
108
- scale_tolerance_kt: 1.0
109
- sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
110
- confidence:
111
- uncalibrated_label: uncalibrated
112
- coverage_label: "real-data coverage recorded"
113
- gate_weight: 0.4
114
- mc_weight: 0.4
115
- interval_weight: 0.2
116
- mc_std_scale_kt: 15
117
- interval_scale_kt: 30
118
- gate:
119
- refusal: "not a tropical cyclone IR image"
120
- grayscale_tolerance: 0.08
121
- min_std: 0.02
122
- min_symmetry: 0.45
123
- min_cold_concentration: 0.36
124
- cold_radius_fraction: 0.45
125
- cold_tail_fraction: 0.25
126
- eye_radius_fraction: 0.12
127
- eyewall_outer_fraction: 0.32
128
- outer_inner_fraction: 0.55
129
- outer_outer_fraction: 0.95
130
- min_wall_contrast: 0.45
131
- radial_bins: 8
132
- cold_value: auto
133
- max_dropout_std_kt: 50
134
- concentration_reference: 0.75
135
- coast:
136
- - {name: Gujarat, lat: 21.64, lon: 69.61}
137
- - {name: Maharashtra, lat: 18.94, lon: 72.84}
138
- - {name: Goa, lat: 15.49, lon: 73.83}
139
- - {name: Karnataka, lat: 12.91, lon: 74.86}
140
- - {name: Kerala, lat: 9.93, lon: 76.26}
141
- - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
142
- - {name: Puducherry, lat: 11.94, lon: 79.83}
143
- - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
144
- - {name: Odisha, lat: 19.81, lon: 85.83}
145
- - {name: West Bengal, lat: 21.63, lon: 87.51}
146
- - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
147
- - {name: Lakshadweep, lat: 10.57, lon: 72.64}
148
- - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
149
- features:
150
- calibrated: false
151
- cold_thresholds: [200, 210, 220, 230, 240]
152
- radial_bins: 8
153
- eye_radius_fraction: 0.12
154
- cdo_outer_fraction: 0.35
155
- eye_contrast_min: 2.0
156
- dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
157
- dav_annulus_width_fraction: 0.08
158
- glcm_levels: 16
159
- glcm_distance: 1
160
- selection:
161
- correlation_threshold: 0.95
162
- max_features: 25
163
- method: correlation_rf
164
- n_estimators: 20
165
- seed: 7
166
- baselines:
167
- n_splits: 2
168
- seed: 7
169
- # Validation per-class intervals. Each resample draws storms with replacement.
170
- # The generator seed is baselines.seed. Rows are not resampled.
171
- bootstrap_resamples: 1000
172
- # List each storm inside a class that has fewer than 3 storms.
173
- per_storm_breakdown: true
174
- regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
175
- classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
176
- use_smote: true
177
- ridge_alpha: 1.0
178
- knn_neighbors: 3
179
- svr_c: 1.0
180
- svc_c: 1.0
181
- rf_estimators: 20
182
- rf_max_depth: 4
183
- xgb_estimators: 20
184
- xgb_max_depth: 3
185
- xgb_learning_rate: 0.1
186
- max_iter: 400
187
- cv_pool: train
188
- cv_group_column: storm_id
189
- cv_collapse_rare: false
190
- cv_assign: stratified
191
- forbidden_features:
192
- - wind_speed_kt
193
- - r34_nmi
194
- - rmw_nmi
195
- - imd5_class
196
- - intensity_bin
 
1
+ project:
2
+ name: cyclone-intensity-estimation-smoke
3
+ seed: 7
4
+ honesty: >
5
+ Smoke images are synthetic. Metrics from this config are a software
6
+ check, not a scientific result and not a forecast.
7
+ paths:
8
+ manifest: data/smoke/manifest.csv
9
+ artifacts: artifacts/smoke
10
+ reports: reports/smoke
11
+ checkpoint_name: checkpoint.pt
12
+ run_records: artifacts/run_records
13
+ runs: artifacts/runs
14
+ nasa_root: data/nasa_tc
15
+ tcir_files: []
16
+ tcir_manifest_dir: data/tcir
17
+ frame_cache: artifacts/frame_cache
18
+ incyde_root: data/incyde
19
+ # Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
20
+ run_id: null
21
+ hf_model_repo: null
22
+ data:
23
+ dataset: smoke
24
+ # Small square so the software check stays fast. The NASA config uses native.
25
+ image_size: 64
26
+ channels: 1
27
+ normalize: zscore
28
+ max_missing_fraction: 0.30
29
+ plausible_wind_kt: [0, 200]
30
+ # Smoke labels are synthetic. They are not HURDAT2 1-minute winds.
31
+ wind_averaging: synthetic
32
+ # Same project bins as config.yaml. IMD itself uses 3-minute winds.
33
+ # 17/34/48/64/91 kt is this project's grouping, not that IMD scale.
34
+ imd5_edges_kt: [17, 34, 48, 64, 91]
35
+ imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
36
+ kt_to_kmh: 1.852
37
+ resize: letterbox
38
+ pad: median
39
+ grouping_note: >
40
+ Intensity category is this project's grouping on the configured knot bins.
41
+ It is not an official IMD class.
42
+ labels:
43
+ label_column: wind_kt_3min
44
+ wind_1min_to_3min: 0.93
45
+ near_land_policy: flag
46
+ open_water_km: 20
47
+ incyde:
48
+ manifest_csv: null
49
+ storm_split_csv: null
50
+ exclusions_csv: null
51
+ archive: null
52
+ drop_qc_flags: []
53
+ n_folds: 5
54
+ cv_val_fold: 0
55
+ cv_seed: 42
56
+ cv_folds_csv: null
57
+ frame_flags_csv: null
58
+ on_fix_only_eval: false
59
+ split:
60
+ strategy: storm_wise
61
+ test_fraction: 0.2
62
+ val_fraction: 0.2
63
+ holdout_years: [2021]
64
+ holdout_basin: NIO
65
+ seed: 7
66
+ model:
67
+ name: simple_cnn
68
+ pretrained: false
69
+ dropout: 0.3
70
+ mc_samples: 20
71
+ n_frames: 4
72
+ hidden: 8
73
+ train:
74
+ batch_size: 8
75
+ epochs: 2
76
+ lr: 0.001
77
+ weight_decay: 0.0001
78
+ patience: 1
79
+ device: auto
80
+ max_steps: null
81
+ grad_accum_steps: 1
82
+ num_workers: 2
83
+ device_parity_tol: 0.05
84
+ class_loss_weight: 0.1
85
+ size_loss_weight: 0.1
86
+ loss_weighting: none
87
+ balanced_sampling: false
88
+ predict:
89
+ advisory_jump_kt: 20
90
+ operational_disclaimer: "This is not an operational forecast."
91
+ no_run_record_review: "no matching real-data run record"
92
+ no_run_record_refusal: >
93
+ This checkpoint has no matching real-data run record.
94
+ There is no model output. This is not a forecast.
95
+ held_out_refusal: >
96
+ This checkpoint's real-data run record has not passed the held-out
97
+ storm check. There is no model output. This is not a forecast.
98
+ landfall_note: "not a landfall forecast"
99
+ coast_reference_note: >
100
+ Reference points are approximate coastal coordinates, not a shoreline
101
+ survey and not a landfall forecast.
102
+ coastal_heading: "nearest Indian coastal states to the current position"
103
+ coastal_count: 3
104
+ earth_radius_km: 6371.0
105
+ latitude_keys: [latitude, lat]
106
+ longitude_keys: [longitude, lon]
107
+ training_mean_width: 3
108
+ scale_tolerance_kt: 1.0
109
+ sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
110
+ confidence:
111
+ uncalibrated_label: uncalibrated
112
+ coverage_label: "real-data coverage recorded"
113
+ gate_weight: 0.4
114
+ mc_weight: 0.4
115
+ interval_weight: 0.2
116
+ mc_std_scale_kt: 15
117
+ interval_scale_kt: 30
118
+ gate:
119
+ refusal: "not a tropical cyclone IR image"
120
+ grayscale_tolerance: 0.08
121
+ min_std: 0.02
122
+ min_symmetry: 0.45
123
+ min_cold_concentration: 0.36
124
+ cold_radius_fraction: 0.45
125
+ cold_tail_fraction: 0.25
126
+ eye_radius_fraction: 0.12
127
+ eyewall_outer_fraction: 0.32
128
+ outer_inner_fraction: 0.55
129
+ outer_outer_fraction: 0.95
130
+ min_wall_contrast: 0.45
131
+ radial_bins: 8
132
+ cold_value: auto
133
+ max_dropout_std_kt: 50
134
+ concentration_reference: 0.75
135
+ coast:
136
+ - {name: Gujarat, lat: 21.64, lon: 69.61}
137
+ - {name: Maharashtra, lat: 18.94, lon: 72.84}
138
+ - {name: Goa, lat: 15.49, lon: 73.83}
139
+ - {name: Karnataka, lat: 12.91, lon: 74.86}
140
+ - {name: Kerala, lat: 9.93, lon: 76.26}
141
+ - {name: Tamil Nadu, lat: 13.08, lon: 80.27}
142
+ - {name: Puducherry, lat: 11.94, lon: 79.83}
143
+ - {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
144
+ - {name: Odisha, lat: 19.81, lon: 85.83}
145
+ - {name: West Bengal, lat: 21.63, lon: 87.51}
146
+ - {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
147
+ - {name: Lakshadweep, lat: 10.57, lon: 72.64}
148
+ - {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
149
+ features:
150
+ calibrated: false
151
+ cold_thresholds: [200, 210, 220, 230, 240]
152
+ radial_bins: 8
153
+ eye_radius_fraction: 0.12
154
+ cdo_outer_fraction: 0.35
155
+ eye_contrast_min: 2.0
156
+ dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
157
+ dav_annulus_width_fraction: 0.08
158
+ glcm_levels: 16
159
+ glcm_distance: 1
160
+ selection:
161
+ correlation_threshold: 0.95
162
+ max_features: 25
163
+ method: correlation_rf
164
+ n_estimators: 20
165
+ seed: 7
166
+ baselines:
167
+ n_splits: 2
168
+ seed: 7
169
+ # Validation per-class intervals. Each resample draws storms with replacement.
170
+ # The generator seed is baselines.seed. Rows are not resampled.
171
+ bootstrap_resamples: 1000
172
+ # List each storm inside a class that has fewer than 3 storms.
173
+ per_storm_breakdown: true
174
+ regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
175
+ classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
176
+ use_smote: true
177
+ ridge_alpha: 1.0
178
+ knn_neighbors: 3
179
+ svr_c: 1.0
180
+ svc_c: 1.0
181
+ rf_estimators: 20
182
+ rf_max_depth: 4
183
+ xgb_estimators: 20
184
+ xgb_max_depth: 3
185
+ xgb_learning_rate: 0.1
186
+ max_iter: 400
187
+ cv_pool: train
188
+ cv_group_column: storm_id
189
+ cv_collapse_rare: false
190
+ cv_assign: stratified
191
+ forbidden_features:
192
+ - wind_speed_kt
193
+ - r34_nmi
194
+ - rmw_nmi
195
+ - imd5_class
196
+ - intensity_bin
config/incyde_cpu.yaml CHANGED
@@ -1,41 +1,41 @@
1
- # INCYDE CPU model v0.1 (SimpleCNN). Used by scripts/incyde_cpu/*.
2
- # Device-neutral: device auto picks xpu, then cuda, then cpu (GPU needs CLOUDIE_ALLOW_GPU=1).
3
- project:
4
- seed: 42
5
- labels:
6
- # Standard: IMD 3-minute sustained wind. INCYDE labels are used unchanged.
7
- # 1-minute sources (TCIR, NASA) are converted with ONE factor:
8
- # 0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, at-sea exposure
9
- # (Harper, Kepert & Ginger 2010). Derived, NOT a WMO constant.
10
- # Pending Researchy's verification.
11
- one_to_three_min_factor: 0.93
12
- one_to_three_min_factor_status: derived_pending_verification
13
- # Rows whose centre is within this distance of land are flagged (near_land).
14
- near_land_km: 20
15
- # false: near-land TCIR rows are left out of pretraining instead of converted.
16
- pretrain_keep_near_land: false
17
- data:
18
- image_size: 96
19
- # Main's project bins (src/schema.py). Not official IMD classes.
20
- imd5_edges_kt: [17, 34, 48, 64, 91]
21
- imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
22
- model:
23
- name: simple_cnn
24
- dropout: 0.3
25
- channels: 1
26
- train:
27
- device: auto
28
- batch_size: 64
29
- epochs: 30
30
- lr: 0.001
31
- weight_decay: 0.0001
32
- patience: 6
33
- class_loss_weight: 0.5
34
- num_workers: 0
35
- cv:
36
- n_folds: 5
37
- seed: 42
38
- augment:
39
- rot_180: true
40
- masked_rotation: true
41
- flips: false
 
1
+ # INCYDE CPU model v0.1 (SimpleCNN). Used by scripts/incyde_cpu/*.
2
+ # Device-neutral: device auto picks xpu, then cuda, then cpu (GPU needs CLOUDIE_ALLOW_GPU=1).
3
+ project:
4
+ seed: 42
5
+ labels:
6
+ # Standard: IMD 3-minute sustained wind. INCYDE labels are used unchanged.
7
+ # 1-minute sources (TCIR, NASA) are converted with ONE factor:
8
+ # 0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, at-sea exposure
9
+ # (Harper, Kepert & Ginger 2010). Derived, NOT a WMO constant.
10
+ # Pending Researchy's verification.
11
+ one_to_three_min_factor: 0.93
12
+ one_to_three_min_factor_status: derived_pending_verification
13
+ # Rows whose centre is within this distance of land are flagged (near_land).
14
+ near_land_km: 20
15
+ # false: near-land TCIR rows are left out of pretraining instead of converted.
16
+ pretrain_keep_near_land: false
17
+ data:
18
+ image_size: 96
19
+ # Main's project bins (src/schema.py). Not official IMD classes.
20
+ imd5_edges_kt: [17, 34, 48, 64, 91]
21
+ imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
22
+ model:
23
+ name: simple_cnn
24
+ dropout: 0.3
25
+ channels: 1
26
+ train:
27
+ device: auto
28
+ batch_size: 64
29
+ epochs: 30
30
+ lr: 0.001
31
+ weight_decay: 0.0001
32
+ patience: 6
33
+ class_loss_weight: 0.5
34
+ num_workers: 0
35
+ cv:
36
+ n_folds: 5
37
+ seed: 42
38
+ augment:
39
+ rot_180: true
40
+ masked_rotation: true
41
+ flips: false
src/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
- """Tropical cyclone intensity estimation framework.
2
-
3
- No trained weights are shipped. This is not a warning system.
4
- """
5
-
6
- __version__ = "0.2.0"
 
1
+ """Tropical cyclone intensity estimation framework.
2
+
3
+ No trained weights are shipped. This is not a warning system.
4
+ """
5
+
6
+ __version__ = "0.2.0"
src/baselines.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/cache_frames.py CHANGED
@@ -1,72 +1,72 @@
1
- """Write fp16 ``.npy`` frames and an index CSV for one dataset.
2
-
3
- Training reads this cache when ``paths.frame_cache/<dataset>/index.csv``
4
- exists and otherwise reads the source files. Nothing is downloaded.
5
- Workers then load a small array instead of decoding the source.
6
-
7
- ``python -m src.cache_frames --dataset nasa``
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import re
14
- from pathlib import Path
15
-
16
- import numpy as np
17
- import pandas as pd
18
-
19
- _SAMPLE_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
20
-
21
-
22
- def _safe_name(sample_id: str) -> str:
23
- cleaned = _SAMPLE_CHARS.sub("_", sample_id.strip())
24
- return cleaned or "frame"
25
-
26
-
27
- def cache_dataset(dataset: str, config: dict) -> Path:
28
- """Read one local dataset and write fp16 frames plus ``index.csv``."""
29
- from src.data_loader import load_image
30
- from src.train import load_training_frame
31
-
32
- name = str(dataset).strip().lower()
33
- root = Path(config["paths"]["frame_cache"])
34
- frame, _excluded = load_training_frame(name, config)
35
- dest_dir = root / name / "frames"
36
- dest_dir.mkdir(parents=True, exist_ok=True)
37
- rows: list[dict[str, str]] = []
38
- for row in frame.itertuples(index=False):
39
- array = np.asarray(load_image(row.image_path), dtype=np.float16)
40
- path = dest_dir / f"{_safe_name(str(row.sample_id))}.npy"
41
- np.save(path, array)
42
- rows.append(
43
- {
44
- "sample_id": str(row.sample_id),
45
- "cache_path": path.resolve().as_posix(),
46
- "source_path": str(row.image_path),
47
- "dataset": name,
48
- "dtype": "float16",
49
- }
50
- )
51
- index = root / name / "index.csv"
52
- pd.DataFrame(rows).to_csv(index, index=False)
53
- print(f"Wrote {index} ({len(rows)} fp16 frames). Not a model result.")
54
- return index
55
-
56
-
57
- def main(argv: list[str] | None = None) -> Path:
58
- """``python -m src.cache_frames --config config/config.yaml --dataset nasa``."""
59
- from src.config import load_config
60
- from src.train import _DATASETS
61
-
62
- parser = argparse.ArgumentParser(
63
- description="Cache one dataset as fp16 npy frames. Does not download imagery."
64
- )
65
- parser.add_argument("--config", type=Path, default=Path("config/config.yaml"))
66
- parser.add_argument("--dataset", required=True, choices=_DATASETS)
67
- args = parser.parse_args(argv)
68
- return cache_dataset(args.dataset, load_config(args.config))
69
-
70
-
71
- if __name__ == "__main__":
72
- main()
 
1
+ """Write fp16 ``.npy`` frames and an index CSV for one dataset.
2
+
3
+ Training reads this cache when ``paths.frame_cache/<dataset>/index.csv``
4
+ exists and otherwise reads the source files. Nothing is downloaded.
5
+ Workers then load a small array instead of decoding the source.
6
+
7
+ ``python -m src.cache_frames --dataset nasa``
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import re
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ _SAMPLE_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
20
+
21
+
22
+ def _safe_name(sample_id: str) -> str:
23
+ cleaned = _SAMPLE_CHARS.sub("_", sample_id.strip())
24
+ return cleaned or "frame"
25
+
26
+
27
+ def cache_dataset(dataset: str, config: dict) -> Path:
28
+ """Read one local dataset and write fp16 frames plus ``index.csv``."""
29
+ from src.data_loader import load_image
30
+ from src.train import load_training_frame
31
+
32
+ name = str(dataset).strip().lower()
33
+ root = Path(config["paths"]["frame_cache"])
34
+ frame, _excluded = load_training_frame(name, config)
35
+ dest_dir = root / name / "frames"
36
+ dest_dir.mkdir(parents=True, exist_ok=True)
37
+ rows: list[dict[str, str]] = []
38
+ for row in frame.itertuples(index=False):
39
+ array = np.asarray(load_image(row.image_path), dtype=np.float16)
40
+ path = dest_dir / f"{_safe_name(str(row.sample_id))}.npy"
41
+ np.save(path, array)
42
+ rows.append(
43
+ {
44
+ "sample_id": str(row.sample_id),
45
+ "cache_path": path.resolve().as_posix(),
46
+ "source_path": str(row.image_path),
47
+ "dataset": name,
48
+ "dtype": "float16",
49
+ }
50
+ )
51
+ index = root / name / "index.csv"
52
+ pd.DataFrame(rows).to_csv(index, index=False)
53
+ print(f"Wrote {index} ({len(rows)} fp16 frames). Not a model result.")
54
+ return index
55
+
56
+
57
+ def main(argv: list[str] | None = None) -> Path:
58
+ """``python -m src.cache_frames --config config/config.yaml --dataset nasa``."""
59
+ from src.config import load_config
60
+ from src.train import _DATASETS
61
+
62
+ parser = argparse.ArgumentParser(
63
+ description="Cache one dataset as fp16 npy frames. Does not download imagery."
64
+ )
65
+ parser.add_argument("--config", type=Path, default=Path("config/config.yaml"))
66
+ parser.add_argument("--dataset", required=True, choices=_DATASETS)
67
+ args = parser.parse_args(argv)
68
+ return cache_dataset(args.dataset, load_config(args.config))
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
src/calibration.py CHANGED
@@ -1,345 +1,345 @@
1
- """Torch-free calibration diagnostics for uncertainty intervals.
2
-
3
- Compares raw MC Dropout intervals with validation-fit scaled conformal
4
- intervals. Computes MACE, ENCE, 90% coverage and width, and Spearman
5
- rank correlation between predicted uncertainty and absolute error.
6
-
7
- This module does **not** import torch. All inputs are NumPy arrays.
8
-
9
- Terminology
10
- -----------
11
- - *Raw MC*: central percentile interval from MC-dropout samples.
12
- - *Scaled conformal*: MC-dropout intervals whose half-widths are rescaled
13
- by a single scalar fit on validation residuals so that empirical coverage
14
- matches the nominal level on the validation set.
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import math
20
- from dataclasses import dataclass, field
21
-
22
- import numpy as np
23
-
24
-
25
- # ---------------------------------------------------------------------------
26
- # Data containers
27
- # ---------------------------------------------------------------------------
28
-
29
- @dataclass(frozen=True)
30
- class IntervalResult:
31
- """Coverage and width for one interval method at one nominal level."""
32
-
33
- nominal: float
34
- empirical_coverage: float
35
- mean_width_kt: float
36
- median_width_kt: float
37
- n: int
38
-
39
-
40
- @dataclass(frozen=True)
41
- class CalibrationReport:
42
- """Full calibration comparison between raw MC and scaled conformal."""
43
-
44
- # Per-level results
45
- raw_mc: dict[str, IntervalResult] = field(default_factory=dict)
46
- scaled_conformal: dict[str, IntervalResult] = field(default_factory=dict)
47
-
48
- # Aggregate scalar metrics
49
- mace: float = float("nan")
50
- ence: float = float("nan")
51
- coverage_90_raw: float = float("nan")
52
- width_90_raw_kt: float = float("nan")
53
- coverage_90_scaled: float = float("nan")
54
- width_90_scaled_kt: float = float("nan")
55
- spearman_rho: float = float("nan")
56
- spearman_p: float = float("nan")
57
-
58
- def to_dict(self) -> dict:
59
- """Serialize to a plain dict for JSON output."""
60
- out: dict = {
61
- "mace": _safe_float(self.mace),
62
- "ence": _safe_float(self.ence),
63
- "spearman_rho": _safe_float(self.spearman_rho),
64
- "spearman_p": _safe_float(self.spearman_p),
65
- "coverage_90_raw": _safe_float(self.coverage_90_raw),
66
- "width_90_raw_kt": _safe_float(self.width_90_raw_kt),
67
- "coverage_90_scaled": _safe_float(self.coverage_90_scaled),
68
- "width_90_scaled_kt": _safe_float(self.width_90_scaled_kt),
69
- }
70
- for label, bucket in (("raw_mc", self.raw_mc), ("scaled_conformal", self.scaled_conformal)):
71
- out[label] = {
72
- key: {
73
- "nominal": result.nominal,
74
- "empirical_coverage": result.empirical_coverage,
75
- "mean_width_kt": result.mean_width_kt,
76
- "median_width_kt": result.median_width_kt,
77
- "n": result.n,
78
- }
79
- for key, result in bucket.items()
80
- }
81
- return out
82
-
83
-
84
- def _safe_float(value: float) -> float | None:
85
- """Return None for nan/inf so JSON serialization works."""
86
- if not np.isfinite(value):
87
- return None
88
- return float(value)
89
-
90
-
91
- # ---------------------------------------------------------------------------
92
- # Low-level interval helpers (no torch)
93
- # ---------------------------------------------------------------------------
94
-
95
- def _mc_intervals(
96
- samples: np.ndarray, level: float
97
- ) -> tuple[np.ndarray, np.ndarray]:
98
- """Central percentile interval from MC-dropout draws.
99
-
100
- Parameters
101
- ----------
102
- samples : array, shape (n_draws, n_rows)
103
- level : float in (0, 1)
104
-
105
- Returns
106
- -------
107
- lower, upper : arrays of shape (n_rows,)
108
- """
109
- draws = np.asarray(samples, dtype=np.float64)
110
- if draws.ndim != 2 or draws.shape[0] < 2:
111
- raise ValueError("samples must have shape (n_draws, n_rows) with >= 2 draws")
112
- alpha = (1.0 - level) / 2.0
113
- lower = np.quantile(draws, alpha, axis=0, method="linear")
114
- upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")
115
- return np.asarray(lower, np.float64), np.asarray(upper, np.float64)
116
-
117
-
118
- def _coverage_and_width(
119
- y_true: np.ndarray,
120
- lower: np.ndarray,
121
- upper: np.ndarray,
122
- ) -> tuple[float, float, float]:
123
- """Empirical coverage, mean width, median width."""
124
- covered = (y_true >= lower) & (y_true <= upper)
125
- widths = upper - lower
126
- return float(np.mean(covered)), float(np.mean(widths)), float(np.median(widths))
127
-
128
-
129
- def _fit_conformal_scale(
130
- y_true_val: np.ndarray,
131
- mc_samples_val: np.ndarray,
132
- level: float,
133
- ) -> float:
134
- """Fit a single multiplicative scalar on validation residuals.
135
-
136
- The scalar *s* is chosen so that the rescaled MC intervals (center ± s·hw)
137
- achieve exactly the requested coverage on the validation set, using
138
- conformalized quantile regression with a single global scale.
139
- """
140
- draws = np.asarray(mc_samples_val, dtype=np.float64)
141
- means = draws.mean(axis=0)
142
- lower, upper = _mc_intervals(draws, level)
143
- half_widths = (upper - lower) / 2.0
144
- # Avoid division by zero for constant predictions.
145
- half_widths = np.maximum(half_widths, 1e-12)
146
- conformity_scores = np.abs(y_true_val - means) / half_widths
147
- # The conformal quantile: the smallest s such that coverage >= level.
148
- quantile = np.quantile(conformity_scores, level, method="higher")
149
- return float(quantile)
150
-
151
-
152
- def _scaled_intervals(
153
- mc_samples: np.ndarray, scale: float, level: float
154
- ) -> tuple[np.ndarray, np.ndarray]:
155
- """Apply conformal scale to MC intervals."""
156
- draws = np.asarray(mc_samples, dtype=np.float64)
157
- means = draws.mean(axis=0)
158
- lower_raw, upper_raw = _mc_intervals(draws, level)
159
- half_widths = (upper_raw - lower_raw) / 2.0
160
- lower = means - scale * half_widths
161
- upper = means + scale * half_widths
162
- return lower, upper
163
-
164
-
165
- # ---------------------------------------------------------------------------
166
- # Aggregate calibration metrics
167
- # ---------------------------------------------------------------------------
168
-
169
- def compute_mace(
170
- y_true: np.ndarray,
171
- mc_samples: np.ndarray,
172
- n_bins: int = 10,
173
- ) -> float:
174
- """Mean Absolute Calibration Error (MACE).
175
-
176
- Evaluates the raw MC intervals at ``n_bins`` equally spaced nominal
177
- levels from 0.1 to 0.9 and returns the mean absolute gap between
178
- nominal and empirical coverage.
179
- """
180
- levels = np.linspace(0.1, 0.9, n_bins)
181
- gaps: list[float] = []
182
- for level in levels:
183
- lower, upper = _mc_intervals(mc_samples, float(level))
184
- cov, _, _ = _coverage_and_width(y_true, lower, upper)
185
- gaps.append(abs(cov - float(level)))
186
- return float(np.mean(gaps))
187
-
188
-
189
- def compute_ence(
190
- y_true: np.ndarray,
191
- mc_samples: np.ndarray,
192
- n_bins: int = 10,
193
- ) -> float:
194
- """Expected Normalized Calibration Error (ENCE).
195
-
196
- Groups rows by predicted uncertainty (MC std), computes per-bin RMSE and
197
- mean predicted std, then averages the relative gap.
198
- """
199
- draws = np.asarray(mc_samples, dtype=np.float64)
200
- pred_mean = draws.mean(axis=0)
201
- pred_std = draws.std(axis=0, ddof=0)
202
- n = len(y_true)
203
- if n < n_bins:
204
- n_bins = max(1, n)
205
- order = np.argsort(pred_std)
206
- bin_edges = np.array_split(order, n_bins)
207
- ence_terms: list[float] = []
208
- for indices in bin_edges:
209
- if len(indices) == 0:
210
- continue
211
- rmse = float(np.sqrt(np.mean((y_true[indices] - pred_mean[indices]) ** 2)))
212
- mean_std = float(np.mean(pred_std[indices]))
213
- if mean_std > 0:
214
- ence_terms.append(abs(rmse - mean_std) / mean_std)
215
- else:
216
- ence_terms.append(0.0 if rmse == 0 else float("inf"))
217
- return float(np.mean(ence_terms)) if ence_terms else float("nan")
218
-
219
-
220
- def compute_spearman(
221
- y_true: np.ndarray,
222
- mc_samples: np.ndarray,
223
- ) -> tuple[float, float]:
224
- """Spearman ρ between predicted uncertainty (MC std) and |error|.
225
-
226
- A higher ρ means the model's uncertainty tracks its actual errors.
227
- """
228
- draws = np.asarray(mc_samples, dtype=np.float64)
229
- pred_mean = draws.mean(axis=0)
230
- pred_std = draws.std(axis=0, ddof=0)
231
- abs_error = np.abs(y_true - pred_mean)
232
- if pred_std.std() == 0 or abs_error.std() == 0:
233
- return 0.0, 1.0
234
- try:
235
- from scipy import stats as sp_stats
236
-
237
- result = sp_stats.spearmanr(pred_std, abs_error)
238
- return float(result.statistic), float(result.pvalue)
239
- except ImportError:
240
- import pandas as pd
241
-
242
- rho = float(pd.Series(pred_std).corr(pd.Series(abs_error), method="spearman"))
243
- n = len(pred_std)
244
- if n > 2 and abs(rho) < 1.0:
245
- t_stat = rho * np.sqrt((n - 2) / (1.0 - rho**2))
246
- pval = float(2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(t_stat) / np.sqrt(2)))))
247
- else:
248
- pval = 0.0 if abs(rho) == 1.0 else 1.0
249
- return rho, pval
250
-
251
-
252
- # ---------------------------------------------------------------------------
253
- # Main calibration comparison
254
- # ---------------------------------------------------------------------------
255
-
256
- NOMINAL_LEVELS = (0.50, 0.80, 0.90, 0.95)
257
-
258
-
259
- def compare_calibration(
260
- y_true_val: np.ndarray,
261
- mc_samples_val: np.ndarray,
262
- y_true_test: np.ndarray,
263
- mc_samples_test: np.ndarray,
264
- levels: tuple[float, ...] = NOMINAL_LEVELS,
265
- ) -> CalibrationReport:
266
- """Compare raw MC Dropout vs validation-fit scaled conformal intervals.
267
-
268
- Parameters
269
- ----------
270
- y_true_val, mc_samples_val
271
- Validation ground truth and MC draws (n_draws, n_val).
272
- y_true_test, mc_samples_test
273
- Test ground truth and MC draws (n_draws, n_test).
274
- levels
275
- Nominal coverage levels to evaluate.
276
-
277
- Returns
278
- -------
279
- CalibrationReport
280
- """
281
- y_val = np.asarray(y_true_val, dtype=np.float64).ravel()
282
- y_test = np.asarray(y_true_test, dtype=np.float64).ravel()
283
- mc_val = np.asarray(mc_samples_val, dtype=np.float64)
284
- mc_test = np.asarray(mc_samples_test, dtype=np.float64)
285
-
286
- if mc_val.ndim != 2 or mc_val.shape[0] < 2:
287
- raise ValueError("mc_samples_val must have shape (n_draws, n_val)")
288
- if mc_test.ndim != 2 or mc_test.shape[0] < 2:
289
- raise ValueError("mc_samples_test must have shape (n_draws, n_test)")
290
- if mc_val.shape[1] != y_val.size:
291
- raise ValueError("mc_samples_val columns must match y_true_val length")
292
- if mc_test.shape[1] != y_test.size:
293
- raise ValueError("mc_samples_test columns must match y_true_test length")
294
-
295
- raw_results: dict[str, IntervalResult] = {}
296
- scaled_results: dict[str, IntervalResult] = {}
297
-
298
- for level in levels:
299
- key = f"{level:.2f}"
300
-
301
- # Raw MC on test
302
- raw_lo, raw_hi = _mc_intervals(mc_test, level)
303
- cov_r, mw_r, mdw_r = _coverage_and_width(y_test, raw_lo, raw_hi)
304
- raw_results[key] = IntervalResult(
305
- nominal=level,
306
- empirical_coverage=cov_r,
307
- mean_width_kt=mw_r,
308
- median_width_kt=mdw_r,
309
- n=y_test.size,
310
- )
311
-
312
- # Scaled conformal on test (scale fit on val)
313
- scale = _fit_conformal_scale(y_val, mc_val, level)
314
- sc_lo, sc_hi = _scaled_intervals(mc_test, scale, level)
315
- cov_s, mw_s, mdw_s = _coverage_and_width(y_test, sc_lo, sc_hi)
316
- scaled_results[key] = IntervalResult(
317
- nominal=level,
318
- empirical_coverage=cov_s,
319
- mean_width_kt=mw_s,
320
- median_width_kt=mdw_s,
321
- n=y_test.size,
322
- )
323
-
324
- # Aggregate metrics on test set using raw MC
325
- mace = compute_mace(y_test, mc_test)
326
- ence = compute_ence(y_test, mc_test)
327
- rho, pval = compute_spearman(y_test, mc_test)
328
-
329
- cov_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
330
- w_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
331
- cov_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
332
- w_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
333
-
334
- return CalibrationReport(
335
- raw_mc=raw_results,
336
- scaled_conformal=scaled_results,
337
- mace=mace,
338
- ence=ence,
339
- coverage_90_raw=cov_90_raw,
340
- width_90_raw_kt=w_90_raw,
341
- coverage_90_scaled=cov_90_sc,
342
- width_90_scaled_kt=w_90_sc,
343
- spearman_rho=rho,
344
- spearman_p=pval,
345
- )
 
1
+ """Torch-free calibration diagnostics for uncertainty intervals.
2
+
3
+ Compares raw MC Dropout intervals with validation-fit scaled conformal
4
+ intervals. Computes MACE, ENCE, 90% coverage and width, and Spearman
5
+ rank correlation between predicted uncertainty and absolute error.
6
+
7
+ This module does **not** import torch. All inputs are NumPy arrays.
8
+
9
+ Terminology
10
+ -----------
11
+ - *Raw MC*: central percentile interval from MC-dropout samples.
12
+ - *Scaled conformal*: MC-dropout intervals whose half-widths are rescaled
13
+ by a single scalar fit on validation residuals so that empirical coverage
14
+ matches the nominal level on the validation set.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ from dataclasses import dataclass, field
21
+
22
+ import numpy as np
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Data containers
27
+ # ---------------------------------------------------------------------------
28
+
29
+ @dataclass(frozen=True)
30
+ class IntervalResult:
31
+ """Coverage and width for one interval method at one nominal level."""
32
+
33
+ nominal: float
34
+ empirical_coverage: float
35
+ mean_width_kt: float
36
+ median_width_kt: float
37
+ n: int
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class CalibrationReport:
42
+ """Full calibration comparison between raw MC and scaled conformal."""
43
+
44
+ # Per-level results
45
+ raw_mc: dict[str, IntervalResult] = field(default_factory=dict)
46
+ scaled_conformal: dict[str, IntervalResult] = field(default_factory=dict)
47
+
48
+ # Aggregate scalar metrics
49
+ mace: float = float("nan")
50
+ ence: float = float("nan")
51
+ coverage_90_raw: float = float("nan")
52
+ width_90_raw_kt: float = float("nan")
53
+ coverage_90_scaled: float = float("nan")
54
+ width_90_scaled_kt: float = float("nan")
55
+ spearman_rho: float = float("nan")
56
+ spearman_p: float = float("nan")
57
+
58
+ def to_dict(self) -> dict:
59
+ """Serialize to a plain dict for JSON output."""
60
+ out: dict = {
61
+ "mace": _safe_float(self.mace),
62
+ "ence": _safe_float(self.ence),
63
+ "spearman_rho": _safe_float(self.spearman_rho),
64
+ "spearman_p": _safe_float(self.spearman_p),
65
+ "coverage_90_raw": _safe_float(self.coverage_90_raw),
66
+ "width_90_raw_kt": _safe_float(self.width_90_raw_kt),
67
+ "coverage_90_scaled": _safe_float(self.coverage_90_scaled),
68
+ "width_90_scaled_kt": _safe_float(self.width_90_scaled_kt),
69
+ }
70
+ for label, bucket in (("raw_mc", self.raw_mc), ("scaled_conformal", self.scaled_conformal)):
71
+ out[label] = {
72
+ key: {
73
+ "nominal": result.nominal,
74
+ "empirical_coverage": result.empirical_coverage,
75
+ "mean_width_kt": result.mean_width_kt,
76
+ "median_width_kt": result.median_width_kt,
77
+ "n": result.n,
78
+ }
79
+ for key, result in bucket.items()
80
+ }
81
+ return out
82
+
83
+
84
+ def _safe_float(value: float) -> float | None:
85
+ """Return None for nan/inf so JSON serialization works."""
86
+ if not np.isfinite(value):
87
+ return None
88
+ return float(value)
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # Low-level interval helpers (no torch)
93
+ # ---------------------------------------------------------------------------
94
+
95
+ def _mc_intervals(
96
+ samples: np.ndarray, level: float
97
+ ) -> tuple[np.ndarray, np.ndarray]:
98
+ """Central percentile interval from MC-dropout draws.
99
+
100
+ Parameters
101
+ ----------
102
+ samples : array, shape (n_draws, n_rows)
103
+ level : float in (0, 1)
104
+
105
+ Returns
106
+ -------
107
+ lower, upper : arrays of shape (n_rows,)
108
+ """
109
+ draws = np.asarray(samples, dtype=np.float64)
110
+ if draws.ndim != 2 or draws.shape[0] < 2:
111
+ raise ValueError("samples must have shape (n_draws, n_rows) with >= 2 draws")
112
+ alpha = (1.0 - level) / 2.0
113
+ lower = np.quantile(draws, alpha, axis=0, method="linear")
114
+ upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")
115
+ return np.asarray(lower, np.float64), np.asarray(upper, np.float64)
116
+
117
+
118
+ def _coverage_and_width(
119
+ y_true: np.ndarray,
120
+ lower: np.ndarray,
121
+ upper: np.ndarray,
122
+ ) -> tuple[float, float, float]:
123
+ """Empirical coverage, mean width, median width."""
124
+ covered = (y_true >= lower) & (y_true <= upper)
125
+ widths = upper - lower
126
+ return float(np.mean(covered)), float(np.mean(widths)), float(np.median(widths))
127
+
128
+
129
+ def _fit_conformal_scale(
130
+ y_true_val: np.ndarray,
131
+ mc_samples_val: np.ndarray,
132
+ level: float,
133
+ ) -> float:
134
+ """Fit a single multiplicative scalar on validation residuals.
135
+
136
+ The scalar *s* is chosen so that the rescaled MC intervals (center ± s·hw)
137
+ achieve exactly the requested coverage on the validation set, using
138
+ conformalized quantile regression with a single global scale.
139
+ """
140
+ draws = np.asarray(mc_samples_val, dtype=np.float64)
141
+ means = draws.mean(axis=0)
142
+ lower, upper = _mc_intervals(draws, level)
143
+ half_widths = (upper - lower) / 2.0
144
+ # Avoid division by zero for constant predictions.
145
+ half_widths = np.maximum(half_widths, 1e-12)
146
+ conformity_scores = np.abs(y_true_val - means) / half_widths
147
+ # The conformal quantile: the smallest s such that coverage >= level.
148
+ quantile = np.quantile(conformity_scores, level, method="higher")
149
+ return float(quantile)
150
+
151
+
152
+ def _scaled_intervals(
153
+ mc_samples: np.ndarray, scale: float, level: float
154
+ ) -> tuple[np.ndarray, np.ndarray]:
155
+ """Apply conformal scale to MC intervals."""
156
+ draws = np.asarray(mc_samples, dtype=np.float64)
157
+ means = draws.mean(axis=0)
158
+ lower_raw, upper_raw = _mc_intervals(draws, level)
159
+ half_widths = (upper_raw - lower_raw) / 2.0
160
+ lower = means - scale * half_widths
161
+ upper = means + scale * half_widths
162
+ return lower, upper
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Aggregate calibration metrics
167
+ # ---------------------------------------------------------------------------
168
+
169
+ def compute_mace(
170
+ y_true: np.ndarray,
171
+ mc_samples: np.ndarray,
172
+ n_bins: int = 10,
173
+ ) -> float:
174
+ """Mean Absolute Calibration Error (MACE).
175
+
176
+ Evaluates the raw MC intervals at ``n_bins`` equally spaced nominal
177
+ levels from 0.1 to 0.9 and returns the mean absolute gap between
178
+ nominal and empirical coverage.
179
+ """
180
+ levels = np.linspace(0.1, 0.9, n_bins)
181
+ gaps: list[float] = []
182
+ for level in levels:
183
+ lower, upper = _mc_intervals(mc_samples, float(level))
184
+ cov, _, _ = _coverage_and_width(y_true, lower, upper)
185
+ gaps.append(abs(cov - float(level)))
186
+ return float(np.mean(gaps))
187
+
188
+
189
+ def compute_ence(
190
+ y_true: np.ndarray,
191
+ mc_samples: np.ndarray,
192
+ n_bins: int = 10,
193
+ ) -> float:
194
+ """Expected Normalized Calibration Error (ENCE).
195
+
196
+ Groups rows by predicted uncertainty (MC std), computes per-bin RMSE and
197
+ mean predicted std, then averages the relative gap.
198
+ """
199
+ draws = np.asarray(mc_samples, dtype=np.float64)
200
+ pred_mean = draws.mean(axis=0)
201
+ pred_std = draws.std(axis=0, ddof=0)
202
+ n = len(y_true)
203
+ if n < n_bins:
204
+ n_bins = max(1, n)
205
+ order = np.argsort(pred_std)
206
+ bin_edges = np.array_split(order, n_bins)
207
+ ence_terms: list[float] = []
208
+ for indices in bin_edges:
209
+ if len(indices) == 0:
210
+ continue
211
+ rmse = float(np.sqrt(np.mean((y_true[indices] - pred_mean[indices]) ** 2)))
212
+ mean_std = float(np.mean(pred_std[indices]))
213
+ if mean_std > 0:
214
+ ence_terms.append(abs(rmse - mean_std) / mean_std)
215
+ else:
216
+ ence_terms.append(0.0 if rmse == 0 else float("inf"))
217
+ return float(np.mean(ence_terms)) if ence_terms else float("nan")
218
+
219
+
220
+ def compute_spearman(
221
+ y_true: np.ndarray,
222
+ mc_samples: np.ndarray,
223
+ ) -> tuple[float, float]:
224
+ """Spearman ρ between predicted uncertainty (MC std) and |error|.
225
+
226
+ A higher ρ means the model's uncertainty tracks its actual errors.
227
+ """
228
+ draws = np.asarray(mc_samples, dtype=np.float64)
229
+ pred_mean = draws.mean(axis=0)
230
+ pred_std = draws.std(axis=0, ddof=0)
231
+ abs_error = np.abs(y_true - pred_mean)
232
+ if pred_std.std() == 0 or abs_error.std() == 0:
233
+ return 0.0, 1.0
234
+ try:
235
+ from scipy import stats as sp_stats
236
+
237
+ result = sp_stats.spearmanr(pred_std, abs_error)
238
+ return float(result.statistic), float(result.pvalue)
239
+ except ImportError:
240
+ import pandas as pd
241
+
242
+ rho = float(pd.Series(pred_std).corr(pd.Series(abs_error), method="spearman"))
243
+ n = len(pred_std)
244
+ if n > 2 and abs(rho) < 1.0:
245
+ t_stat = rho * np.sqrt((n - 2) / (1.0 - rho**2))
246
+ pval = float(2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(t_stat) / np.sqrt(2)))))
247
+ else:
248
+ pval = 0.0 if abs(rho) == 1.0 else 1.0
249
+ return rho, pval
250
+
251
+
252
+ # ---------------------------------------------------------------------------
253
+ # Main calibration comparison
254
+ # ---------------------------------------------------------------------------
255
+
256
+ NOMINAL_LEVELS = (0.50, 0.80, 0.90, 0.95)
257
+
258
+
259
+ def compare_calibration(
260
+ y_true_val: np.ndarray,
261
+ mc_samples_val: np.ndarray,
262
+ y_true_test: np.ndarray,
263
+ mc_samples_test: np.ndarray,
264
+ levels: tuple[float, ...] = NOMINAL_LEVELS,
265
+ ) -> CalibrationReport:
266
+ """Compare raw MC Dropout vs validation-fit scaled conformal intervals.
267
+
268
+ Parameters
269
+ ----------
270
+ y_true_val, mc_samples_val
271
+ Validation ground truth and MC draws (n_draws, n_val).
272
+ y_true_test, mc_samples_test
273
+ Test ground truth and MC draws (n_draws, n_test).
274
+ levels
275
+ Nominal coverage levels to evaluate.
276
+
277
+ Returns
278
+ -------
279
+ CalibrationReport
280
+ """
281
+ y_val = np.asarray(y_true_val, dtype=np.float64).ravel()
282
+ y_test = np.asarray(y_true_test, dtype=np.float64).ravel()
283
+ mc_val = np.asarray(mc_samples_val, dtype=np.float64)
284
+ mc_test = np.asarray(mc_samples_test, dtype=np.float64)
285
+
286
+ if mc_val.ndim != 2 or mc_val.shape[0] < 2:
287
+ raise ValueError("mc_samples_val must have shape (n_draws, n_val)")
288
+ if mc_test.ndim != 2 or mc_test.shape[0] < 2:
289
+ raise ValueError("mc_samples_test must have shape (n_draws, n_test)")
290
+ if mc_val.shape[1] != y_val.size:
291
+ raise ValueError("mc_samples_val columns must match y_true_val length")
292
+ if mc_test.shape[1] != y_test.size:
293
+ raise ValueError("mc_samples_test columns must match y_true_test length")
294
+
295
+ raw_results: dict[str, IntervalResult] = {}
296
+ scaled_results: dict[str, IntervalResult] = {}
297
+
298
+ for level in levels:
299
+ key = f"{level:.2f}"
300
+
301
+ # Raw MC on test
302
+ raw_lo, raw_hi = _mc_intervals(mc_test, level)
303
+ cov_r, mw_r, mdw_r = _coverage_and_width(y_test, raw_lo, raw_hi)
304
+ raw_results[key] = IntervalResult(
305
+ nominal=level,
306
+ empirical_coverage=cov_r,
307
+ mean_width_kt=mw_r,
308
+ median_width_kt=mdw_r,
309
+ n=y_test.size,
310
+ )
311
+
312
+ # Scaled conformal on test (scale fit on val)
313
+ scale = _fit_conformal_scale(y_val, mc_val, level)
314
+ sc_lo, sc_hi = _scaled_intervals(mc_test, scale, level)
315
+ cov_s, mw_s, mdw_s = _coverage_and_width(y_test, sc_lo, sc_hi)
316
+ scaled_results[key] = IntervalResult(
317
+ nominal=level,
318
+ empirical_coverage=cov_s,
319
+ mean_width_kt=mw_s,
320
+ median_width_kt=mdw_s,
321
+ n=y_test.size,
322
+ )
323
+
324
+ # Aggregate metrics on test set using raw MC
325
+ mace = compute_mace(y_test, mc_test)
326
+ ence = compute_ence(y_test, mc_test)
327
+ rho, pval = compute_spearman(y_test, mc_test)
328
+
329
+ cov_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
330
+ w_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
331
+ cov_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
332
+ w_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
333
+
334
+ return CalibrationReport(
335
+ raw_mc=raw_results,
336
+ scaled_conformal=scaled_results,
337
+ mace=mace,
338
+ ence=ence,
339
+ coverage_90_raw=cov_90_raw,
340
+ width_90_raw_kt=w_90_raw,
341
+ coverage_90_scaled=cov_90_sc,
342
+ width_90_scaled_kt=w_90_sc,
343
+ spearman_rho=rho,
344
+ spearman_p=pval,
345
+ )
src/config.py CHANGED
@@ -1,68 +1,68 @@
1
- """YAML config loader. Training and baselines must read hyperparameters from here."""
2
-
3
- from __future__ import annotations
4
-
5
- from pathlib import Path
6
-
7
- import yaml
8
-
9
-
10
- def load_config(path: str | Path) -> dict:
11
- with Path(path).open(encoding="utf-8") as handle:
12
- raw = yaml.safe_load(handle)
13
- if not isinstance(raw, dict):
14
- raise ValueError("config root must be a mapping")
15
- return raw
16
-
17
-
18
- def parse_image_size(value: object) -> int | None:
19
- """Square side to resize to, or None to keep the chip's height and width.
20
-
21
- ``None`` and the string ``native`` do not resize. An integer resizes to
22
- that square. NASA TorchGeo chips are 366 by 366 and TCIR chips are 201
23
- by 201; this function does not assume either size and does not download
24
- imagery.
25
- """
26
- if value is None:
27
- return None
28
- if isinstance(value, str):
29
- text = value.strip().lower()
30
- if text in {"native", "null", "none"}:
31
- return None
32
- if not text:
33
- raise ValueError("data.image_size is blank")
34
- try:
35
- value = int(text)
36
- except ValueError as exc:
37
- raise ValueError(
38
- "data.image_size must be native or a positive integer"
39
- ) from exc
40
- if isinstance(value, bool) or not isinstance(value, (int, float)):
41
- raise ValueError(
42
- f"data.image_size must be native or a positive integer, got {value!r}"
43
- )
44
- size = int(value)
45
- if size < 1 or float(value) != float(size):
46
- raise ValueError("data.image_size must be native or a positive integer")
47
- return size
48
-
49
-
50
- def image_sizes_match(left: object, right: object) -> bool:
51
- """True when both sides resize to the same square, or both stay native."""
52
- return parse_image_size(left) == parse_image_size(right)
53
-
54
-
55
- def checkpoint_path(config: dict, root: str | Path | None = None) -> Path:
56
- """Path of the deep-model checkpoint named in ``paths``.
57
-
58
- ``paths.artifacts`` is the directory. ``paths.checkpoint_name`` is a
59
- file name, not a directory. ``root`` prefixes a relative path.
60
- """
61
- artifacts = Path(config["paths"]["artifacts"])
62
- name = str(config["paths"]["checkpoint_name"])
63
- if not name or name != Path(name).name:
64
- raise ValueError("paths.checkpoint_name must be a file name, not a path")
65
- path = artifacts / name
66
- if root is not None and not path.is_absolute():
67
- path = Path(root) / path
68
- return path
 
1
+ """YAML config loader. Training and baselines must read hyperparameters from here."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+
9
+
10
+ def load_config(path: str | Path) -> dict:
11
+ with Path(path).open(encoding="utf-8") as handle:
12
+ raw = yaml.safe_load(handle)
13
+ if not isinstance(raw, dict):
14
+ raise ValueError("config root must be a mapping")
15
+ return raw
16
+
17
+
18
+ def parse_image_size(value: object) -> int | None:
19
+ """Square side to resize to, or None to keep the chip's height and width.
20
+
21
+ ``None`` and the string ``native`` do not resize. An integer resizes to
22
+ that square. NASA TorchGeo chips are 366 by 366 and TCIR chips are 201
23
+ by 201; this function does not assume either size and does not download
24
+ imagery.
25
+ """
26
+ if value is None:
27
+ return None
28
+ if isinstance(value, str):
29
+ text = value.strip().lower()
30
+ if text in {"native", "null", "none"}:
31
+ return None
32
+ if not text:
33
+ raise ValueError("data.image_size is blank")
34
+ try:
35
+ value = int(text)
36
+ except ValueError as exc:
37
+ raise ValueError(
38
+ "data.image_size must be native or a positive integer"
39
+ ) from exc
40
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
41
+ raise ValueError(
42
+ f"data.image_size must be native or a positive integer, got {value!r}"
43
+ )
44
+ size = int(value)
45
+ if size < 1 or float(value) != float(size):
46
+ raise ValueError("data.image_size must be native or a positive integer")
47
+ return size
48
+
49
+
50
+ def image_sizes_match(left: object, right: object) -> bool:
51
+ """True when both sides resize to the same square, or both stay native."""
52
+ return parse_image_size(left) == parse_image_size(right)
53
+
54
+
55
+ def checkpoint_path(config: dict, root: str | Path | None = None) -> Path:
56
+ """Path of the deep-model checkpoint named in ``paths``.
57
+
58
+ ``paths.artifacts`` is the directory. ``paths.checkpoint_name`` is a
59
+ file name, not a directory. ``root`` prefixes a relative path.
60
+ """
61
+ artifacts = Path(config["paths"]["artifacts"])
62
+ name = str(config["paths"]["checkpoint_name"])
63
+ if not name or name != Path(name).name:
64
+ raise ValueError("paths.checkpoint_name must be a file name, not a path")
65
+ path = artifacts / name
66
+ if root is not None and not path.is_absolute():
67
+ path = Path(root) / path
68
+ return path
src/data_loader.py CHANGED
@@ -1,102 +1,102 @@
1
- """Manifest loading. Image paths are relative to the manifest directory."""
2
-
3
- from __future__ import annotations
4
-
5
- from pathlib import Path
6
-
7
- import numpy as np
8
- import pandas as pd
9
- from PIL import Image
10
-
11
- from src.preprocessing import (
12
- MAX_MISSING_FRACTION,
13
- NormStats,
14
- prepare_image,
15
- stack_prepared,
16
- )
17
- from src.schema import require_valid
18
-
19
-
20
- def load_manifest(path: str | Path) -> pd.DataFrame:
21
- frame = pd.read_csv(path)
22
- return require_valid(frame)
23
-
24
-
25
- def resolve_image(manifest_path: str | Path, image_path: str) -> Path:
26
- candidate = Path(image_path)
27
- if candidate.is_absolute():
28
- return candidate
29
- return Path(manifest_path).parent / candidate
30
-
31
-
32
- def load_image(path: str | Path) -> np.ndarray:
33
- file_path = Path(path)
34
- if not file_path.is_file():
35
- raise FileNotFoundError(file_path)
36
- if file_path.suffix == ".npy":
37
- return np.load(file_path)
38
- return np.asarray(Image.open(file_path), dtype=np.float32)
39
-
40
-
41
- def apply_frame_cache(
42
- frame: pd.DataFrame, dataset: str, cache_root: str | Path | None
43
- ) -> pd.DataFrame:
44
- """Point rows at cached fp16 ``.npy`` files when that dataset's index exists.
45
-
46
- A missing cache leaves ``image_path`` unchanged. A sample that is not
47
- in the index, or whose file is gone, keeps its source path.
48
- """
49
- if cache_root in (None, "", "null"):
50
- return frame
51
- index = Path(cache_root) / str(dataset).strip().lower() / "index.csv"
52
- if not index.is_file():
53
- return frame
54
- cached = pd.read_csv(index)
55
- if "sample_id" not in cached.columns or "cache_path" not in cached.columns:
56
- raise ValueError(f"frame cache index {index} needs sample_id and cache_path")
57
- mapping = {
58
- str(sample): str(path)
59
- for sample, path in zip(cached["sample_id"], cached["cache_path"], strict=False)
60
- }
61
- out = frame.copy()
62
- paths: list[str] = []
63
- replaced = 0
64
- for sample_id, image_path in zip(out["sample_id"].astype(str), out["image_path"].astype(str)):
65
- candidate = mapping.get(sample_id)
66
- if candidate and Path(candidate).is_file():
67
- paths.append(str(Path(candidate).resolve()))
68
- if paths[-1] != str(Path(image_path).resolve()):
69
- replaced += 1
70
- else:
71
- paths.append(image_path)
72
- out["image_path"] = paths
73
- if replaced:
74
- print(f"{dataset} frame cache supplied {replaced} fp16 frames from {index}")
75
- return out
76
-
77
-
78
- def prepare_split(
79
- frame: pd.DataFrame,
80
- manifest_path: str | Path,
81
- split: str,
82
- image_size: int | str | None,
83
- stats: NormStats | None,
84
- max_missing_fraction: float = MAX_MISSING_FRACTION,
85
- ) -> tuple[np.ndarray, np.ndarray]:
86
- """Load one split. ``stats`` must already have been fit on train.
87
-
88
- ``image_size`` comes from ``data.image_size``. ``native`` keeps each
89
- chip's height and width, and those chips must already share a shape.
90
- """
91
- rows = frame[frame["split"] == split]
92
- images = []
93
- winds = []
94
- for row in rows.itertuples(index=False):
95
- path = resolve_image(manifest_path, row.image_path)
96
- images.append(
97
- prepare_image(load_image(path), image_size, stats, max_missing_fraction)
98
- )
99
- winds.append(float(row.wind_speed_kt))
100
- if not images:
101
- raise ValueError(f"split {split} has no rows")
102
- return stack_prepared(images), np.asarray(winds, dtype=np.float32)
 
1
+ """Manifest loading. Image paths are relative to the manifest directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from PIL import Image
10
+
11
+ from src.preprocessing import (
12
+ MAX_MISSING_FRACTION,
13
+ NormStats,
14
+ prepare_image,
15
+ stack_prepared,
16
+ )
17
+ from src.schema import require_valid
18
+
19
+
20
+ def load_manifest(path: str | Path) -> pd.DataFrame:
21
+ frame = pd.read_csv(path)
22
+ return require_valid(frame)
23
+
24
+
25
+ def resolve_image(manifest_path: str | Path, image_path: str) -> Path:
26
+ candidate = Path(image_path)
27
+ if candidate.is_absolute():
28
+ return candidate
29
+ return Path(manifest_path).parent / candidate
30
+
31
+
32
+ def load_image(path: str | Path) -> np.ndarray:
33
+ file_path = Path(path)
34
+ if not file_path.is_file():
35
+ raise FileNotFoundError(file_path)
36
+ if file_path.suffix == ".npy":
37
+ return np.load(file_path)
38
+ return np.asarray(Image.open(file_path), dtype=np.float32)
39
+
40
+
41
+ def apply_frame_cache(
42
+ frame: pd.DataFrame, dataset: str, cache_root: str | Path | None
43
+ ) -> pd.DataFrame:
44
+ """Point rows at cached fp16 ``.npy`` files when that dataset's index exists.
45
+
46
+ A missing cache leaves ``image_path`` unchanged. A sample that is not
47
+ in the index, or whose file is gone, keeps its source path.
48
+ """
49
+ if cache_root in (None, "", "null"):
50
+ return frame
51
+ index = Path(cache_root) / str(dataset).strip().lower() / "index.csv"
52
+ if not index.is_file():
53
+ return frame
54
+ cached = pd.read_csv(index)
55
+ if "sample_id" not in cached.columns or "cache_path" not in cached.columns:
56
+ raise ValueError(f"frame cache index {index} needs sample_id and cache_path")
57
+ mapping = {
58
+ str(sample): str(path)
59
+ for sample, path in zip(cached["sample_id"], cached["cache_path"], strict=False)
60
+ }
61
+ out = frame.copy()
62
+ paths: list[str] = []
63
+ replaced = 0
64
+ for sample_id, image_path in zip(out["sample_id"].astype(str), out["image_path"].astype(str)):
65
+ candidate = mapping.get(sample_id)
66
+ if candidate and Path(candidate).is_file():
67
+ paths.append(str(Path(candidate).resolve()))
68
+ if paths[-1] != str(Path(image_path).resolve()):
69
+ replaced += 1
70
+ else:
71
+ paths.append(image_path)
72
+ out["image_path"] = paths
73
+ if replaced:
74
+ print(f"{dataset} frame cache supplied {replaced} fp16 frames from {index}")
75
+ return out
76
+
77
+
78
+ def prepare_split(
79
+ frame: pd.DataFrame,
80
+ manifest_path: str | Path,
81
+ split: str,
82
+ image_size: int | str | None,
83
+ stats: NormStats | None,
84
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
85
+ ) -> tuple[np.ndarray, np.ndarray]:
86
+ """Load one split. ``stats`` must already have been fit on train.
87
+
88
+ ``image_size`` comes from ``data.image_size``. ``native`` keeps each
89
+ chip's height and width, and those chips must already share a shape.
90
+ """
91
+ rows = frame[frame["split"] == split]
92
+ images = []
93
+ winds = []
94
+ for row in rows.itertuples(index=False):
95
+ path = resolve_image(manifest_path, row.image_path)
96
+ images.append(
97
+ prepare_image(load_image(path), image_size, stats, max_missing_fraction)
98
+ )
99
+ winds.append(float(row.wind_speed_kt))
100
+ if not images:
101
+ raise ValueError(f"split {split} has no rows")
102
+ return stack_prepared(images), np.asarray(winds, dtype=np.float32)
src/device.py CHANGED
@@ -1,390 +1,390 @@
1
- """Device selection and mixed precision for native PyTorch.
2
-
3
- The order is XPU, then CUDA, then CPU. XPU means ``torch.xpu`` in an
4
- official PyTorch build (2.5 or newer; 2.15 is the pinned Windows wheel).
5
- This module does not import or call the archived IPEX package.
6
-
7
- ``CLOUDIE_ALLOW_GPU=1`` is required for XPU and CUDA alike. An explicit
8
- accelerator without that gate is refused. Auto falls back to CPU and
9
- logs the reason. CPU stays fp32. CUDA fp16 is the only path that uses
10
- GradScaler. XPU uses bf16 autocast when native bf16 is supported, and
11
- fp32 otherwise. ``cudnn.benchmark`` is not enabled.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import inspect
17
- import logging
18
- import math
19
- import os
20
- from collections.abc import Iterator
21
- from contextlib import contextmanager, nullcontext
22
- from dataclasses import dataclass
23
-
24
- LOGGER = logging.getLogger("src.device")
25
-
26
- DEVICE_CHOICES = ("auto", "xpu", "cuda", "cpu")
27
- GPU_DEVICES = ("xpu", "cuda")
28
- GPU_GATE = "CLOUDIE_ALLOW_GPU"
29
-
30
-
31
- def _torch():
32
- import torch
33
-
34
- return torch
35
-
36
-
37
- def accelerator_available(torch_module, name: str) -> bool:
38
- """True when this torch build can see ``name``. Missing XPU attributes are false."""
39
- if name == "cpu":
40
- return True
41
- if name == "xpu":
42
- xpu = getattr(torch_module, "xpu", None)
43
- checker = getattr(xpu, "is_available", None) if xpu is not None else None
44
- if not callable(checker):
45
- return False
46
- try:
47
- return bool(checker())
48
- except Exception:
49
- return False
50
- if name == "cuda":
51
- try:
52
- return bool(torch_module.cuda.is_available())
53
- except Exception:
54
- return False
55
- return False
56
-
57
-
58
- def xpu_native_bf16(torch_module) -> bool:
59
- """True when native XPU bf16 is supported.
60
-
61
- Uses ``torch.xpu.is_bf16_supported(including_emulation=False)`` when
62
- that parameter exists, so emulated bf16 does not select the autocast
63
- path. Older builds without the function, or whose call fails, stay
64
- on fp32. A build that has the function but not the parameter is
65
- called with no arguments.
66
- """
67
- xpu = getattr(torch_module, "xpu", None)
68
- checker = getattr(xpu, "is_bf16_supported", None) if xpu is not None else None
69
- if not callable(checker):
70
- return False
71
- try:
72
- parameters = inspect.signature(checker).parameters
73
- has_kwarg = "including_emulation" in parameters
74
- except (TypeError, ValueError):
75
- has_kwarg = False
76
- try:
77
- if has_kwarg:
78
- return bool(checker(including_emulation=False))
79
- return bool(checker())
80
- except TypeError:
81
- try:
82
- return bool(checker())
83
- except Exception:
84
- return False
85
- except Exception:
86
- return False
87
-
88
-
89
- @dataclass(frozen=True)
90
- class AmpPolicy:
91
- """How one device runs the forward and the backward."""
92
-
93
- precision: str
94
- autocast_device: str | None
95
- dtype: object | None
96
- use_grad_scaler: bool
97
-
98
-
99
- def amp_policy_for(device, torch_module=None) -> AmpPolicy:
100
- """fp16+GradScaler on CUDA, native bf16 on XPU, fp32 everywhere else.
101
-
102
- GradScaler is never constructed for XPU or CPU. A missing native bf16
103
- on XPU falls back to fp32 with no autocast.
104
- """
105
- torch_module = torch_module or _torch()
106
- kind = device.type if hasattr(device, "type") else str(device)
107
- if kind == "cuda":
108
- return AmpPolicy("fp16", "cuda", torch_module.float16, True)
109
- if kind == "xpu":
110
- if xpu_native_bf16(torch_module):
111
- return AmpPolicy("bf16", "xpu", torch_module.bfloat16, False)
112
- return AmpPolicy("fp32", None, None, False)
113
- return AmpPolicy("fp32", None, None, False)
114
-
115
-
116
- @contextmanager
117
- def autocast_context(policy: AmpPolicy) -> Iterator[None]:
118
- """Enter ``torch.autocast`` for the policy, or do nothing for fp32."""
119
- if policy.autocast_device is None or policy.dtype is None:
120
- with nullcontext():
121
- yield
122
- return
123
- torch_module = _torch()
124
- with torch_module.autocast(policy.autocast_device, dtype=policy.dtype):
125
- yield
126
-
127
-
128
- def make_grad_scaler(policy: AmpPolicy):
129
- """A CUDA fp16 GradScaler, or None. XPU and CPU never get one."""
130
- if not policy.use_grad_scaler:
131
- return None
132
- if policy.precision != "fp16" or policy.autocast_device != "cuda":
133
- raise RuntimeError("GradScaler is used only for cuda fp16")
134
- torch_module = _torch()
135
- scaler_cls = getattr(getattr(torch_module, "amp", None), "GradScaler", None)
136
- if scaler_cls is not None:
137
- try:
138
- return scaler_cls("cuda")
139
- except TypeError:
140
- pass
141
- return torch_module.cuda.amp.GradScaler()
142
-
143
-
144
- def resolve_device(name: str):
145
- """Pick a ``torch.device``. Auto order is xpu, cuda, cpu.
146
-
147
- Explicit xpu or cuda without ``CLOUDIE_ALLOW_GPU=1`` raises. Auto
148
- that would have picked an accelerator falls back to cpu and logs why.
149
- """
150
- choice = str(name).strip().lower()
151
- if choice not in DEVICE_CHOICES:
152
- raise ValueError("device must be auto, xpu, cuda, or cpu")
153
- torch_module = _torch()
154
- if choice == "auto":
155
- if accelerator_available(torch_module, "xpu"):
156
- picked = "xpu"
157
- elif accelerator_available(torch_module, "cuda"):
158
- picked = "cuda"
159
- else:
160
- picked = "cpu"
161
- if picked != "cpu" and os.environ.get(GPU_GATE) != "1":
162
- message = (
163
- f"Refusing auto-picked device {picked} because {GPU_GATE} is not 1. "
164
- "Falling back to cpu. An XPU or GPU run needs misty wind's approval. "
165
- f"Set {GPU_GATE}=1 only after that approval."
166
- )
167
- LOGGER.warning(message)
168
- print(message)
169
- return torch_module.device("cpu")
170
- choice = picked
171
- if choice in GPU_DEVICES and os.environ.get(GPU_GATE) != "1":
172
- raise RuntimeError(
173
- f"Refusing device {choice}. An XPU or GPU run needs misty wind's approval. "
174
- f"Set {GPU_GATE}=1 only after that approval."
175
- )
176
- if choice == "xpu" and not accelerator_available(torch_module, "xpu"):
177
- raise RuntimeError("device xpu was approved but XPU is not available")
178
- if choice == "cuda" and not accelerator_available(torch_module, "cuda"):
179
- raise RuntimeError("device cuda was approved but CUDA is not available")
180
- try:
181
- return torch_module.device(choice)
182
- except RuntimeError as exc:
183
- raise RuntimeError(f"device {choice} is not supported by this torch build") from exc
184
-
185
-
186
- def reset_peak_memory(device) -> None:
187
- """Clear the allocator peak for the device that tracks it. CPU is a no-op."""
188
- torch_module = _torch()
189
- if getattr(device, "type", None) == "cuda":
190
- reset = getattr(torch_module.cuda, "reset_peak_memory_stats", None)
191
- if callable(reset):
192
- try:
193
- reset()
194
- except Exception:
195
- return
196
- if getattr(device, "type", None) == "xpu":
197
- xpu = getattr(torch_module, "xpu", None)
198
- reset = getattr(xpu, "reset_peak_memory_stats", None) if xpu is not None else None
199
- if callable(reset):
200
- try:
201
- reset()
202
- except Exception:
203
- return
204
-
205
-
206
- def peak_memory_bytes(device) -> int | None:
207
- """Peak bytes from XPU or CUDA, or null when the device does not report it.
208
-
209
- XPU peak memory is trustworthy on the torch 2.15 line. Older builds
210
- may return a number that is not the true peak; the value is still
211
- whatever ``max_memory_allocated`` reports.
212
- """
213
- torch_module = _torch()
214
- kind = getattr(device, "type", None)
215
- if kind == "xpu":
216
- xpu = getattr(torch_module, "xpu", None)
217
- reader = getattr(xpu, "max_memory_allocated", None) if xpu is not None else None
218
- if not callable(reader):
219
- return None
220
- try:
221
- return int(reader())
222
- except Exception:
223
- return None
224
- if kind == "cuda":
225
- reader = getattr(torch_module.cuda, "max_memory_allocated", None)
226
- if not callable(reader):
227
- return None
228
- try:
229
- return int(reader())
230
- except Exception:
231
- return None
232
- return None
233
-
234
-
235
- def _jsonable(value):
236
- if value is None or isinstance(value, (str, int, float, bool)):
237
- if isinstance(value, float) and not math.isfinite(value):
238
- return None
239
- return value
240
- if isinstance(value, (list, tuple)):
241
- return [_jsonable(item) for item in value]
242
- return str(value)
243
-
244
-
245
- def xpu_device_properties(device) -> dict | None:
246
- """``torch.xpu.get_device_properties`` as a JSON object, or null off XPU."""
247
- if getattr(device, "type", None) != "xpu":
248
- return None
249
- torch_module = _torch()
250
- xpu = getattr(torch_module, "xpu", None)
251
- getter = getattr(xpu, "get_device_properties", None) if xpu is not None else None
252
- if not callable(getter):
253
- return None
254
- index = 0
255
- current = getattr(xpu, "current_device", None)
256
- if callable(current):
257
- try:
258
- index = int(current())
259
- except Exception:
260
- index = 0
261
- try:
262
- props = getter(index)
263
- except Exception:
264
- return None
265
- if hasattr(props, "_asdict"):
266
- raw = dict(props._asdict())
267
- else:
268
- raw = {}
269
- for key in dir(props):
270
- if key.startswith("_"):
271
- continue
272
- try:
273
- value = getattr(props, key)
274
- except Exception:
275
- continue
276
- if callable(value):
277
- continue
278
- raw[key] = value
279
- return {str(key): _jsonable(value) for key, value in raw.items()}
280
-
281
-
282
- def parity_verdict(
283
- output_max_abs: float,
284
- loss_max_abs: float,
285
- tolerance: float,
286
- reference_scale: float,
287
- ) -> dict:
288
- """Decide whether a device-versus-CPU gap is inside the tolerance.
289
-
290
- ``tolerance`` is a fraction. The allowed absolute gap is
291
- ``tolerance * max(1, reference_scale)``. The floor of 1 keeps a small
292
- bf16-versus-fp32 drift from failing when the CPU output is near zero.
293
- A larger wind head may move by that fraction of its magnitude.
294
- This does not convert physical units. It only compares two forwards.
295
- """
296
- if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
297
- raise ValueError("device_parity_tol must be a finite number >= 0")
298
- if not math.isfinite(float(tolerance)) or float(tolerance) < 0:
299
- raise ValueError("device_parity_tol must be a finite number >= 0")
300
- output = float(output_max_abs)
301
- loss = float(loss_max_abs)
302
- if not math.isfinite(output) or not math.isfinite(loss):
303
- worst = float("inf")
304
- else:
305
- worst = max(output, loss)
306
- scale = float(reference_scale)
307
- if not math.isfinite(scale) or scale < 1.0:
308
- scale = 1.0
309
- limit = float(tolerance) * scale
310
- return {
311
- "output_max_abs": output,
312
- "loss_max_abs": loss,
313
- "max_abs_diff": worst,
314
- "reference_scale": scale,
315
- "tolerance": float(tolerance),
316
- "limit": limit,
317
- "ok": bool(worst <= limit),
318
- }
319
-
320
-
321
- def warn_if_parity_failed(result: dict) -> None:
322
- """Loud warning when the seeded forward disagrees. Training still continues."""
323
- if result.get("ok"):
324
- return
325
- message = (
326
- "WARNING: device parity check failed. "
327
- f"max abs diff {result['max_abs_diff']:.6g} exceeds limit {result['limit']:.6g} "
328
- f"(tolerance {result['tolerance']:.6g}, scale {result['reference_scale']:.6g}). "
329
- "device_parity_ok is false. Training continues. This is not a forecast."
330
- )
331
- LOGGER.warning(message)
332
- print(message)
333
-
334
-
335
- def seeded_parity_batch(batch_size: int, channels: int, side: int, seed: int = 0, n_frames: int = 1):
336
- """One fixed CPU batch. The same tensors are copied onto the device."""
337
- torch_module = _torch()
338
- generator = torch_module.Generator(device="cpu")
339
- generator.manual_seed(int(seed))
340
- if n_frames > 1:
341
- images = torch_module.randn(
342
- int(batch_size), int(n_frames), int(channels), int(side), int(side), generator=generator
343
- )
344
- else:
345
- images = torch_module.randn(
346
- int(batch_size), int(channels), int(side), int(side), generator=generator
347
- )
348
- winds = torch_module.rand(int(batch_size), 1, generator=generator)
349
- return images, winds
350
-
351
-
352
- def _forward_wind_loss(model, images, winds):
353
- import torch.nn.functional as F
354
-
355
- torch_module = _torch()
356
- was_training = model.training
357
- model.eval()
358
- try:
359
- with torch_module.no_grad():
360
- output = model(images)
361
- wind = output[0] if isinstance(output, tuple) else output
362
- loss = F.smooth_l1_loss(wind.float().view(-1), winds.float().view(-1))
363
- return wind.detach().float().cpu(), loss.detach().float().cpu()
364
- finally:
365
- model.train(was_training)
366
-
367
-
368
- def compare_model_parity(model, images, winds, device, tolerance: float, *, policy=None) -> dict:
369
- """Run one forward on ``device`` and on CPU. Record the max absolute gap.
370
-
371
- The training model is copied. Its weights are not updated. The device
372
- copy uses the same autocast policy as training when one is passed.
373
- """
374
- import copy
375
-
376
- cpu_model = copy.deepcopy(model).to("cpu").eval()
377
- device_model = copy.deepcopy(model).to(device).eval()
378
- cpu_wind, cpu_loss = _forward_wind_loss(cpu_model, images, winds)
379
- if policy is None:
380
- policy = amp_policy_for(device)
381
- with autocast_context(policy):
382
- dev_wind, dev_loss = _forward_wind_loss(
383
- device_model, images.to(device), winds.to(device)
384
- )
385
- output_diff = float((dev_wind - cpu_wind).abs().max())
386
- loss_diff = abs(float(dev_loss) - float(cpu_loss))
387
- scale = max(1.0, float(cpu_wind.abs().max()), abs(float(cpu_loss)))
388
- result = parity_verdict(output_diff, loss_diff, float(tolerance), scale)
389
- warn_if_parity_failed(result)
390
- return result
 
1
+ """Device selection and mixed precision for native PyTorch.
2
+
3
+ The order is XPU, then CUDA, then CPU. XPU means ``torch.xpu`` in an
4
+ official PyTorch build (2.5 or newer; 2.15 is the pinned Windows wheel).
5
+ This module does not import or call the archived IPEX package.
6
+
7
+ ``CLOUDIE_ALLOW_GPU=1`` is required for XPU and CUDA alike. An explicit
8
+ accelerator without that gate is refused. Auto falls back to CPU and
9
+ logs the reason. CPU stays fp32. CUDA fp16 is the only path that uses
10
+ GradScaler. XPU uses bf16 autocast when native bf16 is supported, and
11
+ fp32 otherwise. ``cudnn.benchmark`` is not enabled.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import inspect
17
+ import logging
18
+ import math
19
+ import os
20
+ from collections.abc import Iterator
21
+ from contextlib import contextmanager, nullcontext
22
+ from dataclasses import dataclass
23
+
24
+ LOGGER = logging.getLogger("src.device")
25
+
26
+ DEVICE_CHOICES = ("auto", "xpu", "cuda", "cpu")
27
+ GPU_DEVICES = ("xpu", "cuda")
28
+ GPU_GATE = "CLOUDIE_ALLOW_GPU"
29
+
30
+
31
+ def _torch():
32
+ import torch
33
+
34
+ return torch
35
+
36
+
37
+ def accelerator_available(torch_module, name: str) -> bool:
38
+ """True when this torch build can see ``name``. Missing XPU attributes are false."""
39
+ if name == "cpu":
40
+ return True
41
+ if name == "xpu":
42
+ xpu = getattr(torch_module, "xpu", None)
43
+ checker = getattr(xpu, "is_available", None) if xpu is not None else None
44
+ if not callable(checker):
45
+ return False
46
+ try:
47
+ return bool(checker())
48
+ except Exception:
49
+ return False
50
+ if name == "cuda":
51
+ try:
52
+ return bool(torch_module.cuda.is_available())
53
+ except Exception:
54
+ return False
55
+ return False
56
+
57
+
58
+ def xpu_native_bf16(torch_module) -> bool:
59
+ """True when native XPU bf16 is supported.
60
+
61
+ Uses ``torch.xpu.is_bf16_supported(including_emulation=False)`` when
62
+ that parameter exists, so emulated bf16 does not select the autocast
63
+ path. Older builds without the function, or whose call fails, stay
64
+ on fp32. A build that has the function but not the parameter is
65
+ called with no arguments.
66
+ """
67
+ xpu = getattr(torch_module, "xpu", None)
68
+ checker = getattr(xpu, "is_bf16_supported", None) if xpu is not None else None
69
+ if not callable(checker):
70
+ return False
71
+ try:
72
+ parameters = inspect.signature(checker).parameters
73
+ has_kwarg = "including_emulation" in parameters
74
+ except (TypeError, ValueError):
75
+ has_kwarg = False
76
+ try:
77
+ if has_kwarg:
78
+ return bool(checker(including_emulation=False))
79
+ return bool(checker())
80
+ except TypeError:
81
+ try:
82
+ return bool(checker())
83
+ except Exception:
84
+ return False
85
+ except Exception:
86
+ return False
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class AmpPolicy:
91
+ """How one device runs the forward and the backward."""
92
+
93
+ precision: str
94
+ autocast_device: str | None
95
+ dtype: object | None
96
+ use_grad_scaler: bool
97
+
98
+
99
+ def amp_policy_for(device, torch_module=None) -> AmpPolicy:
100
+ """fp16+GradScaler on CUDA, native bf16 on XPU, fp32 everywhere else.
101
+
102
+ GradScaler is never constructed for XPU or CPU. A missing native bf16
103
+ on XPU falls back to fp32 with no autocast.
104
+ """
105
+ torch_module = torch_module or _torch()
106
+ kind = device.type if hasattr(device, "type") else str(device)
107
+ if kind == "cuda":
108
+ return AmpPolicy("fp16", "cuda", torch_module.float16, True)
109
+ if kind == "xpu":
110
+ if xpu_native_bf16(torch_module):
111
+ return AmpPolicy("bf16", "xpu", torch_module.bfloat16, False)
112
+ return AmpPolicy("fp32", None, None, False)
113
+ return AmpPolicy("fp32", None, None, False)
114
+
115
+
116
+ @contextmanager
117
+ def autocast_context(policy: AmpPolicy) -> Iterator[None]:
118
+ """Enter ``torch.autocast`` for the policy, or do nothing for fp32."""
119
+ if policy.autocast_device is None or policy.dtype is None:
120
+ with nullcontext():
121
+ yield
122
+ return
123
+ torch_module = _torch()
124
+ with torch_module.autocast(policy.autocast_device, dtype=policy.dtype):
125
+ yield
126
+
127
+
128
+ def make_grad_scaler(policy: AmpPolicy):
129
+ """A CUDA fp16 GradScaler, or None. XPU and CPU never get one."""
130
+ if not policy.use_grad_scaler:
131
+ return None
132
+ if policy.precision != "fp16" or policy.autocast_device != "cuda":
133
+ raise RuntimeError("GradScaler is used only for cuda fp16")
134
+ torch_module = _torch()
135
+ scaler_cls = getattr(getattr(torch_module, "amp", None), "GradScaler", None)
136
+ if scaler_cls is not None:
137
+ try:
138
+ return scaler_cls("cuda")
139
+ except TypeError:
140
+ pass
141
+ return torch_module.cuda.amp.GradScaler()
142
+
143
+
144
+ def resolve_device(name: str):
145
+ """Pick a ``torch.device``. Auto order is xpu, cuda, cpu.
146
+
147
+ Explicit xpu or cuda without ``CLOUDIE_ALLOW_GPU=1`` raises. Auto
148
+ that would have picked an accelerator falls back to cpu and logs why.
149
+ """
150
+ choice = str(name).strip().lower()
151
+ if choice not in DEVICE_CHOICES:
152
+ raise ValueError("device must be auto, xpu, cuda, or cpu")
153
+ torch_module = _torch()
154
+ if choice == "auto":
155
+ if accelerator_available(torch_module, "xpu"):
156
+ picked = "xpu"
157
+ elif accelerator_available(torch_module, "cuda"):
158
+ picked = "cuda"
159
+ else:
160
+ picked = "cpu"
161
+ if picked != "cpu" and os.environ.get(GPU_GATE) != "1":
162
+ message = (
163
+ f"Refusing auto-picked device {picked} because {GPU_GATE} is not 1. "
164
+ "Falling back to cpu. An XPU or GPU run needs misty wind's approval. "
165
+ f"Set {GPU_GATE}=1 only after that approval."
166
+ )
167
+ LOGGER.warning(message)
168
+ print(message)
169
+ return torch_module.device("cpu")
170
+ choice = picked
171
+ if choice in GPU_DEVICES and os.environ.get(GPU_GATE) != "1":
172
+ raise RuntimeError(
173
+ f"Refusing device {choice}. An XPU or GPU run needs misty wind's approval. "
174
+ f"Set {GPU_GATE}=1 only after that approval."
175
+ )
176
+ if choice == "xpu" and not accelerator_available(torch_module, "xpu"):
177
+ raise RuntimeError("device xpu was approved but XPU is not available")
178
+ if choice == "cuda" and not accelerator_available(torch_module, "cuda"):
179
+ raise RuntimeError("device cuda was approved but CUDA is not available")
180
+ try:
181
+ return torch_module.device(choice)
182
+ except RuntimeError as exc:
183
+ raise RuntimeError(f"device {choice} is not supported by this torch build") from exc
184
+
185
+
186
+ def reset_peak_memory(device) -> None:
187
+ """Clear the allocator peak for the device that tracks it. CPU is a no-op."""
188
+ torch_module = _torch()
189
+ if getattr(device, "type", None) == "cuda":
190
+ reset = getattr(torch_module.cuda, "reset_peak_memory_stats", None)
191
+ if callable(reset):
192
+ try:
193
+ reset()
194
+ except Exception:
195
+ return
196
+ if getattr(device, "type", None) == "xpu":
197
+ xpu = getattr(torch_module, "xpu", None)
198
+ reset = getattr(xpu, "reset_peak_memory_stats", None) if xpu is not None else None
199
+ if callable(reset):
200
+ try:
201
+ reset()
202
+ except Exception:
203
+ return
204
+
205
+
206
+ def peak_memory_bytes(device) -> int | None:
207
+ """Peak bytes from XPU or CUDA, or null when the device does not report it.
208
+
209
+ XPU peak memory is trustworthy on the torch 2.15 line. Older builds
210
+ may return a number that is not the true peak; the value is still
211
+ whatever ``max_memory_allocated`` reports.
212
+ """
213
+ torch_module = _torch()
214
+ kind = getattr(device, "type", None)
215
+ if kind == "xpu":
216
+ xpu = getattr(torch_module, "xpu", None)
217
+ reader = getattr(xpu, "max_memory_allocated", None) if xpu is not None else None
218
+ if not callable(reader):
219
+ return None
220
+ try:
221
+ return int(reader())
222
+ except Exception:
223
+ return None
224
+ if kind == "cuda":
225
+ reader = getattr(torch_module.cuda, "max_memory_allocated", None)
226
+ if not callable(reader):
227
+ return None
228
+ try:
229
+ return int(reader())
230
+ except Exception:
231
+ return None
232
+ return None
233
+
234
+
235
+ def _jsonable(value):
236
+ if value is None or isinstance(value, (str, int, float, bool)):
237
+ if isinstance(value, float) and not math.isfinite(value):
238
+ return None
239
+ return value
240
+ if isinstance(value, (list, tuple)):
241
+ return [_jsonable(item) for item in value]
242
+ return str(value)
243
+
244
+
245
+ def xpu_device_properties(device) -> dict | None:
246
+ """``torch.xpu.get_device_properties`` as a JSON object, or null off XPU."""
247
+ if getattr(device, "type", None) != "xpu":
248
+ return None
249
+ torch_module = _torch()
250
+ xpu = getattr(torch_module, "xpu", None)
251
+ getter = getattr(xpu, "get_device_properties", None) if xpu is not None else None
252
+ if not callable(getter):
253
+ return None
254
+ index = 0
255
+ current = getattr(xpu, "current_device", None)
256
+ if callable(current):
257
+ try:
258
+ index = int(current())
259
+ except Exception:
260
+ index = 0
261
+ try:
262
+ props = getter(index)
263
+ except Exception:
264
+ return None
265
+ if hasattr(props, "_asdict"):
266
+ raw = dict(props._asdict())
267
+ else:
268
+ raw = {}
269
+ for key in dir(props):
270
+ if key.startswith("_"):
271
+ continue
272
+ try:
273
+ value = getattr(props, key)
274
+ except Exception:
275
+ continue
276
+ if callable(value):
277
+ continue
278
+ raw[key] = value
279
+ return {str(key): _jsonable(value) for key, value in raw.items()}
280
+
281
+
282
+ def parity_verdict(
283
+ output_max_abs: float,
284
+ loss_max_abs: float,
285
+ tolerance: float,
286
+ reference_scale: float,
287
+ ) -> dict:
288
+ """Decide whether a device-versus-CPU gap is inside the tolerance.
289
+
290
+ ``tolerance`` is a fraction. The allowed absolute gap is
291
+ ``tolerance * max(1, reference_scale)``. The floor of 1 keeps a small
292
+ bf16-versus-fp32 drift from failing when the CPU output is near zero.
293
+ A larger wind head may move by that fraction of its magnitude.
294
+ This does not convert physical units. It only compares two forwards.
295
+ """
296
+ if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
297
+ raise ValueError("device_parity_tol must be a finite number >= 0")
298
+ if not math.isfinite(float(tolerance)) or float(tolerance) < 0:
299
+ raise ValueError("device_parity_tol must be a finite number >= 0")
300
+ output = float(output_max_abs)
301
+ loss = float(loss_max_abs)
302
+ if not math.isfinite(output) or not math.isfinite(loss):
303
+ worst = float("inf")
304
+ else:
305
+ worst = max(output, loss)
306
+ scale = float(reference_scale)
307
+ if not math.isfinite(scale) or scale < 1.0:
308
+ scale = 1.0
309
+ limit = float(tolerance) * scale
310
+ return {
311
+ "output_max_abs": output,
312
+ "loss_max_abs": loss,
313
+ "max_abs_diff": worst,
314
+ "reference_scale": scale,
315
+ "tolerance": float(tolerance),
316
+ "limit": limit,
317
+ "ok": bool(worst <= limit),
318
+ }
319
+
320
+
321
+ def warn_if_parity_failed(result: dict) -> None:
322
+ """Loud warning when the seeded forward disagrees. Training still continues."""
323
+ if result.get("ok"):
324
+ return
325
+ message = (
326
+ "WARNING: device parity check failed. "
327
+ f"max abs diff {result['max_abs_diff']:.6g} exceeds limit {result['limit']:.6g} "
328
+ f"(tolerance {result['tolerance']:.6g}, scale {result['reference_scale']:.6g}). "
329
+ "device_parity_ok is false. Training continues. This is not a forecast."
330
+ )
331
+ LOGGER.warning(message)
332
+ print(message)
333
+
334
+
335
+ def seeded_parity_batch(batch_size: int, channels: int, side: int, seed: int = 0, n_frames: int = 1):
336
+ """One fixed CPU batch. The same tensors are copied onto the device."""
337
+ torch_module = _torch()
338
+ generator = torch_module.Generator(device="cpu")
339
+ generator.manual_seed(int(seed))
340
+ if n_frames > 1:
341
+ images = torch_module.randn(
342
+ int(batch_size), int(n_frames), int(channels), int(side), int(side), generator=generator
343
+ )
344
+ else:
345
+ images = torch_module.randn(
346
+ int(batch_size), int(channels), int(side), int(side), generator=generator
347
+ )
348
+ winds = torch_module.rand(int(batch_size), 1, generator=generator)
349
+ return images, winds
350
+
351
+
352
+ def _forward_wind_loss(model, images, winds):
353
+ import torch.nn.functional as F
354
+
355
+ torch_module = _torch()
356
+ was_training = model.training
357
+ model.eval()
358
+ try:
359
+ with torch_module.no_grad():
360
+ output = model(images)
361
+ wind = output[0] if isinstance(output, tuple) else output
362
+ loss = F.smooth_l1_loss(wind.float().view(-1), winds.float().view(-1))
363
+ return wind.detach().float().cpu(), loss.detach().float().cpu()
364
+ finally:
365
+ model.train(was_training)
366
+
367
+
368
+ def compare_model_parity(model, images, winds, device, tolerance: float, *, policy=None) -> dict:
369
+ """Run one forward on ``device`` and on CPU. Record the max absolute gap.
370
+
371
+ The training model is copied. Its weights are not updated. The device
372
+ copy uses the same autocast policy as training when one is passed.
373
+ """
374
+ import copy
375
+
376
+ cpu_model = copy.deepcopy(model).to("cpu").eval()
377
+ device_model = copy.deepcopy(model).to(device).eval()
378
+ cpu_wind, cpu_loss = _forward_wind_loss(cpu_model, images, winds)
379
+ if policy is None:
380
+ policy = amp_policy_for(device)
381
+ with autocast_context(policy):
382
+ dev_wind, dev_loss = _forward_wind_loss(
383
+ device_model, images.to(device), winds.to(device)
384
+ )
385
+ output_diff = float((dev_wind - cpu_wind).abs().max())
386
+ loss_diff = abs(float(dev_loss) - float(cpu_loss))
387
+ scale = max(1.0, float(cpu_wind.abs().max()), abs(float(cpu_loss)))
388
+ result = parity_verdict(output_diff, loss_diff, float(tolerance), scale)
389
+ warn_if_parity_failed(result)
390
+ return result
src/evaluate.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/features.py CHANGED
@@ -1,899 +1,899 @@
1
- """Physically motivated image features for classical intensity baselines.
2
-
3
- Distributional statistics are called ``tb_*`` only when the caller has set
4
- ``features.calibrated``. Otherwise they are ``pixel_*``. Nothing here converts
5
- digital numbers to brightness temperature.
6
-
7
- The simplified DAV terms are the circular variance of the angle between the
8
- image gradient and the radial direction, at fixed fractions of the crop
9
- half-width. That is not operational deviation-angle variance: there is no
10
- radius search, no flight-level wind, and no agency radius product.
11
-
12
- Radial, eye, and DAV features assume the storm is already near the image
13
- center. This module does not recenter with a best-track fix.
14
-
15
- Temporal deltas use the previous frame of the same storm after cross-split
16
- links have been removed. Wind, R34, RMW, and class labels are not features.
17
-
18
- Crop height and width are the array shape. ``data.image_size`` may be
19
- ``native`` or a square resize for the deep model. It is not applied here.
20
- Feature selection calls
21
- ``storm_ids_by_split`` and fits only the training storms.
22
- """
23
-
24
- from __future__ import annotations
25
-
26
- import json
27
- import logging
28
- from dataclasses import dataclass
29
- from pathlib import Path
30
-
31
- import numpy as np
32
- import pandas as pd
33
- from sklearn.ensemble import RandomForestRegressor
34
- from sklearn.feature_selection import RFE
35
- from sklearn.impute import SimpleImputer
36
-
37
- from src.data_loader import load_image, resolve_image
38
- from src.preprocessing import MAX_MISSING_FRACTION, as_channel_first, missing_fraction
39
- from src.schema import FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5
40
- from src.splits import (
41
- LeakageError,
42
- add_previous_frame_id,
43
- assert_no_forbidden_inputs,
44
- null_cross_split_links,
45
- storm_ids_by_split,
46
- )
47
-
48
- logger = logging.getLogger(__name__)
49
-
50
- GLCM_NAMES = (
51
- "glcm_contrast",
52
- "glcm_dissimilarity",
53
- "glcm_homogeneity",
54
- "glcm_energy",
55
- "glcm_correlation",
56
- "glcm_asm",
57
- )
58
- HAAR_NAMES = (
59
- "haar_energy_ll",
60
- "haar_energy_lh",
61
- "haar_energy_hl",
62
- "haar_energy_hh",
63
- )
64
- EYE_NAMES = (
65
- "eye_center_mean",
66
- "cdo_annulus_mean",
67
- "eye_cdo_contrast",
68
- "eye_present",
69
- )
70
-
71
-
72
- @dataclass(frozen=True)
73
- class FeatureSpec:
74
- """Geometry of one feature vector. Thresholds are in image units."""
75
-
76
- calibrated: bool = False
77
- cold_thresholds: tuple[float, ...] = (200.0, 210.0, 220.0, 230.0, 240.0)
78
- radial_bins: int = 8
79
- eye_radius_fraction: float = 0.12
80
- cdo_outer_fraction: float = 0.35
81
- eye_contrast_min: float = 2.0
82
- dav_radii_fractions: tuple[float, ...] = (0.15, 0.30, 0.45, 0.60)
83
- dav_annulus_width_fraction: float = 0.08
84
- glcm_levels: int = 16
85
- glcm_distance: int = 1
86
-
87
- def __post_init__(self) -> None:
88
- if not self.cold_thresholds:
89
- raise ValueError("cold_thresholds must not be empty")
90
- if self.radial_bins < 2:
91
- raise ValueError("radial_bins must be at least 2")
92
- if not 0 < self.eye_radius_fraction < self.cdo_outer_fraction <= 1:
93
- raise ValueError("eye radius must sit inside the CDO annulus")
94
- if self.eye_contrast_min < 0:
95
- raise ValueError("eye_contrast_min must be >= 0")
96
- if any(not 0 < radius < 1 for radius in self.dav_radii_fractions):
97
- raise ValueError("DAV radii must be fractions of the half-width")
98
- if not 0 < self.dav_annulus_width_fraction < 0.5:
99
- raise ValueError("DAV annulus width fraction is out of range")
100
- if not 8 <= self.glcm_levels <= 32:
101
- raise ValueError("glcm_levels must be between 8 and 32")
102
- if self.glcm_distance < 1:
103
- raise ValueError("glcm_distance must be >= 1")
104
-
105
- @property
106
- def prefix(self) -> str:
107
- return "tb" if self.calibrated else "pixel"
108
-
109
- @classmethod
110
- def from_config(cls, config: dict) -> FeatureSpec:
111
- raw = config.get("features")
112
- if not isinstance(raw, dict):
113
- raise KeyError("config features is required")
114
- required = (
115
- "calibrated",
116
- "cold_thresholds",
117
- "radial_bins",
118
- "eye_radius_fraction",
119
- "cdo_outer_fraction",
120
- "eye_contrast_min",
121
- "dav_radii_fractions",
122
- "dav_annulus_width_fraction",
123
- "glcm_levels",
124
- "glcm_distance",
125
- )
126
- missing = [key for key in required if key not in raw]
127
- if missing:
128
- raise KeyError(f"config features missing {missing}")
129
- return cls(
130
- calibrated=bool(raw["calibrated"]),
131
- cold_thresholds=tuple(float(value) for value in raw["cold_thresholds"]),
132
- radial_bins=int(raw["radial_bins"]),
133
- eye_radius_fraction=float(raw["eye_radius_fraction"]),
134
- cdo_outer_fraction=float(raw["cdo_outer_fraction"]),
135
- eye_contrast_min=float(raw["eye_contrast_min"]),
136
- dav_radii_fractions=tuple(float(value) for value in raw["dav_radii_fractions"]),
137
- dav_annulus_width_fraction=float(raw["dav_annulus_width_fraction"]),
138
- glcm_levels=int(raw["glcm_levels"]),
139
- glcm_distance=int(raw["glcm_distance"]),
140
- )
141
-
142
- def feature_groups(self) -> dict[str, tuple[str, ...]]:
143
- """Feature names by group.
144
-
145
- ``pixel_stats`` are order statistics of the stored image values.
146
- They are not brightness temperature unless ``calibrated`` is set,
147
- in which case the same slots use the ``tb_`` prefix.
148
- ``dav_simplified`` is gradient-angle variance, not operational DAV.
149
- """
150
- prefix = self.prefix
151
- return {
152
- "pixel_stats": (
153
- f"{prefix}_min",
154
- f"{prefix}_max",
155
- f"{prefix}_mean",
156
- f"{prefix}_std",
157
- f"{prefix}_p10",
158
- f"{prefix}_p25",
159
- f"{prefix}_p50",
160
- f"{prefix}_p75",
161
- f"{prefix}_p90",
162
- f"{prefix}_iqr",
163
- ),
164
- "cold_cloud": tuple(
165
- f"cold_frac_{_token(threshold)}" for threshold in self.cold_thresholds
166
- ),
167
- "radial": tuple(f"radial_mean_{index:02d}" for index in range(self.radial_bins)),
168
- "eye_cdo": EYE_NAMES,
169
- "dav_simplified": tuple(
170
- f"dav_simplified_r{index:02d}" for index in range(len(self.dav_radii_fractions))
171
- ),
172
- "glcm": GLCM_NAMES,
173
- "haar": HAAR_NAMES,
174
- "temporal": (
175
- "has_prev",
176
- f"delta_{prefix}_mean",
177
- f"delta_{prefix}_min",
178
- "delta_cold_primary",
179
- "delta_eye_cdo_contrast",
180
- "delta_radial_mean_00",
181
- ),
182
- }
183
-
184
- def image_feature_names(self) -> tuple[str, ...]:
185
- groups = self.feature_groups()
186
- names: list[str] = []
187
- for key in (
188
- "pixel_stats",
189
- "cold_cloud",
190
- "radial",
191
- "eye_cdo",
192
- "dav_simplified",
193
- "glcm",
194
- "haar",
195
- ):
196
- names.extend(groups[key])
197
- return tuple(names)
198
-
199
- def feature_names(self) -> tuple[str, ...]:
200
- return self.image_feature_names() + self.feature_groups()["temporal"]
201
-
202
-
203
- @dataclass(frozen=True)
204
- class FeatureSelection:
205
- names: tuple[str, ...]
206
- source_split: str
207
- importances: dict[str, float]
208
- dropped_variance: tuple[str, ...]
209
- dropped_correlation: tuple[str, ...]
210
- train_storms: frozenset[str] = frozenset()
211
-
212
-
213
- def _token(value: float) -> str:
214
- number = float(value)
215
- if number.is_integer():
216
- return str(int(number))
217
- return str(number).replace("-", "m").replace(".", "p")
218
-
219
-
220
- def _single_channel(image: np.ndarray) -> np.ndarray:
221
- return as_channel_first(image)[0]
222
-
223
-
224
- def _finite_fill(image: np.ndarray) -> np.ndarray:
225
- filled = np.array(image, dtype=np.float64, copy=True)
226
- finite = np.isfinite(filled)
227
- fill = float(np.median(filled[finite])) if finite.any() else 0.0
228
- filled[~finite] = fill
229
- return filled
230
-
231
-
232
- def _distribution(image: np.ndarray, prefix: str) -> dict[str, float]:
233
- finite = image[np.isfinite(image)]
234
- if finite.size == 0:
235
- keys = (
236
- "min",
237
- "max",
238
- "mean",
239
- "std",
240
- "p10",
241
- "p25",
242
- "p50",
243
- "p75",
244
- "p90",
245
- "iqr",
246
- )
247
- return {f"{prefix}_{key}": float("nan") for key in keys}
248
- percentiles = np.percentile(finite, [10, 25, 50, 75, 90])
249
- return {
250
- f"{prefix}_min": float(finite.min()),
251
- f"{prefix}_max": float(finite.max()),
252
- f"{prefix}_mean": float(finite.mean()),
253
- f"{prefix}_std": float(finite.std()),
254
- f"{prefix}_p10": float(percentiles[0]),
255
- f"{prefix}_p25": float(percentiles[1]),
256
- f"{prefix}_p50": float(percentiles[2]),
257
- f"{prefix}_p75": float(percentiles[3]),
258
- f"{prefix}_p90": float(percentiles[4]),
259
- f"{prefix}_iqr": float(percentiles[3] - percentiles[1]),
260
- }
261
-
262
-
263
- def _cold_coverage(image: np.ndarray, thresholds: tuple[float, ...]) -> dict[str, float]:
264
- finite = image[np.isfinite(image)]
265
- out: dict[str, float] = {}
266
- for threshold in thresholds:
267
- key = f"cold_frac_{_token(threshold)}"
268
- if finite.size == 0:
269
- out[key] = float("nan")
270
- else:
271
- out[key] = float(np.mean(finite < threshold))
272
- return out
273
-
274
-
275
- def _radial_and_eye(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
276
- height, width = image.shape
277
- yy, xx = np.mgrid[0:height, 0:width]
278
- center_y = (height - 1) / 2.0
279
- center_x = (width - 1) / 2.0
280
- radius = np.hypot(yy - center_y, xx - center_x)
281
- max_radius = max(float(radius.max()), 1e-6)
282
- edges = np.linspace(0.0, max_radius + 1e-6, spec.radial_bins + 1)
283
- out: dict[str, float] = {}
284
- for index in range(spec.radial_bins):
285
- mask = (radius >= edges[index]) & (radius < edges[index + 1]) & np.isfinite(image)
286
- out[f"radial_mean_{index:02d}"] = (
287
- float(image[mask].mean()) if mask.any() else float("nan")
288
- )
289
- half = min(height, width) / 2.0
290
- eye = radius <= spec.eye_radius_fraction * half
291
- annulus = (radius > spec.eye_radius_fraction * half) & (
292
- radius <= spec.cdo_outer_fraction * half
293
- )
294
- eye_values = image[eye & np.isfinite(image)]
295
- annulus_values = image[annulus & np.isfinite(image)]
296
- eye_mean = float(eye_values.mean()) if eye_values.size else float("nan")
297
- annulus_mean = float(annulus_values.mean()) if annulus_values.size else float("nan")
298
- contrast = eye_mean - annulus_mean
299
- eye_present = (
300
- 0.0
301
- if not np.isfinite(contrast)
302
- else float(contrast >= spec.eye_contrast_min)
303
- )
304
- out["eye_center_mean"] = eye_mean
305
- out["cdo_annulus_mean"] = annulus_mean
306
- out["eye_cdo_contrast"] = float(contrast)
307
- out["eye_present"] = eye_present
308
- return out
309
-
310
-
311
- def _deviation_angle_variance(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
312
- """Circular variance of gradient angle minus radial angle. Not operational DAV."""
313
- height, width = image.shape
314
- yy, xx = np.mgrid[0:height, 0:width]
315
- center_y = (height - 1) / 2.0
316
- center_x = (width - 1) / 2.0
317
- dy = yy - center_y
318
- dx = xx - center_x
319
- radius = np.hypot(dy, dx)
320
- half = min(height, width) / 2.0
321
- gradient_y, gradient_x = np.gradient(image)
322
- magnitude = np.hypot(gradient_y, gradient_x)
323
- radial_angle = np.arctan2(dy, dx)
324
- gradient_angle = np.arctan2(gradient_y, gradient_x)
325
- deviation = np.arctan2(
326
- np.sin(gradient_angle - radial_angle),
327
- np.cos(gradient_angle - radial_angle),
328
- )
329
- # Keep the ring at least two pixels thick. On a small crop the fractional
330
- # width can otherwise fall between grid points and the statistic is empty.
331
- width_px = max(spec.dav_annulus_width_fraction * half, 2.0)
332
- out: dict[str, float] = {}
333
- for index, fraction in enumerate(spec.dav_radii_fractions):
334
- radius_px = fraction * half
335
- annulus = (radius >= radius_px - width_px / 2.0) & (
336
- radius <= radius_px + width_px / 2.0
337
- )
338
- # A zero gradient has no direction. arctan2(0, 0) is 0 and would
339
- # look like a full circle of disagreement.
340
- selected = deviation[annulus & (magnitude > 1e-6)]
341
- if selected.size < 8:
342
- out[f"dav_simplified_r{index:02d}"] = float("nan")
343
- continue
344
- mean_vector = np.exp(1j * selected).mean()
345
- out[f"dav_simplified_r{index:02d}"] = float(1.0 - np.abs(mean_vector))
346
- return out
347
-
348
-
349
- def _pair_counts(
350
- bins: np.ndarray, valid: np.ndarray, dy: int, dx: int, levels: int
351
- ) -> np.ndarray | None:
352
- height, width = bins.shape
353
- if abs(dy) >= height or abs(dx) >= width:
354
- return None
355
- if dy >= 0:
356
- src_y, dst_y = slice(0, height - dy), slice(dy, height)
357
- else:
358
- src_y, dst_y = slice(-dy, height), slice(0, height + dy)
359
- if dx >= 0:
360
- src_x, dst_x = slice(0, width - dx), slice(dx, width)
361
- else:
362
- src_x, dst_x = slice(-dx, width), slice(0, width + dx)
363
- mask = valid[src_y, src_x] & valid[dst_y, dst_x]
364
- if not mask.any():
365
- return None
366
- source = bins[src_y, src_x][mask].ravel()
367
- dest = bins[dst_y, dst_x][mask].ravel()
368
- flat = source.astype(np.int64) * levels + dest.astype(np.int64)
369
- counts = np.bincount(flat, minlength=levels * levels).reshape(levels, levels)
370
- total = float(counts.sum())
371
- if total <= 0:
372
- return None
373
- return counts.astype(np.float64) / total
374
-
375
-
376
- def _haralick(probs: np.ndarray) -> dict[str, float]:
377
- levels = probs.shape[0]
378
- rows, cols = np.indices((levels, levels))
379
- contrast = float(((rows - cols) ** 2 * probs).sum())
380
- dissimilarity = float((np.abs(rows - cols) * probs).sum())
381
- homogeneity = float((probs / (1.0 + (rows - cols) ** 2)).sum())
382
- asm = float((probs**2).sum())
383
- energy = float(np.sqrt(asm))
384
- mean_i = float((rows * probs).sum())
385
- mean_j = float((cols * probs).sum())
386
- std_i = float(np.sqrt(((rows - mean_i) ** 2 * probs).sum()))
387
- std_j = float(np.sqrt(((cols - mean_j) ** 2 * probs).sum()))
388
- if std_i < 1e-12 or std_j < 1e-12:
389
- correlation = 0.0
390
- else:
391
- correlation = float(
392
- ((rows - mean_i) * (cols - mean_j) * probs).sum() / (std_i * std_j)
393
- )
394
- return {
395
- "glcm_contrast": contrast,
396
- "glcm_dissimilarity": dissimilarity,
397
- "glcm_homogeneity": homogeneity,
398
- "glcm_energy": energy,
399
- "glcm_correlation": correlation,
400
- "glcm_asm": asm,
401
- }
402
-
403
-
404
- def _glcm_features(image: np.ndarray, levels: int, distance: int) -> dict[str, float]:
405
- height, width = image.shape
406
- empty = {name: float("nan") for name in GLCM_NAMES}
407
- if height <= distance or width <= distance:
408
- return empty
409
- finite = image[np.isfinite(image)]
410
- if finite.size == 0:
411
- return empty
412
- low = float(finite.min())
413
- high = float(finite.max())
414
- if high - low < 1e-6:
415
- bins = np.zeros(image.shape, dtype=np.int32)
416
- else:
417
- scaled = np.clip((image - low) / (high - low), 0.0, 1.0)
418
- bins = np.minimum((scaled * levels).astype(np.int32), levels - 1)
419
- valid = np.isfinite(image)
420
- offsets = (
421
- (0, distance),
422
- (-distance, distance),
423
- (-distance, 0),
424
- (-distance, -distance),
425
- )
426
- collected = []
427
- for dy, dx in offsets:
428
- probs = _pair_counts(bins, valid, dy, dx, levels)
429
- if probs is not None:
430
- collected.append(_haralick(probs))
431
- if not collected:
432
- return empty
433
- return {
434
- name: float(np.mean([item[name] for item in collected])) for name in GLCM_NAMES
435
- }
436
-
437
-
438
- def _haar_energies(image: np.ndarray) -> dict[str, float]:
439
- band = image
440
- if band.shape[0] % 2:
441
- band = band[:-1, :]
442
- if band.shape[1] % 2:
443
- band = band[:, :-1]
444
- if min(band.shape) < 2:
445
- return {name: float("nan") for name in HAAR_NAMES}
446
- even_even = band[0::2, 0::2]
447
- even_odd = band[0::2, 1::2]
448
- odd_even = band[1::2, 0::2]
449
- odd_odd = band[1::2, 1::2]
450
- low_low = (even_even + even_odd + odd_even + odd_odd) / 4.0
451
- low_high = (even_even + odd_even - even_odd - odd_odd) / 4.0
452
- high_low = (even_even - odd_even + even_odd - odd_odd) / 4.0
453
- high_high = (even_even - odd_even - even_odd + odd_odd) / 4.0
454
- energies = {
455
- "haar_energy_ll": float(np.mean(low_low**2)),
456
- "haar_energy_lh": float(np.mean(low_high**2)),
457
- "haar_energy_hl": float(np.mean(high_low**2)),
458
- "haar_energy_hh": float(np.mean(high_high**2)),
459
- }
460
- total = sum(energies.values())
461
- if total <= 1e-12:
462
- return {name: 0.0 for name in HAAR_NAMES}
463
- return {name: value / total for name, value in energies.items()}
464
-
465
-
466
- def native_shape(image: np.ndarray) -> tuple[int, int]:
467
- """Height and width of one crop. This is not ``data.image_size``."""
468
- channel = _single_channel(image)
469
- return int(channel.shape[0]), int(channel.shape[1])
470
-
471
-
472
- def extract_image_features(
473
- image: np.ndarray,
474
- spec: FeatureSpec,
475
- max_missing_fraction: float = MAX_MISSING_FRACTION,
476
- ) -> dict[str, float]:
477
- """Features of one centered IR crop. The label is not an input.
478
-
479
- The crop is not resized. Callers that need the crop size use
480
- ``native_shape``, which reads the array. ``data.image_size`` is not applied.
481
- """
482
- channel = _single_channel(image)
483
- fraction = missing_fraction(channel)
484
- if fraction > max_missing_fraction:
485
- raise ValueError(
486
- f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
487
- )
488
- if not np.isfinite(channel).any():
489
- raise ValueError("image has no finite pixels")
490
- dense = _finite_fill(channel)
491
- features: dict[str, float] = {}
492
- features.update(_distribution(channel, spec.prefix))
493
- features.update(_cold_coverage(channel, spec.cold_thresholds))
494
- features.update(_radial_and_eye(channel, spec))
495
- features.update(_deviation_angle_variance(dense, spec))
496
- features.update(_glcm_features(dense, spec.glcm_levels, spec.glcm_distance))
497
- features.update(_haar_energies(dense))
498
- expected = spec.image_feature_names()
499
- missing = [name for name in expected if name not in features]
500
- if missing:
501
- raise RuntimeError(f"feature extractor omitted {missing}")
502
- return {name: float(features[name]) for name in expected}
503
-
504
-
505
- def _temporal_defaults(spec: FeatureSpec) -> dict[str, float]:
506
- prefix = spec.prefix
507
- return {
508
- "has_prev": 0.0,
509
- f"delta_{prefix}_mean": float("nan"),
510
- f"delta_{prefix}_min": float("nan"),
511
- "delta_cold_primary": float("nan"),
512
- "delta_eye_cdo_contrast": float("nan"),
513
- "delta_radial_mean_00": float("nan"),
514
- }
515
-
516
-
517
- # Optional frame labels. Copied when the manifest has them. Not model features.
518
- _CARRIED_COLUMNS = (
519
- "timestamp",
520
- "relative_time_s",
521
- "source_split",
522
- "wind_averaging",
523
- "wind_averaging_s",
524
- "on_fix",
525
- "near_land",
526
- "distance_to_land_km",
527
- "cv_group",
528
- )
529
-
530
-
531
- def _extract_path(task: tuple[str, FeatureSpec, float]) -> dict[str, float]:
532
- """Load one image and return its feature dict. Used by the worker pool."""
533
- path, spec, max_missing_fraction = task
534
- return extract_image_features(load_image(path), spec, max_missing_fraction)
535
-
536
-
537
- def _spec_fingerprint(spec: FeatureSpec, max_missing_fraction: float) -> str:
538
- """Identity of the extractor settings stored next to an image checkpoint."""
539
- payload = {
540
- "calibrated": bool(spec.calibrated),
541
- "cold_thresholds": [float(value) for value in spec.cold_thresholds],
542
- "radial_bins": int(spec.radial_bins),
543
- "eye_radius_fraction": float(spec.eye_radius_fraction),
544
- "cdo_outer_fraction": float(spec.cdo_outer_fraction),
545
- "eye_contrast_min": float(spec.eye_contrast_min),
546
- "dav_radii_fractions": [float(value) for value in spec.dav_radii_fractions],
547
- "dav_annulus_width_fraction": float(spec.dav_annulus_width_fraction),
548
- "glcm_levels": int(spec.glcm_levels),
549
- "glcm_distance": int(spec.glcm_distance),
550
- "max_missing_fraction": float(max_missing_fraction),
551
- }
552
- return json.dumps(payload, sort_keys=True)
553
-
554
-
555
- def _checkpoint_spec_path(path: Path) -> Path:
556
- return path.with_suffix(path.suffix + ".spec.json")
557
-
558
-
559
- def _image_checkpoint_rows(
560
- path: Path, spec: FeatureSpec, max_missing_fraction: float
561
- ) -> dict[str, dict[str, float]]:
562
- if not path.is_file():
563
- return {}
564
- spec_path = _checkpoint_spec_path(path)
565
- if not spec_path.is_file():
566
- return {}
567
- saved_spec = json.loads(spec_path.read_text(encoding="utf-8"))
568
- if saved_spec.get("fingerprint") != _spec_fingerprint(spec, max_missing_fraction):
569
- return {}
570
- saved = pd.read_csv(path)
571
- if "sample_id" not in saved.columns:
572
- return {}
573
- rows: dict[str, dict[str, float]] = {}
574
- for record in saved.to_dict(orient="records"):
575
- sample_id = str(record.pop("sample_id"))
576
- rows[sample_id] = record
577
- return rows
578
-
579
-
580
- def _write_image_checkpoint(
581
- path: Path,
582
- rows: dict[str, dict[str, float]],
583
- spec: FeatureSpec,
584
- max_missing_fraction: float,
585
- ) -> None:
586
- records = [{"sample_id": sample_id, **features} for sample_id, features in rows.items()]
587
- path.parent.mkdir(parents=True, exist_ok=True)
588
- pd.DataFrame(records).to_csv(path, index=False)
589
- _checkpoint_spec_path(path).write_text(
590
- json.dumps(
591
- {"fingerprint": _spec_fingerprint(spec, max_missing_fraction)},
592
- indent=2,
593
- sort_keys=True,
594
- )
595
- + "\n",
596
- encoding="utf-8",
597
- )
598
-
599
-
600
- def extract_feature_table(
601
- frame: pd.DataFrame,
602
- manifest_path: str,
603
- spec: FeatureSpec,
604
- max_missing_fraction: float = MAX_MISSING_FRACTION,
605
- workers: int = 1,
606
- image_checkpoint: str | Path | None = None,
607
- ) -> tuple[pd.DataFrame, int]:
608
- """Extract features and same-split temporal deltas.
609
-
610
- Previous-frame ids are recomputed from ``storm_id`` and the observation
611
- clock (``timestamp``, else NASA ``relative_time_s``), then any link that
612
- crosses ``split`` is dropped before the delta is taken. ``workers`` above
613
- 1 only parallelizes the per-image extract. It does not change the values.
614
- ``image_checkpoint``, when set, stores per-image features so a restarted
615
- run does not re-read frames that already finished. Temporal deltas are
616
- still computed after every frame in this call has image features.
617
- """
618
- if "split" not in frame.columns:
619
- raise LeakageError("feature extraction requires a split column")
620
- if workers < 1:
621
- raise ValueError("workers must be at least 1")
622
- linked = add_previous_frame_id(frame)
623
- linked, dropped = null_cross_split_links(linked)
624
- rows_in = linked.to_dict(orient="records")
625
- tasks = [
626
- (str(resolve_image(manifest_path, str(row["image_path"]))), spec, max_missing_fraction)
627
- for row in rows_in
628
- ]
629
- expected = spec.image_feature_names()
630
- checkpoint = Path(image_checkpoint) if image_checkpoint else None
631
- stored = (
632
- _image_checkpoint_rows(checkpoint, spec, max_missing_fraction) if checkpoint else {}
633
- )
634
- extracted: list[dict[str, float] | None] = [None] * len(rows_in)
635
- pending: list[int] = []
636
- for index, row in enumerate(rows_in):
637
- sample_id = str(row["sample_id"])
638
- cached = stored.get(sample_id)
639
- if cached is not None and all(name in cached for name in expected):
640
- extracted[index] = {name: float(cached[name]) for name in expected}
641
- else:
642
- pending.append(index)
643
- if pending:
644
- logger.info("Extracting %s images (%s already cached)", len(pending), len(rows_in) - len(pending))
645
-
646
- def _finish(index: int) -> tuple[int, dict[str, float]]:
647
- return index, _extract_path(tasks[index])
648
-
649
- batch = 200
650
- if workers == 1:
651
- for start in range(0, len(pending), batch):
652
- chunk = pending[start : start + batch]
653
- for index in chunk:
654
- _index, features = _finish(index)
655
- extracted[_index] = features
656
- stored[str(rows_in[_index]["sample_id"])] = features
657
- if checkpoint:
658
- _write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
659
- logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
660
- else:
661
- from concurrent.futures import ThreadPoolExecutor
662
-
663
- with ThreadPoolExecutor(max_workers=workers) as pool:
664
- for start in range(0, len(pending), batch):
665
- chunk = pending[start : start + batch]
666
- for index, features in pool.map(_finish, chunk):
667
- extracted[index] = features
668
- stored[str(rows_in[index]["sample_id"])] = features
669
- if checkpoint:
670
- _write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
671
- logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
672
- if any(item is None for item in extracted):
673
- raise RuntimeError("image feature extraction left a row empty")
674
- cache: dict[str, tuple[str, dict[str, float]]] = {}
675
- packed: list[tuple[dict[str, object], dict[str, float]]] = []
676
- for row, image_features in zip(rows_in, extracted, strict=True):
677
- sample_id = str(row["sample_id"])
678
- cache[sample_id] = (str(row["split"]), image_features)
679
- packed.append((row, image_features))
680
-
681
- prefix = spec.prefix
682
- cold_key = f"cold_frac_{_token(spec.cold_thresholds[0])}"
683
- rows: list[dict[str, object]] = []
684
- for row, image_features in packed:
685
- temporal = _temporal_defaults(spec)
686
- prev = row.get("prev_sample_id")
687
- if not pd.isna(prev) and str(prev) in cache:
688
- prev_split, previous = cache[str(prev)]
689
- if prev_split != str(row["split"]):
690
- raise LeakageError(
691
- f"temporal feature for {row['sample_id']} crossed a split"
692
- )
693
- temporal["has_prev"] = 1.0
694
- temporal[f"delta_{prefix}_mean"] = (
695
- image_features[f"{prefix}_mean"] - previous[f"{prefix}_mean"]
696
- )
697
- temporal[f"delta_{prefix}_min"] = (
698
- image_features[f"{prefix}_min"] - previous[f"{prefix}_min"]
699
- )
700
- temporal["delta_cold_primary"] = image_features[cold_key] - previous[cold_key]
701
- temporal["delta_eye_cdo_contrast"] = (
702
- image_features["eye_cdo_contrast"] - previous["eye_cdo_contrast"]
703
- )
704
- temporal["delta_radial_mean_00"] = (
705
- image_features["radial_mean_00"] - previous["radial_mean_00"]
706
- )
707
- klass = row.get("imd5_class")
708
- if pd.isna(klass):
709
- klass = wind_to_imd5(float(row["wind_speed_kt"]))
710
- built: dict[str, object] = {
711
- "sample_id": str(row["sample_id"]),
712
- "storm_id": str(row["storm_id"]),
713
- "split": str(row["split"]),
714
- "wind_speed_kt": float(row["wind_speed_kt"]),
715
- "imd5_class": klass,
716
- }
717
- if "is_synthetic" in row:
718
- built["is_synthetic"] = parse_is_synthetic(row["is_synthetic"])
719
- for column in _CARRIED_COLUMNS:
720
- if column in row:
721
- built[column] = row[column]
722
- built.update(image_features)
723
- built.update(temporal)
724
- rows.append(built)
725
- table = pd.DataFrame(rows)
726
- assert_no_forbidden_inputs(spec.feature_names(), "feature names include labels")
727
- return table, dropped
728
-
729
-
730
- def model_matrix(frame: pd.DataFrame, names: tuple[str, ...] | list[str]) -> np.ndarray:
731
- """Numeric feature matrix. Raises if a label column is requested."""
732
- assert_no_forbidden_inputs(names, "forbidden features in model matrix")
733
- missing = [name for name in names if name not in frame.columns]
734
- if missing:
735
- raise KeyError(f"missing feature columns: {missing}")
736
- return frame.loc[:, list(names)].to_numpy(dtype=np.float64)
737
-
738
-
739
- def _impute_matrix(values: np.ndarray) -> np.ndarray:
740
- imputer = SimpleImputer(strategy="median", keep_empty_features=True)
741
- filled = imputer.fit_transform(values)
742
- return np.where(np.isfinite(filled), filled, 0.0)
743
-
744
-
745
- def _training_view(
746
- frame: pd.DataFrame, target: np.ndarray
747
- ) -> tuple[pd.DataFrame, np.ndarray, frozenset[str]]:
748
- """Rows whose storm is in the train side of ``storm_ids_by_split``.
749
-
750
- Val and test rows stay in ``frame`` so a caller can pass a full manifest,
751
- and they are dropped before any selection statistic is computed. A storm
752
- that sits in two splits raises ``LeakageError``.
753
- """
754
- if "storm_id" not in frame.columns or "split" not in frame.columns:
755
- raise LeakageError("feature selection requires storm_id and split")
756
- y = np.asarray(target, dtype=np.float64).ravel()
757
- if len(y) != len(frame):
758
- raise ValueError("target must align with the selection frame")
759
- groups = storm_ids_by_split(frame)
760
- train_ids = groups["train"]
761
- if not train_ids:
762
- raise LeakageError("feature selection needs at least one training storm")
763
- mask = frame["storm_id"].astype(str).isin(train_ids).to_numpy()
764
- mask = mask & (frame["split"].astype(str) == "train").to_numpy()
765
- train = frame.loc[mask].reset_index(drop=True)
766
- if train.empty:
767
- raise LeakageError("feature selection needs at least one training storm")
768
- return train, y[mask], train_ids
769
-
770
-
771
- def select_features(
772
- frame: pd.DataFrame,
773
- feature_names: tuple[str, ...] | list[str],
774
- target: np.ndarray,
775
- *,
776
- source_split: str,
777
- correlation_threshold: float = 0.95,
778
- max_features: int = 25,
779
- method: str = "correlation_rf",
780
- n_estimators: int = 40,
781
- seed: int = 42,
782
- ) -> FeatureSelection:
783
- """Fit a correlation filter and RF importance or RFE on train storms.
784
-
785
- Correlation filtering does not look at the label. Forest importance and
786
- RFE do. Both see only the storms ``storm_ids_by_split`` assigns to train.
787
- Changing val or test rows does not change the returned names.
788
- """
789
- if source_split != "train":
790
- raise LeakageError("feature selection is allowed on the train split only")
791
- names = tuple(feature_names)
792
- assert_no_forbidden_inputs(names, "forbidden features in selection")
793
- train, y, train_storms = _training_view(frame, target)
794
- if len(train) < 5:
795
- raise ValueError("feature selection needs at least 5 training rows")
796
- method = method.lower().strip()
797
- if method not in {"correlation_rf", "rfe", "none"}:
798
- raise ValueError(f"unknown selection method: {method}")
799
-
800
- values = _impute_matrix(model_matrix(train, names))
801
- variance = values.var(axis=0)
802
- kept_mask = variance > 1e-8
803
- dropped_variance = tuple(name for name, keep in zip(names, kept_mask, strict=True) if not keep)
804
- kept_names = [name for name, keep in zip(names, kept_mask, strict=True) if keep]
805
- kept_values = values[:, kept_mask]
806
- if not kept_names:
807
- raise ValueError("every candidate feature was constant on the train split")
808
-
809
- dropped_correlation: list[str] = []
810
- if method in {"correlation_rf", "rfe", "none"} and len(kept_names) > 1:
811
- corr = np.corrcoef(kept_values, rowvar=False)
812
- corr = np.where(np.isfinite(corr), corr, 0.0)
813
- drop_flags = np.zeros(len(kept_names), dtype=bool)
814
- for left in range(len(kept_names)):
815
- if drop_flags[left]:
816
- continue
817
- for right in range(left + 1, len(kept_names)):
818
- if drop_flags[right]:
819
- continue
820
- if abs(corr[left, right]) > correlation_threshold:
821
- drop_flags[right] = True
822
- dropped_correlation.append(kept_names[right])
823
- kept_names = [name for name, drop in zip(kept_names, drop_flags, strict=True) if not drop]
824
- kept_values = kept_values[:, ~drop_flags]
825
-
826
- cap = max(1, int(max_features))
827
- if method == "none":
828
- chosen = kept_names[:cap]
829
- importances: dict[str, float] = {}
830
- elif method == "correlation_rf":
831
- rank_cap = cap if len(kept_names) > cap else len(kept_names)
832
- ranked, importances = _rank_by_forest(
833
- kept_values, y, kept_names, rank_cap, n_estimators, seed
834
- )
835
- chosen = ranked if len(kept_names) > cap else kept_names
836
- else:
837
- chosen, importances = _rank_by_rfe(
838
- kept_values, y, kept_names, min(cap, len(kept_names)), n_estimators, seed
839
- )
840
-
841
- return FeatureSelection(
842
- names=tuple(chosen),
843
- source_split=source_split,
844
- importances=importances,
845
- dropped_variance=dropped_variance,
846
- dropped_correlation=tuple(dropped_correlation),
847
- train_storms=train_storms,
848
- )
849
-
850
-
851
- def _rank_by_forest(
852
- values: np.ndarray,
853
- target: np.ndarray,
854
- names: list[str],
855
- cap: int,
856
- n_estimators: int,
857
- seed: int,
858
- ) -> tuple[list[str], dict[str, float]]:
859
- forest = RandomForestRegressor(
860
- n_estimators=max(10, int(n_estimators)),
861
- max_depth=4,
862
- random_state=seed,
863
- n_jobs=1,
864
- )
865
- forest.fit(values, target)
866
- importance = np.asarray(forest.feature_importances_, dtype=np.float64)
867
- order = sorted(
868
- range(len(names)),
869
- key=lambda index: (-importance[index], names[index]),
870
- )
871
- chosen = [names[index] for index in order[:cap]]
872
- return chosen, {names[index]: float(importance[index]) for index in order}
873
-
874
-
875
- def _rank_by_rfe(
876
- values: np.ndarray,
877
- target: np.ndarray,
878
- names: list[str],
879
- cap: int,
880
- n_estimators: int,
881
- seed: int,
882
- ) -> tuple[list[str], dict[str, float]]:
883
- forest = RandomForestRegressor(
884
- n_estimators=max(10, int(n_estimators)),
885
- max_depth=4,
886
- random_state=seed,
887
- n_jobs=1,
888
- )
889
- step = max(1, len(names) // 10)
890
- selector = RFE(
891
- forest,
892
- n_features_to_select=max(1, min(cap, len(names))),
893
- step=step,
894
- )
895
- selector.fit(values, target)
896
- ranking = np.asarray(selector.ranking_)
897
- chosen = [name for name, keep in zip(names, selector.support_, strict=True) if keep]
898
- importance = {name: float(1.0 / rank) for name, rank in zip(names, ranking, strict=True)}
899
- return chosen, importance
 
1
+ """Physically motivated image features for classical intensity baselines.
2
+
3
+ Distributional statistics are called ``tb_*`` only when the caller has set
4
+ ``features.calibrated``. Otherwise they are ``pixel_*``. Nothing here converts
5
+ digital numbers to brightness temperature.
6
+
7
+ The simplified DAV terms are the circular variance of the angle between the
8
+ image gradient and the radial direction, at fixed fractions of the crop
9
+ half-width. That is not operational deviation-angle variance: there is no
10
+ radius search, no flight-level wind, and no agency radius product.
11
+
12
+ Radial, eye, and DAV features assume the storm is already near the image
13
+ center. This module does not recenter with a best-track fix.
14
+
15
+ Temporal deltas use the previous frame of the same storm after cross-split
16
+ links have been removed. Wind, R34, RMW, and class labels are not features.
17
+
18
+ Crop height and width are the array shape. ``data.image_size`` may be
19
+ ``native`` or a square resize for the deep model. It is not applied here.
20
+ Feature selection calls
21
+ ``storm_ids_by_split`` and fits only the training storms.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import logging
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+ from sklearn.ensemble import RandomForestRegressor
34
+ from sklearn.feature_selection import RFE
35
+ from sklearn.impute import SimpleImputer
36
+
37
+ from src.data_loader import load_image, resolve_image
38
+ from src.preprocessing import MAX_MISSING_FRACTION, as_channel_first, missing_fraction
39
+ from src.schema import FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5
40
+ from src.splits import (
41
+ LeakageError,
42
+ add_previous_frame_id,
43
+ assert_no_forbidden_inputs,
44
+ null_cross_split_links,
45
+ storm_ids_by_split,
46
+ )
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ GLCM_NAMES = (
51
+ "glcm_contrast",
52
+ "glcm_dissimilarity",
53
+ "glcm_homogeneity",
54
+ "glcm_energy",
55
+ "glcm_correlation",
56
+ "glcm_asm",
57
+ )
58
+ HAAR_NAMES = (
59
+ "haar_energy_ll",
60
+ "haar_energy_lh",
61
+ "haar_energy_hl",
62
+ "haar_energy_hh",
63
+ )
64
+ EYE_NAMES = (
65
+ "eye_center_mean",
66
+ "cdo_annulus_mean",
67
+ "eye_cdo_contrast",
68
+ "eye_present",
69
+ )
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class FeatureSpec:
74
+ """Geometry of one feature vector. Thresholds are in image units."""
75
+
76
+ calibrated: bool = False
77
+ cold_thresholds: tuple[float, ...] = (200.0, 210.0, 220.0, 230.0, 240.0)
78
+ radial_bins: int = 8
79
+ eye_radius_fraction: float = 0.12
80
+ cdo_outer_fraction: float = 0.35
81
+ eye_contrast_min: float = 2.0
82
+ dav_radii_fractions: tuple[float, ...] = (0.15, 0.30, 0.45, 0.60)
83
+ dav_annulus_width_fraction: float = 0.08
84
+ glcm_levels: int = 16
85
+ glcm_distance: int = 1
86
+
87
+ def __post_init__(self) -> None:
88
+ if not self.cold_thresholds:
89
+ raise ValueError("cold_thresholds must not be empty")
90
+ if self.radial_bins < 2:
91
+ raise ValueError("radial_bins must be at least 2")
92
+ if not 0 < self.eye_radius_fraction < self.cdo_outer_fraction <= 1:
93
+ raise ValueError("eye radius must sit inside the CDO annulus")
94
+ if self.eye_contrast_min < 0:
95
+ raise ValueError("eye_contrast_min must be >= 0")
96
+ if any(not 0 < radius < 1 for radius in self.dav_radii_fractions):
97
+ raise ValueError("DAV radii must be fractions of the half-width")
98
+ if not 0 < self.dav_annulus_width_fraction < 0.5:
99
+ raise ValueError("DAV annulus width fraction is out of range")
100
+ if not 8 <= self.glcm_levels <= 32:
101
+ raise ValueError("glcm_levels must be between 8 and 32")
102
+ if self.glcm_distance < 1:
103
+ raise ValueError("glcm_distance must be >= 1")
104
+
105
+ @property
106
+ def prefix(self) -> str:
107
+ return "tb" if self.calibrated else "pixel"
108
+
109
+ @classmethod
110
+ def from_config(cls, config: dict) -> FeatureSpec:
111
+ raw = config.get("features")
112
+ if not isinstance(raw, dict):
113
+ raise KeyError("config features is required")
114
+ required = (
115
+ "calibrated",
116
+ "cold_thresholds",
117
+ "radial_bins",
118
+ "eye_radius_fraction",
119
+ "cdo_outer_fraction",
120
+ "eye_contrast_min",
121
+ "dav_radii_fractions",
122
+ "dav_annulus_width_fraction",
123
+ "glcm_levels",
124
+ "glcm_distance",
125
+ )
126
+ missing = [key for key in required if key not in raw]
127
+ if missing:
128
+ raise KeyError(f"config features missing {missing}")
129
+ return cls(
130
+ calibrated=bool(raw["calibrated"]),
131
+ cold_thresholds=tuple(float(value) for value in raw["cold_thresholds"]),
132
+ radial_bins=int(raw["radial_bins"]),
133
+ eye_radius_fraction=float(raw["eye_radius_fraction"]),
134
+ cdo_outer_fraction=float(raw["cdo_outer_fraction"]),
135
+ eye_contrast_min=float(raw["eye_contrast_min"]),
136
+ dav_radii_fractions=tuple(float(value) for value in raw["dav_radii_fractions"]),
137
+ dav_annulus_width_fraction=float(raw["dav_annulus_width_fraction"]),
138
+ glcm_levels=int(raw["glcm_levels"]),
139
+ glcm_distance=int(raw["glcm_distance"]),
140
+ )
141
+
142
+ def feature_groups(self) -> dict[str, tuple[str, ...]]:
143
+ """Feature names by group.
144
+
145
+ ``pixel_stats`` are order statistics of the stored image values.
146
+ They are not brightness temperature unless ``calibrated`` is set,
147
+ in which case the same slots use the ``tb_`` prefix.
148
+ ``dav_simplified`` is gradient-angle variance, not operational DAV.
149
+ """
150
+ prefix = self.prefix
151
+ return {
152
+ "pixel_stats": (
153
+ f"{prefix}_min",
154
+ f"{prefix}_max",
155
+ f"{prefix}_mean",
156
+ f"{prefix}_std",
157
+ f"{prefix}_p10",
158
+ f"{prefix}_p25",
159
+ f"{prefix}_p50",
160
+ f"{prefix}_p75",
161
+ f"{prefix}_p90",
162
+ f"{prefix}_iqr",
163
+ ),
164
+ "cold_cloud": tuple(
165
+ f"cold_frac_{_token(threshold)}" for threshold in self.cold_thresholds
166
+ ),
167
+ "radial": tuple(f"radial_mean_{index:02d}" for index in range(self.radial_bins)),
168
+ "eye_cdo": EYE_NAMES,
169
+ "dav_simplified": tuple(
170
+ f"dav_simplified_r{index:02d}" for index in range(len(self.dav_radii_fractions))
171
+ ),
172
+ "glcm": GLCM_NAMES,
173
+ "haar": HAAR_NAMES,
174
+ "temporal": (
175
+ "has_prev",
176
+ f"delta_{prefix}_mean",
177
+ f"delta_{prefix}_min",
178
+ "delta_cold_primary",
179
+ "delta_eye_cdo_contrast",
180
+ "delta_radial_mean_00",
181
+ ),
182
+ }
183
+
184
+ def image_feature_names(self) -> tuple[str, ...]:
185
+ groups = self.feature_groups()
186
+ names: list[str] = []
187
+ for key in (
188
+ "pixel_stats",
189
+ "cold_cloud",
190
+ "radial",
191
+ "eye_cdo",
192
+ "dav_simplified",
193
+ "glcm",
194
+ "haar",
195
+ ):
196
+ names.extend(groups[key])
197
+ return tuple(names)
198
+
199
+ def feature_names(self) -> tuple[str, ...]:
200
+ return self.image_feature_names() + self.feature_groups()["temporal"]
201
+
202
+
203
+ @dataclass(frozen=True)
204
+ class FeatureSelection:
205
+ names: tuple[str, ...]
206
+ source_split: str
207
+ importances: dict[str, float]
208
+ dropped_variance: tuple[str, ...]
209
+ dropped_correlation: tuple[str, ...]
210
+ train_storms: frozenset[str] = frozenset()
211
+
212
+
213
+ def _token(value: float) -> str:
214
+ number = float(value)
215
+ if number.is_integer():
216
+ return str(int(number))
217
+ return str(number).replace("-", "m").replace(".", "p")
218
+
219
+
220
+ def _single_channel(image: np.ndarray) -> np.ndarray:
221
+ return as_channel_first(image)[0]
222
+
223
+
224
+ def _finite_fill(image: np.ndarray) -> np.ndarray:
225
+ filled = np.array(image, dtype=np.float64, copy=True)
226
+ finite = np.isfinite(filled)
227
+ fill = float(np.median(filled[finite])) if finite.any() else 0.0
228
+ filled[~finite] = fill
229
+ return filled
230
+
231
+
232
+ def _distribution(image: np.ndarray, prefix: str) -> dict[str, float]:
233
+ finite = image[np.isfinite(image)]
234
+ if finite.size == 0:
235
+ keys = (
236
+ "min",
237
+ "max",
238
+ "mean",
239
+ "std",
240
+ "p10",
241
+ "p25",
242
+ "p50",
243
+ "p75",
244
+ "p90",
245
+ "iqr",
246
+ )
247
+ return {f"{prefix}_{key}": float("nan") for key in keys}
248
+ percentiles = np.percentile(finite, [10, 25, 50, 75, 90])
249
+ return {
250
+ f"{prefix}_min": float(finite.min()),
251
+ f"{prefix}_max": float(finite.max()),
252
+ f"{prefix}_mean": float(finite.mean()),
253
+ f"{prefix}_std": float(finite.std()),
254
+ f"{prefix}_p10": float(percentiles[0]),
255
+ f"{prefix}_p25": float(percentiles[1]),
256
+ f"{prefix}_p50": float(percentiles[2]),
257
+ f"{prefix}_p75": float(percentiles[3]),
258
+ f"{prefix}_p90": float(percentiles[4]),
259
+ f"{prefix}_iqr": float(percentiles[3] - percentiles[1]),
260
+ }
261
+
262
+
263
+ def _cold_coverage(image: np.ndarray, thresholds: tuple[float, ...]) -> dict[str, float]:
264
+ finite = image[np.isfinite(image)]
265
+ out: dict[str, float] = {}
266
+ for threshold in thresholds:
267
+ key = f"cold_frac_{_token(threshold)}"
268
+ if finite.size == 0:
269
+ out[key] = float("nan")
270
+ else:
271
+ out[key] = float(np.mean(finite < threshold))
272
+ return out
273
+
274
+
275
+ def _radial_and_eye(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
276
+ height, width = image.shape
277
+ yy, xx = np.mgrid[0:height, 0:width]
278
+ center_y = (height - 1) / 2.0
279
+ center_x = (width - 1) / 2.0
280
+ radius = np.hypot(yy - center_y, xx - center_x)
281
+ max_radius = max(float(radius.max()), 1e-6)
282
+ edges = np.linspace(0.0, max_radius + 1e-6, spec.radial_bins + 1)
283
+ out: dict[str, float] = {}
284
+ for index in range(spec.radial_bins):
285
+ mask = (radius >= edges[index]) & (radius < edges[index + 1]) & np.isfinite(image)
286
+ out[f"radial_mean_{index:02d}"] = (
287
+ float(image[mask].mean()) if mask.any() else float("nan")
288
+ )
289
+ half = min(height, width) / 2.0
290
+ eye = radius <= spec.eye_radius_fraction * half
291
+ annulus = (radius > spec.eye_radius_fraction * half) & (
292
+ radius <= spec.cdo_outer_fraction * half
293
+ )
294
+ eye_values = image[eye & np.isfinite(image)]
295
+ annulus_values = image[annulus & np.isfinite(image)]
296
+ eye_mean = float(eye_values.mean()) if eye_values.size else float("nan")
297
+ annulus_mean = float(annulus_values.mean()) if annulus_values.size else float("nan")
298
+ contrast = eye_mean - annulus_mean
299
+ eye_present = (
300
+ 0.0
301
+ if not np.isfinite(contrast)
302
+ else float(contrast >= spec.eye_contrast_min)
303
+ )
304
+ out["eye_center_mean"] = eye_mean
305
+ out["cdo_annulus_mean"] = annulus_mean
306
+ out["eye_cdo_contrast"] = float(contrast)
307
+ out["eye_present"] = eye_present
308
+ return out
309
+
310
+
311
+ def _deviation_angle_variance(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
312
+ """Circular variance of gradient angle minus radial angle. Not operational DAV."""
313
+ height, width = image.shape
314
+ yy, xx = np.mgrid[0:height, 0:width]
315
+ center_y = (height - 1) / 2.0
316
+ center_x = (width - 1) / 2.0
317
+ dy = yy - center_y
318
+ dx = xx - center_x
319
+ radius = np.hypot(dy, dx)
320
+ half = min(height, width) / 2.0
321
+ gradient_y, gradient_x = np.gradient(image)
322
+ magnitude = np.hypot(gradient_y, gradient_x)
323
+ radial_angle = np.arctan2(dy, dx)
324
+ gradient_angle = np.arctan2(gradient_y, gradient_x)
325
+ deviation = np.arctan2(
326
+ np.sin(gradient_angle - radial_angle),
327
+ np.cos(gradient_angle - radial_angle),
328
+ )
329
+ # Keep the ring at least two pixels thick. On a small crop the fractional
330
+ # width can otherwise fall between grid points and the statistic is empty.
331
+ width_px = max(spec.dav_annulus_width_fraction * half, 2.0)
332
+ out: dict[str, float] = {}
333
+ for index, fraction in enumerate(spec.dav_radii_fractions):
334
+ radius_px = fraction * half
335
+ annulus = (radius >= radius_px - width_px / 2.0) & (
336
+ radius <= radius_px + width_px / 2.0
337
+ )
338
+ # A zero gradient has no direction. arctan2(0, 0) is 0 and would
339
+ # look like a full circle of disagreement.
340
+ selected = deviation[annulus & (magnitude > 1e-6)]
341
+ if selected.size < 8:
342
+ out[f"dav_simplified_r{index:02d}"] = float("nan")
343
+ continue
344
+ mean_vector = np.exp(1j * selected).mean()
345
+ out[f"dav_simplified_r{index:02d}"] = float(1.0 - np.abs(mean_vector))
346
+ return out
347
+
348
+
349
+ def _pair_counts(
350
+ bins: np.ndarray, valid: np.ndarray, dy: int, dx: int, levels: int
351
+ ) -> np.ndarray | None:
352
+ height, width = bins.shape
353
+ if abs(dy) >= height or abs(dx) >= width:
354
+ return None
355
+ if dy >= 0:
356
+ src_y, dst_y = slice(0, height - dy), slice(dy, height)
357
+ else:
358
+ src_y, dst_y = slice(-dy, height), slice(0, height + dy)
359
+ if dx >= 0:
360
+ src_x, dst_x = slice(0, width - dx), slice(dx, width)
361
+ else:
362
+ src_x, dst_x = slice(-dx, width), slice(0, width + dx)
363
+ mask = valid[src_y, src_x] & valid[dst_y, dst_x]
364
+ if not mask.any():
365
+ return None
366
+ source = bins[src_y, src_x][mask].ravel()
367
+ dest = bins[dst_y, dst_x][mask].ravel()
368
+ flat = source.astype(np.int64) * levels + dest.astype(np.int64)
369
+ counts = np.bincount(flat, minlength=levels * levels).reshape(levels, levels)
370
+ total = float(counts.sum())
371
+ if total <= 0:
372
+ return None
373
+ return counts.astype(np.float64) / total
374
+
375
+
376
+ def _haralick(probs: np.ndarray) -> dict[str, float]:
377
+ levels = probs.shape[0]
378
+ rows, cols = np.indices((levels, levels))
379
+ contrast = float(((rows - cols) ** 2 * probs).sum())
380
+ dissimilarity = float((np.abs(rows - cols) * probs).sum())
381
+ homogeneity = float((probs / (1.0 + (rows - cols) ** 2)).sum())
382
+ asm = float((probs**2).sum())
383
+ energy = float(np.sqrt(asm))
384
+ mean_i = float((rows * probs).sum())
385
+ mean_j = float((cols * probs).sum())
386
+ std_i = float(np.sqrt(((rows - mean_i) ** 2 * probs).sum()))
387
+ std_j = float(np.sqrt(((cols - mean_j) ** 2 * probs).sum()))
388
+ if std_i < 1e-12 or std_j < 1e-12:
389
+ correlation = 0.0
390
+ else:
391
+ correlation = float(
392
+ ((rows - mean_i) * (cols - mean_j) * probs).sum() / (std_i * std_j)
393
+ )
394
+ return {
395
+ "glcm_contrast": contrast,
396
+ "glcm_dissimilarity": dissimilarity,
397
+ "glcm_homogeneity": homogeneity,
398
+ "glcm_energy": energy,
399
+ "glcm_correlation": correlation,
400
+ "glcm_asm": asm,
401
+ }
402
+
403
+
404
+ def _glcm_features(image: np.ndarray, levels: int, distance: int) -> dict[str, float]:
405
+ height, width = image.shape
406
+ empty = {name: float("nan") for name in GLCM_NAMES}
407
+ if height <= distance or width <= distance:
408
+ return empty
409
+ finite = image[np.isfinite(image)]
410
+ if finite.size == 0:
411
+ return empty
412
+ low = float(finite.min())
413
+ high = float(finite.max())
414
+ if high - low < 1e-6:
415
+ bins = np.zeros(image.shape, dtype=np.int32)
416
+ else:
417
+ scaled = np.clip((image - low) / (high - low), 0.0, 1.0)
418
+ bins = np.minimum((scaled * levels).astype(np.int32), levels - 1)
419
+ valid = np.isfinite(image)
420
+ offsets = (
421
+ (0, distance),
422
+ (-distance, distance),
423
+ (-distance, 0),
424
+ (-distance, -distance),
425
+ )
426
+ collected = []
427
+ for dy, dx in offsets:
428
+ probs = _pair_counts(bins, valid, dy, dx, levels)
429
+ if probs is not None:
430
+ collected.append(_haralick(probs))
431
+ if not collected:
432
+ return empty
433
+ return {
434
+ name: float(np.mean([item[name] for item in collected])) for name in GLCM_NAMES
435
+ }
436
+
437
+
438
+ def _haar_energies(image: np.ndarray) -> dict[str, float]:
439
+ band = image
440
+ if band.shape[0] % 2:
441
+ band = band[:-1, :]
442
+ if band.shape[1] % 2:
443
+ band = band[:, :-1]
444
+ if min(band.shape) < 2:
445
+ return {name: float("nan") for name in HAAR_NAMES}
446
+ even_even = band[0::2, 0::2]
447
+ even_odd = band[0::2, 1::2]
448
+ odd_even = band[1::2, 0::2]
449
+ odd_odd = band[1::2, 1::2]
450
+ low_low = (even_even + even_odd + odd_even + odd_odd) / 4.0
451
+ low_high = (even_even + odd_even - even_odd - odd_odd) / 4.0
452
+ high_low = (even_even - odd_even + even_odd - odd_odd) / 4.0
453
+ high_high = (even_even - odd_even - even_odd + odd_odd) / 4.0
454
+ energies = {
455
+ "haar_energy_ll": float(np.mean(low_low**2)),
456
+ "haar_energy_lh": float(np.mean(low_high**2)),
457
+ "haar_energy_hl": float(np.mean(high_low**2)),
458
+ "haar_energy_hh": float(np.mean(high_high**2)),
459
+ }
460
+ total = sum(energies.values())
461
+ if total <= 1e-12:
462
+ return {name: 0.0 for name in HAAR_NAMES}
463
+ return {name: value / total for name, value in energies.items()}
464
+
465
+
466
+ def native_shape(image: np.ndarray) -> tuple[int, int]:
467
+ """Height and width of one crop. This is not ``data.image_size``."""
468
+ channel = _single_channel(image)
469
+ return int(channel.shape[0]), int(channel.shape[1])
470
+
471
+
472
+ def extract_image_features(
473
+ image: np.ndarray,
474
+ spec: FeatureSpec,
475
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
476
+ ) -> dict[str, float]:
477
+ """Features of one centered IR crop. The label is not an input.
478
+
479
+ The crop is not resized. Callers that need the crop size use
480
+ ``native_shape``, which reads the array. ``data.image_size`` is not applied.
481
+ """
482
+ channel = _single_channel(image)
483
+ fraction = missing_fraction(channel)
484
+ if fraction > max_missing_fraction:
485
+ raise ValueError(
486
+ f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
487
+ )
488
+ if not np.isfinite(channel).any():
489
+ raise ValueError("image has no finite pixels")
490
+ dense = _finite_fill(channel)
491
+ features: dict[str, float] = {}
492
+ features.update(_distribution(channel, spec.prefix))
493
+ features.update(_cold_coverage(channel, spec.cold_thresholds))
494
+ features.update(_radial_and_eye(channel, spec))
495
+ features.update(_deviation_angle_variance(dense, spec))
496
+ features.update(_glcm_features(dense, spec.glcm_levels, spec.glcm_distance))
497
+ features.update(_haar_energies(dense))
498
+ expected = spec.image_feature_names()
499
+ missing = [name for name in expected if name not in features]
500
+ if missing:
501
+ raise RuntimeError(f"feature extractor omitted {missing}")
502
+ return {name: float(features[name]) for name in expected}
503
+
504
+
505
+ def _temporal_defaults(spec: FeatureSpec) -> dict[str, float]:
506
+ prefix = spec.prefix
507
+ return {
508
+ "has_prev": 0.0,
509
+ f"delta_{prefix}_mean": float("nan"),
510
+ f"delta_{prefix}_min": float("nan"),
511
+ "delta_cold_primary": float("nan"),
512
+ "delta_eye_cdo_contrast": float("nan"),
513
+ "delta_radial_mean_00": float("nan"),
514
+ }
515
+
516
+
517
+ # Optional frame labels. Copied when the manifest has them. Not model features.
518
+ _CARRIED_COLUMNS = (
519
+ "timestamp",
520
+ "relative_time_s",
521
+ "source_split",
522
+ "wind_averaging",
523
+ "wind_averaging_s",
524
+ "on_fix",
525
+ "near_land",
526
+ "distance_to_land_km",
527
+ "cv_group",
528
+ )
529
+
530
+
531
+ def _extract_path(task: tuple[str, FeatureSpec, float]) -> dict[str, float]:
532
+ """Load one image and return its feature dict. Used by the worker pool."""
533
+ path, spec, max_missing_fraction = task
534
+ return extract_image_features(load_image(path), spec, max_missing_fraction)
535
+
536
+
537
+ def _spec_fingerprint(spec: FeatureSpec, max_missing_fraction: float) -> str:
538
+ """Identity of the extractor settings stored next to an image checkpoint."""
539
+ payload = {
540
+ "calibrated": bool(spec.calibrated),
541
+ "cold_thresholds": [float(value) for value in spec.cold_thresholds],
542
+ "radial_bins": int(spec.radial_bins),
543
+ "eye_radius_fraction": float(spec.eye_radius_fraction),
544
+ "cdo_outer_fraction": float(spec.cdo_outer_fraction),
545
+ "eye_contrast_min": float(spec.eye_contrast_min),
546
+ "dav_radii_fractions": [float(value) for value in spec.dav_radii_fractions],
547
+ "dav_annulus_width_fraction": float(spec.dav_annulus_width_fraction),
548
+ "glcm_levels": int(spec.glcm_levels),
549
+ "glcm_distance": int(spec.glcm_distance),
550
+ "max_missing_fraction": float(max_missing_fraction),
551
+ }
552
+ return json.dumps(payload, sort_keys=True)
553
+
554
+
555
+ def _checkpoint_spec_path(path: Path) -> Path:
556
+ return path.with_suffix(path.suffix + ".spec.json")
557
+
558
+
559
+ def _image_checkpoint_rows(
560
+ path: Path, spec: FeatureSpec, max_missing_fraction: float
561
+ ) -> dict[str, dict[str, float]]:
562
+ if not path.is_file():
563
+ return {}
564
+ spec_path = _checkpoint_spec_path(path)
565
+ if not spec_path.is_file():
566
+ return {}
567
+ saved_spec = json.loads(spec_path.read_text(encoding="utf-8"))
568
+ if saved_spec.get("fingerprint") != _spec_fingerprint(spec, max_missing_fraction):
569
+ return {}
570
+ saved = pd.read_csv(path)
571
+ if "sample_id" not in saved.columns:
572
+ return {}
573
+ rows: dict[str, dict[str, float]] = {}
574
+ for record in saved.to_dict(orient="records"):
575
+ sample_id = str(record.pop("sample_id"))
576
+ rows[sample_id] = record
577
+ return rows
578
+
579
+
580
+ def _write_image_checkpoint(
581
+ path: Path,
582
+ rows: dict[str, dict[str, float]],
583
+ spec: FeatureSpec,
584
+ max_missing_fraction: float,
585
+ ) -> None:
586
+ records = [{"sample_id": sample_id, **features} for sample_id, features in rows.items()]
587
+ path.parent.mkdir(parents=True, exist_ok=True)
588
+ pd.DataFrame(records).to_csv(path, index=False)
589
+ _checkpoint_spec_path(path).write_text(
590
+ json.dumps(
591
+ {"fingerprint": _spec_fingerprint(spec, max_missing_fraction)},
592
+ indent=2,
593
+ sort_keys=True,
594
+ )
595
+ + "\n",
596
+ encoding="utf-8",
597
+ )
598
+
599
+
600
+ def extract_feature_table(
601
+ frame: pd.DataFrame,
602
+ manifest_path: str,
603
+ spec: FeatureSpec,
604
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
605
+ workers: int = 1,
606
+ image_checkpoint: str | Path | None = None,
607
+ ) -> tuple[pd.DataFrame, int]:
608
+ """Extract features and same-split temporal deltas.
609
+
610
+ Previous-frame ids are recomputed from ``storm_id`` and the observation
611
+ clock (``timestamp``, else NASA ``relative_time_s``), then any link that
612
+ crosses ``split`` is dropped before the delta is taken. ``workers`` above
613
+ 1 only parallelizes the per-image extract. It does not change the values.
614
+ ``image_checkpoint``, when set, stores per-image features so a restarted
615
+ run does not re-read frames that already finished. Temporal deltas are
616
+ still computed after every frame in this call has image features.
617
+ """
618
+ if "split" not in frame.columns:
619
+ raise LeakageError("feature extraction requires a split column")
620
+ if workers < 1:
621
+ raise ValueError("workers must be at least 1")
622
+ linked = add_previous_frame_id(frame)
623
+ linked, dropped = null_cross_split_links(linked)
624
+ rows_in = linked.to_dict(orient="records")
625
+ tasks = [
626
+ (str(resolve_image(manifest_path, str(row["image_path"]))), spec, max_missing_fraction)
627
+ for row in rows_in
628
+ ]
629
+ expected = spec.image_feature_names()
630
+ checkpoint = Path(image_checkpoint) if image_checkpoint else None
631
+ stored = (
632
+ _image_checkpoint_rows(checkpoint, spec, max_missing_fraction) if checkpoint else {}
633
+ )
634
+ extracted: list[dict[str, float] | None] = [None] * len(rows_in)
635
+ pending: list[int] = []
636
+ for index, row in enumerate(rows_in):
637
+ sample_id = str(row["sample_id"])
638
+ cached = stored.get(sample_id)
639
+ if cached is not None and all(name in cached for name in expected):
640
+ extracted[index] = {name: float(cached[name]) for name in expected}
641
+ else:
642
+ pending.append(index)
643
+ if pending:
644
+ logger.info("Extracting %s images (%s already cached)", len(pending), len(rows_in) - len(pending))
645
+
646
+ def _finish(index: int) -> tuple[int, dict[str, float]]:
647
+ return index, _extract_path(tasks[index])
648
+
649
+ batch = 200
650
+ if workers == 1:
651
+ for start in range(0, len(pending), batch):
652
+ chunk = pending[start : start + batch]
653
+ for index in chunk:
654
+ _index, features = _finish(index)
655
+ extracted[_index] = features
656
+ stored[str(rows_in[_index]["sample_id"])] = features
657
+ if checkpoint:
658
+ _write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
659
+ logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
660
+ else:
661
+ from concurrent.futures import ThreadPoolExecutor
662
+
663
+ with ThreadPoolExecutor(max_workers=workers) as pool:
664
+ for start in range(0, len(pending), batch):
665
+ chunk = pending[start : start + batch]
666
+ for index, features in pool.map(_finish, chunk):
667
+ extracted[index] = features
668
+ stored[str(rows_in[index]["sample_id"])] = features
669
+ if checkpoint:
670
+ _write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
671
+ logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
672
+ if any(item is None for item in extracted):
673
+ raise RuntimeError("image feature extraction left a row empty")
674
+ cache: dict[str, tuple[str, dict[str, float]]] = {}
675
+ packed: list[tuple[dict[str, object], dict[str, float]]] = []
676
+ for row, image_features in zip(rows_in, extracted, strict=True):
677
+ sample_id = str(row["sample_id"])
678
+ cache[sample_id] = (str(row["split"]), image_features)
679
+ packed.append((row, image_features))
680
+
681
+ prefix = spec.prefix
682
+ cold_key = f"cold_frac_{_token(spec.cold_thresholds[0])}"
683
+ rows: list[dict[str, object]] = []
684
+ for row, image_features in packed:
685
+ temporal = _temporal_defaults(spec)
686
+ prev = row.get("prev_sample_id")
687
+ if not pd.isna(prev) and str(prev) in cache:
688
+ prev_split, previous = cache[str(prev)]
689
+ if prev_split != str(row["split"]):
690
+ raise LeakageError(
691
+ f"temporal feature for {row['sample_id']} crossed a split"
692
+ )
693
+ temporal["has_prev"] = 1.0
694
+ temporal[f"delta_{prefix}_mean"] = (
695
+ image_features[f"{prefix}_mean"] - previous[f"{prefix}_mean"]
696
+ )
697
+ temporal[f"delta_{prefix}_min"] = (
698
+ image_features[f"{prefix}_min"] - previous[f"{prefix}_min"]
699
+ )
700
+ temporal["delta_cold_primary"] = image_features[cold_key] - previous[cold_key]
701
+ temporal["delta_eye_cdo_contrast"] = (
702
+ image_features["eye_cdo_contrast"] - previous["eye_cdo_contrast"]
703
+ )
704
+ temporal["delta_radial_mean_00"] = (
705
+ image_features["radial_mean_00"] - previous["radial_mean_00"]
706
+ )
707
+ klass = row.get("imd5_class")
708
+ if pd.isna(klass):
709
+ klass = wind_to_imd5(float(row["wind_speed_kt"]))
710
+ built: dict[str, object] = {
711
+ "sample_id": str(row["sample_id"]),
712
+ "storm_id": str(row["storm_id"]),
713
+ "split": str(row["split"]),
714
+ "wind_speed_kt": float(row["wind_speed_kt"]),
715
+ "imd5_class": klass,
716
+ }
717
+ if "is_synthetic" in row:
718
+ built["is_synthetic"] = parse_is_synthetic(row["is_synthetic"])
719
+ for column in _CARRIED_COLUMNS:
720
+ if column in row:
721
+ built[column] = row[column]
722
+ built.update(image_features)
723
+ built.update(temporal)
724
+ rows.append(built)
725
+ table = pd.DataFrame(rows)
726
+ assert_no_forbidden_inputs(spec.feature_names(), "feature names include labels")
727
+ return table, dropped
728
+
729
+
730
+ def model_matrix(frame: pd.DataFrame, names: tuple[str, ...] | list[str]) -> np.ndarray:
731
+ """Numeric feature matrix. Raises if a label column is requested."""
732
+ assert_no_forbidden_inputs(names, "forbidden features in model matrix")
733
+ missing = [name for name in names if name not in frame.columns]
734
+ if missing:
735
+ raise KeyError(f"missing feature columns: {missing}")
736
+ return frame.loc[:, list(names)].to_numpy(dtype=np.float64)
737
+
738
+
739
+ def _impute_matrix(values: np.ndarray) -> np.ndarray:
740
+ imputer = SimpleImputer(strategy="median", keep_empty_features=True)
741
+ filled = imputer.fit_transform(values)
742
+ return np.where(np.isfinite(filled), filled, 0.0)
743
+
744
+
745
+ def _training_view(
746
+ frame: pd.DataFrame, target: np.ndarray
747
+ ) -> tuple[pd.DataFrame, np.ndarray, frozenset[str]]:
748
+ """Rows whose storm is in the train side of ``storm_ids_by_split``.
749
+
750
+ Val and test rows stay in ``frame`` so a caller can pass a full manifest,
751
+ and they are dropped before any selection statistic is computed. A storm
752
+ that sits in two splits raises ``LeakageError``.
753
+ """
754
+ if "storm_id" not in frame.columns or "split" not in frame.columns:
755
+ raise LeakageError("feature selection requires storm_id and split")
756
+ y = np.asarray(target, dtype=np.float64).ravel()
757
+ if len(y) != len(frame):
758
+ raise ValueError("target must align with the selection frame")
759
+ groups = storm_ids_by_split(frame)
760
+ train_ids = groups["train"]
761
+ if not train_ids:
762
+ raise LeakageError("feature selection needs at least one training storm")
763
+ mask = frame["storm_id"].astype(str).isin(train_ids).to_numpy()
764
+ mask = mask & (frame["split"].astype(str) == "train").to_numpy()
765
+ train = frame.loc[mask].reset_index(drop=True)
766
+ if train.empty:
767
+ raise LeakageError("feature selection needs at least one training storm")
768
+ return train, y[mask], train_ids
769
+
770
+
771
+ def select_features(
772
+ frame: pd.DataFrame,
773
+ feature_names: tuple[str, ...] | list[str],
774
+ target: np.ndarray,
775
+ *,
776
+ source_split: str,
777
+ correlation_threshold: float = 0.95,
778
+ max_features: int = 25,
779
+ method: str = "correlation_rf",
780
+ n_estimators: int = 40,
781
+ seed: int = 42,
782
+ ) -> FeatureSelection:
783
+ """Fit a correlation filter and RF importance or RFE on train storms.
784
+
785
+ Correlation filtering does not look at the label. Forest importance and
786
+ RFE do. Both see only the storms ``storm_ids_by_split`` assigns to train.
787
+ Changing val or test rows does not change the returned names.
788
+ """
789
+ if source_split != "train":
790
+ raise LeakageError("feature selection is allowed on the train split only")
791
+ names = tuple(feature_names)
792
+ assert_no_forbidden_inputs(names, "forbidden features in selection")
793
+ train, y, train_storms = _training_view(frame, target)
794
+ if len(train) < 5:
795
+ raise ValueError("feature selection needs at least 5 training rows")
796
+ method = method.lower().strip()
797
+ if method not in {"correlation_rf", "rfe", "none"}:
798
+ raise ValueError(f"unknown selection method: {method}")
799
+
800
+ values = _impute_matrix(model_matrix(train, names))
801
+ variance = values.var(axis=0)
802
+ kept_mask = variance > 1e-8
803
+ dropped_variance = tuple(name for name, keep in zip(names, kept_mask, strict=True) if not keep)
804
+ kept_names = [name for name, keep in zip(names, kept_mask, strict=True) if keep]
805
+ kept_values = values[:, kept_mask]
806
+ if not kept_names:
807
+ raise ValueError("every candidate feature was constant on the train split")
808
+
809
+ dropped_correlation: list[str] = []
810
+ if method in {"correlation_rf", "rfe", "none"} and len(kept_names) > 1:
811
+ corr = np.corrcoef(kept_values, rowvar=False)
812
+ corr = np.where(np.isfinite(corr), corr, 0.0)
813
+ drop_flags = np.zeros(len(kept_names), dtype=bool)
814
+ for left in range(len(kept_names)):
815
+ if drop_flags[left]:
816
+ continue
817
+ for right in range(left + 1, len(kept_names)):
818
+ if drop_flags[right]:
819
+ continue
820
+ if abs(corr[left, right]) > correlation_threshold:
821
+ drop_flags[right] = True
822
+ dropped_correlation.append(kept_names[right])
823
+ kept_names = [name for name, drop in zip(kept_names, drop_flags, strict=True) if not drop]
824
+ kept_values = kept_values[:, ~drop_flags]
825
+
826
+ cap = max(1, int(max_features))
827
+ if method == "none":
828
+ chosen = kept_names[:cap]
829
+ importances: dict[str, float] = {}
830
+ elif method == "correlation_rf":
831
+ rank_cap = cap if len(kept_names) > cap else len(kept_names)
832
+ ranked, importances = _rank_by_forest(
833
+ kept_values, y, kept_names, rank_cap, n_estimators, seed
834
+ )
835
+ chosen = ranked if len(kept_names) > cap else kept_names
836
+ else:
837
+ chosen, importances = _rank_by_rfe(
838
+ kept_values, y, kept_names, min(cap, len(kept_names)), n_estimators, seed
839
+ )
840
+
841
+ return FeatureSelection(
842
+ names=tuple(chosen),
843
+ source_split=source_split,
844
+ importances=importances,
845
+ dropped_variance=dropped_variance,
846
+ dropped_correlation=tuple(dropped_correlation),
847
+ train_storms=train_storms,
848
+ )
849
+
850
+
851
+ def _rank_by_forest(
852
+ values: np.ndarray,
853
+ target: np.ndarray,
854
+ names: list[str],
855
+ cap: int,
856
+ n_estimators: int,
857
+ seed: int,
858
+ ) -> tuple[list[str], dict[str, float]]:
859
+ forest = RandomForestRegressor(
860
+ n_estimators=max(10, int(n_estimators)),
861
+ max_depth=4,
862
+ random_state=seed,
863
+ n_jobs=1,
864
+ )
865
+ forest.fit(values, target)
866
+ importance = np.asarray(forest.feature_importances_, dtype=np.float64)
867
+ order = sorted(
868
+ range(len(names)),
869
+ key=lambda index: (-importance[index], names[index]),
870
+ )
871
+ chosen = [names[index] for index in order[:cap]]
872
+ return chosen, {names[index]: float(importance[index]) for index in order}
873
+
874
+
875
+ def _rank_by_rfe(
876
+ values: np.ndarray,
877
+ target: np.ndarray,
878
+ names: list[str],
879
+ cap: int,
880
+ n_estimators: int,
881
+ seed: int,
882
+ ) -> tuple[list[str], dict[str, float]]:
883
+ forest = RandomForestRegressor(
884
+ n_estimators=max(10, int(n_estimators)),
885
+ max_depth=4,
886
+ random_state=seed,
887
+ n_jobs=1,
888
+ )
889
+ step = max(1, len(names) // 10)
890
+ selector = RFE(
891
+ forest,
892
+ n_features_to_select=max(1, min(cap, len(names))),
893
+ step=step,
894
+ )
895
+ selector.fit(values, target)
896
+ ranking = np.asarray(selector.ranking_)
897
+ chosen = [name for name, keep in zip(names, selector.support_, strict=True) if keep]
898
+ importance = {name: float(1.0 / rank) for name, rank in zip(names, ranking, strict=True)}
899
+ return chosen, importance
src/incyde.py CHANGED
@@ -1,778 +1,778 @@
1
- """INCYDE loader for the cropped INSAT-3D North Indian Ocean set.
2
-
3
- Images come from the Zenodo 8015544 file ``Cropped_cyclone_data.zip``
4
- (MD5 ``ed5dac254c689e5a327dee7580324347``). This module never downloads
5
- that zip. Point ``paths.incyde_root`` at an extracted copy.
6
-
7
- Filename times are IST (UTC+05:30). ``Sequence`` in the labels CSV is the
8
- storm key. The trailing ``obj`` index is not a storm id. The default split
9
- and the exclusion list are ``incyde/audit/storm_split.csv`` and
10
- ``incyde/audit/exclusions.csv``.
11
-
12
- ``on_fix``, ``distance_to_land_km``, and ``near_land`` are joined from
13
- ``incyde/audit/frame_flags.csv`` on the source filename. A ``rot_180``
14
- copy inherits that source row. A filename the table does not list stays
15
- unknown: ``on_fix`` is ``unknown``, the distance is null, and
16
- ``near_land`` is ``unknown``. Those gaps are not filled with false or
17
- zero. The labels are already 3-minute winds, so the join does not
18
- rescale them. ``basin`` value ``LAND`` is the IMD basin of a land
19
- depression, not a frame landfall.
20
-
21
- Only original frames and ``rot_180`` copies are kept. ``rot_180`` is
22
- synthetic, stays with its source storm, and is train-only. Flips reverse
23
- cyclone spin. ``rot_90`` and ``rot_270`` add black bars. Both are dropped.
24
- """
25
-
26
- from __future__ import annotations
27
-
28
- import argparse
29
- import hashlib
30
- import re
31
- from datetime import datetime, timedelta, timezone
32
- from pathlib import Path
33
-
34
- import numpy as np
35
- import pandas as pd
36
-
37
- from src.schema import require_valid
38
- from src.splits import LeakageError
39
-
40
- ZIP_MD5 = "ed5dac254c689e5a327dee7580324347"
41
- WIND_AVERAGING = "3min"
42
- WIND_AVERAGING_S = 180
43
- CV_SEED = 42
44
- YEAR_HOLDOUT_NOTE = (
45
- "indicative only: different training years and images from "
46
- "Agrawal et al. 2024, arXiv:2410.08218. Landfall frames are kept; "
47
- "the audit outputs have no landfall flag."
48
- )
49
- KEPT_AUG = frozenset({"", "rot_180"})
50
- DROPPED_AUG = frozenset({"flip_h", "flip_v", "rot_90", "rot_270"})
51
- _IST = timezone(timedelta(hours=5, minutes=30))
52
- _MONTHS = {
53
- name: index
54
- for index, name in enumerate(
55
- ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),
56
- start=1,
57
- )
58
- }
59
- _FILENAME = re.compile(
60
- r"^(?P<day>\d{2})(?P<mon>[A-Za-z]{3})(?P<year>\d{4})_"
61
- r"(?P<hour>\d{2})(?P<minute>\d{2})_(?P<obj>\d+)"
62
- r"(?:_(?P<aug>flip_h|flip_v|rot_90|rot_180|rot_270))?\.jpe?g$",
63
- re.IGNORECASE,
64
- )
65
- _AUG_SUFFIX = re.compile(
66
- r"_(?:flip_h|flip_v|rot_90|rot_180|rot_270)(?=\.jpe?g$)",
67
- re.IGNORECASE,
68
- )
69
- _STORM_ID = re.compile(r"^INCYDE-S\d+_IMD-(?P<year>\d{4})-\d+$")
70
- _AUDIT_DIR = Path(__file__).resolve().parents[1] / "incyde" / "audit"
71
- DEFAULT_STORM_SPLIT = _AUDIT_DIR / "storm_split.csv"
72
- DEFAULT_EXCLUSIONS = _AUDIT_DIR / "exclusions.csv"
73
- DEFAULT_FRAME_FLAGS = _AUDIT_DIR / "frame_flags.csv"
74
- _FRAME_FLAG_COLUMNS = ("filename", "on_fix", "distance_to_land_km", "near_land")
75
-
76
-
77
- def imd_class_of(wind_kt: float) -> str:
78
- """IMD class on a 3-minute wind, in knots.
79
-
80
- D ≤27, DD ≤33, CS ≤47, SCS ≤63, VSCS ≤89, ESCS ≤119, SuCS ≥120.
81
- Below 17 kt is ``<17``. These are not the project's 17/34/48/64/91 bins.
82
- """
83
- wind = float(wind_kt)
84
- if wind < 17:
85
- return "<17"
86
- if wind <= 27:
87
- return "D"
88
- if wind <= 33:
89
- return "DD"
90
- if wind <= 47:
91
- return "CS"
92
- if wind <= 63:
93
- return "SCS"
94
- if wind <= 89:
95
- return "VSCS"
96
- if wind <= 119:
97
- return "ESCS"
98
- return "SuCS"
99
-
100
-
101
- def storm_year(storm_id: object) -> int:
102
- """Year from ``INCYDE-Sxx_IMD-yyyy-nnn``. Filename dates are not used."""
103
- match = _STORM_ID.match(str(storm_id).strip())
104
- if match is None:
105
- raise ValueError(f"storm_id {storm_id!r} is not INCYDE-Sxx_IMD-yyyy-nnn")
106
- return int(match.group("year"))
107
-
108
-
109
- def assert_one_storm_year(frame: pd.DataFrame) -> pd.Series:
110
- """Each storm id maps to one IMD year. A filename that crosses 1 January does not add a second year."""
111
- years = frame["storm_id"].map(storm_year)
112
- counts = pd.DataFrame({"storm_id": frame["storm_id"].astype(str), "year": years}).groupby("storm_id")["year"].nunique()
113
- if bool((counts > 1).any()):
114
- raise LeakageError("a storm_id maps to more than one year")
115
- return years
116
-
117
-
118
- def archive_md5(path: str | Path) -> str:
119
- """MD5 of a local file. Does not download."""
120
- digest = hashlib.md5(usedforsecurity=False)
121
- with Path(path).open("rb") as handle:
122
- for chunk in iter(lambda: handle.read(1 << 20), b""):
123
- digest.update(chunk)
124
- return digest.hexdigest()
125
-
126
-
127
- def assert_archive_md5(path: str | Path) -> None:
128
- """Refuse a cropped-zip copy whose MD5 is not the Zenodo value."""
129
- found = archive_md5(path)
130
- if found != ZIP_MD5:
131
- raise ValueError(f"INCYDE archive md5 is {found}, expected {ZIP_MD5}")
132
-
133
-
134
- def _optional_path(value: object, default: Path) -> Path:
135
- if value is None:
136
- return default
137
- text = str(value).strip()
138
- if text.lower() in {"", "none", "null"}:
139
- return default
140
- return Path(text)
141
-
142
-
143
- def read_storm_split(path: str | Path | None = None) -> pd.DataFrame:
144
- """One row per Sequence. ``proposed_split`` is Bean's grouped split."""
145
- table = pd.read_csv(_optional_path(path, DEFAULT_STORM_SPLIT))
146
- table.columns = [str(column).strip() for column in table.columns]
147
- required = {"Sequence", "storm_id", "proposed_split", "cooccurrence_group"}
148
- missing = sorted(required - set(table.columns))
149
- if missing:
150
- raise ValueError(f"storm_split.csv missing {missing}")
151
- out = table.copy()
152
- out["Sequence"] = pd.to_numeric(out["Sequence"], errors="raise").astype(int)
153
- out["storm_id"] = out["storm_id"].astype(str).str.strip()
154
- out["proposed_split"] = out["proposed_split"].astype(str).str.strip()
155
- out["cooccurrence_group"] = pd.to_numeric(out["cooccurrence_group"], errors="raise").astype(int)
156
- if out["storm_id"].duplicated().any() or out["Sequence"].duplicated().any():
157
- raise ValueError("storm_split.csv repeats a storm")
158
- bad = sorted(set(out["proposed_split"]) - {"train", "val", "test"})
159
- if bad:
160
- raise ValueError(f"storm_split.csv has unknown splits {bad}")
161
- assert_one_storm_year(out)
162
- return out
163
-
164
-
165
- def read_exclusions(path: str | Path | None = None) -> pd.DataFrame:
166
- table = pd.read_csv(_optional_path(path, DEFAULT_EXCLUSIONS))
167
- table.columns = [str(column).strip() for column in table.columns]
168
- required = {"filename", "qc_flag", "default_exclude"}
169
- missing = sorted(required - set(table.columns))
170
- if missing:
171
- raise ValueError(f"exclusions.csv missing {missing}")
172
- out = table.copy()
173
- out["filename"] = out["filename"].astype(str).map(lambda name: Path(name).name)
174
- out["qc_flag"] = out["qc_flag"].fillna("").astype(str)
175
- out["default_exclude"] = [_is_true(value) for value in out["default_exclude"].tolist()]
176
- if out["filename"].duplicated().any():
177
- raise ValueError("exclusions.csv repeats a filename")
178
- return out
179
-
180
-
181
- def _is_true(value: object) -> bool:
182
- if isinstance(value, (bool, np.bool_)):
183
- return bool(value)
184
- return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}
185
-
186
-
187
- def _blank_flag(value: object) -> bool:
188
- if value is None:
189
- return True
190
- try:
191
- if pd.isna(value):
192
- return True
193
- except (TypeError, ValueError):
194
- return False
195
- return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
196
-
197
-
198
- def _on_fix_value(value: object) -> bool | str:
199
- """Explicit bool, or ``unknown`` when the audit did not decide.
200
-
201
- ``unknown`` is not stored as false. A later on-fix metric uses only
202
- the true rows.
203
- """
204
- if isinstance(value, (bool, np.bool_)):
205
- return bool(value)
206
- if _blank_flag(value):
207
- return "unknown"
208
- text = str(value).strip().lower()
209
- if text in {"1", "true", "yes", "y", "t"}:
210
- return True
211
- if text in {"0", "false", "no", "n", "f"}:
212
- return False
213
- if text in {"unknown", "na", "n/a"}:
214
- return "unknown"
215
- raise ValueError(f"on_fix value {value!r} is not true, false, or unknown")
216
-
217
-
218
- def _near_land_token(value: object) -> str:
219
- """``true``, ``false``, or ``unknown``. Blank stays unknown."""
220
- if isinstance(value, (bool, np.bool_)):
221
- return "true" if bool(value) else "false"
222
- if _blank_flag(value):
223
- return "unknown"
224
- text = str(value).strip().lower()
225
- if text in {"1", "true", "yes", "y", "t"}:
226
- return "true"
227
- if text in {"0", "false", "no", "n", "f"}:
228
- return "false"
229
- if text in {"unknown", "na", "n/a"}:
230
- return "unknown"
231
- raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
232
-
233
-
234
- def _distance_km(value: object) -> float:
235
- """Kilometres, or NaN when the audit left the cell blank."""
236
- if _blank_flag(value):
237
- return float("nan")
238
- try:
239
- number = float(value)
240
- except (TypeError, ValueError) as exc:
241
- raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
242
- if not np.isfinite(number):
243
- return float("nan")
244
- return number
245
-
246
-
247
- def read_frame_flags(path: str | Path | None = None) -> pd.DataFrame:
248
- """Original-frame flags. Augmented filenames are not required in the file."""
249
- table = pd.read_csv(_optional_path(path, DEFAULT_FRAME_FLAGS))
250
- table.columns = [str(column).strip() for column in table.columns]
251
- missing = [column for column in _FRAME_FLAG_COLUMNS if column not in table.columns]
252
- if missing:
253
- raise ValueError(f"frame_flags.csv missing {missing}")
254
- on_fix = [_on_fix_value(value) for value in table["on_fix"].tolist()]
255
- out = pd.DataFrame(
256
- {
257
- "filename": table["filename"].astype(str).map(lambda name: Path(name).name),
258
- "distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
259
- "near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
260
- }
261
- )
262
- # Object dtype so a homogeneous true/false column stays a Python bool
263
- # and an unknown cell is not coerced to false.
264
- out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
265
- if out["filename"].duplicated().any():
266
- raise ValueError("frame_flags.csv repeats a filename")
267
- return out
268
-
269
-
270
- def _flag_key(frame: pd.DataFrame) -> pd.Series:
271
- """Source filename. Augmented copies inherit; they are not their own key."""
272
- if "source_frame_id" in frame.columns:
273
- return frame["source_frame_id"].astype(str).map(lambda name: Path(name).name)
274
- if "filename" in frame.columns:
275
- return frame["filename"].astype(str).map(lambda name: Path(_AUG_SUFFIX.sub("", name)).name)
276
- raise ValueError("frame flags need source_frame_id or filename")
277
-
278
-
279
- def attach_frame_flags(frame: pd.DataFrame, flags: pd.DataFrame) -> pd.DataFrame:
280
- """Add ``on_fix``, ``distance_to_land_km``, and ``near_land``.
281
-
282
- The lookup key is the source filename, so a ``rot_180`` copy receives
283
- the original frame's row. A miss stays unknown. Distance is not filled
284
- with 0, and ``on_fix`` is not filled with false.
285
- """
286
- lookup = flags.drop_duplicates("filename").set_index("filename")
287
- on_fix: list[object] = []
288
- distance: list[float] = []
289
- near: list[str] = []
290
- for key in _flag_key(frame).tolist():
291
- if key not in lookup.index:
292
- on_fix.append("unknown")
293
- distance.append(float("nan"))
294
- near.append("unknown")
295
- continue
296
- row = lookup.loc[key]
297
- if isinstance(row, pd.DataFrame):
298
- raise ValueError(f"frame_flags.csv repeats {key}")
299
- on_fix.append(_on_fix_value(row["on_fix"]))
300
- distance.append(_distance_km(row["distance_to_land_km"]))
301
- near.append(_near_land_token(row["near_land"]))
302
- out = frame.copy()
303
- out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
304
- out["distance_to_land_km"] = np.asarray(distance, dtype=float)
305
- out["near_land"] = near
306
- return out
307
-
308
-
309
- def parse_filename(filename: str) -> dict[str, object]:
310
- """Parse ``DDMONYYYY_HHMM_<obj>[_aug].jpg``. ``obj`` is not a storm id."""
311
- name = Path(str(filename)).name
312
- match = _FILENAME.match(name)
313
- if match is None:
314
- raise ValueError(
315
- f"INCYDE filename {name} does not match DDMONYYYY_HHMM_<obj>[_aug].jpg"
316
- )
317
- parts = match.groupdict()
318
- month = _MONTHS.get(parts["mon"].upper())
319
- if month is None:
320
- raise ValueError(f"INCYDE filename {name} has an unknown month")
321
- ist = datetime(
322
- int(parts["year"]),
323
- month,
324
- int(parts["day"]),
325
- int(parts["hour"]),
326
- int(parts["minute"]),
327
- tzinfo=_IST,
328
- )
329
- utc = ist.astimezone(timezone.utc)
330
- aug = "" if not parts["aug"] else parts["aug"].lower()
331
- return {
332
- "filename": name,
333
- "time_ist": ist.isoformat(),
334
- "time_utc": utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
335
- "object_index": int(parts["obj"]),
336
- "aug_type": aug,
337
- "source_frame_id": _AUG_SUFFIX.sub("", name),
338
- }
339
-
340
-
341
- def _source_table(frame: pd.DataFrame) -> pd.DataFrame:
342
- """Labels CSV or the audit manifest, reduced to one column set."""
343
- columns = {str(column).strip(): column for column in frame.columns}
344
- renamed = frame.rename(columns={raw: clean for clean, raw in columns.items()})
345
- if "Sequence" in renamed.columns and ("MSWS kts" in renamed.columns or "label_kt" in renamed.columns):
346
- wind_column = "MSWS kts" if "MSWS kts" in renamed.columns else "label_kt"
347
- filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
348
- out = pd.DataFrame(
349
- {
350
- "sequence": pd.to_numeric(renamed["Sequence"], errors="raise").astype(int),
351
- "filename": filename.astype(str),
352
- "wind_kt": pd.to_numeric(renamed[wind_column], errors="coerce"),
353
- "source_category": renamed["Category"].astype(str) if "Category" in renamed.columns else "",
354
- "incyde_set": renamed["Set"].astype(str) if "Set" in renamed.columns else "",
355
- "given_storm_id": renamed["storm_id"].astype(str) if "storm_id" in renamed.columns else pd.NA,
356
- }
357
- )
358
- return out
359
- if "storm_id" in renamed.columns and "label_kt" in renamed.columns:
360
- filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
361
- sequence = renamed["incyde_sequence"] if "incyde_sequence" in renamed.columns else pd.Series(pd.NA, index=renamed.index)
362
- category = renamed["label_class_imd"] if "label_class_imd" in renamed.columns else ""
363
- return pd.DataFrame(
364
- {
365
- "sequence": pd.to_numeric(sequence, errors="coerce"),
366
- "filename": filename.astype(str),
367
- "wind_kt": pd.to_numeric(renamed["label_kt"], errors="coerce"),
368
- "source_category": category.astype(str) if not isinstance(category, str) else category,
369
- "incyde_set": renamed["incyde_set"].astype(str) if "incyde_set" in renamed.columns else "",
370
- "given_storm_id": renamed["storm_id"].astype(str),
371
- }
372
- )
373
- raise ValueError(
374
- "INCYDE manifest needs the labels columns (Sequence, MSWS kts, filename) "
375
- "or the audit columns (storm_id, label_kt, file)"
376
- )
377
-
378
-
379
- def _locate_labels(root: Path) -> Path:
380
- candidates = [
381
- root / "Cropped_cyclone_labels.csv",
382
- root / "Cropped_cyclone_data" / "Cropped_cyclone_labels.csv",
383
- root / "labels.csv",
384
- ]
385
- for path in candidates:
386
- if path.is_file():
387
- return path
388
- raise FileNotFoundError(
389
- f"No INCYDE labels CSV under {root}. This loader does not download imagery."
390
- )
391
-
392
-
393
- def locate_image(root: Path, filename: str) -> Path:
394
- name = Path(filename).name
395
- candidates = [
396
- root / name,
397
- root / "Cropped_cyclone_images" / name,
398
- root / "Cropped_cyclone_data" / "Cropped_cyclone_images" / name,
399
- root / "Cropped_cyclone_data" / name,
400
- ]
401
- for path in candidates:
402
- if path.is_file():
403
- return path
404
- raise FileNotFoundError(
405
- f"INCYDE image {name} is missing under {root}. This loader does not download imagery."
406
- )
407
-
408
-
409
- def _qc_tokens(flag: object) -> set[str]:
410
- text = "" if flag is None or (isinstance(flag, float) and np.isnan(flag)) else str(flag)
411
- return {part.strip() for part in text.split(";") if part.strip()}
412
-
413
-
414
- def _drop_reason(aug: str, exclude: bool, qc_flag: str, drop_qc_flags: set[str]) -> str | None:
415
- if exclude:
416
- return "default_exclude"
417
- if aug in DROPPED_AUG:
418
- return f"dropped aug {aug}"
419
- if aug not in KEPT_AUG:
420
- return f"unknown aug {aug or 'blank'}"
421
- if drop_qc_flags and _qc_tokens(qc_flag) & drop_qc_flags:
422
- return "drop_qc_flags"
423
- return None
424
-
425
-
426
- def read_rows(
427
- root: str | Path,
428
- *,
429
- manifest_csv: str | Path | None = None,
430
- storm_split_csv: str | Path | None = None,
431
- exclusions_csv: str | Path | None = None,
432
- frame_flags_csv: str | Path | None = None,
433
- drop_qc_flags: list[str] | tuple[str, ...] | None = None,
434
- check_images: bool = True,
435
- ) -> tuple[pd.DataFrame, int]:
436
- """Frame rows before the final split. ``rot_180`` is still present.
437
-
438
- Flips, ``rot_90``, ``rot_270``, and ``default_exclude`` rows are gone.
439
- The returned count is how many source rows were dropped here.
440
- """
441
- root = Path(root)
442
- if not root.is_dir():
443
- raise FileNotFoundError(
444
- f"INCYDE root {root} is missing. Set paths.incyde_root to the extracted "
445
- "Cropped_cyclone_data directory. This entrypoint does not download imagery."
446
- )
447
- label_path = Path(manifest_csv) if manifest_csv not in (None, "", "null") else _locate_labels(root)
448
- if not label_path.is_file():
449
- raise FileNotFoundError(f"INCYDE manifest {label_path} is missing. Nothing is downloaded.")
450
- storms = read_storm_split(storm_split_csv)
451
- exclusions = read_exclusions(exclusions_csv)
452
- source = _source_table(pd.read_csv(label_path, encoding="utf-8-sig"))
453
- parsed = [parse_filename(name) for name in source["filename"].tolist()]
454
- parsed_frame = pd.DataFrame(parsed).drop(columns=["filename"])
455
- work = pd.concat([source.reset_index(drop=True), parsed_frame], axis=1)
456
- work["filename"] = work["filename"].map(lambda name: Path(str(name)).name)
457
- by_sequence = storms.set_index("Sequence")
458
- by_storm = storms.drop_duplicates("storm_id").set_index("storm_id")
459
- storm_ids: list[str] = []
460
- sequences: list[int] = []
461
- proposed: list[str] = []
462
- groups: list[int] = []
463
- names: list[str] = []
464
- basins: list[str] = []
465
- for sequence, given in zip(work["sequence"].tolist(), work["given_storm_id"].tolist(), strict=True):
466
- row = None
467
- if pd.notna(sequence) and int(sequence) in by_sequence.index:
468
- row = by_sequence.loc[int(sequence)]
469
- elif isinstance(given, str) and given in by_storm.index:
470
- row = by_storm.loc[given]
471
- if row is None:
472
- raise ValueError(f"no storm_split row for sequence {sequence!r} storm {given!r}")
473
- if isinstance(row, pd.DataFrame):
474
- raise ValueError(f"storm_split matched more than one row for sequence {sequence}")
475
- storm_id = str(row["storm_id"]) if "storm_id" in row.index else str(row.name)
476
- sequence_id = int(row["Sequence"]) if "Sequence" in row.index else int(row.name)
477
- if isinstance(given, str) and given not in {"", "nan", "<NA>"} and given != storm_id:
478
- raise ValueError(f"manifest storm_id {given} does not match storm_split.csv ({storm_id})")
479
- storm_ids.append(storm_id)
480
- sequences.append(sequence_id)
481
- proposed.append(str(row["proposed_split"]))
482
- groups.append(int(row["cooccurrence_group"]))
483
- names.append("" if "name" not in row.index or pd.isna(row["name"]) else str(row["name"]))
484
- basins.append("" if "basin" not in row.index or pd.isna(row["basin"]) else str(row["basin"]))
485
- work["storm_id"] = storm_ids
486
- work["sequence"] = sequences
487
- work["proposed_split"] = proposed
488
- work["cooccurrence_group"] = groups
489
- work["name"] = names
490
- work["basin"] = basins
491
- qc = exclusions.set_index("filename")
492
- flags = []
493
- exclude = []
494
- for filename in work["filename"].tolist():
495
- if filename in qc.index:
496
- flags.append(str(qc.at[filename, "qc_flag"]))
497
- exclude.append(bool(qc.at[filename, "default_exclude"]))
498
- else:
499
- flags.append("")
500
- exclude.append(False)
501
- work["qc_flag"] = flags
502
- drop_flags = {str(flag).strip() for flag in (drop_qc_flags or []) if str(flag).strip()}
503
- reasons = [
504
- _drop_reason(aug, dropped, flag, drop_flags)
505
- for aug, dropped, flag in zip(work["aug_type"], exclude, work["qc_flag"], strict=True)
506
- ]
507
- dropped_count = sum(reason is not None for reason in reasons)
508
- kept = work.loc[[reason is None for reason in reasons]].reset_index(drop=True)
509
- if kept.empty:
510
- raise ValueError("INCYDE filters removed every row")
511
- if kept["filename"].duplicated().any():
512
- raise ValueError("INCYDE labels repeat a filename")
513
- years = assert_one_storm_year(kept)
514
- image_paths: list[str] = []
515
- heights: list[int] = []
516
- widths: list[int] = []
517
- if check_images:
518
- from PIL import Image
519
-
520
- for filename in kept["filename"].tolist():
521
- path = locate_image(root, filename)
522
- image_paths.append(path.resolve().as_posix())
523
- with Image.open(path) as image:
524
- widths.append(int(image.width))
525
- heights.append(int(image.height))
526
- else:
527
- image_paths = kept["filename"].tolist()
528
- heights = [0] * len(kept)
529
- widths = [0] * len(kept)
530
- frame = pd.DataFrame(
531
- {
532
- "sample_id": [Path(name).stem for name in kept["filename"].tolist()],
533
- "image_path": image_paths,
534
- "storm_id": kept["storm_id"].astype(str),
535
- "wind_speed_kt": kept["wind_kt"].to_numpy(dtype=float),
536
- "wind_kt": kept["wind_kt"].to_numpy(dtype=float),
537
- "wind_averaging": WIND_AVERAGING,
538
- "wind_averaging_s": WIND_AVERAGING_S,
539
- "is_synthetic": [aug == "rot_180" for aug in kept["aug_type"].tolist()],
540
- "imd_class": [imd_class_of(wind) for wind in kept["wind_kt"].tolist()],
541
- "split": kept["proposed_split"].astype(str),
542
- "proposed_split": kept["proposed_split"].astype(str),
543
- "cooccurrence_group": kept["cooccurrence_group"].astype(int),
544
- "time_utc": kept["time_utc"].astype(str),
545
- "time_ist": kept["time_ist"].astype(str),
546
- "storm_year": years.to_numpy(dtype=int),
547
- "aug_type": kept["aug_type"].astype(str),
548
- "source_frame_id": kept["source_frame_id"].astype(str),
549
- "object_index": kept["object_index"].astype(int),
550
- "qc_flag": kept["qc_flag"].astype(str),
551
- "incyde_sequence": kept["sequence"].astype(int),
552
- "incyde_set": kept["incyde_set"].astype(str),
553
- "source_category": kept["source_category"].astype(str),
554
- "name": kept["name"].astype(str),
555
- "basin": kept["basin"].astype(str),
556
- "native_height": heights,
557
- "native_width": widths,
558
- "orig_size": [height if height == width else -1 for height, width in zip(heights, widths, strict=True)],
559
- "sensor": "INSAT-3D",
560
- "channel": "IR",
561
- "pixel_units": "jpeg_uncalibrated",
562
- "label_source": "incyde_imd_3min",
563
- "center_source": "dataset_precentered",
564
- }
565
- )
566
- # Join after the row filter so dropped augs are not looked up. The
567
- # source filename is the key; unknown audit cells stay unknown.
568
- flagged = attach_frame_flags(frame, read_frame_flags(frame_flags_csv))
569
- return require_valid(flagged), int(dropped_count)
570
-
571
-
572
- def build_cv_folds(storms: pd.DataFrame, n_folds: int, seed: int) -> pd.DataFrame:
573
- """Storm-grouped folds over train+val only. Test storms are absent.
574
-
575
- Groups are shuffled with ``seed`` and dealt round-robin, so every storm
576
- in one ``cooccurrence_group`` shares a fold. The training path passes
577
- ``incyde.cv_seed`` (42 in the YAML).
578
- """
579
- folds = int(n_folds)
580
- if folds < 2:
581
- raise ValueError("incyde.n_folds must be at least 2")
582
- pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
583
- if pool.empty:
584
- raise ValueError("storm_cv needs train and val storms")
585
- groups = sorted({int(group) for group in pool["cooccurrence_group"].tolist()})
586
- order = np.random.default_rng(int(seed)).permutation(len(groups))
587
- shuffled = [groups[int(index)] for index in order]
588
- group_fold = {group: index % folds for index, group in enumerate(shuffled)}
589
- out = pd.DataFrame(
590
- {
591
- "storm_id": pool["storm_id"].astype(str).tolist(),
592
- "fold": [int(group_fold[int(group)]) for group in pool["cooccurrence_group"].tolist()],
593
- }
594
- )
595
- return out.sort_values(["fold", "storm_id"]).reset_index(drop=True)
596
-
597
-
598
- def read_cv_folds(path: str | Path) -> pd.DataFrame:
599
- """Use a folds file verbatim. Columns are ``storm_id`` and ``fold``."""
600
- table = pd.read_csv(path)
601
- table.columns = [str(column).strip() for column in table.columns]
602
- if "storm_id" not in table.columns or "fold" not in table.columns:
603
- raise ValueError("cv folds csv needs columns storm_id and fold")
604
- out = pd.DataFrame(
605
- {
606
- "storm_id": table["storm_id"].astype(str).str.strip(),
607
- "fold": pd.to_numeric(table["fold"], errors="raise").astype(int),
608
- }
609
- )
610
- if out["storm_id"].duplicated().any():
611
- raise ValueError("cv folds csv repeats a storm_id")
612
- return out.reset_index(drop=True)
613
-
614
-
615
- def validate_cv_folds(folds: pd.DataFrame, storms: pd.DataFrame) -> None:
616
- """No test storm, and no cooccurrence group spread across folds."""
617
- test_ids = set(storms.loc[storms["proposed_split"].astype(str) == "test", "storm_id"].astype(str))
618
- listed = set(folds["storm_id"].astype(str))
619
- leaked = sorted(listed & test_ids)
620
- if leaked:
621
- raise LeakageError(f"cv folds include test storms {leaked[:8]}")
622
- pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
623
- pool_ids = set(pool["storm_id"].astype(str))
624
- missing = sorted(pool_ids - listed)
625
- extra = sorted(listed - pool_ids)
626
- if missing:
627
- raise ValueError(f"cv folds omit train/val storms {missing[:8]}")
628
- if extra:
629
- raise ValueError(f"cv folds name storms that are not train/val {extra[:8]}")
630
- merged = pool.assign(storm_id=pool["storm_id"].astype(str)).merge(folds, on="storm_id", how="left")
631
- spread = merged.groupby("cooccurrence_group")["fold"].nunique()
632
- if bool((spread > 1).any()):
633
- groups = [int(group) for group in spread.index[spread > 1].tolist()]
634
- raise LeakageError(f"cooccurrence_group spans folds {groups[:8]}")
635
-
636
-
637
- def _folds_for(storms: pd.DataFrame, n_folds: int, seed: int, cv_folds_csv: str | Path | None) -> pd.DataFrame:
638
- if cv_folds_csv not in (None, "", "null"):
639
- folds = read_cv_folds(cv_folds_csv)
640
- else:
641
- folds = build_cv_folds(storms, n_folds, seed)
642
- validate_cv_folds(folds, storms)
643
- return folds
644
-
645
-
646
- def _assert_storms(frame: pd.DataFrame) -> None:
647
- per_storm = frame.groupby(frame["storm_id"].astype(str))["split"].nunique()
648
- if bool((per_storm > 1).any()):
649
- raise LeakageError("a storm is in more than one split")
650
- synthetic = frame["is_synthetic"].astype(bool) & frame["split"].astype(str).ne("train")
651
- if bool(synthetic.any()):
652
- raise LeakageError("synthetic INCYDE rows are train-only")
653
- bad_aug = sorted(set(frame["aug_type"].astype(str)) - KEPT_AUG)
654
- if bad_aug:
655
- raise LeakageError(f"INCYDE kept dropped augmentations {bad_aug}")
656
-
657
-
658
- def _assert_groups(frame: pd.DataFrame) -> None:
659
- spread = frame.groupby("cooccurrence_group")["split"].nunique()
660
- if bool((spread > 1).any()):
661
- raise LeakageError("a cooccurrence_group is in more than one split")
662
-
663
-
664
- def assign_incyde_split(
665
- frame: pd.DataFrame,
666
- strategy: str,
667
- *,
668
- n_folds: int = 5,
669
- cv_val_fold: int = 0,
670
- cv_seed: int = CV_SEED,
671
- cv_folds_csv: str | Path | None = None,
672
- ) -> tuple[pd.DataFrame, int]:
673
- """Write ``split`` and drop synthetic rows that are not in train.
674
-
675
- ``storm_wise`` uses ``proposed_split`` (60/14/17 on the audit file).
676
- ``storm_cv`` keeps test storms out of the folds. ``year_holdout_2019``
677
- puts 2019 in test and 2021 in val. The year comes from ``storm_id``.
678
- """
679
- name = str(strategy).strip().lower()
680
- work = frame.copy()
681
- if "proposed_split" not in work.columns:
682
- raise ValueError("INCYDE rows need proposed_split from storm_split.csv")
683
- storms = work.groupby("storm_id", as_index=False).agg(
684
- proposed_split=("proposed_split", "first"),
685
- cooccurrence_group=("cooccurrence_group", "first"),
686
- )
687
- assert_one_storm_year(work)
688
- if name in {"storm_wise", "proposed", "bean"}:
689
- work["split"] = work["proposed_split"].astype(str)
690
- _assert_groups(work)
691
- elif name == "storm_cv":
692
- using_file = cv_folds_csv not in (None, "", "null")
693
- folds = _folds_for(storms, n_folds, cv_seed, cv_folds_csv)
694
- chosen = int(cv_val_fold)
695
- if not using_file and (chosen < 0 or chosen >= int(n_folds)):
696
- raise ValueError("incyde.cv_val_fold is outside 0 .. n_folds-1")
697
- fold_of = dict(zip(folds["storm_id"].astype(str), folds["fold"].astype(int), strict=True))
698
- splits = []
699
- for storm_id, proposed in zip(work["storm_id"].astype(str), work["proposed_split"].astype(str), strict=True):
700
- if proposed == "test":
701
- splits.append("test")
702
- else:
703
- splits.append("val" if fold_of[storm_id] == chosen else "train")
704
- work["split"] = splits
705
- work["cv_fold"] = work["storm_id"].astype(str).map(lambda storm_id: fold_of.get(storm_id, pd.NA))
706
- _assert_groups(work)
707
- elif name == "year_holdout_2019":
708
- years = work["storm_id"].map(storm_year)
709
- work["split"] = np.where(years.eq(2019), "test", np.where(years.eq(2021), "val", "train"))
710
- else:
711
- raise LeakageError(f"unknown INCYDE split strategy {strategy}")
712
- synthetic_eval = work["is_synthetic"].astype(bool) & work["split"].astype(str).ne("train")
713
- dropped = int(synthetic_eval.sum())
714
- work = work.loc[~synthetic_eval].reset_index(drop=True)
715
- _assert_storms(work)
716
- for split_name in ("train", "val", "test"):
717
- if split_name not in set(work["split"].astype(str)):
718
- raise LeakageError(f"INCYDE split {name} produced no {split_name} rows")
719
- return work, dropped
720
-
721
-
722
- def load_frame(config: dict) -> tuple[pd.DataFrame, int]:
723
- """Rows for ``python -m src.train --dataset incyde``. Nothing is downloaded."""
724
- paths = config["paths"]
725
- block = config["incyde"]
726
- archive = block["archive"]
727
- if archive not in (None, "", "null"):
728
- assert_archive_md5(archive)
729
- frame, dropped = read_rows(
730
- paths["incyde_root"],
731
- manifest_csv=block["manifest_csv"],
732
- storm_split_csv=block["storm_split_csv"],
733
- exclusions_csv=block["exclusions_csv"],
734
- frame_flags_csv=block.get("frame_flags_csv"),
735
- drop_qc_flags=list(block["drop_qc_flags"] or []),
736
- check_images=True,
737
- )
738
- assigned, synthetic_dropped = assign_incyde_split(
739
- frame,
740
- str(config["split"]["strategy"]),
741
- n_folds=int(block["n_folds"]),
742
- cv_val_fold=int(block["cv_val_fold"]),
743
- cv_seed=int(block["cv_seed"]),
744
- cv_folds_csv=block["cv_folds_csv"],
745
- )
746
- return assigned, int(dropped) + int(synthetic_dropped)
747
-
748
-
749
- def main(argv: list[str] | None = None) -> Path:
750
- """Write a manifest from a local extracted tree. Does not download."""
751
- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
752
- parser.add_argument("--root", type=Path, required=True)
753
- parser.add_argument("--manifest-csv", type=Path, default=None)
754
- parser.add_argument("--storm-split", type=Path, default=None)
755
- parser.add_argument("--exclusions", type=Path, default=None)
756
- parser.add_argument("--frame-flags", type=Path, default=None)
757
- parser.add_argument("--out", type=Path, required=True)
758
- parser.add_argument("--strategy", default="storm_wise")
759
- parser.add_argument("--archive", type=Path, default=None)
760
- args = parser.parse_args(argv)
761
- if args.archive is not None:
762
- assert_archive_md5(args.archive)
763
- frame, dropped = read_rows(
764
- args.root,
765
- manifest_csv=args.manifest_csv,
766
- storm_split_csv=args.storm_split,
767
- exclusions_csv=args.exclusions,
768
- frame_flags_csv=args.frame_flags,
769
- )
770
- assigned, synthetic_dropped = assign_incyde_split(frame, args.strategy)
771
- args.out.parent.mkdir(parents=True, exist_ok=True)
772
- assigned.to_csv(args.out, index=False)
773
- print(f"Wrote {args.out} ({len(assigned)} rows, dropped {dropped + synthetic_dropped}). Not a forecast.")
774
- return args.out
775
-
776
-
777
- if __name__ == "__main__":
778
- main()
 
1
+ """INCYDE loader for the cropped INSAT-3D North Indian Ocean set.
2
+
3
+ Images come from the Zenodo 8015544 file ``Cropped_cyclone_data.zip``
4
+ (MD5 ``ed5dac254c689e5a327dee7580324347``). This module never downloads
5
+ that zip. Point ``paths.incyde_root`` at an extracted copy.
6
+
7
+ Filename times are IST (UTC+05:30). ``Sequence`` in the labels CSV is the
8
+ storm key. The trailing ``obj`` index is not a storm id. The default split
9
+ and the exclusion list are ``incyde/audit/storm_split.csv`` and
10
+ ``incyde/audit/exclusions.csv``.
11
+
12
+ ``on_fix``, ``distance_to_land_km``, and ``near_land`` are joined from
13
+ ``incyde/audit/frame_flags.csv`` on the source filename. A ``rot_180``
14
+ copy inherits that source row. A filename the table does not list stays
15
+ unknown: ``on_fix`` is ``unknown``, the distance is null, and
16
+ ``near_land`` is ``unknown``. Those gaps are not filled with false or
17
+ zero. The labels are already 3-minute winds, so the join does not
18
+ rescale them. ``basin`` value ``LAND`` is the IMD basin of a land
19
+ depression, not a frame landfall.
20
+
21
+ Only original frames and ``rot_180`` copies are kept. ``rot_180`` is
22
+ synthetic, stays with its source storm, and is train-only. Flips reverse
23
+ cyclone spin. ``rot_90`` and ``rot_270`` add black bars. Both are dropped.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import hashlib
30
+ import re
31
+ from datetime import datetime, timedelta, timezone
32
+ from pathlib import Path
33
+
34
+ import numpy as np
35
+ import pandas as pd
36
+
37
+ from src.schema import require_valid
38
+ from src.splits import LeakageError
39
+
40
+ ZIP_MD5 = "ed5dac254c689e5a327dee7580324347"
41
+ WIND_AVERAGING = "3min"
42
+ WIND_AVERAGING_S = 180
43
+ CV_SEED = 42
44
+ YEAR_HOLDOUT_NOTE = (
45
+ "indicative only: different training years and images from "
46
+ "Agrawal et al. 2024, arXiv:2410.08218. Landfall frames are kept; "
47
+ "the audit outputs have no landfall flag."
48
+ )
49
+ KEPT_AUG = frozenset({"", "rot_180"})
50
+ DROPPED_AUG = frozenset({"flip_h", "flip_v", "rot_90", "rot_270"})
51
+ _IST = timezone(timedelta(hours=5, minutes=30))
52
+ _MONTHS = {
53
+ name: index
54
+ for index, name in enumerate(
55
+ ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),
56
+ start=1,
57
+ )
58
+ }
59
+ _FILENAME = re.compile(
60
+ r"^(?P<day>\d{2})(?P<mon>[A-Za-z]{3})(?P<year>\d{4})_"
61
+ r"(?P<hour>\d{2})(?P<minute>\d{2})_(?P<obj>\d+)"
62
+ r"(?:_(?P<aug>flip_h|flip_v|rot_90|rot_180|rot_270))?\.jpe?g$",
63
+ re.IGNORECASE,
64
+ )
65
+ _AUG_SUFFIX = re.compile(
66
+ r"_(?:flip_h|flip_v|rot_90|rot_180|rot_270)(?=\.jpe?g$)",
67
+ re.IGNORECASE,
68
+ )
69
+ _STORM_ID = re.compile(r"^INCYDE-S\d+_IMD-(?P<year>\d{4})-\d+$")
70
+ _AUDIT_DIR = Path(__file__).resolve().parents[1] / "incyde" / "audit"
71
+ DEFAULT_STORM_SPLIT = _AUDIT_DIR / "storm_split.csv"
72
+ DEFAULT_EXCLUSIONS = _AUDIT_DIR / "exclusions.csv"
73
+ DEFAULT_FRAME_FLAGS = _AUDIT_DIR / "frame_flags.csv"
74
+ _FRAME_FLAG_COLUMNS = ("filename", "on_fix", "distance_to_land_km", "near_land")
75
+
76
+
77
+ def imd_class_of(wind_kt: float) -> str:
78
+ """IMD class on a 3-minute wind, in knots.
79
+
80
+ D ≤27, DD ≤33, CS ≤47, SCS ≤63, VSCS ≤89, ESCS ≤119, SuCS ≥120.
81
+ Below 17 kt is ``<17``. These are not the project's 17/34/48/64/91 bins.
82
+ """
83
+ wind = float(wind_kt)
84
+ if wind < 17:
85
+ return "<17"
86
+ if wind <= 27:
87
+ return "D"
88
+ if wind <= 33:
89
+ return "DD"
90
+ if wind <= 47:
91
+ return "CS"
92
+ if wind <= 63:
93
+ return "SCS"
94
+ if wind <= 89:
95
+ return "VSCS"
96
+ if wind <= 119:
97
+ return "ESCS"
98
+ return "SuCS"
99
+
100
+
101
+ def storm_year(storm_id: object) -> int:
102
+ """Year from ``INCYDE-Sxx_IMD-yyyy-nnn``. Filename dates are not used."""
103
+ match = _STORM_ID.match(str(storm_id).strip())
104
+ if match is None:
105
+ raise ValueError(f"storm_id {storm_id!r} is not INCYDE-Sxx_IMD-yyyy-nnn")
106
+ return int(match.group("year"))
107
+
108
+
109
+ def assert_one_storm_year(frame: pd.DataFrame) -> pd.Series:
110
+ """Each storm id maps to one IMD year. A filename that crosses 1 January does not add a second year."""
111
+ years = frame["storm_id"].map(storm_year)
112
+ counts = pd.DataFrame({"storm_id": frame["storm_id"].astype(str), "year": years}).groupby("storm_id")["year"].nunique()
113
+ if bool((counts > 1).any()):
114
+ raise LeakageError("a storm_id maps to more than one year")
115
+ return years
116
+
117
+
118
+ def archive_md5(path: str | Path) -> str:
119
+ """MD5 of a local file. Does not download."""
120
+ digest = hashlib.md5(usedforsecurity=False)
121
+ with Path(path).open("rb") as handle:
122
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
123
+ digest.update(chunk)
124
+ return digest.hexdigest()
125
+
126
+
127
+ def assert_archive_md5(path: str | Path) -> None:
128
+ """Refuse a cropped-zip copy whose MD5 is not the Zenodo value."""
129
+ found = archive_md5(path)
130
+ if found != ZIP_MD5:
131
+ raise ValueError(f"INCYDE archive md5 is {found}, expected {ZIP_MD5}")
132
+
133
+
134
+ def _optional_path(value: object, default: Path) -> Path:
135
+ if value is None:
136
+ return default
137
+ text = str(value).strip()
138
+ if text.lower() in {"", "none", "null"}:
139
+ return default
140
+ return Path(text)
141
+
142
+
143
+ def read_storm_split(path: str | Path | None = None) -> pd.DataFrame:
144
+ """One row per Sequence. ``proposed_split`` is Bean's grouped split."""
145
+ table = pd.read_csv(_optional_path(path, DEFAULT_STORM_SPLIT))
146
+ table.columns = [str(column).strip() for column in table.columns]
147
+ required = {"Sequence", "storm_id", "proposed_split", "cooccurrence_group"}
148
+ missing = sorted(required - set(table.columns))
149
+ if missing:
150
+ raise ValueError(f"storm_split.csv missing {missing}")
151
+ out = table.copy()
152
+ out["Sequence"] = pd.to_numeric(out["Sequence"], errors="raise").astype(int)
153
+ out["storm_id"] = out["storm_id"].astype(str).str.strip()
154
+ out["proposed_split"] = out["proposed_split"].astype(str).str.strip()
155
+ out["cooccurrence_group"] = pd.to_numeric(out["cooccurrence_group"], errors="raise").astype(int)
156
+ if out["storm_id"].duplicated().any() or out["Sequence"].duplicated().any():
157
+ raise ValueError("storm_split.csv repeats a storm")
158
+ bad = sorted(set(out["proposed_split"]) - {"train", "val", "test"})
159
+ if bad:
160
+ raise ValueError(f"storm_split.csv has unknown splits {bad}")
161
+ assert_one_storm_year(out)
162
+ return out
163
+
164
+
165
+ def read_exclusions(path: str | Path | None = None) -> pd.DataFrame:
166
+ table = pd.read_csv(_optional_path(path, DEFAULT_EXCLUSIONS))
167
+ table.columns = [str(column).strip() for column in table.columns]
168
+ required = {"filename", "qc_flag", "default_exclude"}
169
+ missing = sorted(required - set(table.columns))
170
+ if missing:
171
+ raise ValueError(f"exclusions.csv missing {missing}")
172
+ out = table.copy()
173
+ out["filename"] = out["filename"].astype(str).map(lambda name: Path(name).name)
174
+ out["qc_flag"] = out["qc_flag"].fillna("").astype(str)
175
+ out["default_exclude"] = [_is_true(value) for value in out["default_exclude"].tolist()]
176
+ if out["filename"].duplicated().any():
177
+ raise ValueError("exclusions.csv repeats a filename")
178
+ return out
179
+
180
+
181
+ def _is_true(value: object) -> bool:
182
+ if isinstance(value, (bool, np.bool_)):
183
+ return bool(value)
184
+ return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}
185
+
186
+
187
+ def _blank_flag(value: object) -> bool:
188
+ if value is None:
189
+ return True
190
+ try:
191
+ if pd.isna(value):
192
+ return True
193
+ except (TypeError, ValueError):
194
+ return False
195
+ return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
196
+
197
+
198
+ def _on_fix_value(value: object) -> bool | str:
199
+ """Explicit bool, or ``unknown`` when the audit did not decide.
200
+
201
+ ``unknown`` is not stored as false. A later on-fix metric uses only
202
+ the true rows.
203
+ """
204
+ if isinstance(value, (bool, np.bool_)):
205
+ return bool(value)
206
+ if _blank_flag(value):
207
+ return "unknown"
208
+ text = str(value).strip().lower()
209
+ if text in {"1", "true", "yes", "y", "t"}:
210
+ return True
211
+ if text in {"0", "false", "no", "n", "f"}:
212
+ return False
213
+ if text in {"unknown", "na", "n/a"}:
214
+ return "unknown"
215
+ raise ValueError(f"on_fix value {value!r} is not true, false, or unknown")
216
+
217
+
218
+ def _near_land_token(value: object) -> str:
219
+ """``true``, ``false``, or ``unknown``. Blank stays unknown."""
220
+ if isinstance(value, (bool, np.bool_)):
221
+ return "true" if bool(value) else "false"
222
+ if _blank_flag(value):
223
+ return "unknown"
224
+ text = str(value).strip().lower()
225
+ if text in {"1", "true", "yes", "y", "t"}:
226
+ return "true"
227
+ if text in {"0", "false", "no", "n", "f"}:
228
+ return "false"
229
+ if text in {"unknown", "na", "n/a"}:
230
+ return "unknown"
231
+ raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
232
+
233
+
234
+ def _distance_km(value: object) -> float:
235
+ """Kilometres, or NaN when the audit left the cell blank."""
236
+ if _blank_flag(value):
237
+ return float("nan")
238
+ try:
239
+ number = float(value)
240
+ except (TypeError, ValueError) as exc:
241
+ raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
242
+ if not np.isfinite(number):
243
+ return float("nan")
244
+ return number
245
+
246
+
247
+ def read_frame_flags(path: str | Path | None = None) -> pd.DataFrame:
248
+ """Original-frame flags. Augmented filenames are not required in the file."""
249
+ table = pd.read_csv(_optional_path(path, DEFAULT_FRAME_FLAGS))
250
+ table.columns = [str(column).strip() for column in table.columns]
251
+ missing = [column for column in _FRAME_FLAG_COLUMNS if column not in table.columns]
252
+ if missing:
253
+ raise ValueError(f"frame_flags.csv missing {missing}")
254
+ on_fix = [_on_fix_value(value) for value in table["on_fix"].tolist()]
255
+ out = pd.DataFrame(
256
+ {
257
+ "filename": table["filename"].astype(str).map(lambda name: Path(name).name),
258
+ "distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
259
+ "near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
260
+ }
261
+ )
262
+ # Object dtype so a homogeneous true/false column stays a Python bool
263
+ # and an unknown cell is not coerced to false.
264
+ out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
265
+ if out["filename"].duplicated().any():
266
+ raise ValueError("frame_flags.csv repeats a filename")
267
+ return out
268
+
269
+
270
+ def _flag_key(frame: pd.DataFrame) -> pd.Series:
271
+ """Source filename. Augmented copies inherit; they are not their own key."""
272
+ if "source_frame_id" in frame.columns:
273
+ return frame["source_frame_id"].astype(str).map(lambda name: Path(name).name)
274
+ if "filename" in frame.columns:
275
+ return frame["filename"].astype(str).map(lambda name: Path(_AUG_SUFFIX.sub("", name)).name)
276
+ raise ValueError("frame flags need source_frame_id or filename")
277
+
278
+
279
+ def attach_frame_flags(frame: pd.DataFrame, flags: pd.DataFrame) -> pd.DataFrame:
280
+ """Add ``on_fix``, ``distance_to_land_km``, and ``near_land``.
281
+
282
+ The lookup key is the source filename, so a ``rot_180`` copy receives
283
+ the original frame's row. A miss stays unknown. Distance is not filled
284
+ with 0, and ``on_fix`` is not filled with false.
285
+ """
286
+ lookup = flags.drop_duplicates("filename").set_index("filename")
287
+ on_fix: list[object] = []
288
+ distance: list[float] = []
289
+ near: list[str] = []
290
+ for key in _flag_key(frame).tolist():
291
+ if key not in lookup.index:
292
+ on_fix.append("unknown")
293
+ distance.append(float("nan"))
294
+ near.append("unknown")
295
+ continue
296
+ row = lookup.loc[key]
297
+ if isinstance(row, pd.DataFrame):
298
+ raise ValueError(f"frame_flags.csv repeats {key}")
299
+ on_fix.append(_on_fix_value(row["on_fix"]))
300
+ distance.append(_distance_km(row["distance_to_land_km"]))
301
+ near.append(_near_land_token(row["near_land"]))
302
+ out = frame.copy()
303
+ out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
304
+ out["distance_to_land_km"] = np.asarray(distance, dtype=float)
305
+ out["near_land"] = near
306
+ return out
307
+
308
+
309
+ def parse_filename(filename: str) -> dict[str, object]:
310
+ """Parse ``DDMONYYYY_HHMM_<obj>[_aug].jpg``. ``obj`` is not a storm id."""
311
+ name = Path(str(filename)).name
312
+ match = _FILENAME.match(name)
313
+ if match is None:
314
+ raise ValueError(
315
+ f"INCYDE filename {name} does not match DDMONYYYY_HHMM_<obj>[_aug].jpg"
316
+ )
317
+ parts = match.groupdict()
318
+ month = _MONTHS.get(parts["mon"].upper())
319
+ if month is None:
320
+ raise ValueError(f"INCYDE filename {name} has an unknown month")
321
+ ist = datetime(
322
+ int(parts["year"]),
323
+ month,
324
+ int(parts["day"]),
325
+ int(parts["hour"]),
326
+ int(parts["minute"]),
327
+ tzinfo=_IST,
328
+ )
329
+ utc = ist.astimezone(timezone.utc)
330
+ aug = "" if not parts["aug"] else parts["aug"].lower()
331
+ return {
332
+ "filename": name,
333
+ "time_ist": ist.isoformat(),
334
+ "time_utc": utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
335
+ "object_index": int(parts["obj"]),
336
+ "aug_type": aug,
337
+ "source_frame_id": _AUG_SUFFIX.sub("", name),
338
+ }
339
+
340
+
341
+ def _source_table(frame: pd.DataFrame) -> pd.DataFrame:
342
+ """Labels CSV or the audit manifest, reduced to one column set."""
343
+ columns = {str(column).strip(): column for column in frame.columns}
344
+ renamed = frame.rename(columns={raw: clean for clean, raw in columns.items()})
345
+ if "Sequence" in renamed.columns and ("MSWS kts" in renamed.columns or "label_kt" in renamed.columns):
346
+ wind_column = "MSWS kts" if "MSWS kts" in renamed.columns else "label_kt"
347
+ filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
348
+ out = pd.DataFrame(
349
+ {
350
+ "sequence": pd.to_numeric(renamed["Sequence"], errors="raise").astype(int),
351
+ "filename": filename.astype(str),
352
+ "wind_kt": pd.to_numeric(renamed[wind_column], errors="coerce"),
353
+ "source_category": renamed["Category"].astype(str) if "Category" in renamed.columns else "",
354
+ "incyde_set": renamed["Set"].astype(str) if "Set" in renamed.columns else "",
355
+ "given_storm_id": renamed["storm_id"].astype(str) if "storm_id" in renamed.columns else pd.NA,
356
+ }
357
+ )
358
+ return out
359
+ if "storm_id" in renamed.columns and "label_kt" in renamed.columns:
360
+ filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
361
+ sequence = renamed["incyde_sequence"] if "incyde_sequence" in renamed.columns else pd.Series(pd.NA, index=renamed.index)
362
+ category = renamed["label_class_imd"] if "label_class_imd" in renamed.columns else ""
363
+ return pd.DataFrame(
364
+ {
365
+ "sequence": pd.to_numeric(sequence, errors="coerce"),
366
+ "filename": filename.astype(str),
367
+ "wind_kt": pd.to_numeric(renamed["label_kt"], errors="coerce"),
368
+ "source_category": category.astype(str) if not isinstance(category, str) else category,
369
+ "incyde_set": renamed["incyde_set"].astype(str) if "incyde_set" in renamed.columns else "",
370
+ "given_storm_id": renamed["storm_id"].astype(str),
371
+ }
372
+ )
373
+ raise ValueError(
374
+ "INCYDE manifest needs the labels columns (Sequence, MSWS kts, filename) "
375
+ "or the audit columns (storm_id, label_kt, file)"
376
+ )
377
+
378
+
379
+ def _locate_labels(root: Path) -> Path:
380
+ candidates = [
381
+ root / "Cropped_cyclone_labels.csv",
382
+ root / "Cropped_cyclone_data" / "Cropped_cyclone_labels.csv",
383
+ root / "labels.csv",
384
+ ]
385
+ for path in candidates:
386
+ if path.is_file():
387
+ return path
388
+ raise FileNotFoundError(
389
+ f"No INCYDE labels CSV under {root}. This loader does not download imagery."
390
+ )
391
+
392
+
393
+ def locate_image(root: Path, filename: str) -> Path:
394
+ name = Path(filename).name
395
+ candidates = [
396
+ root / name,
397
+ root / "Cropped_cyclone_images" / name,
398
+ root / "Cropped_cyclone_data" / "Cropped_cyclone_images" / name,
399
+ root / "Cropped_cyclone_data" / name,
400
+ ]
401
+ for path in candidates:
402
+ if path.is_file():
403
+ return path
404
+ raise FileNotFoundError(
405
+ f"INCYDE image {name} is missing under {root}. This loader does not download imagery."
406
+ )
407
+
408
+
409
+ def _qc_tokens(flag: object) -> set[str]:
410
+ text = "" if flag is None or (isinstance(flag, float) and np.isnan(flag)) else str(flag)
411
+ return {part.strip() for part in text.split(";") if part.strip()}
412
+
413
+
414
+ def _drop_reason(aug: str, exclude: bool, qc_flag: str, drop_qc_flags: set[str]) -> str | None:
415
+ if exclude:
416
+ return "default_exclude"
417
+ if aug in DROPPED_AUG:
418
+ return f"dropped aug {aug}"
419
+ if aug not in KEPT_AUG:
420
+ return f"unknown aug {aug or 'blank'}"
421
+ if drop_qc_flags and _qc_tokens(qc_flag) & drop_qc_flags:
422
+ return "drop_qc_flags"
423
+ return None
424
+
425
+
426
+ def read_rows(
427
+ root: str | Path,
428
+ *,
429
+ manifest_csv: str | Path | None = None,
430
+ storm_split_csv: str | Path | None = None,
431
+ exclusions_csv: str | Path | None = None,
432
+ frame_flags_csv: str | Path | None = None,
433
+ drop_qc_flags: list[str] | tuple[str, ...] | None = None,
434
+ check_images: bool = True,
435
+ ) -> tuple[pd.DataFrame, int]:
436
+ """Frame rows before the final split. ``rot_180`` is still present.
437
+
438
+ Flips, ``rot_90``, ``rot_270``, and ``default_exclude`` rows are gone.
439
+ The returned count is how many source rows were dropped here.
440
+ """
441
+ root = Path(root)
442
+ if not root.is_dir():
443
+ raise FileNotFoundError(
444
+ f"INCYDE root {root} is missing. Set paths.incyde_root to the extracted "
445
+ "Cropped_cyclone_data directory. This entrypoint does not download imagery."
446
+ )
447
+ label_path = Path(manifest_csv) if manifest_csv not in (None, "", "null") else _locate_labels(root)
448
+ if not label_path.is_file():
449
+ raise FileNotFoundError(f"INCYDE manifest {label_path} is missing. Nothing is downloaded.")
450
+ storms = read_storm_split(storm_split_csv)
451
+ exclusions = read_exclusions(exclusions_csv)
452
+ source = _source_table(pd.read_csv(label_path, encoding="utf-8-sig"))
453
+ parsed = [parse_filename(name) for name in source["filename"].tolist()]
454
+ parsed_frame = pd.DataFrame(parsed).drop(columns=["filename"])
455
+ work = pd.concat([source.reset_index(drop=True), parsed_frame], axis=1)
456
+ work["filename"] = work["filename"].map(lambda name: Path(str(name)).name)
457
+ by_sequence = storms.set_index("Sequence")
458
+ by_storm = storms.drop_duplicates("storm_id").set_index("storm_id")
459
+ storm_ids: list[str] = []
460
+ sequences: list[int] = []
461
+ proposed: list[str] = []
462
+ groups: list[int] = []
463
+ names: list[str] = []
464
+ basins: list[str] = []
465
+ for sequence, given in zip(work["sequence"].tolist(), work["given_storm_id"].tolist(), strict=True):
466
+ row = None
467
+ if pd.notna(sequence) and int(sequence) in by_sequence.index:
468
+ row = by_sequence.loc[int(sequence)]
469
+ elif isinstance(given, str) and given in by_storm.index:
470
+ row = by_storm.loc[given]
471
+ if row is None:
472
+ raise ValueError(f"no storm_split row for sequence {sequence!r} storm {given!r}")
473
+ if isinstance(row, pd.DataFrame):
474
+ raise ValueError(f"storm_split matched more than one row for sequence {sequence}")
475
+ storm_id = str(row["storm_id"]) if "storm_id" in row.index else str(row.name)
476
+ sequence_id = int(row["Sequence"]) if "Sequence" in row.index else int(row.name)
477
+ if isinstance(given, str) and given not in {"", "nan", "<NA>"} and given != storm_id:
478
+ raise ValueError(f"manifest storm_id {given} does not match storm_split.csv ({storm_id})")
479
+ storm_ids.append(storm_id)
480
+ sequences.append(sequence_id)
481
+ proposed.append(str(row["proposed_split"]))
482
+ groups.append(int(row["cooccurrence_group"]))
483
+ names.append("" if "name" not in row.index or pd.isna(row["name"]) else str(row["name"]))
484
+ basins.append("" if "basin" not in row.index or pd.isna(row["basin"]) else str(row["basin"]))
485
+ work["storm_id"] = storm_ids
486
+ work["sequence"] = sequences
487
+ work["proposed_split"] = proposed
488
+ work["cooccurrence_group"] = groups
489
+ work["name"] = names
490
+ work["basin"] = basins
491
+ qc = exclusions.set_index("filename")
492
+ flags = []
493
+ exclude = []
494
+ for filename in work["filename"].tolist():
495
+ if filename in qc.index:
496
+ flags.append(str(qc.at[filename, "qc_flag"]))
497
+ exclude.append(bool(qc.at[filename, "default_exclude"]))
498
+ else:
499
+ flags.append("")
500
+ exclude.append(False)
501
+ work["qc_flag"] = flags
502
+ drop_flags = {str(flag).strip() for flag in (drop_qc_flags or []) if str(flag).strip()}
503
+ reasons = [
504
+ _drop_reason(aug, dropped, flag, drop_flags)
505
+ for aug, dropped, flag in zip(work["aug_type"], exclude, work["qc_flag"], strict=True)
506
+ ]
507
+ dropped_count = sum(reason is not None for reason in reasons)
508
+ kept = work.loc[[reason is None for reason in reasons]].reset_index(drop=True)
509
+ if kept.empty:
510
+ raise ValueError("INCYDE filters removed every row")
511
+ if kept["filename"].duplicated().any():
512
+ raise ValueError("INCYDE labels repeat a filename")
513
+ years = assert_one_storm_year(kept)
514
+ image_paths: list[str] = []
515
+ heights: list[int] = []
516
+ widths: list[int] = []
517
+ if check_images:
518
+ from PIL import Image
519
+
520
+ for filename in kept["filename"].tolist():
521
+ path = locate_image(root, filename)
522
+ image_paths.append(path.resolve().as_posix())
523
+ with Image.open(path) as image:
524
+ widths.append(int(image.width))
525
+ heights.append(int(image.height))
526
+ else:
527
+ image_paths = kept["filename"].tolist()
528
+ heights = [0] * len(kept)
529
+ widths = [0] * len(kept)
530
+ frame = pd.DataFrame(
531
+ {
532
+ "sample_id": [Path(name).stem for name in kept["filename"].tolist()],
533
+ "image_path": image_paths,
534
+ "storm_id": kept["storm_id"].astype(str),
535
+ "wind_speed_kt": kept["wind_kt"].to_numpy(dtype=float),
536
+ "wind_kt": kept["wind_kt"].to_numpy(dtype=float),
537
+ "wind_averaging": WIND_AVERAGING,
538
+ "wind_averaging_s": WIND_AVERAGING_S,
539
+ "is_synthetic": [aug == "rot_180" for aug in kept["aug_type"].tolist()],
540
+ "imd_class": [imd_class_of(wind) for wind in kept["wind_kt"].tolist()],
541
+ "split": kept["proposed_split"].astype(str),
542
+ "proposed_split": kept["proposed_split"].astype(str),
543
+ "cooccurrence_group": kept["cooccurrence_group"].astype(int),
544
+ "time_utc": kept["time_utc"].astype(str),
545
+ "time_ist": kept["time_ist"].astype(str),
546
+ "storm_year": years.to_numpy(dtype=int),
547
+ "aug_type": kept["aug_type"].astype(str),
548
+ "source_frame_id": kept["source_frame_id"].astype(str),
549
+ "object_index": kept["object_index"].astype(int),
550
+ "qc_flag": kept["qc_flag"].astype(str),
551
+ "incyde_sequence": kept["sequence"].astype(int),
552
+ "incyde_set": kept["incyde_set"].astype(str),
553
+ "source_category": kept["source_category"].astype(str),
554
+ "name": kept["name"].astype(str),
555
+ "basin": kept["basin"].astype(str),
556
+ "native_height": heights,
557
+ "native_width": widths,
558
+ "orig_size": [height if height == width else -1 for height, width in zip(heights, widths, strict=True)],
559
+ "sensor": "INSAT-3D",
560
+ "channel": "IR",
561
+ "pixel_units": "jpeg_uncalibrated",
562
+ "label_source": "incyde_imd_3min",
563
+ "center_source": "dataset_precentered",
564
+ }
565
+ )
566
+ # Join after the row filter so dropped augs are not looked up. The
567
+ # source filename is the key; unknown audit cells stay unknown.
568
+ flagged = attach_frame_flags(frame, read_frame_flags(frame_flags_csv))
569
+ return require_valid(flagged), int(dropped_count)
570
+
571
+
572
+ def build_cv_folds(storms: pd.DataFrame, n_folds: int, seed: int) -> pd.DataFrame:
573
+ """Storm-grouped folds over train+val only. Test storms are absent.
574
+
575
+ Groups are shuffled with ``seed`` and dealt round-robin, so every storm
576
+ in one ``cooccurrence_group`` shares a fold. The training path passes
577
+ ``incyde.cv_seed`` (42 in the YAML).
578
+ """
579
+ folds = int(n_folds)
580
+ if folds < 2:
581
+ raise ValueError("incyde.n_folds must be at least 2")
582
+ pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
583
+ if pool.empty:
584
+ raise ValueError("storm_cv needs train and val storms")
585
+ groups = sorted({int(group) for group in pool["cooccurrence_group"].tolist()})
586
+ order = np.random.default_rng(int(seed)).permutation(len(groups))
587
+ shuffled = [groups[int(index)] for index in order]
588
+ group_fold = {group: index % folds for index, group in enumerate(shuffled)}
589
+ out = pd.DataFrame(
590
+ {
591
+ "storm_id": pool["storm_id"].astype(str).tolist(),
592
+ "fold": [int(group_fold[int(group)]) for group in pool["cooccurrence_group"].tolist()],
593
+ }
594
+ )
595
+ return out.sort_values(["fold", "storm_id"]).reset_index(drop=True)
596
+
597
+
598
+ def read_cv_folds(path: str | Path) -> pd.DataFrame:
599
+ """Use a folds file verbatim. Columns are ``storm_id`` and ``fold``."""
600
+ table = pd.read_csv(path)
601
+ table.columns = [str(column).strip() for column in table.columns]
602
+ if "storm_id" not in table.columns or "fold" not in table.columns:
603
+ raise ValueError("cv folds csv needs columns storm_id and fold")
604
+ out = pd.DataFrame(
605
+ {
606
+ "storm_id": table["storm_id"].astype(str).str.strip(),
607
+ "fold": pd.to_numeric(table["fold"], errors="raise").astype(int),
608
+ }
609
+ )
610
+ if out["storm_id"].duplicated().any():
611
+ raise ValueError("cv folds csv repeats a storm_id")
612
+ return out.reset_index(drop=True)
613
+
614
+
615
+ def validate_cv_folds(folds: pd.DataFrame, storms: pd.DataFrame) -> None:
616
+ """No test storm, and no cooccurrence group spread across folds."""
617
+ test_ids = set(storms.loc[storms["proposed_split"].astype(str) == "test", "storm_id"].astype(str))
618
+ listed = set(folds["storm_id"].astype(str))
619
+ leaked = sorted(listed & test_ids)
620
+ if leaked:
621
+ raise LeakageError(f"cv folds include test storms {leaked[:8]}")
622
+ pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
623
+ pool_ids = set(pool["storm_id"].astype(str))
624
+ missing = sorted(pool_ids - listed)
625
+ extra = sorted(listed - pool_ids)
626
+ if missing:
627
+ raise ValueError(f"cv folds omit train/val storms {missing[:8]}")
628
+ if extra:
629
+ raise ValueError(f"cv folds name storms that are not train/val {extra[:8]}")
630
+ merged = pool.assign(storm_id=pool["storm_id"].astype(str)).merge(folds, on="storm_id", how="left")
631
+ spread = merged.groupby("cooccurrence_group")["fold"].nunique()
632
+ if bool((spread > 1).any()):
633
+ groups = [int(group) for group in spread.index[spread > 1].tolist()]
634
+ raise LeakageError(f"cooccurrence_group spans folds {groups[:8]}")
635
+
636
+
637
+ def _folds_for(storms: pd.DataFrame, n_folds: int, seed: int, cv_folds_csv: str | Path | None) -> pd.DataFrame:
638
+ if cv_folds_csv not in (None, "", "null"):
639
+ folds = read_cv_folds(cv_folds_csv)
640
+ else:
641
+ folds = build_cv_folds(storms, n_folds, seed)
642
+ validate_cv_folds(folds, storms)
643
+ return folds
644
+
645
+
646
+ def _assert_storms(frame: pd.DataFrame) -> None:
647
+ per_storm = frame.groupby(frame["storm_id"].astype(str))["split"].nunique()
648
+ if bool((per_storm > 1).any()):
649
+ raise LeakageError("a storm is in more than one split")
650
+ synthetic = frame["is_synthetic"].astype(bool) & frame["split"].astype(str).ne("train")
651
+ if bool(synthetic.any()):
652
+ raise LeakageError("synthetic INCYDE rows are train-only")
653
+ bad_aug = sorted(set(frame["aug_type"].astype(str)) - KEPT_AUG)
654
+ if bad_aug:
655
+ raise LeakageError(f"INCYDE kept dropped augmentations {bad_aug}")
656
+
657
+
658
+ def _assert_groups(frame: pd.DataFrame) -> None:
659
+ spread = frame.groupby("cooccurrence_group")["split"].nunique()
660
+ if bool((spread > 1).any()):
661
+ raise LeakageError("a cooccurrence_group is in more than one split")
662
+
663
+
664
+ def assign_incyde_split(
665
+ frame: pd.DataFrame,
666
+ strategy: str,
667
+ *,
668
+ n_folds: int = 5,
669
+ cv_val_fold: int = 0,
670
+ cv_seed: int = CV_SEED,
671
+ cv_folds_csv: str | Path | None = None,
672
+ ) -> tuple[pd.DataFrame, int]:
673
+ """Write ``split`` and drop synthetic rows that are not in train.
674
+
675
+ ``storm_wise`` uses ``proposed_split`` (60/14/17 on the audit file).
676
+ ``storm_cv`` keeps test storms out of the folds. ``year_holdout_2019``
677
+ puts 2019 in test and 2021 in val. The year comes from ``storm_id``.
678
+ """
679
+ name = str(strategy).strip().lower()
680
+ work = frame.copy()
681
+ if "proposed_split" not in work.columns:
682
+ raise ValueError("INCYDE rows need proposed_split from storm_split.csv")
683
+ storms = work.groupby("storm_id", as_index=False).agg(
684
+ proposed_split=("proposed_split", "first"),
685
+ cooccurrence_group=("cooccurrence_group", "first"),
686
+ )
687
+ assert_one_storm_year(work)
688
+ if name in {"storm_wise", "proposed", "bean"}:
689
+ work["split"] = work["proposed_split"].astype(str)
690
+ _assert_groups(work)
691
+ elif name == "storm_cv":
692
+ using_file = cv_folds_csv not in (None, "", "null")
693
+ folds = _folds_for(storms, n_folds, cv_seed, cv_folds_csv)
694
+ chosen = int(cv_val_fold)
695
+ if not using_file and (chosen < 0 or chosen >= int(n_folds)):
696
+ raise ValueError("incyde.cv_val_fold is outside 0 .. n_folds-1")
697
+ fold_of = dict(zip(folds["storm_id"].astype(str), folds["fold"].astype(int), strict=True))
698
+ splits = []
699
+ for storm_id, proposed in zip(work["storm_id"].astype(str), work["proposed_split"].astype(str), strict=True):
700
+ if proposed == "test":
701
+ splits.append("test")
702
+ else:
703
+ splits.append("val" if fold_of[storm_id] == chosen else "train")
704
+ work["split"] = splits
705
+ work["cv_fold"] = work["storm_id"].astype(str).map(lambda storm_id: fold_of.get(storm_id, pd.NA))
706
+ _assert_groups(work)
707
+ elif name == "year_holdout_2019":
708
+ years = work["storm_id"].map(storm_year)
709
+ work["split"] = np.where(years.eq(2019), "test", np.where(years.eq(2021), "val", "train"))
710
+ else:
711
+ raise LeakageError(f"unknown INCYDE split strategy {strategy}")
712
+ synthetic_eval = work["is_synthetic"].astype(bool) & work["split"].astype(str).ne("train")
713
+ dropped = int(synthetic_eval.sum())
714
+ work = work.loc[~synthetic_eval].reset_index(drop=True)
715
+ _assert_storms(work)
716
+ for split_name in ("train", "val", "test"):
717
+ if split_name not in set(work["split"].astype(str)):
718
+ raise LeakageError(f"INCYDE split {name} produced no {split_name} rows")
719
+ return work, dropped
720
+
721
+
722
+ def load_frame(config: dict) -> tuple[pd.DataFrame, int]:
723
+ """Rows for ``python -m src.train --dataset incyde``. Nothing is downloaded."""
724
+ paths = config["paths"]
725
+ block = config["incyde"]
726
+ archive = block["archive"]
727
+ if archive not in (None, "", "null"):
728
+ assert_archive_md5(archive)
729
+ frame, dropped = read_rows(
730
+ paths["incyde_root"],
731
+ manifest_csv=block["manifest_csv"],
732
+ storm_split_csv=block["storm_split_csv"],
733
+ exclusions_csv=block["exclusions_csv"],
734
+ frame_flags_csv=block.get("frame_flags_csv"),
735
+ drop_qc_flags=list(block["drop_qc_flags"] or []),
736
+ check_images=True,
737
+ )
738
+ assigned, synthetic_dropped = assign_incyde_split(
739
+ frame,
740
+ str(config["split"]["strategy"]),
741
+ n_folds=int(block["n_folds"]),
742
+ cv_val_fold=int(block["cv_val_fold"]),
743
+ cv_seed=int(block["cv_seed"]),
744
+ cv_folds_csv=block["cv_folds_csv"],
745
+ )
746
+ return assigned, int(dropped) + int(synthetic_dropped)
747
+
748
+
749
+ def main(argv: list[str] | None = None) -> Path:
750
+ """Write a manifest from a local extracted tree. Does not download."""
751
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
752
+ parser.add_argument("--root", type=Path, required=True)
753
+ parser.add_argument("--manifest-csv", type=Path, default=None)
754
+ parser.add_argument("--storm-split", type=Path, default=None)
755
+ parser.add_argument("--exclusions", type=Path, default=None)
756
+ parser.add_argument("--frame-flags", type=Path, default=None)
757
+ parser.add_argument("--out", type=Path, required=True)
758
+ parser.add_argument("--strategy", default="storm_wise")
759
+ parser.add_argument("--archive", type=Path, default=None)
760
+ args = parser.parse_args(argv)
761
+ if args.archive is not None:
762
+ assert_archive_md5(args.archive)
763
+ frame, dropped = read_rows(
764
+ args.root,
765
+ manifest_csv=args.manifest_csv,
766
+ storm_split_csv=args.storm_split,
767
+ exclusions_csv=args.exclusions,
768
+ frame_flags_csv=args.frame_flags,
769
+ )
770
+ assigned, synthetic_dropped = assign_incyde_split(frame, args.strategy)
771
+ args.out.parent.mkdir(parents=True, exist_ok=True)
772
+ assigned.to_csv(args.out, index=False)
773
+ print(f"Wrote {args.out} ({len(assigned)} rows, dropped {dropped + synthetic_dropped}). Not a forecast.")
774
+ return args.out
775
+
776
+
777
+ if __name__ == "__main__":
778
+ main()
src/inference.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/labels.py CHANGED
@@ -1,216 +1,216 @@
1
- """IMD 3-minute wind target.
2
-
3
- NASA and TCIR labels are 1-minute sustained winds. INCYDE labels are already
4
- IMD 3-minute winds. The training target is ``wind_kt_3min``. Raw knots stay
5
- on ``wind_speed_kt`` and ``wind_kt``.
6
-
7
- The 1-minute to 3-minute factor is ``labels.wind_1min_to_3min`` (0.93 in the
8
- YAML). It is a derived at-sea gust factor from WMO/TD-1555 Tables 1.1 and
9
- 1.2 (Harper, Kepert and Ginger 2010), not a WMO constant, and it is meant
10
- for open water more than 20 km offshore. This module does not download a
11
- coastline. A dataset with no land indicator is marked unknown.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import math
17
-
18
- import numpy as np
19
- import pandas as pd
20
-
21
- from src.schema import wind_averaging_seconds
22
-
23
- # Citation for the default factor. The numeric factor itself lives in the YAML.
24
- WIND_CONVERSION_NOTE = (
25
- "0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
26
- "at-sea exposure (not a WMO constant)"
27
- )
28
- HELD_RAW_NOTE = "held raw: near land, at-sea factor not applied"
29
- NEAR_LAND_POLICIES = ("flag", "raw")
30
-
31
-
32
- def conversion_note(factor: float) -> str:
33
- """Provenance string for a row whose 1-minute wind was multiplied.
34
-
35
- The default factor of 0.93 uses the citation verbatim. Any other
36
- configured factor keeps the same source and names that factor.
37
- """
38
- if not math.isfinite(factor) or factor <= 0:
39
- raise ValueError("wind factor must be a positive finite number")
40
- if f"{float(factor):.2f}" == "0.93":
41
- return WIND_CONVERSION_NOTE
42
- return (
43
- f"{float(factor):.2f}, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
44
- "at-sea exposure (not a WMO constant)"
45
- )
46
-
47
-
48
- def _blank(value: object) -> bool:
49
- if value is None:
50
- return True
51
- try:
52
- if pd.isna(value):
53
- return True
54
- except (TypeError, ValueError):
55
- return False
56
- return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
57
-
58
-
59
- def _flag(value: object) -> str:
60
- """``true``, ``false``, or ``unknown``."""
61
- if isinstance(value, (bool, np.bool_)):
62
- return "true" if bool(value) else "false"
63
- if _blank(value):
64
- return "unknown"
65
- text = str(value).strip().lower()
66
- if text in {"1", "true", "yes", "y", "t"}:
67
- return "true"
68
- if text in {"0", "false", "no", "n", "f"}:
69
- return "false"
70
- if text in {"unknown", "na", "n/a"}:
71
- return "unknown"
72
- raise ValueError(f"land indicator {value!r} is not true, false, or unknown")
73
-
74
-
75
- def near_land_status(frame: pd.DataFrame, open_water_km: float) -> pd.Series:
76
- """Per-row near-land status: ``true``, ``false``, or ``unknown``.
77
-
78
- ``distance_to_land_km`` is the quantitative indicator. Open water is
79
- strictly farther than ``open_water_km`` (20 km in the YAML). A
80
- ``near_land`` or ``landfall`` column is used when there is no distance.
81
- Latitude and longitude are not a land indicator. With none of those
82
- columns the whole frame is unknown.
83
- """
84
- if open_water_km < 0 or not math.isfinite(open_water_km):
85
- raise ValueError("open_water_km must be a non-negative finite distance")
86
- if "distance_to_land_km" in frame.columns:
87
- distance = pd.to_numeric(frame["distance_to_land_km"], errors="coerce")
88
- status = np.where(
89
- distance.isna(),
90
- "unknown",
91
- np.where(distance > float(open_water_km), "false", "true"),
92
- )
93
- return pd.Series(status, index=frame.index, dtype=object)
94
- if "near_land" in frame.columns:
95
- return pd.Series(
96
- [_flag(value) for value in frame["near_land"].tolist()],
97
- index=frame.index,
98
- dtype=object,
99
- )
100
- if "landfall" in frame.columns:
101
- return pd.Series(
102
- [_flag(value) for value in frame["landfall"].tolist()],
103
- index=frame.index,
104
- dtype=object,
105
- )
106
- return pd.Series("unknown", index=frame.index, dtype=object)
107
-
108
-
109
- def _raw_knots(frame: pd.DataFrame) -> pd.Series:
110
- if "wind_speed_kt" not in frame.columns and "wind_kt" not in frame.columns:
111
- raise ValueError("a wind row needs wind_speed_kt or wind_kt")
112
- if "wind_speed_kt" in frame.columns and "wind_kt" in frame.columns:
113
- left = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
114
- right = pd.to_numeric(frame["wind_kt"], errors="coerce")
115
- if not np.allclose(left.to_numpy(dtype=float), right.to_numpy(dtype=float), equal_nan=True):
116
- raise ValueError("wind_kt and wind_speed_kt disagree; refusing to convert either")
117
- return left
118
- column = "wind_speed_kt" if "wind_speed_kt" in frame.columns else "wind_kt"
119
- return pd.to_numeric(frame[column], errors="coerce")
120
-
121
-
122
- def apply_wind_standard(
123
- frame: pd.DataFrame,
124
- *,
125
- factor: float,
126
- policy: str,
127
- open_water_km: float,
128
- ) -> pd.DataFrame:
129
- """Add ``wind_kt_3min`` without overwriting the raw label.
130
-
131
- 3-minute rows, including INCYDE, pass through (``wind_kt_3min == wind_kt``).
132
- 1-minute rows are multiplied by ``factor`` unless ``policy`` is ``raw``
133
- and the row is near land. ``flag`` (the default) still multiplies those
134
- rows and sets ``conversion_exposure_flag`` true. Unknown exposure is
135
- converted and the flag stays ``unknown``, so the at-sea factor is not
136
- recorded as an open-water measurement.
137
- """
138
- choice = str(policy).strip().lower()
139
- if choice not in NEAR_LAND_POLICIES:
140
- raise ValueError("labels.near_land_policy must be flag or raw")
141
- note = conversion_note(factor)
142
- if "wind_averaging" not in frame.columns:
143
- raise ValueError("wind_averaging is required before the 3-minute target is added")
144
- raw = _raw_knots(frame).to_numpy(dtype=float)
145
- status = near_land_status(frame, open_water_km).tolist()
146
- periods = [str(value).strip() for value in frame["wind_averaging"].tolist()]
147
- target = np.empty(len(frame), dtype=float)
148
- scale = np.empty(len(frame), dtype=float)
149
- notes: list[str] = []
150
- flags: list[str] = []
151
- seconds: list[int | None] = []
152
- for index, (period, land) in enumerate(zip(periods, status, strict=True)):
153
- duration = wind_averaging_seconds(period)
154
- seconds.append(duration)
155
- if duration == 60:
156
- hold = land == "true" and choice == "raw"
157
- if hold:
158
- target[index] = raw[index]
159
- scale[index] = 1.0
160
- notes.append(HELD_RAW_NOTE)
161
- flags.append("true")
162
- else:
163
- target[index] = raw[index] * float(factor)
164
- scale[index] = float(factor)
165
- notes.append(note)
166
- flags.append(land)
167
- else:
168
- target[index] = raw[index]
169
- scale[index] = 1.0
170
- notes.append("")
171
- flags.append("")
172
- out = frame.copy()
173
- out["wind_speed_kt"] = raw
174
- out["wind_kt"] = raw
175
- out["wind_kt_3min"] = target
176
- out["wind_kt_scale"] = scale
177
- out["wind_conversion"] = notes
178
- out["conversion_exposure_flag"] = flags
179
- out["near_land"] = status
180
- out["wind_averaging_s"] = pd.array(seconds, dtype="Int64")
181
- return out
182
-
183
-
184
- def run_conversion_note(frame: pd.DataFrame) -> str | None:
185
- """The single conversion note on this frame, or null when nothing was scaled."""
186
- if "wind_conversion" not in frame.columns or frame.empty:
187
- return None
188
- notes = []
189
- for value in frame["wind_conversion"].tolist():
190
- if _blank(value):
191
- continue
192
- text = str(value).strip()
193
- if text.lower() in {"nan", "none", "null"}:
194
- continue
195
- notes.append(text)
196
- notes = sorted(set(notes))
197
- if not notes:
198
- return None
199
- if len(notes) == 1:
200
- return notes[0]
201
- return " | ".join(notes)
202
-
203
-
204
- def back_converted_prediction(prediction: np.ndarray, scale: np.ndarray) -> np.ndarray:
205
- """Map a 3-minute prediction back to the raw label.
206
-
207
- Converted 1-minute rows use ``prediction / factor``. Pass-through rows
208
- have scale 1. Near-land rows held at the raw label also have scale 1.
209
- """
210
- pred = np.asarray(prediction, dtype=np.float64).reshape(-1)
211
- weights = np.asarray(scale, dtype=np.float64).reshape(-1)
212
- if pred.shape != weights.shape:
213
- raise ValueError("prediction and wind_kt_scale must have the same length")
214
- if weights.size and (not np.isfinite(weights).all() or np.any(weights <= 0)):
215
- raise ValueError("wind_kt_scale must be a positive finite multiplier")
216
- return pred / weights
 
1
+ """IMD 3-minute wind target.
2
+
3
+ NASA and TCIR labels are 1-minute sustained winds. INCYDE labels are already
4
+ IMD 3-minute winds. The training target is ``wind_kt_3min``. Raw knots stay
5
+ on ``wind_speed_kt`` and ``wind_kt``.
6
+
7
+ The 1-minute to 3-minute factor is ``labels.wind_1min_to_3min`` (0.93 in the
8
+ YAML). It is a derived at-sea gust factor from WMO/TD-1555 Tables 1.1 and
9
+ 1.2 (Harper, Kepert and Ginger 2010), not a WMO constant, and it is meant
10
+ for open water more than 20 km offshore. This module does not download a
11
+ coastline. A dataset with no land indicator is marked unknown.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from src.schema import wind_averaging_seconds
22
+
23
+ # Citation for the default factor. The numeric factor itself lives in the YAML.
24
+ WIND_CONVERSION_NOTE = (
25
+ "0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
26
+ "at-sea exposure (not a WMO constant)"
27
+ )
28
+ HELD_RAW_NOTE = "held raw: near land, at-sea factor not applied"
29
+ NEAR_LAND_POLICIES = ("flag", "raw")
30
+
31
+
32
+ def conversion_note(factor: float) -> str:
33
+ """Provenance string for a row whose 1-minute wind was multiplied.
34
+
35
+ The default factor of 0.93 uses the citation verbatim. Any other
36
+ configured factor keeps the same source and names that factor.
37
+ """
38
+ if not math.isfinite(factor) or factor <= 0:
39
+ raise ValueError("wind factor must be a positive finite number")
40
+ if f"{float(factor):.2f}" == "0.93":
41
+ return WIND_CONVERSION_NOTE
42
+ return (
43
+ f"{float(factor):.2f}, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
44
+ "at-sea exposure (not a WMO constant)"
45
+ )
46
+
47
+
48
+ def _blank(value: object) -> bool:
49
+ if value is None:
50
+ return True
51
+ try:
52
+ if pd.isna(value):
53
+ return True
54
+ except (TypeError, ValueError):
55
+ return False
56
+ return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
57
+
58
+
59
+ def _flag(value: object) -> str:
60
+ """``true``, ``false``, or ``unknown``."""
61
+ if isinstance(value, (bool, np.bool_)):
62
+ return "true" if bool(value) else "false"
63
+ if _blank(value):
64
+ return "unknown"
65
+ text = str(value).strip().lower()
66
+ if text in {"1", "true", "yes", "y", "t"}:
67
+ return "true"
68
+ if text in {"0", "false", "no", "n", "f"}:
69
+ return "false"
70
+ if text in {"unknown", "na", "n/a"}:
71
+ return "unknown"
72
+ raise ValueError(f"land indicator {value!r} is not true, false, or unknown")
73
+
74
+
75
+ def near_land_status(frame: pd.DataFrame, open_water_km: float) -> pd.Series:
76
+ """Per-row near-land status: ``true``, ``false``, or ``unknown``.
77
+
78
+ ``distance_to_land_km`` is the quantitative indicator. Open water is
79
+ strictly farther than ``open_water_km`` (20 km in the YAML). A
80
+ ``near_land`` or ``landfall`` column is used when there is no distance.
81
+ Latitude and longitude are not a land indicator. With none of those
82
+ columns the whole frame is unknown.
83
+ """
84
+ if open_water_km < 0 or not math.isfinite(open_water_km):
85
+ raise ValueError("open_water_km must be a non-negative finite distance")
86
+ if "distance_to_land_km" in frame.columns:
87
+ distance = pd.to_numeric(frame["distance_to_land_km"], errors="coerce")
88
+ status = np.where(
89
+ distance.isna(),
90
+ "unknown",
91
+ np.where(distance > float(open_water_km), "false", "true"),
92
+ )
93
+ return pd.Series(status, index=frame.index, dtype=object)
94
+ if "near_land" in frame.columns:
95
+ return pd.Series(
96
+ [_flag(value) for value in frame["near_land"].tolist()],
97
+ index=frame.index,
98
+ dtype=object,
99
+ )
100
+ if "landfall" in frame.columns:
101
+ return pd.Series(
102
+ [_flag(value) for value in frame["landfall"].tolist()],
103
+ index=frame.index,
104
+ dtype=object,
105
+ )
106
+ return pd.Series("unknown", index=frame.index, dtype=object)
107
+
108
+
109
+ def _raw_knots(frame: pd.DataFrame) -> pd.Series:
110
+ if "wind_speed_kt" not in frame.columns and "wind_kt" not in frame.columns:
111
+ raise ValueError("a wind row needs wind_speed_kt or wind_kt")
112
+ if "wind_speed_kt" in frame.columns and "wind_kt" in frame.columns:
113
+ left = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
114
+ right = pd.to_numeric(frame["wind_kt"], errors="coerce")
115
+ if not np.allclose(left.to_numpy(dtype=float), right.to_numpy(dtype=float), equal_nan=True):
116
+ raise ValueError("wind_kt and wind_speed_kt disagree; refusing to convert either")
117
+ return left
118
+ column = "wind_speed_kt" if "wind_speed_kt" in frame.columns else "wind_kt"
119
+ return pd.to_numeric(frame[column], errors="coerce")
120
+
121
+
122
+ def apply_wind_standard(
123
+ frame: pd.DataFrame,
124
+ *,
125
+ factor: float,
126
+ policy: str,
127
+ open_water_km: float,
128
+ ) -> pd.DataFrame:
129
+ """Add ``wind_kt_3min`` without overwriting the raw label.
130
+
131
+ 3-minute rows, including INCYDE, pass through (``wind_kt_3min == wind_kt``).
132
+ 1-minute rows are multiplied by ``factor`` unless ``policy`` is ``raw``
133
+ and the row is near land. ``flag`` (the default) still multiplies those
134
+ rows and sets ``conversion_exposure_flag`` true. Unknown exposure is
135
+ converted and the flag stays ``unknown``, so the at-sea factor is not
136
+ recorded as an open-water measurement.
137
+ """
138
+ choice = str(policy).strip().lower()
139
+ if choice not in NEAR_LAND_POLICIES:
140
+ raise ValueError("labels.near_land_policy must be flag or raw")
141
+ note = conversion_note(factor)
142
+ if "wind_averaging" not in frame.columns:
143
+ raise ValueError("wind_averaging is required before the 3-minute target is added")
144
+ raw = _raw_knots(frame).to_numpy(dtype=float)
145
+ status = near_land_status(frame, open_water_km).tolist()
146
+ periods = [str(value).strip() for value in frame["wind_averaging"].tolist()]
147
+ target = np.empty(len(frame), dtype=float)
148
+ scale = np.empty(len(frame), dtype=float)
149
+ notes: list[str] = []
150
+ flags: list[str] = []
151
+ seconds: list[int | None] = []
152
+ for index, (period, land) in enumerate(zip(periods, status, strict=True)):
153
+ duration = wind_averaging_seconds(period)
154
+ seconds.append(duration)
155
+ if duration == 60:
156
+ hold = land == "true" and choice == "raw"
157
+ if hold:
158
+ target[index] = raw[index]
159
+ scale[index] = 1.0
160
+ notes.append(HELD_RAW_NOTE)
161
+ flags.append("true")
162
+ else:
163
+ target[index] = raw[index] * float(factor)
164
+ scale[index] = float(factor)
165
+ notes.append(note)
166
+ flags.append(land)
167
+ else:
168
+ target[index] = raw[index]
169
+ scale[index] = 1.0
170
+ notes.append("")
171
+ flags.append("")
172
+ out = frame.copy()
173
+ out["wind_speed_kt"] = raw
174
+ out["wind_kt"] = raw
175
+ out["wind_kt_3min"] = target
176
+ out["wind_kt_scale"] = scale
177
+ out["wind_conversion"] = notes
178
+ out["conversion_exposure_flag"] = flags
179
+ out["near_land"] = status
180
+ out["wind_averaging_s"] = pd.array(seconds, dtype="Int64")
181
+ return out
182
+
183
+
184
+ def run_conversion_note(frame: pd.DataFrame) -> str | None:
185
+ """The single conversion note on this frame, or null when nothing was scaled."""
186
+ if "wind_conversion" not in frame.columns or frame.empty:
187
+ return None
188
+ notes = []
189
+ for value in frame["wind_conversion"].tolist():
190
+ if _blank(value):
191
+ continue
192
+ text = str(value).strip()
193
+ if text.lower() in {"nan", "none", "null"}:
194
+ continue
195
+ notes.append(text)
196
+ notes = sorted(set(notes))
197
+ if not notes:
198
+ return None
199
+ if len(notes) == 1:
200
+ return notes[0]
201
+ return " | ".join(notes)
202
+
203
+
204
+ def back_converted_prediction(prediction: np.ndarray, scale: np.ndarray) -> np.ndarray:
205
+ """Map a 3-minute prediction back to the raw label.
206
+
207
+ Converted 1-minute rows use ``prediction / factor``. Pass-through rows
208
+ have scale 1. Near-land rows held at the raw label also have scale 1.
209
+ """
210
+ pred = np.asarray(prediction, dtype=np.float64).reshape(-1)
211
+ weights = np.asarray(scale, dtype=np.float64).reshape(-1)
212
+ if pred.shape != weights.shape:
213
+ raise ValueError("prediction and wind_kt_scale must have the same length")
214
+ if weights.size and (not np.isfinite(weights).all() or np.any(weights <= 0)):
215
+ raise ValueError("wind_kt_scale must be a positive finite multiplier")
216
+ return pred / weights
src/make_smoke_data.py CHANGED
@@ -1,153 +1,153 @@
1
- """Synthetic images for software tests. These are not cyclones."""
2
-
3
- from __future__ import annotations
4
-
5
- import argparse
6
- from pathlib import Path
7
-
8
- import numpy as np
9
- import pandas as pd
10
-
11
- # Project-class winds that stay inside the bin when a few knots are added.
12
- CLASS_WINDS = (
13
- ("D_DD", 26.0),
14
- ("CS", 40.0),
15
- ("SCS", 55.0),
16
- ("VSCS", 75.0),
17
- ("ESCS_SUCS", 105.0),
18
- )
19
-
20
-
21
- def _synthetic_ir(size: int, wind_kt: float, rng: np.random.Generator) -> np.ndarray:
22
- yy, xx = np.mgrid[0:size, 0:size]
23
- radius = np.hypot(yy - size / 2, xx - size / 2)
24
- cold_core = 220.0 - (wind_kt - 20.0) * 0.7 * np.exp(-(radius**2) / (2 * 8.0**2))
25
- noise = rng.normal(0.0, 1.5, size=(size, size))
26
- return (cold_core + noise).astype(np.float32)
27
-
28
-
29
- def _write_rows(root: Path, rows: list[dict[str, object]]) -> Path:
30
- manifest = root / "manifest.csv"
31
- pd.DataFrame(rows).to_csv(manifest, index=False)
32
- return manifest
33
-
34
-
35
- def write_smoke(
36
- root: Path,
37
- n_storms: int = 8,
38
- frames_per_storm: int = 4,
39
- size: int = 64,
40
- seed: int = 7,
41
- ) -> Path:
42
- """Write a manifest and ``.npy`` images.
43
-
44
- Storm ``S06`` has frames in 2020 and 2021 so the year-holdout test can
45
- prove that a boundary storm is not cut.
46
- """
47
- rng = np.random.default_rng(seed)
48
- root.mkdir(parents=True, exist_ok=True)
49
- image_dir = root / "images"
50
- image_dir.mkdir(exist_ok=True)
51
- rows: list[dict[str, object]] = []
52
- for index in range(n_storms):
53
- storm_id = f"S{index:02d}"
54
- basin = "NIO" if index % 2 else "NA"
55
- year = 2018 + (index % 4)
56
- for time_index in range(frames_per_storm):
57
- year_t = 2021 if index == 6 and time_index >= 2 else year
58
- wind = float(np.clip(25 + index * 12 + time_index * 2, 20, 140))
59
- relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
60
- np.save(root / relative, _synthetic_ir(size, wind, rng))
61
- rows.append(
62
- {
63
- "sample_id": f"{storm_id}_{time_index:02d}",
64
- "image_path": relative.as_posix(),
65
- "storm_id": storm_id,
66
- "timestamp": f"{year_t}-06-01T{time_index:02d}:00:00Z",
67
- "year": year_t,
68
- "basin": basin,
69
- "sensor": "synthetic",
70
- "channel": "IR",
71
- "wind_speed_kt": wind,
72
- "wind_averaging": "synthetic",
73
- "label_source": "smoke",
74
- "is_synthetic": True,
75
- }
76
- )
77
- return _write_rows(root, rows)
78
-
79
-
80
- def write_balanced_smoke(
81
- root: Path,
82
- storms_per_class: int = 5,
83
- frames_per_storm: int = 4,
84
- size: int = 48,
85
- seed: int = 7,
86
- ) -> Path:
87
- """One wind bin per storm, several storms per project class.
88
-
89
- Used to exercise grouped classification splits. Still synthetic.
90
- """
91
- if storms_per_class < 3:
92
- raise ValueError("storms_per_class must be at least 3 for grouped folds")
93
- rng = np.random.default_rng(seed)
94
- root.mkdir(parents=True, exist_ok=True)
95
- image_dir = root / "images"
96
- image_dir.mkdir(exist_ok=True)
97
- rows: list[dict[str, object]] = []
98
- for class_index, (_name, base_wind) in enumerate(CLASS_WINDS):
99
- for storm_index in range(storms_per_class):
100
- storm_id = f"C{class_index}{storm_index}"
101
- basin = "NIO" if (class_index + storm_index) % 2 else "NA"
102
- year = 2016 + ((class_index + storm_index) % 6)
103
- for time_index in range(frames_per_storm):
104
- wind = float(base_wind + time_index)
105
- relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
106
- np.save(root / relative, _synthetic_ir(size, wind, rng))
107
- rows.append(
108
- {
109
- "sample_id": f"{storm_id}_{time_index:02d}",
110
- "image_path": relative.as_posix(),
111
- "storm_id": storm_id,
112
- "timestamp": f"{year}-08-01T{time_index:02d}:00:00Z",
113
- "year": year,
114
- "basin": basin,
115
- "sensor": "synthetic",
116
- "channel": "IR",
117
- "wind_speed_kt": wind,
118
- "wind_averaging": "synthetic",
119
- "label_source": "smoke",
120
- "is_synthetic": True,
121
- }
122
- )
123
- return _write_rows(root, rows)
124
-
125
-
126
- def _default_out() -> Path:
127
- """Directory that holds ``paths.manifest`` in the smoke config."""
128
- from src.config import load_config
129
-
130
- root = Path(__file__).resolve().parents[1]
131
- manifest = Path(load_config(root / "config" / "config_smoke.yaml")["paths"]["manifest"])
132
- return manifest.parent
133
-
134
-
135
- def main() -> None:
136
- parser = argparse.ArgumentParser(description=__doc__)
137
- parser.add_argument("--out", type=Path, default=_default_out())
138
- parser.add_argument(
139
- "--profile",
140
- choices=("span", "balanced"),
141
- default="span",
142
- help="span: year-boundary storm. balanced: several storms per class.",
143
- )
144
- args = parser.parse_args()
145
- if args.profile == "balanced":
146
- path = write_balanced_smoke(args.out)
147
- else:
148
- path = write_smoke(args.out)
149
- print(f"Wrote synthetic manifest {path}. Not real cyclones. Do not report scores from it.")
150
-
151
-
152
- if __name__ == "__main__":
153
- main()
 
1
+ """Synthetic images for software tests. These are not cyclones."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ # Project-class winds that stay inside the bin when a few knots are added.
12
+ CLASS_WINDS = (
13
+ ("D_DD", 26.0),
14
+ ("CS", 40.0),
15
+ ("SCS", 55.0),
16
+ ("VSCS", 75.0),
17
+ ("ESCS_SUCS", 105.0),
18
+ )
19
+
20
+
21
+ def _synthetic_ir(size: int, wind_kt: float, rng: np.random.Generator) -> np.ndarray:
22
+ yy, xx = np.mgrid[0:size, 0:size]
23
+ radius = np.hypot(yy - size / 2, xx - size / 2)
24
+ cold_core = 220.0 - (wind_kt - 20.0) * 0.7 * np.exp(-(radius**2) / (2 * 8.0**2))
25
+ noise = rng.normal(0.0, 1.5, size=(size, size))
26
+ return (cold_core + noise).astype(np.float32)
27
+
28
+
29
+ def _write_rows(root: Path, rows: list[dict[str, object]]) -> Path:
30
+ manifest = root / "manifest.csv"
31
+ pd.DataFrame(rows).to_csv(manifest, index=False)
32
+ return manifest
33
+
34
+
35
+ def write_smoke(
36
+ root: Path,
37
+ n_storms: int = 8,
38
+ frames_per_storm: int = 4,
39
+ size: int = 64,
40
+ seed: int = 7,
41
+ ) -> Path:
42
+ """Write a manifest and ``.npy`` images.
43
+
44
+ Storm ``S06`` has frames in 2020 and 2021 so the year-holdout test can
45
+ prove that a boundary storm is not cut.
46
+ """
47
+ rng = np.random.default_rng(seed)
48
+ root.mkdir(parents=True, exist_ok=True)
49
+ image_dir = root / "images"
50
+ image_dir.mkdir(exist_ok=True)
51
+ rows: list[dict[str, object]] = []
52
+ for index in range(n_storms):
53
+ storm_id = f"S{index:02d}"
54
+ basin = "NIO" if index % 2 else "NA"
55
+ year = 2018 + (index % 4)
56
+ for time_index in range(frames_per_storm):
57
+ year_t = 2021 if index == 6 and time_index >= 2 else year
58
+ wind = float(np.clip(25 + index * 12 + time_index * 2, 20, 140))
59
+ relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
60
+ np.save(root / relative, _synthetic_ir(size, wind, rng))
61
+ rows.append(
62
+ {
63
+ "sample_id": f"{storm_id}_{time_index:02d}",
64
+ "image_path": relative.as_posix(),
65
+ "storm_id": storm_id,
66
+ "timestamp": f"{year_t}-06-01T{time_index:02d}:00:00Z",
67
+ "year": year_t,
68
+ "basin": basin,
69
+ "sensor": "synthetic",
70
+ "channel": "IR",
71
+ "wind_speed_kt": wind,
72
+ "wind_averaging": "synthetic",
73
+ "label_source": "smoke",
74
+ "is_synthetic": True,
75
+ }
76
+ )
77
+ return _write_rows(root, rows)
78
+
79
+
80
+ def write_balanced_smoke(
81
+ root: Path,
82
+ storms_per_class: int = 5,
83
+ frames_per_storm: int = 4,
84
+ size: int = 48,
85
+ seed: int = 7,
86
+ ) -> Path:
87
+ """One wind bin per storm, several storms per project class.
88
+
89
+ Used to exercise grouped classification splits. Still synthetic.
90
+ """
91
+ if storms_per_class < 3:
92
+ raise ValueError("storms_per_class must be at least 3 for grouped folds")
93
+ rng = np.random.default_rng(seed)
94
+ root.mkdir(parents=True, exist_ok=True)
95
+ image_dir = root / "images"
96
+ image_dir.mkdir(exist_ok=True)
97
+ rows: list[dict[str, object]] = []
98
+ for class_index, (_name, base_wind) in enumerate(CLASS_WINDS):
99
+ for storm_index in range(storms_per_class):
100
+ storm_id = f"C{class_index}{storm_index}"
101
+ basin = "NIO" if (class_index + storm_index) % 2 else "NA"
102
+ year = 2016 + ((class_index + storm_index) % 6)
103
+ for time_index in range(frames_per_storm):
104
+ wind = float(base_wind + time_index)
105
+ relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
106
+ np.save(root / relative, _synthetic_ir(size, wind, rng))
107
+ rows.append(
108
+ {
109
+ "sample_id": f"{storm_id}_{time_index:02d}",
110
+ "image_path": relative.as_posix(),
111
+ "storm_id": storm_id,
112
+ "timestamp": f"{year}-08-01T{time_index:02d}:00:00Z",
113
+ "year": year,
114
+ "basin": basin,
115
+ "sensor": "synthetic",
116
+ "channel": "IR",
117
+ "wind_speed_kt": wind,
118
+ "wind_averaging": "synthetic",
119
+ "label_source": "smoke",
120
+ "is_synthetic": True,
121
+ }
122
+ )
123
+ return _write_rows(root, rows)
124
+
125
+
126
+ def _default_out() -> Path:
127
+ """Directory that holds ``paths.manifest`` in the smoke config."""
128
+ from src.config import load_config
129
+
130
+ root = Path(__file__).resolve().parents[1]
131
+ manifest = Path(load_config(root / "config" / "config_smoke.yaml")["paths"]["manifest"])
132
+ return manifest.parent
133
+
134
+
135
+ def main() -> None:
136
+ parser = argparse.ArgumentParser(description=__doc__)
137
+ parser.add_argument("--out", type=Path, default=_default_out())
138
+ parser.add_argument(
139
+ "--profile",
140
+ choices=("span", "balanced"),
141
+ default="span",
142
+ help="span: year-boundary storm. balanced: several storms per class.",
143
+ )
144
+ args = parser.parse_args()
145
+ if args.profile == "balanced":
146
+ path = write_balanced_smoke(args.out)
147
+ else:
148
+ path = write_smoke(args.out)
149
+ print(f"Wrote synthetic manifest {path}. Not real cyclones. Do not report scores from it.")
150
+
151
+
152
+ if __name__ == "__main__":
153
+ main()
src/metrics.py CHANGED
@@ -1,174 +1,174 @@
1
- """Regression and classification metrics. No operational baseline is implied."""
2
-
3
- from __future__ import annotations
4
-
5
- import numpy as np
6
- import pandas as pd
7
- from sklearn.metrics import f1_score, recall_score
8
-
9
-
10
- def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
11
- truth = np.asarray(y_true, dtype=np.float64).ravel()
12
- pred = np.asarray(y_pred, dtype=np.float64).ravel()
13
- if truth.shape != pred.shape or truth.size == 0:
14
- raise ValueError("y_true and y_pred must be non-empty and the same shape")
15
- error = pred - truth
16
- return {
17
- "n": float(truth.size),
18
- "mae_kt": float(np.mean(np.abs(error))),
19
- "rmse_kt": float(np.sqrt(np.mean(error**2))),
20
- "bias_kt": float(np.mean(error)),
21
- }
22
-
23
-
24
- def _as_seed(value: int, name: str) -> int:
25
- if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
26
- raise ValueError(f"{name} must be an integer")
27
- return int(value)
28
-
29
-
30
- def _storm_index(storm_ids: np.ndarray) -> list[np.ndarray]:
31
- """Row positions of each storm, in order of first appearance."""
32
- order: list[str] = []
33
- buckets: dict[str, list[int]] = {}
34
- for index, storm in enumerate(np.asarray(storm_ids, dtype=object).ravel().tolist()):
35
- if storm is None or pd.isna(storm):
36
- raise ValueError("storm_ids must be present on every row")
37
- key = str(storm)
38
- if key not in buckets:
39
- buckets[key] = []
40
- order.append(key)
41
- buckets[key].append(index)
42
- return [np.asarray(buckets[key], dtype=np.int64) for key in order]
43
-
44
-
45
- def storm_bootstrap_metrics(
46
- y_true: np.ndarray,
47
- y_pred: np.ndarray,
48
- storm_ids: np.ndarray,
49
- *,
50
- n_resamples: int = 1000,
51
- seed: int = 0,
52
- ci_level: float = 0.95,
53
- ) -> dict[str, float | int | str]:
54
- """RMSE, MAE, and bias with a percentile interval that resamples storms.
55
-
56
- Bias is prediction minus true wind. Each resample draws as many storm
57
- IDs as there are storms, with replacement, and keeps every row of a
58
- drawn storm. A storm drawn twice contributes its rows twice. Rows are
59
- not drawn on their own. The point values are the full sample, not the
60
- mean of the resamples. Storms are ordered by first appearance. The
61
- generator is ``numpy.random.default_rng(seed)``.
62
- """
63
- truth = np.asarray(y_true, dtype=np.float64).ravel()
64
- pred = np.asarray(y_pred, dtype=np.float64).ravel()
65
- if truth.shape != pred.shape or truth.size == 0:
66
- raise ValueError("y_true and y_pred must be non-empty and the same shape")
67
- if not np.isfinite(truth).all() or not np.isfinite(pred).all():
68
- raise ValueError("y_true and y_pred must be finite")
69
- ids = np.asarray(storm_ids, dtype=object).ravel()
70
- if ids.size != truth.size:
71
- raise ValueError("storm_ids must align with y_true")
72
- groups = _storm_index(ids)
73
- if not groups:
74
- raise ValueError("storm_ids must align with y_true")
75
- resamples = _as_seed(n_resamples, "n_resamples")
76
- if resamples < 1:
77
- raise ValueError("n_resamples must be at least 1")
78
- seed_value = _as_seed(seed, "seed")
79
- level = float(ci_level)
80
- if not 0.0 < level < 1.0:
81
- raise ValueError(f"ci_level must be between 0 and 1, got {level}")
82
- point = regression_metrics(truth, pred)
83
- error = pred - truth
84
- n_per = np.asarray([group.size for group in groups], dtype=np.float64)
85
- sum_abs = np.asarray([np.abs(error[group]).sum() for group in groups], dtype=np.float64)
86
- sum_sq = np.asarray([(error[group] ** 2).sum() for group in groups], dtype=np.float64)
87
- sum_err = np.asarray([error[group].sum() for group in groups], dtype=np.float64)
88
- drawn = np.random.default_rng(seed_value).integers(0, len(groups), size=(resamples, len(groups)))
89
- mae_s = np.empty(resamples, dtype=np.float64)
90
- rmse_s = np.empty(resamples, dtype=np.float64)
91
- bias_s = np.empty(resamples, dtype=np.float64)
92
- for index, draw in enumerate(drawn):
93
- counts = np.bincount(draw, minlength=len(groups)).astype(np.float64)
94
- total = float(counts @ n_per)
95
- mae_s[index] = float(counts @ sum_abs) / total
96
- rmse_s[index] = float(np.sqrt((counts @ sum_sq) / total))
97
- bias_s[index] = float(counts @ sum_err) / total
98
- alpha = (1.0 - level) / 2.0
99
- out: dict[str, float | int | str] = {
100
- "n_rows": int(truth.size),
101
- "n_storms": int(len(groups)),
102
- "mae_kt": float(point["mae_kt"]),
103
- "rmse_kt": float(point["rmse_kt"]),
104
- "bias_kt": float(point["bias_kt"]),
105
- "n_resamples": resamples,
106
- "seed": seed_value,
107
- "ci_level": level,
108
- "resample": "storm_id",
109
- }
110
- for name, samples in (
111
- ("mae_kt", mae_s),
112
- ("rmse_kt", rmse_s),
113
- ("bias_kt", bias_s),
114
- ):
115
- out[f"{name}_ci_low"] = float(np.quantile(samples, alpha, method="linear"))
116
- out[f"{name}_ci_high"] = float(np.quantile(samples, 1.0 - alpha, method="linear"))
117
- return out
118
-
119
-
120
- def metrics_by_class(
121
- y_true: np.ndarray, y_pred: np.ndarray, classes: np.ndarray
122
- ) -> dict[str, dict[str, float]]:
123
- truth = np.asarray(y_true, dtype=np.float64).ravel()
124
- pred = np.asarray(y_pred, dtype=np.float64).ravel()
125
- labels = np.asarray(classes)
126
- if len(labels) != truth.size:
127
- raise ValueError("classes must align with y_true")
128
- out: dict[str, dict[str, float]] = {}
129
- for name in pd.unique(labels):
130
- if pd.isna(name):
131
- continue
132
- mask = labels == name
133
- if np.asarray(mask).sum() == 0:
134
- continue
135
- out[str(name)] = regression_metrics(truth[mask], pred[mask])
136
- return out
137
-
138
-
139
- def mean_baseline(y_train: np.ndarray, n_rows: int) -> np.ndarray:
140
- """Predict the training mean. Fit this on train storms only."""
141
- return np.full(n_rows, float(np.mean(np.asarray(y_train, dtype=np.float64))))
142
-
143
-
144
- def classification_metrics(
145
- y_true: np.ndarray,
146
- y_pred: np.ndarray,
147
- labels: tuple[str, ...],
148
- ) -> dict[str, float]:
149
- """Macro-F1 over classes present in ``y_true``, plus per-class recall.
150
-
151
- Recall is NaN when the validation side has no samples of that class.
152
- Accuracy is omitted on purpose: a single headline rate hides the rare
153
- intense classes.
154
- """
155
- truth = np.asarray(y_true).ravel()
156
- pred = np.asarray(y_pred).ravel()
157
- if truth.shape != pred.shape or truth.size == 0:
158
- raise ValueError("y_true and y_pred must be non-empty and the same shape")
159
- present = [label for label in labels if np.any(truth == label)]
160
- if not present:
161
- present = [str(value) for value in pd.unique(truth)]
162
- macro = float(
163
- f1_score(truth, pred, labels=present, average="macro", zero_division=0)
164
- )
165
- recalls = recall_score(
166
- truth, pred, labels=list(labels), average=None, zero_division=0
167
- )
168
- out: dict[str, float] = {"n": float(truth.size), "macro_f1": macro}
169
- for label, recall in zip(labels, recalls, strict=True):
170
- if not np.any(truth == label):
171
- out[f"recall_{label}"] = float("nan")
172
- else:
173
- out[f"recall_{label}"] = float(recall)
174
- return out
 
1
+ """Regression and classification metrics. No operational baseline is implied."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from sklearn.metrics import f1_score, recall_score
8
+
9
+
10
+ def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
11
+ truth = np.asarray(y_true, dtype=np.float64).ravel()
12
+ pred = np.asarray(y_pred, dtype=np.float64).ravel()
13
+ if truth.shape != pred.shape or truth.size == 0:
14
+ raise ValueError("y_true and y_pred must be non-empty and the same shape")
15
+ error = pred - truth
16
+ return {
17
+ "n": float(truth.size),
18
+ "mae_kt": float(np.mean(np.abs(error))),
19
+ "rmse_kt": float(np.sqrt(np.mean(error**2))),
20
+ "bias_kt": float(np.mean(error)),
21
+ }
22
+
23
+
24
+ def _as_seed(value: int, name: str) -> int:
25
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
26
+ raise ValueError(f"{name} must be an integer")
27
+ return int(value)
28
+
29
+
30
+ def _storm_index(storm_ids: np.ndarray) -> list[np.ndarray]:
31
+ """Row positions of each storm, in order of first appearance."""
32
+ order: list[str] = []
33
+ buckets: dict[str, list[int]] = {}
34
+ for index, storm in enumerate(np.asarray(storm_ids, dtype=object).ravel().tolist()):
35
+ if storm is None or pd.isna(storm):
36
+ raise ValueError("storm_ids must be present on every row")
37
+ key = str(storm)
38
+ if key not in buckets:
39
+ buckets[key] = []
40
+ order.append(key)
41
+ buckets[key].append(index)
42
+ return [np.asarray(buckets[key], dtype=np.int64) for key in order]
43
+
44
+
45
+ def storm_bootstrap_metrics(
46
+ y_true: np.ndarray,
47
+ y_pred: np.ndarray,
48
+ storm_ids: np.ndarray,
49
+ *,
50
+ n_resamples: int = 1000,
51
+ seed: int = 0,
52
+ ci_level: float = 0.95,
53
+ ) -> dict[str, float | int | str]:
54
+ """RMSE, MAE, and bias with a percentile interval that resamples storms.
55
+
56
+ Bias is prediction minus true wind. Each resample draws as many storm
57
+ IDs as there are storms, with replacement, and keeps every row of a
58
+ drawn storm. A storm drawn twice contributes its rows twice. Rows are
59
+ not drawn on their own. The point values are the full sample, not the
60
+ mean of the resamples. Storms are ordered by first appearance. The
61
+ generator is ``numpy.random.default_rng(seed)``.
62
+ """
63
+ truth = np.asarray(y_true, dtype=np.float64).ravel()
64
+ pred = np.asarray(y_pred, dtype=np.float64).ravel()
65
+ if truth.shape != pred.shape or truth.size == 0:
66
+ raise ValueError("y_true and y_pred must be non-empty and the same shape")
67
+ if not np.isfinite(truth).all() or not np.isfinite(pred).all():
68
+ raise ValueError("y_true and y_pred must be finite")
69
+ ids = np.asarray(storm_ids, dtype=object).ravel()
70
+ if ids.size != truth.size:
71
+ raise ValueError("storm_ids must align with y_true")
72
+ groups = _storm_index(ids)
73
+ if not groups:
74
+ raise ValueError("storm_ids must align with y_true")
75
+ resamples = _as_seed(n_resamples, "n_resamples")
76
+ if resamples < 1:
77
+ raise ValueError("n_resamples must be at least 1")
78
+ seed_value = _as_seed(seed, "seed")
79
+ level = float(ci_level)
80
+ if not 0.0 < level < 1.0:
81
+ raise ValueError(f"ci_level must be between 0 and 1, got {level}")
82
+ point = regression_metrics(truth, pred)
83
+ error = pred - truth
84
+ n_per = np.asarray([group.size for group in groups], dtype=np.float64)
85
+ sum_abs = np.asarray([np.abs(error[group]).sum() for group in groups], dtype=np.float64)
86
+ sum_sq = np.asarray([(error[group] ** 2).sum() for group in groups], dtype=np.float64)
87
+ sum_err = np.asarray([error[group].sum() for group in groups], dtype=np.float64)
88
+ drawn = np.random.default_rng(seed_value).integers(0, len(groups), size=(resamples, len(groups)))
89
+ mae_s = np.empty(resamples, dtype=np.float64)
90
+ rmse_s = np.empty(resamples, dtype=np.float64)
91
+ bias_s = np.empty(resamples, dtype=np.float64)
92
+ for index, draw in enumerate(drawn):
93
+ counts = np.bincount(draw, minlength=len(groups)).astype(np.float64)
94
+ total = float(counts @ n_per)
95
+ mae_s[index] = float(counts @ sum_abs) / total
96
+ rmse_s[index] = float(np.sqrt((counts @ sum_sq) / total))
97
+ bias_s[index] = float(counts @ sum_err) / total
98
+ alpha = (1.0 - level) / 2.0
99
+ out: dict[str, float | int | str] = {
100
+ "n_rows": int(truth.size),
101
+ "n_storms": int(len(groups)),
102
+ "mae_kt": float(point["mae_kt"]),
103
+ "rmse_kt": float(point["rmse_kt"]),
104
+ "bias_kt": float(point["bias_kt"]),
105
+ "n_resamples": resamples,
106
+ "seed": seed_value,
107
+ "ci_level": level,
108
+ "resample": "storm_id",
109
+ }
110
+ for name, samples in (
111
+ ("mae_kt", mae_s),
112
+ ("rmse_kt", rmse_s),
113
+ ("bias_kt", bias_s),
114
+ ):
115
+ out[f"{name}_ci_low"] = float(np.quantile(samples, alpha, method="linear"))
116
+ out[f"{name}_ci_high"] = float(np.quantile(samples, 1.0 - alpha, method="linear"))
117
+ return out
118
+
119
+
120
+ def metrics_by_class(
121
+ y_true: np.ndarray, y_pred: np.ndarray, classes: np.ndarray
122
+ ) -> dict[str, dict[str, float]]:
123
+ truth = np.asarray(y_true, dtype=np.float64).ravel()
124
+ pred = np.asarray(y_pred, dtype=np.float64).ravel()
125
+ labels = np.asarray(classes)
126
+ if len(labels) != truth.size:
127
+ raise ValueError("classes must align with y_true")
128
+ out: dict[str, dict[str, float]] = {}
129
+ for name in pd.unique(labels):
130
+ if pd.isna(name):
131
+ continue
132
+ mask = labels == name
133
+ if np.asarray(mask).sum() == 0:
134
+ continue
135
+ out[str(name)] = regression_metrics(truth[mask], pred[mask])
136
+ return out
137
+
138
+
139
+ def mean_baseline(y_train: np.ndarray, n_rows: int) -> np.ndarray:
140
+ """Predict the training mean. Fit this on train storms only."""
141
+ return np.full(n_rows, float(np.mean(np.asarray(y_train, dtype=np.float64))))
142
+
143
+
144
+ def classification_metrics(
145
+ y_true: np.ndarray,
146
+ y_pred: np.ndarray,
147
+ labels: tuple[str, ...],
148
+ ) -> dict[str, float]:
149
+ """Macro-F1 over classes present in ``y_true``, plus per-class recall.
150
+
151
+ Recall is NaN when the validation side has no samples of that class.
152
+ Accuracy is omitted on purpose: a single headline rate hides the rare
153
+ intense classes.
154
+ """
155
+ truth = np.asarray(y_true).ravel()
156
+ pred = np.asarray(y_pred).ravel()
157
+ if truth.shape != pred.shape or truth.size == 0:
158
+ raise ValueError("y_true and y_pred must be non-empty and the same shape")
159
+ present = [label for label in labels if np.any(truth == label)]
160
+ if not present:
161
+ present = [str(value) for value in pd.unique(truth)]
162
+ macro = float(
163
+ f1_score(truth, pred, labels=present, average="macro", zero_division=0)
164
+ )
165
+ recalls = recall_score(
166
+ truth, pred, labels=list(labels), average=None, zero_division=0
167
+ )
168
+ out: dict[str, float] = {"n": float(truth.size), "macro_f1": macro}
169
+ for label, recall in zip(labels, recalls, strict=True):
170
+ if not np.any(truth == label):
171
+ out[f"recall_{label}"] = float("nan")
172
+ else:
173
+ out[f"recall_{label}"] = float(recall)
174
+ return out
src/model.py CHANGED
@@ -1,262 +1,262 @@
1
- """Model interfaces. Importing this module requires torch.
2
-
3
- Spatial size is not fixed. The caller supplies the frame size (``data.image_size``
4
- or a native infrared frame). Both regressors pool with ``AdaptiveAvgPool2d``
5
- before the heads. ``pretrained=True`` downloads ImageNet weights and is refused
6
- unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import os
12
-
13
- import torch
14
- from torch import nn
15
-
16
-
17
- class OptionalClassHead:
18
- """Project-class logits. Absent when the caller does not ask for them."""
19
-
20
- @staticmethod
21
- def build(feature_dim: int, n_classes: int | None) -> nn.Linear | None:
22
- if n_classes is None:
23
- return None
24
- count = int(n_classes)
25
- if count < 1:
26
- raise ValueError("n_classes must be at least 1")
27
- return nn.Linear(feature_dim, count)
28
-
29
-
30
- class SimpleCNN(nn.Module):
31
- """Small regressor for smoke tests and a first real baseline.
32
-
33
- The regression head predicts wind speed in knots. ``n_classes`` adds a
34
- class head on the same pooled features. Dropout stays on the wind head.
35
- """
36
-
37
- def __init__(
38
- self,
39
- in_channels: int = 1,
40
- dropout: float = 0.3,
41
- n_classes: int | None = None,
42
- ) -> None:
43
- super().__init__()
44
- self.feature_dim = 64
45
- self.features = nn.Sequential(
46
- nn.Conv2d(in_channels, 16, 3, padding=1),
47
- nn.ReLU(),
48
- nn.MaxPool2d(2),
49
- nn.Conv2d(16, 32, 3, padding=1),
50
- nn.ReLU(),
51
- nn.MaxPool2d(2),
52
- nn.Conv2d(32, 64, 3, padding=1),
53
- nn.ReLU(),
54
- nn.AdaptiveAvgPool2d(1),
55
- )
56
- self.head = nn.Sequential(nn.Flatten(), nn.Dropout(dropout), nn.Linear(64, 1))
57
- self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
58
-
59
- def encode(self, inputs: torch.Tensor) -> torch.Tensor:
60
- return self.features(inputs).flatten(1)
61
-
62
- def forward(
63
- self, inputs: torch.Tensor
64
- ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
65
- features = self.encode(inputs)
66
- wind = self.head(features)
67
- if self.class_head is None:
68
- return wind
69
- return wind, self.class_head(features)
70
-
71
-
72
- class ResNetRegressor(nn.Module):
73
- """ResNet-18 regressor. One-channel IR is repeated to three channels.
74
-
75
- Repeating keeps the pretrained first convolution. Replacing it would
76
- discard those weights. ImageNet pretraining is not a physical prior.
77
- ``pretrained=True`` downloads weights and must not run in CI unless
78
- ``CLOUDIE_ALLOW_PRETRAINED=1``. The regression head predicts wind speed
79
- in knots. ``n_classes`` adds a class head on the same pooled features.
80
- """
81
-
82
- def __init__(
83
- self,
84
- in_channels: int = 1,
85
- pretrained: bool = False,
86
- dropout: float = 0.2,
87
- n_classes: int | None = None,
88
- ) -> None:
89
- super().__init__()
90
- if in_channels not in (1, 3):
91
- raise ValueError(
92
- "ResNet-18 keeps the 3-channel conv1. "
93
- "Pass 1 channel to repeat it, or 3 channels."
94
- )
95
- weights = self.imagenet_weights(pretrained)
96
- from torchvision.models import resnet18
97
-
98
- backbone = resnet18(weights=weights)
99
- if int(backbone.conv1.in_channels) != 3:
100
- raise RuntimeError("pretrained conv1 must stay 3-channel")
101
- # Adaptive pool, so a native frame and a resized frame share the head.
102
- backbone.avgpool = nn.AdaptiveAvgPool2d(1)
103
- in_features = backbone.fc.in_features
104
- backbone.fc = nn.Identity()
105
- self.backbone = backbone
106
- self.feature_dim = in_features
107
- self.repeat_to_rgb = in_channels == 1
108
- self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(in_features, 1))
109
- self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
110
-
111
- @staticmethod
112
- def imagenet_weights(pretrained: bool):
113
- """ImageNet weights, or None.
114
-
115
- ``weights=None`` builds the architecture without a download.
116
- ``pretrained=True`` asks for ``ResNet18_Weights.DEFAULT`` and is
117
- refused unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
118
- """
119
- if not pretrained:
120
- return None
121
- if os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":
122
- raise RuntimeError(
123
- "pretrained: true downloads ImageNet weights and must not run in CI. "
124
- "Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download."
125
- )
126
- from torchvision.models import ResNet18_Weights
127
-
128
- return ResNet18_Weights.DEFAULT
129
-
130
- def encode(self, inputs: torch.Tensor) -> torch.Tensor:
131
- if self.repeat_to_rgb and inputs.shape[1] == 1:
132
- inputs = inputs.repeat(1, 3, 1, 1)
133
- return self.backbone(inputs)
134
-
135
- def forward(
136
- self, inputs: torch.Tensor
137
- ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
138
- features = self.encode(inputs)
139
- wind = self.head(features)
140
- if self.class_head is None:
141
- return wind
142
- return wind, self.class_head(features)
143
-
144
-
145
- class ConvLSTMCell(nn.Module):
146
- """One convolutional LSTM step. Hidden state stays on the image grid."""
147
-
148
- def __init__(self, in_channels: int, hidden: int) -> None:
149
- super().__init__()
150
- self.hidden = hidden
151
- self.gates = nn.Conv2d(in_channels + hidden, 4 * hidden, kernel_size=3, padding=1)
152
-
153
- def forward(
154
- self, inputs: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor]
155
- ) -> tuple[torch.Tensor, torch.Tensor]:
156
- hidden, cell = state
157
- input_gate, forget_gate, candidate, output_gate = self.gates(
158
- torch.cat([inputs, hidden], dim=1)
159
- ).chunk(4, dim=1)
160
- cell = torch.sigmoid(forget_gate) * cell + torch.sigmoid(input_gate) * torch.tanh(
161
- candidate
162
- )
163
- hidden = torch.sigmoid(output_gate) * torch.tanh(cell)
164
- return hidden, cell
165
-
166
-
167
- class ConvLSTMRegressor(nn.Module):
168
- """Four-frame ConvLSTM. The tensor is infrared imagery.
169
-
170
- Best-track wind, R34, and radius of maximum wind are not inputs. The
171
- training net attaches a size head to ``encode`` only after those labels
172
- exist. This module does not flip Southern Hemisphere frames.
173
- """
174
-
175
- def __init__(
176
- self,
177
- in_channels: int = 1,
178
- hidden: int = 16,
179
- n_frames: int = 4,
180
- dropout: float = 0.3,
181
- ) -> None:
182
- super().__init__()
183
- if n_frames != 4:
184
- raise ValueError("ConvLSTM uses 4 frames")
185
- if hidden < 1:
186
- raise ValueError("hidden must be at least 1")
187
- self.n_frames = n_frames
188
- self.hidden = hidden
189
- self.feature_dim = hidden
190
- self.cell = ConvLSTMCell(in_channels, hidden)
191
- self.pool = nn.AdaptiveAvgPool2d(1)
192
- self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden, 1))
193
-
194
- def encode(self, inputs: torch.Tensor) -> torch.Tensor:
195
- if inputs.ndim != 5:
196
- raise ValueError(
197
- "ConvLSTM expects (batch, 4, channels, height, width) infrared frames"
198
- )
199
- if int(inputs.shape[1]) != self.n_frames:
200
- raise ValueError(
201
- f"ConvLSTM expects {self.n_frames} frames, got {int(inputs.shape[1])}"
202
- )
203
- batch, _steps, _channels, height, width = inputs.shape
204
- hidden = inputs.new_zeros(batch, self.hidden, height, width)
205
- cell = inputs.new_zeros(batch, self.hidden, height, width)
206
- for step in range(self.n_frames):
207
- hidden, cell = self.cell(inputs[:, step], (hidden, cell))
208
- return self.pool(hidden).flatten(1)
209
-
210
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
211
- return self.head(self.encode(inputs))
212
-
213
-
214
- class MCDropout:
215
- """Stochastic passes with BatchNorm frozen and Dropout left active.
216
-
217
- The returned standard deviation is dropout noise. It is not a calibrated
218
- prediction interval.
219
- """
220
-
221
- @staticmethod
222
- def enable(module: nn.Module) -> None:
223
- """Eval mode for the module, then train mode for Dropout only."""
224
- module.eval()
225
- for layer in module.modules():
226
- if isinstance(layer, nn.Dropout):
227
- layer.train()
228
-
229
- @staticmethod
230
- @torch.no_grad()
231
- def predict(
232
- module: nn.Module, inputs: torch.Tensor, n_samples: int
233
- ) -> tuple[torch.Tensor, torch.Tensor]:
234
- """Mean and std over ``n_samples`` stochastic forwards.
235
-
236
- ``n_samples`` is ``model.mc_samples`` from config. A class-head tuple
237
- contributes the wind-speed tensor only.
238
- """
239
- if n_samples < 2:
240
- raise ValueError("n_samples must be at least 2")
241
- MCDropout.enable(module)
242
- draws = []
243
- for _ in range(n_samples):
244
- output = module(inputs)
245
- if isinstance(output, tuple):
246
- output = output[0]
247
- draws.append(output)
248
- stacked = torch.stack(draws, dim=0)
249
- return stacked.mean(dim=0), stacked.std(dim=0, unbiased=True)
250
-
251
-
252
- def enable_mc_dropout(module: nn.Module) -> None:
253
- """Eval mode for BatchNorm, train mode for Dropout."""
254
- MCDropout.enable(module)
255
-
256
-
257
- @torch.no_grad()
258
- def mc_dropout_predict(
259
- module: nn.Module, inputs: torch.Tensor, n_samples: int = 20
260
- ) -> tuple[torch.Tensor, torch.Tensor]:
261
- """Return mean and std. This is not a calibrated prediction interval."""
262
- return MCDropout.predict(module, inputs, n_samples)
 
1
+ """Model interfaces. Importing this module requires torch.
2
+
3
+ Spatial size is not fixed. The caller supplies the frame size (``data.image_size``
4
+ or a native infrared frame). Both regressors pool with ``AdaptiveAvgPool2d``
5
+ before the heads. ``pretrained=True`` downloads ImageNet weights and is refused
6
+ unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ import torch
14
+ from torch import nn
15
+
16
+
17
+ class OptionalClassHead:
18
+ """Project-class logits. Absent when the caller does not ask for them."""
19
+
20
+ @staticmethod
21
+ def build(feature_dim: int, n_classes: int | None) -> nn.Linear | None:
22
+ if n_classes is None:
23
+ return None
24
+ count = int(n_classes)
25
+ if count < 1:
26
+ raise ValueError("n_classes must be at least 1")
27
+ return nn.Linear(feature_dim, count)
28
+
29
+
30
+ class SimpleCNN(nn.Module):
31
+ """Small regressor for smoke tests and a first real baseline.
32
+
33
+ The regression head predicts wind speed in knots. ``n_classes`` adds a
34
+ class head on the same pooled features. Dropout stays on the wind head.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ in_channels: int = 1,
40
+ dropout: float = 0.3,
41
+ n_classes: int | None = None,
42
+ ) -> None:
43
+ super().__init__()
44
+ self.feature_dim = 64
45
+ self.features = nn.Sequential(
46
+ nn.Conv2d(in_channels, 16, 3, padding=1),
47
+ nn.ReLU(),
48
+ nn.MaxPool2d(2),
49
+ nn.Conv2d(16, 32, 3, padding=1),
50
+ nn.ReLU(),
51
+ nn.MaxPool2d(2),
52
+ nn.Conv2d(32, 64, 3, padding=1),
53
+ nn.ReLU(),
54
+ nn.AdaptiveAvgPool2d(1),
55
+ )
56
+ self.head = nn.Sequential(nn.Flatten(), nn.Dropout(dropout), nn.Linear(64, 1))
57
+ self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
58
+
59
+ def encode(self, inputs: torch.Tensor) -> torch.Tensor:
60
+ return self.features(inputs).flatten(1)
61
+
62
+ def forward(
63
+ self, inputs: torch.Tensor
64
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
65
+ features = self.encode(inputs)
66
+ wind = self.head(features)
67
+ if self.class_head is None:
68
+ return wind
69
+ return wind, self.class_head(features)
70
+
71
+
72
+ class ResNetRegressor(nn.Module):
73
+ """ResNet-18 regressor. One-channel IR is repeated to three channels.
74
+
75
+ Repeating keeps the pretrained first convolution. Replacing it would
76
+ discard those weights. ImageNet pretraining is not a physical prior.
77
+ ``pretrained=True`` downloads weights and must not run in CI unless
78
+ ``CLOUDIE_ALLOW_PRETRAINED=1``. The regression head predicts wind speed
79
+ in knots. ``n_classes`` adds a class head on the same pooled features.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ in_channels: int = 1,
85
+ pretrained: bool = False,
86
+ dropout: float = 0.2,
87
+ n_classes: int | None = None,
88
+ ) -> None:
89
+ super().__init__()
90
+ if in_channels not in (1, 3):
91
+ raise ValueError(
92
+ "ResNet-18 keeps the 3-channel conv1. "
93
+ "Pass 1 channel to repeat it, or 3 channels."
94
+ )
95
+ weights = self.imagenet_weights(pretrained)
96
+ from torchvision.models import resnet18
97
+
98
+ backbone = resnet18(weights=weights)
99
+ if int(backbone.conv1.in_channels) != 3:
100
+ raise RuntimeError("pretrained conv1 must stay 3-channel")
101
+ # Adaptive pool, so a native frame and a resized frame share the head.
102
+ backbone.avgpool = nn.AdaptiveAvgPool2d(1)
103
+ in_features = backbone.fc.in_features
104
+ backbone.fc = nn.Identity()
105
+ self.backbone = backbone
106
+ self.feature_dim = in_features
107
+ self.repeat_to_rgb = in_channels == 1
108
+ self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(in_features, 1))
109
+ self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
110
+
111
+ @staticmethod
112
+ def imagenet_weights(pretrained: bool):
113
+ """ImageNet weights, or None.
114
+
115
+ ``weights=None`` builds the architecture without a download.
116
+ ``pretrained=True`` asks for ``ResNet18_Weights.DEFAULT`` and is
117
+ refused unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
118
+ """
119
+ if not pretrained:
120
+ return None
121
+ if os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":
122
+ raise RuntimeError(
123
+ "pretrained: true downloads ImageNet weights and must not run in CI. "
124
+ "Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download."
125
+ )
126
+ from torchvision.models import ResNet18_Weights
127
+
128
+ return ResNet18_Weights.DEFAULT
129
+
130
+ def encode(self, inputs: torch.Tensor) -> torch.Tensor:
131
+ if self.repeat_to_rgb and inputs.shape[1] == 1:
132
+ inputs = inputs.repeat(1, 3, 1, 1)
133
+ return self.backbone(inputs)
134
+
135
+ def forward(
136
+ self, inputs: torch.Tensor
137
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
138
+ features = self.encode(inputs)
139
+ wind = self.head(features)
140
+ if self.class_head is None:
141
+ return wind
142
+ return wind, self.class_head(features)
143
+
144
+
145
+ class ConvLSTMCell(nn.Module):
146
+ """One convolutional LSTM step. Hidden state stays on the image grid."""
147
+
148
+ def __init__(self, in_channels: int, hidden: int) -> None:
149
+ super().__init__()
150
+ self.hidden = hidden
151
+ self.gates = nn.Conv2d(in_channels + hidden, 4 * hidden, kernel_size=3, padding=1)
152
+
153
+ def forward(
154
+ self, inputs: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor]
155
+ ) -> tuple[torch.Tensor, torch.Tensor]:
156
+ hidden, cell = state
157
+ input_gate, forget_gate, candidate, output_gate = self.gates(
158
+ torch.cat([inputs, hidden], dim=1)
159
+ ).chunk(4, dim=1)
160
+ cell = torch.sigmoid(forget_gate) * cell + torch.sigmoid(input_gate) * torch.tanh(
161
+ candidate
162
+ )
163
+ hidden = torch.sigmoid(output_gate) * torch.tanh(cell)
164
+ return hidden, cell
165
+
166
+
167
+ class ConvLSTMRegressor(nn.Module):
168
+ """Four-frame ConvLSTM. The tensor is infrared imagery.
169
+
170
+ Best-track wind, R34, and radius of maximum wind are not inputs. The
171
+ training net attaches a size head to ``encode`` only after those labels
172
+ exist. This module does not flip Southern Hemisphere frames.
173
+ """
174
+
175
+ def __init__(
176
+ self,
177
+ in_channels: int = 1,
178
+ hidden: int = 16,
179
+ n_frames: int = 4,
180
+ dropout: float = 0.3,
181
+ ) -> None:
182
+ super().__init__()
183
+ if n_frames != 4:
184
+ raise ValueError("ConvLSTM uses 4 frames")
185
+ if hidden < 1:
186
+ raise ValueError("hidden must be at least 1")
187
+ self.n_frames = n_frames
188
+ self.hidden = hidden
189
+ self.feature_dim = hidden
190
+ self.cell = ConvLSTMCell(in_channels, hidden)
191
+ self.pool = nn.AdaptiveAvgPool2d(1)
192
+ self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden, 1))
193
+
194
+ def encode(self, inputs: torch.Tensor) -> torch.Tensor:
195
+ if inputs.ndim != 5:
196
+ raise ValueError(
197
+ "ConvLSTM expects (batch, 4, channels, height, width) infrared frames"
198
+ )
199
+ if int(inputs.shape[1]) != self.n_frames:
200
+ raise ValueError(
201
+ f"ConvLSTM expects {self.n_frames} frames, got {int(inputs.shape[1])}"
202
+ )
203
+ batch, _steps, _channels, height, width = inputs.shape
204
+ hidden = inputs.new_zeros(batch, self.hidden, height, width)
205
+ cell = inputs.new_zeros(batch, self.hidden, height, width)
206
+ for step in range(self.n_frames):
207
+ hidden, cell = self.cell(inputs[:, step], (hidden, cell))
208
+ return self.pool(hidden).flatten(1)
209
+
210
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
211
+ return self.head(self.encode(inputs))
212
+
213
+
214
+ class MCDropout:
215
+ """Stochastic passes with BatchNorm frozen and Dropout left active.
216
+
217
+ The returned standard deviation is dropout noise. It is not a calibrated
218
+ prediction interval.
219
+ """
220
+
221
+ @staticmethod
222
+ def enable(module: nn.Module) -> None:
223
+ """Eval mode for the module, then train mode for Dropout only."""
224
+ module.eval()
225
+ for layer in module.modules():
226
+ if isinstance(layer, nn.Dropout):
227
+ layer.train()
228
+
229
+ @staticmethod
230
+ @torch.no_grad()
231
+ def predict(
232
+ module: nn.Module, inputs: torch.Tensor, n_samples: int
233
+ ) -> tuple[torch.Tensor, torch.Tensor]:
234
+ """Mean and std over ``n_samples`` stochastic forwards.
235
+
236
+ ``n_samples`` is ``model.mc_samples`` from config. A class-head tuple
237
+ contributes the wind-speed tensor only.
238
+ """
239
+ if n_samples < 2:
240
+ raise ValueError("n_samples must be at least 2")
241
+ MCDropout.enable(module)
242
+ draws = []
243
+ for _ in range(n_samples):
244
+ output = module(inputs)
245
+ if isinstance(output, tuple):
246
+ output = output[0]
247
+ draws.append(output)
248
+ stacked = torch.stack(draws, dim=0)
249
+ return stacked.mean(dim=0), stacked.std(dim=0, unbiased=True)
250
+
251
+
252
+ def enable_mc_dropout(module: nn.Module) -> None:
253
+ """Eval mode for BatchNorm, train mode for Dropout."""
254
+ MCDropout.enable(module)
255
+
256
+
257
+ @torch.no_grad()
258
+ def mc_dropout_predict(
259
+ module: nn.Module, inputs: torch.Tensor, n_samples: int = 20
260
+ ) -> tuple[torch.Tensor, torch.Tensor]:
261
+ """Return mean and std. This is not a calibrated prediction interval."""
262
+ return MCDropout.predict(module, inputs, n_samples)
src/model_access.py CHANGED
@@ -1,26 +1,26 @@
1
- """The only import point for the network and for MC-dropout.
2
-
3
- ``src.model.MCDropout`` is the class from the merged regressor work.
4
- ``src.train.build_net`` wraps that module and ``cloudie.train`` re-exports
5
- it. This file does not copy either implementation.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
-
11
- class ModelAccess:
12
- """Lazy imports so a gate check does not load torch."""
13
-
14
- @staticmethod
15
- def mc_dropout():
16
- """Return ``src.model.MCDropout``."""
17
- from src.model import MCDropout
18
-
19
- return MCDropout
20
-
21
- @staticmethod
22
- def build_net(config: dict, size_head: bool = False):
23
- """Return the training wrapper around the configured regressor."""
24
- from src.train import build_net
25
-
26
- return build_net(config, size_head=size_head)
 
1
+ """The only import point for the network and for MC-dropout.
2
+
3
+ ``src.model.MCDropout`` is the class from the merged regressor work.
4
+ ``src.train.build_net`` wraps that module and ``cloudie.train`` re-exports
5
+ it. This file does not copy either implementation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class ModelAccess:
12
+ """Lazy imports so a gate check does not load torch."""
13
+
14
+ @staticmethod
15
+ def mc_dropout():
16
+ """Return ``src.model.MCDropout``."""
17
+ from src.model import MCDropout
18
+
19
+ return MCDropout
20
+
21
+ @staticmethod
22
+ def build_net(config: dict, size_head: bool = False):
23
+ """Return the training wrapper around the configured regressor."""
24
+ from src.train import build_net
25
+
26
+ return build_net(config, size_head=size_head)
src/nasa_tc.py CHANGED
@@ -1,360 +1,360 @@
1
- """Build a Cloudie manifest from the NASA Tropical Storm Wind Speed dataset.
2
-
3
- The main path is TorchGeo ``TropicalCyclone`` (Maskey et al. 2020,
4
- https://doi.org/10.1109/JSTARS.2020.3011907). TorchGeo checks the files and
5
- reads ``{training,test}_set_{features,labels}.csv``; images sit at
6
- ``<root>/<split>/<Image ID>.jpg``. A one-time download is
7
- ``TropicalCyclone(root, split, download=True)`` from the public Source
8
- Cooperative blob. The copy tool and the mirror are named in
9
- ``docs/DATA_SOURCES.md``. The Hugging Face repo
10
- ``torchgeo/tropical_cyclone`` is only a mirror. CI never downloads either.
11
-
12
- Images keep their native size. Nothing in this module resizes. Most frames
13
- are 366 x 366, but the real train side also has 1093 x 1093 frames (stored
14
- as grey in an RGB JPEG), which TorchGeo's own ``__getitem__`` bilinearly
15
- resizes to 366. ``native_height``, ``native_width`` and ``orig_size`` are
16
- recorded per row. An empirical check (scripted in the PR notes) found that a
17
- 1093 frame covers the same footprint as a 366 frame at about 3x the pixel
18
- density: its spatial autocorrelation length is about 3.2x longer in pixels,
19
- and after a 3x area average its texture and cold-cloud fraction match the
20
- 366 frames, while a 366 centre crop does not. ``to_working_grid`` therefore
21
- area-averages to the 366 working grid, and ``working_resample`` marks which
22
- rows need it. The manifest itself is never resampled.
23
-
24
- Colour-enhanced frames (``npf_000``, ``npf_001``) are not grey IR. They are
25
- dropped from the manifest and listed with a reason in an exclusions CSV next
26
- to it.
27
-
28
- The manifest never has a ``split`` column. The official side goes only to
29
- ``source_split``. ``src.splits.assign_storms`` writes ``split`` by storm.
30
-
31
- Pixel values are an 8-bit rendering of IR brightness, not calibrated Kelvin.
32
- Call them pixel stats until a calibration table exists.
33
-
34
- Labels are HURDAT2 best-track maximum sustained winds in knots. HURDAT2 uses
35
- 1-minute sustained winds, so ``wind_averaging`` is ``1min``.
36
-
37
- There is no distance-to-land join. ``storm_id`` is a 3-letter competition
38
- identifier and the only time field is ``relative_time_s``, so an IBTrACS
39
- match would be a guess. ``near_land`` stays unknown. See
40
- ``nasa_tc/audit/README.md``. Do not invent a mapping.
41
-
42
- The competition's own train/test sides split frames, not storms: many test
43
- storms also appear in train. ``source_split`` keeps that side for reference
44
- only. Do not train on one side and score on the other. Use the storm-wise
45
- splitter in ``src.splits`` on the union instead.
46
- """
47
-
48
- from __future__ import annotations
49
-
50
- import argparse
51
- import json
52
- from collections.abc import Callable
53
- from pathlib import Path
54
-
55
- import numpy as np
56
- import pandas as pd
57
-
58
- from src.schema import require_valid
59
-
60
- WIND_AVERAGING = "1min"
61
- LABEL_SOURCE = "nasa_tropical_storm_competition_hurdat2"
62
- SPLITS = ("train", "test")
63
- WORKING_SIZE = 366 # TorchGeo's grid and config data.image_size: native (PR #16)
64
- # Known non-IR frames in this release. Frames detected as colour are excluded too.
65
- KNOWN_EXCLUSIONS = {
66
- "npf_000": "colour-enhanced render, not grey IR",
67
- "npf_001": "colour-enhanced render, not grey IR",
68
- }
69
- EXCLUSION_COLUMNS = ["sample_id", "storm_id", "source_split", "reason"]
70
- _FILE_STEM = {"train": "training_set", "test": "test_set"}
71
-
72
-
73
- def torchgeo_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
74
- """Return TorchGeo's features and labels frames for one competition side.
75
-
76
- Imports TorchGeo lazily so tests and the web app do not need it.
77
- ``download`` stays false: this reader never fetches imagery.
78
- """
79
- import importlib
80
-
81
- tropical = importlib.import_module("torchgeo.datasets")
82
- dataset = tropical.TropicalCyclone(root=str(root), split=split, download=False)
83
- return dataset.features, dataset.labels
84
-
85
-
86
- def csv_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
87
- """Read the same CSVs TorchGeo reads, without importing TorchGeo."""
88
- stem = _FILE_STEM[split]
89
- root = Path(root)
90
- return (
91
- pd.read_csv(root / f"{stem}_features.csv"),
92
- pd.read_csv(root / f"{stem}_labels.csv"),
93
- )
94
-
95
-
96
- def build_manifest(
97
- root: str | Path,
98
- manifest_dir: str | Path,
99
- splits: tuple[str, ...] = SPLITS,
100
- tables: Callable[[str | Path, str], tuple[pd.DataFrame, pd.DataFrame]] = torchgeo_tables,
101
- check_images: bool = True,
102
- keep_excluded: bool = False,
103
- ) -> pd.DataFrame:
104
- """Return a validated manifest. ``image_path`` is relative to ``manifest_dir``."""
105
- root = Path(root).resolve()
106
- manifest_dir = Path(manifest_dir).resolve()
107
- frames = []
108
- for split in splits:
109
- if split not in _FILE_STEM:
110
- raise ValueError(f"unknown split {split}")
111
- features, labels = tables(root, split)
112
- merged = features.merge(labels, on="Image ID", how="inner", validate="1:1")
113
- if len(merged) != len(labels) or len(merged) != len(features):
114
- raise ValueError(f"{split}: features and labels do not line up")
115
- image_dir = root / split
116
- paths = [image_dir / f"{image_id}.jpg" for image_id in merged["Image ID"]]
117
- frames.append(
118
- pd.DataFrame(
119
- {
120
- "sample_id": merged["Image ID"].astype(str),
121
- "image_path": [_relative(path, manifest_dir) for path in paths],
122
- "storm_id": merged["Storm ID"].astype(str),
123
- "wind_speed_kt": pd.to_numeric(merged["Wind Speed"]),
124
- "relative_time_s": pd.to_numeric(merged["Relative Time"]),
125
- "ocean": merged["Ocean"].astype(int),
126
- "basin": merged["Ocean"].map({1: "ATL", 2: "EPAC"}).fillna("unknown"),
127
- "sensor": "GOES",
128
- "channel": "IR",
129
- "pixel_units": "8bit_uncalibrated",
130
- "wind_averaging": WIND_AVERAGING,
131
- "label_source": LABEL_SOURCE,
132
- "center_source": "dataset_precentered",
133
- "source_split": split,
134
- "is_synthetic": False,
135
- }
136
- )
137
- )
138
- frame = pd.concat(frames, ignore_index=True)
139
- if check_images:
140
- frame = add_native_size(frame, manifest_dir)
141
- if keep_excluded:
142
- return frame
143
- frame, _ = split_exclusions(frame)
144
- return require_valid(frame)
145
-
146
-
147
- def split_exclusions(frame: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
148
- """Return (kept, excluded). Excluded rows carry a ``reason``."""
149
- reasons = frame["sample_id"].map(KNOWN_EXCLUSIONS)
150
- if "grey_ir" in frame:
151
- detected = ~frame["grey_ir"].astype(bool) & reasons.isna()
152
- reasons = reasons.mask(detected, "channels differ, not grey IR")
153
- drop = reasons.notna()
154
- excluded = frame.loc[drop, ["sample_id", "storm_id", "source_split"]].assign(reason=reasons[drop])
155
- return frame.loc[~drop].reset_index(drop=True), excluded.reset_index(drop=True)
156
-
157
-
158
- def exclusions_for(frame: pd.DataFrame) -> pd.DataFrame:
159
- """Exclusions for a raw (pre-filter) frame, in the CSV column order."""
160
- return split_exclusions(frame)[1][EXCLUSION_COLUMNS]
161
-
162
-
163
- def _relative(path: Path, base: Path) -> str:
164
- try:
165
- return path.relative_to(base).as_posix()
166
- except ValueError:
167
- return path.as_posix()
168
-
169
-
170
- def add_native_size(frame: pd.DataFrame, manifest_dir: str | Path) -> pd.DataFrame:
171
- """Record native size and JPEG mode. Fails if any image is missing."""
172
- from PIL import Image
173
-
174
- manifest_dir = Path(manifest_dir)
175
- heights, widths, modes, grey, missing = [], [], [], [], []
176
- for image_path in frame["image_path"]:
177
- path = Path(image_path)
178
- path = path if path.is_absolute() else manifest_dir / path
179
- if not path.is_file():
180
- missing.append(str(path))
181
- heights.append(-1)
182
- widths.append(-1)
183
- modes.append("")
184
- grey.append(False)
185
- continue
186
- with Image.open(path) as image:
187
- widths.append(image.width)
188
- heights.append(image.height)
189
- modes.append(image.mode)
190
- grey.append(image.mode == "L" or _channels_identical(np.asarray(image)))
191
- if missing:
192
- raise FileNotFoundError(f"{len(missing)} images missing, first: {missing[:3]}")
193
- out = frame.copy()
194
- out["native_height"] = heights
195
- out["native_width"] = widths
196
- out["source_mode"] = modes
197
- # False for colour-enhanced frames (npf_000/001 in this release). load_ir
198
- # refuses them, so filter on this column before training.
199
- out["grey_ir"] = grey
200
- out["orig_size"] = [h if h == w else -1 for h, w in zip(heights, widths)]
201
- if (out["orig_size"] < 0).any():
202
- raise ValueError("non-square frame found; orig_size assumes square chips")
203
- out["working_resample"] = np.where(out["orig_size"] == WORKING_SIZE, "none", "area_average")
204
- return out
205
-
206
-
207
- def _channels_identical(array: np.ndarray) -> bool:
208
- if array.ndim != 3:
209
- return True
210
- return bool(np.array_equal(array[..., 0], array[..., 1]) and np.array_equal(array[..., 0], array[..., 2]))
211
-
212
-
213
- def load_ir(path: str | Path) -> np.ndarray:
214
- """Read one frame as float32 at native size, single channel.
215
-
216
- Three-channel JPEGs are accepted only when all channels match, so a
217
- colour enhancement is never mistaken for IR.
218
- """
219
- from PIL import Image
220
-
221
- with Image.open(path) as image:
222
- array = np.asarray(image)
223
- if array.ndim == 3:
224
- if not _channels_identical(array):
225
- raise ValueError(f"{path}: channels differ, not a grey IR render")
226
- array = array[..., 0]
227
- return array.astype(np.float32)
228
-
229
-
230
- def to_working_grid(array: np.ndarray, size: int = WORKING_SIZE) -> tuple[np.ndarray, bool]:
231
- """Area-average a frame onto the ``size`` grid. Returns (array, resampled).
232
-
233
- Use only for frames that cover the same footprint (the 1093 frames do).
234
- A frame already at ``size`` is returned unchanged.
235
- """
236
- from PIL import Image
237
-
238
- if array.shape == (size, size):
239
- return array.astype(np.float32), False
240
- if array.ndim != 2 or array.shape[0] != array.shape[1] or array.shape[0] < size:
241
- raise ValueError(f"expected a square frame of at least {size}px, got {array.shape}")
242
- image = Image.fromarray(array.astype(np.float32), mode="F")
243
- return np.asarray(image.resize((size, size), resample=Image.BOX), dtype=np.float32), True
244
-
245
-
246
- def summarize(frame: pd.DataFrame) -> dict[str, object]:
247
- by_side = {
248
- side: {
249
- "rows": int((frame["source_split"] == side).sum()),
250
- "storms": int(frame.loc[frame["source_split"] == side, "storm_id"].nunique()),
251
- }
252
- for side in sorted(frame["source_split"].unique())
253
- }
254
- sides = [set(frame.loc[frame["source_split"] == side, "storm_id"]) for side in by_side]
255
- shared = len(set.intersection(*sides)) if len(sides) > 1 else 0
256
- return {
257
- "rows": int(len(frame)),
258
- "unique_storms": int(frame["storm_id"].nunique()),
259
- "by_source_split": by_side,
260
- "storms_on_both_source_sides": shared,
261
- "wind_kt_min": float(frame["wind_speed_kt"].min()),
262
- "wind_kt_max": float(frame["wind_speed_kt"].max()),
263
- "wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
264
- "native_sizes": sorted(
265
- {f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}
266
- )
267
- if "native_height" in frame
268
- else [],
269
- "source_modes": frame["source_mode"].value_counts().to_dict()
270
- if "source_mode" in frame
271
- else {},
272
- "frames_not_grey_ir": sorted(frame.loc[~frame["grey_ir"], "sample_id"]) if "grey_ir" in frame else [],
273
- "native_size_counts": {
274
- f"{h}x{w}": int(n)
275
- for (h, w), n in frame.groupby(["native_height", "native_width"]).size().items()
276
- }
277
- if "native_height" in frame
278
- else {},
279
- "orig_size_counts": {int(k): int(v) for k, v in frame["orig_size"].value_counts().items()}
280
- if "orig_size" in frame
281
- else {},
282
- "frames_to_area_average_to_366": int((frame["working_resample"] == "area_average").sum())
283
- if "working_resample" in frame
284
- else 0,
285
- "has_split_column": "split" in frame.columns,
286
- "wind_averaging": sorted(frame["wind_averaging"].unique()),
287
- "is_synthetic": bool(frame["is_synthetic"].any()),
288
- }
289
-
290
-
291
- def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path, index: int = 0) -> dict[str, object]:
292
- import matplotlib
293
-
294
- matplotlib.use("Agg")
295
- import matplotlib.pyplot as plt
296
-
297
- row = frame.iloc[index]
298
- path = Path(row["image_path"])
299
- path = path if path.is_absolute() else Path(manifest_dir) / path
300
- image = load_ir(path)
301
- fig, ax = plt.subplots(figsize=(4, 4))
302
- ax.imshow(image, cmap="gray")
303
- ax.set_title(f"{row['sample_id']} | {row['wind_speed_kt']:.0f} kt (1min) | NASA TC, real")
304
- ax.axis("off")
305
- Path(out).parent.mkdir(parents=True, exist_ok=True)
306
- fig.savefig(out, dpi=100, bbox_inches="tight")
307
- plt.close(fig)
308
- return {"sample_id": row["sample_id"], "wind_speed_kt": float(row["wind_speed_kt"]), "shape": list(image.shape), "png": str(out)}
309
-
310
-
311
- def storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:
312
- """Run the project splitter on the combined manifest and assert no storm leaks."""
313
- from src.splits import assert_no_group_leakage, assign_storms
314
-
315
- if "split" in frame.columns:
316
- raise ValueError("manifest must not carry split; use source_split for the official side")
317
- assigned = assign_storms(frame, strategy, seed=seed)
318
- parts = [assigned.loc[assigned["split"] == name] for name in ("train", "val", "test")]
319
- assert_no_group_leakage(*parts)
320
- return {
321
- "strategy": strategy,
322
- "rows": {name: int(len(part)) for name, part in zip(("train", "val", "test"), parts)},
323
- "storms": {name: int(part["storm_id"].nunique()) for name, part in zip(("train", "val", "test"), parts)},
324
- "leakage": "none",
325
- }
326
-
327
-
328
- def main() -> None:
329
- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
330
- parser.add_argument("--root", required=True, help="TorchGeo TropicalCyclone root")
331
- parser.add_argument("--out", default="data/nasa_tc/manifest.csv")
332
- parser.add_argument("--splits", nargs="+", default=list(SPLITS))
333
- parser.add_argument("--reader", choices=["torchgeo", "csv"], default="torchgeo")
334
- parser.add_argument("--summary", default="reports/nasa_tc_summary.json")
335
- parser.add_argument("--sample-png", default="reports/nasa_tc_sample.png")
336
- parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/nasa_tc_exclusions.csv")
337
- args = parser.parse_args()
338
-
339
- out = Path(args.out)
340
- out.parent.mkdir(parents=True, exist_ok=True)
341
- tables = torchgeo_tables if args.reader == "torchgeo" else csv_tables
342
- raw = build_manifest(args.root, out.parent, tuple(args.splits), tables, keep_excluded=True)
343
- excluded = exclusions_for(raw)
344
- frame = require_valid(split_exclusions(raw)[0])
345
- exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "nasa_tc_exclusions.csv"
346
- excluded.to_csv(exclusions_path, index=False)
347
- frame.drop(columns=["imd5_class"]).to_csv(out, index=False)
348
- summary = summarize(frame)
349
- summary["excluded"] = {"count": int(len(excluded)), "sample_ids": excluded["sample_id"].tolist(), "file": str(exclusions_path)}
350
- summary["storm_split_check"] = storm_split_check(frame)
351
- summary["reader"] = args.reader
352
- summary["manifest"] = str(out)
353
- summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
354
- Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
355
- Path(args.summary).write_text(json.dumps(summary, indent=2))
356
- print(json.dumps(summary, indent=2))
357
-
358
-
359
- if __name__ == "__main__":
360
- main()
 
1
+ """Build a Cloudie manifest from the NASA Tropical Storm Wind Speed dataset.
2
+
3
+ The main path is TorchGeo ``TropicalCyclone`` (Maskey et al. 2020,
4
+ https://doi.org/10.1109/JSTARS.2020.3011907). TorchGeo checks the files and
5
+ reads ``{training,test}_set_{features,labels}.csv``; images sit at
6
+ ``<root>/<split>/<Image ID>.jpg``. A one-time download is
7
+ ``TropicalCyclone(root, split, download=True)`` from the public Source
8
+ Cooperative blob. The copy tool and the mirror are named in
9
+ ``docs/DATA_SOURCES.md``. The Hugging Face repo
10
+ ``torchgeo/tropical_cyclone`` is only a mirror. CI never downloads either.
11
+
12
+ Images keep their native size. Nothing in this module resizes. Most frames
13
+ are 366 x 366, but the real train side also has 1093 x 1093 frames (stored
14
+ as grey in an RGB JPEG), which TorchGeo's own ``__getitem__`` bilinearly
15
+ resizes to 366. ``native_height``, ``native_width`` and ``orig_size`` are
16
+ recorded per row. An empirical check (scripted in the PR notes) found that a
17
+ 1093 frame covers the same footprint as a 366 frame at about 3x the pixel
18
+ density: its spatial autocorrelation length is about 3.2x longer in pixels,
19
+ and after a 3x area average its texture and cold-cloud fraction match the
20
+ 366 frames, while a 366 centre crop does not. ``to_working_grid`` therefore
21
+ area-averages to the 366 working grid, and ``working_resample`` marks which
22
+ rows need it. The manifest itself is never resampled.
23
+
24
+ Colour-enhanced frames (``npf_000``, ``npf_001``) are not grey IR. They are
25
+ dropped from the manifest and listed with a reason in an exclusions CSV next
26
+ to it.
27
+
28
+ The manifest never has a ``split`` column. The official side goes only to
29
+ ``source_split``. ``src.splits.assign_storms`` writes ``split`` by storm.
30
+
31
+ Pixel values are an 8-bit rendering of IR brightness, not calibrated Kelvin.
32
+ Call them pixel stats until a calibration table exists.
33
+
34
+ Labels are HURDAT2 best-track maximum sustained winds in knots. HURDAT2 uses
35
+ 1-minute sustained winds, so ``wind_averaging`` is ``1min``.
36
+
37
+ There is no distance-to-land join. ``storm_id`` is a 3-letter competition
38
+ identifier and the only time field is ``relative_time_s``, so an IBTrACS
39
+ match would be a guess. ``near_land`` stays unknown. See
40
+ ``nasa_tc/audit/README.md``. Do not invent a mapping.
41
+
42
+ The competition's own train/test sides split frames, not storms: many test
43
+ storms also appear in train. ``source_split`` keeps that side for reference
44
+ only. Do not train on one side and score on the other. Use the storm-wise
45
+ splitter in ``src.splits`` on the union instead.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import argparse
51
+ import json
52
+ from collections.abc import Callable
53
+ from pathlib import Path
54
+
55
+ import numpy as np
56
+ import pandas as pd
57
+
58
+ from src.schema import require_valid
59
+
60
+ WIND_AVERAGING = "1min"
61
+ LABEL_SOURCE = "nasa_tropical_storm_competition_hurdat2"
62
+ SPLITS = ("train", "test")
63
+ WORKING_SIZE = 366 # TorchGeo's grid and config data.image_size: native (PR #16)
64
+ # Known non-IR frames in this release. Frames detected as colour are excluded too.
65
+ KNOWN_EXCLUSIONS = {
66
+ "npf_000": "colour-enhanced render, not grey IR",
67
+ "npf_001": "colour-enhanced render, not grey IR",
68
+ }
69
+ EXCLUSION_COLUMNS = ["sample_id", "storm_id", "source_split", "reason"]
70
+ _FILE_STEM = {"train": "training_set", "test": "test_set"}
71
+
72
+
73
+ def torchgeo_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
74
+ """Return TorchGeo's features and labels frames for one competition side.
75
+
76
+ Imports TorchGeo lazily so tests and the web app do not need it.
77
+ ``download`` stays false: this reader never fetches imagery.
78
+ """
79
+ import importlib
80
+
81
+ tropical = importlib.import_module("torchgeo.datasets")
82
+ dataset = tropical.TropicalCyclone(root=str(root), split=split, download=False)
83
+ return dataset.features, dataset.labels
84
+
85
+
86
+ def csv_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
87
+ """Read the same CSVs TorchGeo reads, without importing TorchGeo."""
88
+ stem = _FILE_STEM[split]
89
+ root = Path(root)
90
+ return (
91
+ pd.read_csv(root / f"{stem}_features.csv"),
92
+ pd.read_csv(root / f"{stem}_labels.csv"),
93
+ )
94
+
95
+
96
+ def build_manifest(
97
+ root: str | Path,
98
+ manifest_dir: str | Path,
99
+ splits: tuple[str, ...] = SPLITS,
100
+ tables: Callable[[str | Path, str], tuple[pd.DataFrame, pd.DataFrame]] = torchgeo_tables,
101
+ check_images: bool = True,
102
+ keep_excluded: bool = False,
103
+ ) -> pd.DataFrame:
104
+ """Return a validated manifest. ``image_path`` is relative to ``manifest_dir``."""
105
+ root = Path(root).resolve()
106
+ manifest_dir = Path(manifest_dir).resolve()
107
+ frames = []
108
+ for split in splits:
109
+ if split not in _FILE_STEM:
110
+ raise ValueError(f"unknown split {split}")
111
+ features, labels = tables(root, split)
112
+ merged = features.merge(labels, on="Image ID", how="inner", validate="1:1")
113
+ if len(merged) != len(labels) or len(merged) != len(features):
114
+ raise ValueError(f"{split}: features and labels do not line up")
115
+ image_dir = root / split
116
+ paths = [image_dir / f"{image_id}.jpg" for image_id in merged["Image ID"]]
117
+ frames.append(
118
+ pd.DataFrame(
119
+ {
120
+ "sample_id": merged["Image ID"].astype(str),
121
+ "image_path": [_relative(path, manifest_dir) for path in paths],
122
+ "storm_id": merged["Storm ID"].astype(str),
123
+ "wind_speed_kt": pd.to_numeric(merged["Wind Speed"]),
124
+ "relative_time_s": pd.to_numeric(merged["Relative Time"]),
125
+ "ocean": merged["Ocean"].astype(int),
126
+ "basin": merged["Ocean"].map({1: "ATL", 2: "EPAC"}).fillna("unknown"),
127
+ "sensor": "GOES",
128
+ "channel": "IR",
129
+ "pixel_units": "8bit_uncalibrated",
130
+ "wind_averaging": WIND_AVERAGING,
131
+ "label_source": LABEL_SOURCE,
132
+ "center_source": "dataset_precentered",
133
+ "source_split": split,
134
+ "is_synthetic": False,
135
+ }
136
+ )
137
+ )
138
+ frame = pd.concat(frames, ignore_index=True)
139
+ if check_images:
140
+ frame = add_native_size(frame, manifest_dir)
141
+ if keep_excluded:
142
+ return frame
143
+ frame, _ = split_exclusions(frame)
144
+ return require_valid(frame)
145
+
146
+
147
+ def split_exclusions(frame: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
148
+ """Return (kept, excluded). Excluded rows carry a ``reason``."""
149
+ reasons = frame["sample_id"].map(KNOWN_EXCLUSIONS)
150
+ if "grey_ir" in frame:
151
+ detected = ~frame["grey_ir"].astype(bool) & reasons.isna()
152
+ reasons = reasons.mask(detected, "channels differ, not grey IR")
153
+ drop = reasons.notna()
154
+ excluded = frame.loc[drop, ["sample_id", "storm_id", "source_split"]].assign(reason=reasons[drop])
155
+ return frame.loc[~drop].reset_index(drop=True), excluded.reset_index(drop=True)
156
+
157
+
158
+ def exclusions_for(frame: pd.DataFrame) -> pd.DataFrame:
159
+ """Exclusions for a raw (pre-filter) frame, in the CSV column order."""
160
+ return split_exclusions(frame)[1][EXCLUSION_COLUMNS]
161
+
162
+
163
+ def _relative(path: Path, base: Path) -> str:
164
+ try:
165
+ return path.relative_to(base).as_posix()
166
+ except ValueError:
167
+ return path.as_posix()
168
+
169
+
170
+ def add_native_size(frame: pd.DataFrame, manifest_dir: str | Path) -> pd.DataFrame:
171
+ """Record native size and JPEG mode. Fails if any image is missing."""
172
+ from PIL import Image
173
+
174
+ manifest_dir = Path(manifest_dir)
175
+ heights, widths, modes, grey, missing = [], [], [], [], []
176
+ for image_path in frame["image_path"]:
177
+ path = Path(image_path)
178
+ path = path if path.is_absolute() else manifest_dir / path
179
+ if not path.is_file():
180
+ missing.append(str(path))
181
+ heights.append(-1)
182
+ widths.append(-1)
183
+ modes.append("")
184
+ grey.append(False)
185
+ continue
186
+ with Image.open(path) as image:
187
+ widths.append(image.width)
188
+ heights.append(image.height)
189
+ modes.append(image.mode)
190
+ grey.append(image.mode == "L" or _channels_identical(np.asarray(image)))
191
+ if missing:
192
+ raise FileNotFoundError(f"{len(missing)} images missing, first: {missing[:3]}")
193
+ out = frame.copy()
194
+ out["native_height"] = heights
195
+ out["native_width"] = widths
196
+ out["source_mode"] = modes
197
+ # False for colour-enhanced frames (npf_000/001 in this release). load_ir
198
+ # refuses them, so filter on this column before training.
199
+ out["grey_ir"] = grey
200
+ out["orig_size"] = [h if h == w else -1 for h, w in zip(heights, widths)]
201
+ if (out["orig_size"] < 0).any():
202
+ raise ValueError("non-square frame found; orig_size assumes square chips")
203
+ out["working_resample"] = np.where(out["orig_size"] == WORKING_SIZE, "none", "area_average")
204
+ return out
205
+
206
+
207
+ def _channels_identical(array: np.ndarray) -> bool:
208
+ if array.ndim != 3:
209
+ return True
210
+ return bool(np.array_equal(array[..., 0], array[..., 1]) and np.array_equal(array[..., 0], array[..., 2]))
211
+
212
+
213
+ def load_ir(path: str | Path) -> np.ndarray:
214
+ """Read one frame as float32 at native size, single channel.
215
+
216
+ Three-channel JPEGs are accepted only when all channels match, so a
217
+ colour enhancement is never mistaken for IR.
218
+ """
219
+ from PIL import Image
220
+
221
+ with Image.open(path) as image:
222
+ array = np.asarray(image)
223
+ if array.ndim == 3:
224
+ if not _channels_identical(array):
225
+ raise ValueError(f"{path}: channels differ, not a grey IR render")
226
+ array = array[..., 0]
227
+ return array.astype(np.float32)
228
+
229
+
230
+ def to_working_grid(array: np.ndarray, size: int = WORKING_SIZE) -> tuple[np.ndarray, bool]:
231
+ """Area-average a frame onto the ``size`` grid. Returns (array, resampled).
232
+
233
+ Use only for frames that cover the same footprint (the 1093 frames do).
234
+ A frame already at ``size`` is returned unchanged.
235
+ """
236
+ from PIL import Image
237
+
238
+ if array.shape == (size, size):
239
+ return array.astype(np.float32), False
240
+ if array.ndim != 2 or array.shape[0] != array.shape[1] or array.shape[0] < size:
241
+ raise ValueError(f"expected a square frame of at least {size}px, got {array.shape}")
242
+ image = Image.fromarray(array.astype(np.float32), mode="F")
243
+ return np.asarray(image.resize((size, size), resample=Image.BOX), dtype=np.float32), True
244
+
245
+
246
+ def summarize(frame: pd.DataFrame) -> dict[str, object]:
247
+ by_side = {
248
+ side: {
249
+ "rows": int((frame["source_split"] == side).sum()),
250
+ "storms": int(frame.loc[frame["source_split"] == side, "storm_id"].nunique()),
251
+ }
252
+ for side in sorted(frame["source_split"].unique())
253
+ }
254
+ sides = [set(frame.loc[frame["source_split"] == side, "storm_id"]) for side in by_side]
255
+ shared = len(set.intersection(*sides)) if len(sides) > 1 else 0
256
+ return {
257
+ "rows": int(len(frame)),
258
+ "unique_storms": int(frame["storm_id"].nunique()),
259
+ "by_source_split": by_side,
260
+ "storms_on_both_source_sides": shared,
261
+ "wind_kt_min": float(frame["wind_speed_kt"].min()),
262
+ "wind_kt_max": float(frame["wind_speed_kt"].max()),
263
+ "wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
264
+ "native_sizes": sorted(
265
+ {f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}
266
+ )
267
+ if "native_height" in frame
268
+ else [],
269
+ "source_modes": frame["source_mode"].value_counts().to_dict()
270
+ if "source_mode" in frame
271
+ else {},
272
+ "frames_not_grey_ir": sorted(frame.loc[~frame["grey_ir"], "sample_id"]) if "grey_ir" in frame else [],
273
+ "native_size_counts": {
274
+ f"{h}x{w}": int(n)
275
+ for (h, w), n in frame.groupby(["native_height", "native_width"]).size().items()
276
+ }
277
+ if "native_height" in frame
278
+ else {},
279
+ "orig_size_counts": {int(k): int(v) for k, v in frame["orig_size"].value_counts().items()}
280
+ if "orig_size" in frame
281
+ else {},
282
+ "frames_to_area_average_to_366": int((frame["working_resample"] == "area_average").sum())
283
+ if "working_resample" in frame
284
+ else 0,
285
+ "has_split_column": "split" in frame.columns,
286
+ "wind_averaging": sorted(frame["wind_averaging"].unique()),
287
+ "is_synthetic": bool(frame["is_synthetic"].any()),
288
+ }
289
+
290
+
291
+ def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path, index: int = 0) -> dict[str, object]:
292
+ import matplotlib
293
+
294
+ matplotlib.use("Agg")
295
+ import matplotlib.pyplot as plt
296
+
297
+ row = frame.iloc[index]
298
+ path = Path(row["image_path"])
299
+ path = path if path.is_absolute() else Path(manifest_dir) / path
300
+ image = load_ir(path)
301
+ fig, ax = plt.subplots(figsize=(4, 4))
302
+ ax.imshow(image, cmap="gray")
303
+ ax.set_title(f"{row['sample_id']} | {row['wind_speed_kt']:.0f} kt (1min) | NASA TC, real")
304
+ ax.axis("off")
305
+ Path(out).parent.mkdir(parents=True, exist_ok=True)
306
+ fig.savefig(out, dpi=100, bbox_inches="tight")
307
+ plt.close(fig)
308
+ return {"sample_id": row["sample_id"], "wind_speed_kt": float(row["wind_speed_kt"]), "shape": list(image.shape), "png": str(out)}
309
+
310
+
311
+ def storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:
312
+ """Run the project splitter on the combined manifest and assert no storm leaks."""
313
+ from src.splits import assert_no_group_leakage, assign_storms
314
+
315
+ if "split" in frame.columns:
316
+ raise ValueError("manifest must not carry split; use source_split for the official side")
317
+ assigned = assign_storms(frame, strategy, seed=seed)
318
+ parts = [assigned.loc[assigned["split"] == name] for name in ("train", "val", "test")]
319
+ assert_no_group_leakage(*parts)
320
+ return {
321
+ "strategy": strategy,
322
+ "rows": {name: int(len(part)) for name, part in zip(("train", "val", "test"), parts)},
323
+ "storms": {name: int(part["storm_id"].nunique()) for name, part in zip(("train", "val", "test"), parts)},
324
+ "leakage": "none",
325
+ }
326
+
327
+
328
+ def main() -> None:
329
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
330
+ parser.add_argument("--root", required=True, help="TorchGeo TropicalCyclone root")
331
+ parser.add_argument("--out", default="data/nasa_tc/manifest.csv")
332
+ parser.add_argument("--splits", nargs="+", default=list(SPLITS))
333
+ parser.add_argument("--reader", choices=["torchgeo", "csv"], default="torchgeo")
334
+ parser.add_argument("--summary", default="reports/nasa_tc_summary.json")
335
+ parser.add_argument("--sample-png", default="reports/nasa_tc_sample.png")
336
+ parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/nasa_tc_exclusions.csv")
337
+ args = parser.parse_args()
338
+
339
+ out = Path(args.out)
340
+ out.parent.mkdir(parents=True, exist_ok=True)
341
+ tables = torchgeo_tables if args.reader == "torchgeo" else csv_tables
342
+ raw = build_manifest(args.root, out.parent, tuple(args.splits), tables, keep_excluded=True)
343
+ excluded = exclusions_for(raw)
344
+ frame = require_valid(split_exclusions(raw)[0])
345
+ exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "nasa_tc_exclusions.csv"
346
+ excluded.to_csv(exclusions_path, index=False)
347
+ frame.drop(columns=["imd5_class"]).to_csv(out, index=False)
348
+ summary = summarize(frame)
349
+ summary["excluded"] = {"count": int(len(excluded)), "sample_ids": excluded["sample_id"].tolist(), "file": str(exclusions_path)}
350
+ summary["storm_split_check"] = storm_split_check(frame)
351
+ summary["reader"] = args.reader
352
+ summary["manifest"] = str(out)
353
+ summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
354
+ Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
355
+ Path(args.summary).write_text(json.dumps(summary, indent=2))
356
+ print(json.dumps(summary, indent=2))
357
+
358
+
359
+ if __name__ == "__main__":
360
+ main()
src/plots.py CHANGED
@@ -1,109 +1,109 @@
1
- """Comparison figures for classical baselines.
2
-
3
- Figures are software artifacts. A title that includes a number is not a
4
- result to quote, and these plots are not warnings.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from pathlib import Path
10
-
11
- import numpy as np
12
-
13
- from src.schema import DEFAULT_NAMES
14
-
15
-
16
- def _pyplot():
17
- import matplotlib
18
-
19
- matplotlib.use("Agg")
20
- import matplotlib.pyplot as plt
21
-
22
- return plt
23
-
24
-
25
- def save_confusion_matrix(
26
- y_true: np.ndarray,
27
- y_pred: np.ndarray,
28
- path: str | Path,
29
- title: str,
30
- labels: tuple[str, ...] = DEFAULT_NAMES,
31
- ) -> Path:
32
- """Write a count matrix. Classes absent from both sides stay in the grid."""
33
- plt = _pyplot()
34
- truth = np.asarray(y_true).ravel()
35
- pred = np.asarray(y_pred).ravel()
36
- index = {label: position for position, label in enumerate(labels)}
37
- counts = np.zeros((len(labels), len(labels)), dtype=int)
38
- for actual, guess in zip(truth, pred, strict=True):
39
- if actual not in index or guess not in index:
40
- continue
41
- counts[index[actual], index[guess]] += 1
42
- figure, axis = plt.subplots(figsize=(6.2, 5.2))
43
- image = axis.imshow(counts, cmap="Blues")
44
- axis.set_xticks(range(len(labels)), labels, rotation=45, ha="right")
45
- axis.set_yticks(range(len(labels)), labels)
46
- axis.set_xlabel("Predicted class")
47
- axis.set_ylabel("Best-track class (noisy label)")
48
- axis.set_title(title)
49
- for row in range(counts.shape[0]):
50
- for col in range(counts.shape[1]):
51
- axis.text(col, row, str(counts[row, col]), ha="center", va="center", fontsize=8)
52
- figure.colorbar(image, ax=axis, fraction=0.046)
53
- figure.tight_layout()
54
- destination = Path(path)
55
- destination.parent.mkdir(parents=True, exist_ok=True)
56
- figure.savefig(destination, dpi=100)
57
- plt.close(figure)
58
- return destination
59
-
60
-
61
- def save_feature_importance(
62
- importances: dict[str, float],
63
- path: str | Path,
64
- title: str,
65
- limit: int = 15,
66
- ) -> Path | None:
67
- """Horizontal bars for a train-only selection score. Empty input writes nothing."""
68
- if not importances:
69
- return None
70
- plt = _pyplot()
71
- ordered = sorted(importances.items(), key=lambda item: (item[1], item[0]))
72
- ordered = ordered[-limit:]
73
- labels = [name for name, _score in ordered]
74
- scores = [score for _name, score in ordered]
75
- figure, axis = plt.subplots(figsize=(7.0, 5.0))
76
- axis.barh(labels, scores, color="#3d5a40")
77
- axis.set_xlabel("Train-split selection score")
78
- axis.set_title(title)
79
- figure.tight_layout()
80
- destination = Path(path)
81
- destination.parent.mkdir(parents=True, exist_ok=True)
82
- figure.savefig(destination, dpi=100)
83
- plt.close(figure)
84
- return destination
85
-
86
-
87
- def save_regression_scatter(
88
- y_true: np.ndarray,
89
- y_pred: np.ndarray,
90
- path: str | Path,
91
- title: str,
92
- ) -> Path:
93
- plt = _pyplot()
94
- truth = np.asarray(y_true, dtype=np.float64).ravel()
95
- pred = np.asarray(y_pred, dtype=np.float64).ravel()
96
- figure, axis = plt.subplots(figsize=(5.2, 5.0))
97
- axis.scatter(truth, pred, s=18, alpha=0.8, color="#1d3557")
98
- low = float(min(truth.min(), pred.min()))
99
- high = float(max(truth.max(), pred.max()))
100
- axis.plot([low, high], [low, high], color="#9b2226", linewidth=1)
101
- axis.set_xlabel("Label wind (kt)")
102
- axis.set_ylabel("Predicted wind (kt)")
103
- axis.set_title(title)
104
- figure.tight_layout()
105
- destination = Path(path)
106
- destination.parent.mkdir(parents=True, exist_ok=True)
107
- figure.savefig(destination, dpi=100)
108
- plt.close(figure)
109
- return destination
 
1
+ """Comparison figures for classical baselines.
2
+
3
+ Figures are software artifacts. A title that includes a number is not a
4
+ result to quote, and these plots are not warnings.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ from src.schema import DEFAULT_NAMES
14
+
15
+
16
+ def _pyplot():
17
+ import matplotlib
18
+
19
+ matplotlib.use("Agg")
20
+ import matplotlib.pyplot as plt
21
+
22
+ return plt
23
+
24
+
25
+ def save_confusion_matrix(
26
+ y_true: np.ndarray,
27
+ y_pred: np.ndarray,
28
+ path: str | Path,
29
+ title: str,
30
+ labels: tuple[str, ...] = DEFAULT_NAMES,
31
+ ) -> Path:
32
+ """Write a count matrix. Classes absent from both sides stay in the grid."""
33
+ plt = _pyplot()
34
+ truth = np.asarray(y_true).ravel()
35
+ pred = np.asarray(y_pred).ravel()
36
+ index = {label: position for position, label in enumerate(labels)}
37
+ counts = np.zeros((len(labels), len(labels)), dtype=int)
38
+ for actual, guess in zip(truth, pred, strict=True):
39
+ if actual not in index or guess not in index:
40
+ continue
41
+ counts[index[actual], index[guess]] += 1
42
+ figure, axis = plt.subplots(figsize=(6.2, 5.2))
43
+ image = axis.imshow(counts, cmap="Blues")
44
+ axis.set_xticks(range(len(labels)), labels, rotation=45, ha="right")
45
+ axis.set_yticks(range(len(labels)), labels)
46
+ axis.set_xlabel("Predicted class")
47
+ axis.set_ylabel("Best-track class (noisy label)")
48
+ axis.set_title(title)
49
+ for row in range(counts.shape[0]):
50
+ for col in range(counts.shape[1]):
51
+ axis.text(col, row, str(counts[row, col]), ha="center", va="center", fontsize=8)
52
+ figure.colorbar(image, ax=axis, fraction=0.046)
53
+ figure.tight_layout()
54
+ destination = Path(path)
55
+ destination.parent.mkdir(parents=True, exist_ok=True)
56
+ figure.savefig(destination, dpi=100)
57
+ plt.close(figure)
58
+ return destination
59
+
60
+
61
+ def save_feature_importance(
62
+ importances: dict[str, float],
63
+ path: str | Path,
64
+ title: str,
65
+ limit: int = 15,
66
+ ) -> Path | None:
67
+ """Horizontal bars for a train-only selection score. Empty input writes nothing."""
68
+ if not importances:
69
+ return None
70
+ plt = _pyplot()
71
+ ordered = sorted(importances.items(), key=lambda item: (item[1], item[0]))
72
+ ordered = ordered[-limit:]
73
+ labels = [name for name, _score in ordered]
74
+ scores = [score for _name, score in ordered]
75
+ figure, axis = plt.subplots(figsize=(7.0, 5.0))
76
+ axis.barh(labels, scores, color="#3d5a40")
77
+ axis.set_xlabel("Train-split selection score")
78
+ axis.set_title(title)
79
+ figure.tight_layout()
80
+ destination = Path(path)
81
+ destination.parent.mkdir(parents=True, exist_ok=True)
82
+ figure.savefig(destination, dpi=100)
83
+ plt.close(figure)
84
+ return destination
85
+
86
+
87
+ def save_regression_scatter(
88
+ y_true: np.ndarray,
89
+ y_pred: np.ndarray,
90
+ path: str | Path,
91
+ title: str,
92
+ ) -> Path:
93
+ plt = _pyplot()
94
+ truth = np.asarray(y_true, dtype=np.float64).ravel()
95
+ pred = np.asarray(y_pred, dtype=np.float64).ravel()
96
+ figure, axis = plt.subplots(figsize=(5.2, 5.0))
97
+ axis.scatter(truth, pred, s=18, alpha=0.8, color="#1d3557")
98
+ low = float(min(truth.min(), pred.min()))
99
+ high = float(max(truth.max(), pred.max()))
100
+ axis.plot([low, high], [low, high], color="#9b2226", linewidth=1)
101
+ axis.set_xlabel("Label wind (kt)")
102
+ axis.set_ylabel("Predicted wind (kt)")
103
+ axis.set_title(title)
104
+ figure.tight_layout()
105
+ destination = Path(path)
106
+ destination.parent.mkdir(parents=True, exist_ok=True)
107
+ figure.savefig(destination, dpi=100)
108
+ plt.close(figure)
109
+ return destination
src/preprocessing.py CHANGED
@@ -1,314 +1,314 @@
1
- """Image checks, resize, train-only normalization, and train-only augmentation.
2
-
3
- Southern Hemisphere frames stay as stored. ``leave_unflipped`` records a
4
- hemisphere label and does not mirror the array.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from dataclasses import dataclass
10
-
11
- import numpy as np
12
- from PIL import Image
13
-
14
- from src.config import parse_image_size
15
- from src.splits import LeakageError
16
-
17
- # A missing-pixel fraction above this value fails closed. It does not warn.
18
- MAX_MISSING_FRACTION = 0.30
19
-
20
-
21
- @dataclass(frozen=True)
22
- class NormStats:
23
- mean: float
24
- std: float
25
- source_split: str
26
-
27
-
28
- # Pixel units stay on the dataset that produced them. NASA chips are 8-bit
29
- # counts. TCIR IR1 is brightness temperature in kelvin. They are never
30
- # pooled into one mean and std. A later dataset gets its own entry.
31
- PIXEL_KIND = {
32
- "nasa": "uint8",
33
- "tcir": "brightness_temperature_k",
34
- "incyde": "jpeg_uncalibrated",
35
- "smoke": "synthetic",
36
- }
37
-
38
-
39
- def pixel_kind(dataset: str) -> str:
40
- """Unit label for one dataset. Unknown datasets stay unspecified."""
41
- return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")
42
-
43
-
44
- def norm_by_dataset(dataset: str, stats: NormStats) -> dict:
45
- """One dataset's train-split stats. The map has that key only."""
46
- if stats.source_split != "train":
47
- raise LeakageError("normalization stats may be fit on the train split only")
48
- name = str(dataset).strip().lower()
49
- if not name:
50
- raise ValueError("dataset name is required for normalization stats")
51
- return {
52
- name: {
53
- "mean": float(stats.mean),
54
- "std": float(stats.std),
55
- "source_split": "train",
56
- "pixel_kind": pixel_kind(name),
57
- }
58
- }
59
-
60
-
61
- def norm_stats_from_checkpoint(payload: dict) -> NormStats:
62
- """Stats for the checkpoint's own dataset. Mixed maps are refused.
63
-
64
- A checkpoint written before per-dataset stats still uses ``norm_mean``
65
- and ``norm_std``. A map with two datasets, or a key that is not the
66
- checkpoint dataset, is not applied.
67
- """
68
- grouped = payload.get("norm_by_dataset")
69
- dataset = payload.get("dataset")
70
- if isinstance(grouped, dict) and grouped:
71
- if len(grouped) != 1:
72
- raise ValueError(
73
- "checkpoint mixes normalization stats across datasets; refusing to apply them"
74
- )
75
- name = None if dataset is None else str(dataset)
76
- if name not in grouped:
77
- raise ValueError(
78
- "checkpoint norm_by_dataset does not match the checkpoint dataset; "
79
- "refusing to mix normalization stats"
80
- )
81
- entry = grouped[name]
82
- if str(entry.get("source_split")) != "train":
83
- raise ValueError("checkpoint normalization was not fit on train")
84
- return NormStats(
85
- mean=float(entry["mean"]),
86
- std=float(entry["std"]),
87
- source_split="train",
88
- )
89
- if "norm_mean" not in payload or "norm_std" not in payload:
90
- raise ValueError("checkpoint is missing normalization stats")
91
- source = payload.get("norm_source_split")
92
- if source is not None and str(source) != "train":
93
- raise ValueError("checkpoint normalization was not fit on train")
94
- return NormStats(
95
- mean=float(payload["norm_mean"]),
96
- std=float(payload["norm_std"]),
97
- source_split="train",
98
- )
99
-
100
-
101
- def as_channel_first(image: np.ndarray) -> np.ndarray:
102
- array = np.asarray(image, dtype=np.float32)
103
- if array.ndim == 2:
104
- return array[None, ...]
105
- if array.ndim != 3:
106
- raise ValueError(f"expected a 2D or 3D image, got {array.shape}")
107
- if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
108
- return array
109
- if array.shape[-1] <= 4:
110
- return np.moveaxis(array, -1, 0)
111
- raise ValueError(f"cannot infer the channel axis for shape {array.shape}")
112
-
113
-
114
- def missing_fraction(image: np.ndarray) -> float:
115
- return float((~np.isfinite(image)).mean())
116
-
117
-
118
- def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:
119
- """Fit mean and std. Refuses anything other than the train split."""
120
- if source_split != "train":
121
- raise LeakageError("normalization stats may be fit on the train split only")
122
- if not images:
123
- raise ValueError("need at least one train image")
124
- values = [np.asarray(image, dtype=np.float32) for image in images]
125
- finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])
126
- if finite.size == 0:
127
- raise ValueError("train images have no finite pixels")
128
- std = float(finite.std())
129
- if std < 1e-6:
130
- std = 1.0
131
- return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)
132
-
133
-
134
- def stack_prepared(images: list[np.ndarray]) -> np.ndarray:
135
- """Stack chips that have already been prepared.
136
-
137
- A native ``image_size`` does not resize, so every chip in the stack
138
- must already share a height and width.
139
- """
140
- if not images:
141
- raise ValueError("no images to stack")
142
- try:
143
- return np.stack(images)
144
- except ValueError as exc:
145
- shapes = sorted({tuple(np.shape(image)) for image in images})
146
- raise ValueError(
147
- "prepared chips do not share a height and width "
148
- f"{shapes}. A native image_size does not resize them onto one grid."
149
- ) from exc
150
-
151
-
152
- def _resize(image: np.ndarray, size: int) -> np.ndarray:
153
- channels = []
154
- for channel in image:
155
- picture = Image.fromarray(channel.astype(np.float32), mode="F")
156
- picture = picture.resize((size, size), Image.Resampling.BILINEAR)
157
- channels.append(np.asarray(picture, dtype=np.float32))
158
- return np.stack(channels, axis=0)
159
-
160
-
161
- def prepare_image(
162
- image: np.ndarray,
163
- image_size: int | str | None,
164
- stats: NormStats | None,
165
- max_missing_fraction: float = MAX_MISSING_FRACTION,
166
- ) -> np.ndarray:
167
- """Return ``(C, H, W)`` float32. Does not invent brightness temperature.
168
-
169
- ``image_size`` ``None`` or ``native`` keeps the chip's height and width.
170
- An integer resizes to that square. ``max_missing_fraction`` is
171
- ``data.max_missing_fraction`` when the caller has a config.
172
- A missing-pixel fraction above ``max_missing_fraction`` raises. Raw
173
- digital numbers stay pixel values; this function does not name them Tb.
174
- """
175
- array = as_channel_first(image)
176
- fraction = missing_fraction(array)
177
- if fraction > max_missing_fraction:
178
- raise ValueError(
179
- f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
180
- )
181
- filled = array.copy()
182
- for index in range(filled.shape[0]):
183
- finite = np.isfinite(filled[index])
184
- fill = float(np.median(filled[index][finite])) if finite.any() else 0.0
185
- filled[index][~finite] = fill
186
- side = parse_image_size(image_size)
187
- output = filled if side is None else _resize(filled, side)
188
- if stats is not None:
189
- output = (output - stats.mean) / stats.std
190
- return output
191
-
192
-
193
- def dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:
194
- """Apply a caller-supplied calibration. This does not look up a sensor table."""
195
- return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)
196
-
197
-
198
- def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:
199
- """Use the frame as stored.
200
-
201
- Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` records
202
- the caller's label and does not change the array.
203
- """
204
- del hemisphere
205
- return np.asarray(image)
206
-
207
-
208
- def as_grey_plane(image: np.ndarray) -> np.ndarray:
209
- """One plane. Identical RGB channels collapse. Differing channels raise.
210
-
211
- PIL JPEGs are often ``(H, W, C)`` even when every channel is the same
212
- grey IR value. A leading singleton channel is accepted too.
213
- """
214
- array = np.asarray(image, dtype=np.float32)
215
- if array.ndim == 2:
216
- return array
217
- if array.ndim != 3:
218
- raise ValueError(f"expected one grey plane, got {array.shape}")
219
- channel_last = (
220
- array.shape[-1] <= 4
221
- and array.shape[0] > array.shape[-1]
222
- and array.shape[1] > array.shape[-1]
223
- )
224
- channel_first = (
225
- array.shape[0] <= 4
226
- and array.shape[1] > array.shape[0]
227
- and array.shape[2] > array.shape[0]
228
- )
229
- if channel_last:
230
- count = int(array.shape[-1])
231
- if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):
232
- return array[..., 0]
233
- raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
234
- if channel_first:
235
- count = int(array.shape[0])
236
- if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):
237
- return array[0]
238
- raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
239
- raise ValueError(f"expected grey IR, got {array.shape}")
240
-
241
-
242
- def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:
243
- """Rotate about the centre and drop pixels outside the inscribed circle.
244
-
245
- There is no flip. A square rotation otherwise paints the corners from
246
- empty space, and those bars must not enter training. The disk of
247
- diameter equal to the short side stays inside the original chip for
248
- any angle, so the kept pixels are source pixels. Outside the disk the
249
- values are NaN. Callers that already normalized fill those NaNs with 0.
250
- Channel-last grey JPEGs are accepted and returned as one plane.
251
- """
252
- plane = as_grey_plane(image)
253
- finite = np.isfinite(plane)
254
- filled = plane.copy()
255
- filled[~finite] = 0.0
256
- picture = Image.fromarray(filled, mode="F")
257
- rotated = np.asarray(
258
- picture.rotate(
259
- float(angle_deg),
260
- resample=Image.Resampling.BILINEAR,
261
- fillcolor=0.0,
262
- ),
263
- dtype=np.float32,
264
- )
265
- height, width = rotated.shape
266
- yy, xx = np.ogrid[:height, :width]
267
- center_y = (height - 1) / 2.0
268
- center_x = (width - 1) / 2.0
269
- radius = min(height, width) / 2.0
270
- disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2
271
- out = rotated.copy()
272
- out[~disk] = np.nan
273
- return out
274
-
275
-
276
- def prepare_training_chip(
277
- image: np.ndarray,
278
- image_size: int | str | None,
279
- angle: float | None,
280
- stats: NormStats | None,
281
- max_missing_fraction: float = MAX_MISSING_FRACTION,
282
- ) -> np.ndarray:
283
- """Prepare one training chip, then optionally rotate on that grid.
284
-
285
- The missing-pixel gate sees the source image, before the circular mask.
286
- A configured square resize happens first, so the mask is the inscribed
287
- circle of the training grid (about a fifth of the square) and not the
288
- corners of a wide native crop. Masked pixels are 0 after normalization,
289
- which is the training mean, not a black bar.
290
- """
291
- prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)
292
- if angle is None:
293
- return prepared
294
- masked = rotate_with_circular_mask(prepared, float(angle))
295
- if masked.ndim == 2:
296
- masked = masked[None, ...]
297
- return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)
298
-
299
-
300
- def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:
301
- """Flip or rotate a train image. Refuses every other split.
302
-
303
- Classical features do not call this. A later training loop may, and only
304
- on rows whose split is ``train``.
305
- """
306
- if split != "train":
307
- raise LeakageError("augmentation is allowed on the train split only")
308
- array = as_channel_first(image)
309
- choice = int(rng.integers(0, 3))
310
- if choice == 0:
311
- return np.flip(array, axis=-1).copy()
312
- if choice == 1:
313
- return np.rot90(array, k=1, axes=(-2, -1)).copy()
314
- return array.copy()
 
1
+ """Image checks, resize, train-only normalization, and train-only augmentation.
2
+
3
+ Southern Hemisphere frames stay as stored. ``leave_unflipped`` records a
4
+ hemisphere label and does not mirror the array.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+ from src.config import parse_image_size
15
+ from src.splits import LeakageError
16
+
17
+ # A missing-pixel fraction above this value fails closed. It does not warn.
18
+ MAX_MISSING_FRACTION = 0.30
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class NormStats:
23
+ mean: float
24
+ std: float
25
+ source_split: str
26
+
27
+
28
+ # Pixel units stay on the dataset that produced them. NASA chips are 8-bit
29
+ # counts. TCIR IR1 is brightness temperature in kelvin. They are never
30
+ # pooled into one mean and std. A later dataset gets its own entry.
31
+ PIXEL_KIND = {
32
+ "nasa": "uint8",
33
+ "tcir": "brightness_temperature_k",
34
+ "incyde": "jpeg_uncalibrated",
35
+ "smoke": "synthetic",
36
+ }
37
+
38
+
39
+ def pixel_kind(dataset: str) -> str:
40
+ """Unit label for one dataset. Unknown datasets stay unspecified."""
41
+ return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")
42
+
43
+
44
+ def norm_by_dataset(dataset: str, stats: NormStats) -> dict:
45
+ """One dataset's train-split stats. The map has that key only."""
46
+ if stats.source_split != "train":
47
+ raise LeakageError("normalization stats may be fit on the train split only")
48
+ name = str(dataset).strip().lower()
49
+ if not name:
50
+ raise ValueError("dataset name is required for normalization stats")
51
+ return {
52
+ name: {
53
+ "mean": float(stats.mean),
54
+ "std": float(stats.std),
55
+ "source_split": "train",
56
+ "pixel_kind": pixel_kind(name),
57
+ }
58
+ }
59
+
60
+
61
+ def norm_stats_from_checkpoint(payload: dict) -> NormStats:
62
+ """Stats for the checkpoint's own dataset. Mixed maps are refused.
63
+
64
+ A checkpoint written before per-dataset stats still uses ``norm_mean``
65
+ and ``norm_std``. A map with two datasets, or a key that is not the
66
+ checkpoint dataset, is not applied.
67
+ """
68
+ grouped = payload.get("norm_by_dataset")
69
+ dataset = payload.get("dataset")
70
+ if isinstance(grouped, dict) and grouped:
71
+ if len(grouped) != 1:
72
+ raise ValueError(
73
+ "checkpoint mixes normalization stats across datasets; refusing to apply them"
74
+ )
75
+ name = None if dataset is None else str(dataset)
76
+ if name not in grouped:
77
+ raise ValueError(
78
+ "checkpoint norm_by_dataset does not match the checkpoint dataset; "
79
+ "refusing to mix normalization stats"
80
+ )
81
+ entry = grouped[name]
82
+ if str(entry.get("source_split")) != "train":
83
+ raise ValueError("checkpoint normalization was not fit on train")
84
+ return NormStats(
85
+ mean=float(entry["mean"]),
86
+ std=float(entry["std"]),
87
+ source_split="train",
88
+ )
89
+ if "norm_mean" not in payload or "norm_std" not in payload:
90
+ raise ValueError("checkpoint is missing normalization stats")
91
+ source = payload.get("norm_source_split")
92
+ if source is not None and str(source) != "train":
93
+ raise ValueError("checkpoint normalization was not fit on train")
94
+ return NormStats(
95
+ mean=float(payload["norm_mean"]),
96
+ std=float(payload["norm_std"]),
97
+ source_split="train",
98
+ )
99
+
100
+
101
+ def as_channel_first(image: np.ndarray) -> np.ndarray:
102
+ array = np.asarray(image, dtype=np.float32)
103
+ if array.ndim == 2:
104
+ return array[None, ...]
105
+ if array.ndim != 3:
106
+ raise ValueError(f"expected a 2D or 3D image, got {array.shape}")
107
+ if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
108
+ return array
109
+ if array.shape[-1] <= 4:
110
+ return np.moveaxis(array, -1, 0)
111
+ raise ValueError(f"cannot infer the channel axis for shape {array.shape}")
112
+
113
+
114
+ def missing_fraction(image: np.ndarray) -> float:
115
+ return float((~np.isfinite(image)).mean())
116
+
117
+
118
+ def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:
119
+ """Fit mean and std. Refuses anything other than the train split."""
120
+ if source_split != "train":
121
+ raise LeakageError("normalization stats may be fit on the train split only")
122
+ if not images:
123
+ raise ValueError("need at least one train image")
124
+ values = [np.asarray(image, dtype=np.float32) for image in images]
125
+ finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])
126
+ if finite.size == 0:
127
+ raise ValueError("train images have no finite pixels")
128
+ std = float(finite.std())
129
+ if std < 1e-6:
130
+ std = 1.0
131
+ return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)
132
+
133
+
134
+ def stack_prepared(images: list[np.ndarray]) -> np.ndarray:
135
+ """Stack chips that have already been prepared.
136
+
137
+ A native ``image_size`` does not resize, so every chip in the stack
138
+ must already share a height and width.
139
+ """
140
+ if not images:
141
+ raise ValueError("no images to stack")
142
+ try:
143
+ return np.stack(images)
144
+ except ValueError as exc:
145
+ shapes = sorted({tuple(np.shape(image)) for image in images})
146
+ raise ValueError(
147
+ "prepared chips do not share a height and width "
148
+ f"{shapes}. A native image_size does not resize them onto one grid."
149
+ ) from exc
150
+
151
+
152
+ def _resize(image: np.ndarray, size: int) -> np.ndarray:
153
+ channels = []
154
+ for channel in image:
155
+ picture = Image.fromarray(channel.astype(np.float32), mode="F")
156
+ picture = picture.resize((size, size), Image.Resampling.BILINEAR)
157
+ channels.append(np.asarray(picture, dtype=np.float32))
158
+ return np.stack(channels, axis=0)
159
+
160
+
161
+ def prepare_image(
162
+ image: np.ndarray,
163
+ image_size: int | str | None,
164
+ stats: NormStats | None,
165
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
166
+ ) -> np.ndarray:
167
+ """Return ``(C, H, W)`` float32. Does not invent brightness temperature.
168
+
169
+ ``image_size`` ``None`` or ``native`` keeps the chip's height and width.
170
+ An integer resizes to that square. ``max_missing_fraction`` is
171
+ ``data.max_missing_fraction`` when the caller has a config.
172
+ A missing-pixel fraction above ``max_missing_fraction`` raises. Raw
173
+ digital numbers stay pixel values; this function does not name them Tb.
174
+ """
175
+ array = as_channel_first(image)
176
+ fraction = missing_fraction(array)
177
+ if fraction > max_missing_fraction:
178
+ raise ValueError(
179
+ f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
180
+ )
181
+ filled = array.copy()
182
+ for index in range(filled.shape[0]):
183
+ finite = np.isfinite(filled[index])
184
+ fill = float(np.median(filled[index][finite])) if finite.any() else 0.0
185
+ filled[index][~finite] = fill
186
+ side = parse_image_size(image_size)
187
+ output = filled if side is None else _resize(filled, side)
188
+ if stats is not None:
189
+ output = (output - stats.mean) / stats.std
190
+ return output
191
+
192
+
193
+ def dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:
194
+ """Apply a caller-supplied calibration. This does not look up a sensor table."""
195
+ return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)
196
+
197
+
198
+ def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:
199
+ """Use the frame as stored.
200
+
201
+ Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` records
202
+ the caller's label and does not change the array.
203
+ """
204
+ del hemisphere
205
+ return np.asarray(image)
206
+
207
+
208
+ def as_grey_plane(image: np.ndarray) -> np.ndarray:
209
+ """One plane. Identical RGB channels collapse. Differing channels raise.
210
+
211
+ PIL JPEGs are often ``(H, W, C)`` even when every channel is the same
212
+ grey IR value. A leading singleton channel is accepted too.
213
+ """
214
+ array = np.asarray(image, dtype=np.float32)
215
+ if array.ndim == 2:
216
+ return array
217
+ if array.ndim != 3:
218
+ raise ValueError(f"expected one grey plane, got {array.shape}")
219
+ channel_last = (
220
+ array.shape[-1] <= 4
221
+ and array.shape[0] > array.shape[-1]
222
+ and array.shape[1] > array.shape[-1]
223
+ )
224
+ channel_first = (
225
+ array.shape[0] <= 4
226
+ and array.shape[1] > array.shape[0]
227
+ and array.shape[2] > array.shape[0]
228
+ )
229
+ if channel_last:
230
+ count = int(array.shape[-1])
231
+ if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):
232
+ return array[..., 0]
233
+ raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
234
+ if channel_first:
235
+ count = int(array.shape[0])
236
+ if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):
237
+ return array[0]
238
+ raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
239
+ raise ValueError(f"expected grey IR, got {array.shape}")
240
+
241
+
242
+ def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:
243
+ """Rotate about the centre and drop pixels outside the inscribed circle.
244
+
245
+ There is no flip. A square rotation otherwise paints the corners from
246
+ empty space, and those bars must not enter training. The disk of
247
+ diameter equal to the short side stays inside the original chip for
248
+ any angle, so the kept pixels are source pixels. Outside the disk the
249
+ values are NaN. Callers that already normalized fill those NaNs with 0.
250
+ Channel-last grey JPEGs are accepted and returned as one plane.
251
+ """
252
+ plane = as_grey_plane(image)
253
+ finite = np.isfinite(plane)
254
+ filled = plane.copy()
255
+ filled[~finite] = 0.0
256
+ picture = Image.fromarray(filled, mode="F")
257
+ rotated = np.asarray(
258
+ picture.rotate(
259
+ float(angle_deg),
260
+ resample=Image.Resampling.BILINEAR,
261
+ fillcolor=0.0,
262
+ ),
263
+ dtype=np.float32,
264
+ )
265
+ height, width = rotated.shape
266
+ yy, xx = np.ogrid[:height, :width]
267
+ center_y = (height - 1) / 2.0
268
+ center_x = (width - 1) / 2.0
269
+ radius = min(height, width) / 2.0
270
+ disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2
271
+ out = rotated.copy()
272
+ out[~disk] = np.nan
273
+ return out
274
+
275
+
276
+ def prepare_training_chip(
277
+ image: np.ndarray,
278
+ image_size: int | str | None,
279
+ angle: float | None,
280
+ stats: NormStats | None,
281
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
282
+ ) -> np.ndarray:
283
+ """Prepare one training chip, then optionally rotate on that grid.
284
+
285
+ The missing-pixel gate sees the source image, before the circular mask.
286
+ A configured square resize happens first, so the mask is the inscribed
287
+ circle of the training grid (about a fifth of the square) and not the
288
+ corners of a wide native crop. Masked pixels are 0 after normalization,
289
+ which is the training mean, not a black bar.
290
+ """
291
+ prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)
292
+ if angle is None:
293
+ return prepared
294
+ masked = rotate_with_circular_mask(prepared, float(angle))
295
+ if masked.ndim == 2:
296
+ masked = masked[None, ...]
297
+ return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)
298
+
299
+
300
+ def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:
301
+ """Flip or rotate a train image. Refuses every other split.
302
+
303
+ Classical features do not call this. A later training loop may, and only
304
+ on rows whose split is ``train``.
305
+ """
306
+ if split != "train":
307
+ raise LeakageError("augmentation is allowed on the train split only")
308
+ array = as_channel_first(image)
309
+ choice = int(rng.integers(0, 3))
310
+ if choice == 0:
311
+ return np.flip(array, axis=-1).copy()
312
+ if choice == 1:
313
+ return np.rot90(array, k=1, axes=(-2, -1)).copy()
314
+ return array.copy()
src/reproducibility.py CHANGED
@@ -1,46 +1,46 @@
1
- """Centralized seed helper for reproducible runs.
2
-
3
- Sets Python, NumPy, and (when available) PyTorch random seeds in one call.
4
- Training, baselines, and splits should call ``seed_everything`` before any
5
- stochastic operation. This module does not import torch at module level so
6
- that CPU-only installs still work.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import os
12
- import random
13
-
14
- import numpy as np
15
-
16
-
17
- def seed_everything(seed: int = 42) -> int:
18
- """Set Python, NumPy, and optional PyTorch seeds.
19
-
20
- Returns the seed so callers can log it.
21
-
22
- Parameters
23
- ----------
24
- seed : int
25
- Non-negative integer seed. The same value is forwarded to every
26
- generator so a single config entry controls all randomness.
27
- """
28
- if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:
29
- raise ValueError(f"seed must be a non-negative integer, got {seed!r}")
30
-
31
- random.seed(seed)
32
- np.random.seed(seed)
33
- os.environ["PYTHONHASHSEED"] = str(seed)
34
-
35
- try:
36
- import torch
37
- except ImportError:
38
- pass
39
- else:
40
- torch.manual_seed(seed)
41
- if torch.cuda.is_available():
42
- torch.cuda.manual_seed_all(seed)
43
- if hasattr(torch, "xpu") and torch.xpu.is_available():
44
- torch.xpu.manual_seed(seed)
45
-
46
- return seed
 
1
+ """Centralized seed helper for reproducible runs.
2
+
3
+ Sets Python, NumPy, and (when available) PyTorch random seeds in one call.
4
+ Training, baselines, and splits should call ``seed_everything`` before any
5
+ stochastic operation. This module does not import torch at module level so
6
+ that CPU-only installs still work.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import random
13
+
14
+ import numpy as np
15
+
16
+
17
+ def seed_everything(seed: int = 42) -> int:
18
+ """Set Python, NumPy, and optional PyTorch seeds.
19
+
20
+ Returns the seed so callers can log it.
21
+
22
+ Parameters
23
+ ----------
24
+ seed : int
25
+ Non-negative integer seed. The same value is forwarded to every
26
+ generator so a single config entry controls all randomness.
27
+ """
28
+ if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:
29
+ raise ValueError(f"seed must be a non-negative integer, got {seed!r}")
30
+
31
+ random.seed(seed)
32
+ np.random.seed(seed)
33
+ os.environ["PYTHONHASHSEED"] = str(seed)
34
+
35
+ try:
36
+ import torch
37
+ except ImportError:
38
+ pass
39
+ else:
40
+ torch.manual_seed(seed)
41
+ if torch.cuda.is_available():
42
+ torch.cuda.manual_seed_all(seed)
43
+ if hasattr(torch, "xpu") and torch.xpu.is_available():
44
+ torch.xpu.manual_seed(seed)
45
+
46
+ return seed
src/schema.py CHANGED
@@ -1,342 +1,342 @@
1
- """Manifest schema and row-level quality gates.
2
-
3
- Required columns are ``sample_id``, ``image_path``, ``storm_id``, and
4
- ``wind_speed_kt``. ``require_valid`` raises ``SchemaError`` on a failed
5
- gate. It does not warn and continue.
6
-
7
- ``wind_averaging`` must record one period for the whole manifest, such as
8
- ``1-min``, ``3-min``, or ``10-min``. Mixed or blank periods are rejected.
9
- ``is_synthetic`` must be an explicit true or false on every row so a
10
- synthetic sample cannot be read as real.
11
-
12
- Image statistics are pixel stats. This schema has no brightness-temperature
13
- columns. Raw digital numbers are not named ``tb``. Those names are used
14
- only after a brightness-temperature calibration table exists.
15
-
16
- The 17/34/48/64/91 kt bins are this project's grouping, not official IMD
17
- classes, and they are not a warning product. ``imd5_class`` stores that
18
- project group.
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- from dataclasses import dataclass
24
-
25
- import pandas as pd
26
-
27
- REQUIRED_COLUMNS = ("sample_id", "image_path", "storm_id", "wind_speed_kt")
28
- FORBIDDEN_FEATURES = frozenset(
29
- {"wind_speed_kt", "r34_nmi", "rmw_nmi", "imd5_class", "intensity_bin"}
30
- )
31
- # Project metric labels, not an IMD warning. Five names group D+DD and
32
- # ESCS+SuCS. The edges 17/34/48/64/91 kt are this project's own grouping.
33
- # IMD operational winds are 3-minute averages and are not these bins.
34
- # NASA HURDAT2 labels are 1-minute winds; config data.wind_averaging is
35
- # 1min for that dataset. Keep these tuples equal to data.imd5_edges_kt
36
- # and data.imd5_names. The July 2024 IMD 3-minute sheet starts Extremely
37
- # Severe at 90 kt, so 90 kt is VSCS here.
38
- DEFAULT_EDGES_KT = (17.0, 34.0, 48.0, 64.0, 91.0)
39
- DEFAULT_NAMES = ("D_DD", "CS", "SCS", "VSCS", "ESCS_SUCS")
40
- DEFAULT_WIND_MIN_KT = 0.0
41
- DEFAULT_WIND_MAX_KT = 200.0
42
-
43
- _TRUE_TEXT = frozenset({"1", "true", "yes", "y", "t"})
44
- _FALSE_TEXT = frozenset({"0", "false", "no", "n", "f"})
45
- _MISSING_TEXT = frozenset({"", "nan", "none", "<na>", "nat", "null"})
46
-
47
-
48
- class SchemaError(ValueError):
49
- """A manifest failed a quality gate."""
50
-
51
-
52
- @dataclass(frozen=True)
53
- class QualityReport:
54
- n_rows: int
55
- n_storms: int
56
- errors: tuple[str, ...]
57
-
58
- @property
59
- def ok(self) -> bool:
60
- return not self.errors
61
-
62
-
63
- def wind_to_imd5(
64
- wind_kt: float,
65
- edges: tuple[float, ...] = DEFAULT_EDGES_KT,
66
- names: tuple[str, ...] = DEFAULT_NAMES,
67
- ) -> str | None:
68
- """Return this project's intensity group, or None below the lowest edge.
69
-
70
- The names and edges are this project's grouping. They are not official IMD classes, IMD 3-minute categories, or a warning product.
71
- """
72
- if len(edges) != len(names):
73
- raise ValueError("edges and names must have the same length")
74
- if pd.isna(wind_kt) or float(wind_kt) < edges[0]:
75
- return None
76
- value = float(wind_kt)
77
- for lower, upper, name in zip(edges, edges[1:], names):
78
- if lower <= value < upper:
79
- return name
80
- return names[-1]
81
-
82
-
83
- def _unpack_scalar(value: object) -> object:
84
- """Return a Python scalar when ``value`` is a numpy scalar."""
85
- if isinstance(value, (str, bytes, bytearray, bool)):
86
- return value
87
- item = getattr(value, "item", None)
88
- if not callable(item):
89
- return value
90
- try:
91
- unpacked = item()
92
- except (TypeError, ValueError):
93
- return value
94
- if type(unpacked) is type(value):
95
- return value
96
- return unpacked
97
-
98
-
99
- def _is_missing(value: object) -> bool:
100
- if value is None:
101
- return True
102
- try:
103
- missing = pd.isna(value)
104
- except (TypeError, ValueError):
105
- return False
106
- if missing is True:
107
- return True
108
- return False
109
-
110
-
111
- def _sample_key(value: object) -> str:
112
- if isinstance(value, bool):
113
- return "True" if value else "False"
114
- if _is_missing(value):
115
- return ""
116
- if isinstance(value, str):
117
- return value.strip()
118
- value = _unpack_scalar(value)
119
- if isinstance(value, bool):
120
- return "True" if value else "False"
121
- if _is_missing(value):
122
- return ""
123
- if isinstance(value, str):
124
- return value.strip()
125
- if isinstance(value, int) and not isinstance(value, bool):
126
- return str(value)
127
- if isinstance(value, float):
128
- if value != value:
129
- return ""
130
- if value.is_integer():
131
- return str(int(value))
132
- return str(value).strip()
133
-
134
-
135
- def parse_is_synthetic(value: object) -> bool:
136
- """Return an explicit synthetic flag. Ambiguous values raise.
137
-
138
- Null, blank, and unrecognized values are not treated as real data.
139
- """
140
- if isinstance(value, bool):
141
- return value
142
- if isinstance(value, str):
143
- text = value.strip().lower()
144
- if text in _TRUE_TEXT:
145
- return True
146
- if text in _FALSE_TEXT:
147
- return False
148
- if text in _MISSING_TEXT:
149
- raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
150
- try:
151
- number = float(text)
152
- except ValueError:
153
- raise SchemaError(
154
- f"is_synthetic value {value!r} is not an explicit true or false"
155
- ) from None
156
- return parse_is_synthetic(number)
157
- value = _unpack_scalar(value)
158
- if isinstance(value, bool):
159
- return value
160
- if _is_missing(value):
161
- raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
162
- if isinstance(value, str):
163
- return parse_is_synthetic(value)
164
- if isinstance(value, int) and not isinstance(value, bool):
165
- if value in (0, 1):
166
- return bool(value)
167
- raise SchemaError(
168
- f"is_synthetic value {value!r} is not an explicit true or false"
169
- )
170
- if isinstance(value, float):
171
- if value != value or value in (float("inf"), float("-inf")):
172
- raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
173
- if value == 1.0:
174
- return True
175
- if value == 0.0:
176
- return False
177
- raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")
178
-
179
-
180
- def recorded_wind_averaging(frame: pd.DataFrame) -> str:
181
- """Return the single averaging period recorded on this manifest.
182
-
183
- The column is required. A blank row or two different periods raises.
184
- """
185
- if "wind_averaging" not in frame.columns:
186
- raise SchemaError(
187
- "wind_averaging is required; record one period for the manifest "
188
- "(for example 1-min, 3-min, or 10-min)"
189
- )
190
- if len(frame) == 0:
191
- raise SchemaError(
192
- "wind_averaging is required; record one period for the manifest"
193
- )
194
- periods: list[str] = []
195
- for value in frame["wind_averaging"].tolist():
196
- if isinstance(value, str):
197
- text = value.strip()
198
- elif _is_missing(value):
199
- text = ""
200
- else:
201
- unpacked = _unpack_scalar(value)
202
- if _is_missing(unpacked):
203
- text = ""
204
- else:
205
- text = str(unpacked).strip()
206
- if text.lower() in _MISSING_TEXT:
207
- raise SchemaError(
208
- "wind_averaging has nulls; record one period for every row"
209
- )
210
- periods.append(text)
211
- unique = sorted(set(periods))
212
- if len(unique) != 1:
213
- raise SchemaError(
214
- f"mixed wind_averaging periods {unique}; split or convert explicitly"
215
- )
216
- return unique[0]
217
-
218
-
219
- # The label's duration in seconds. This is not a wind conversion factor.
220
- _AVERAGING_SECONDS = {
221
- "1min": 60,
222
- "1-min": 60,
223
- "1minute": 60,
224
- "1-minute": 60,
225
- "3min": 180,
226
- "3-min": 180,
227
- "3minute": 180,
228
- "3-minute": 180,
229
- "10min": 600,
230
- "10-min": 600,
231
- "10minute": 600,
232
- "10-minute": 600,
233
- }
234
-
235
-
236
- def wind_averaging_seconds(period: object) -> int | None:
237
- """Seconds for a 1, 3, or 10 minute label. Other labels have no duration.
238
-
239
- ``1min`` is 60, ``3-min`` is 180, and ``10min`` is 600. Synthetic and
240
- unknown text stay null. This does not rescale a wind speed.
241
- """
242
- if period is None:
243
- return None
244
- text = str(period).strip().lower().replace(" ", "").replace("_", "-")
245
- if not text:
246
- return None
247
- return _AVERAGING_SECONDS.get(text)
248
-
249
-
250
- def split_wind_averaging(frame: pd.DataFrame) -> dict[str, dict[str, list]]:
251
- """``wind_averaging`` and ``wind_averaging_s`` for train, val, and test.
252
-
253
- Each split lists the set of labels on its rows. Seconds follow the
254
- label. A label with no known duration stores null and is not converted.
255
- """
256
- if "split" not in frame.columns:
257
- raise SchemaError("split is required to record wind_averaging by split")
258
- if "wind_averaging" not in frame.columns:
259
- raise SchemaError("wind_averaging is required")
260
- report: dict[str, dict[str, list]] = {}
261
- for name in ("train", "val", "test"):
262
- rows = frame.loc[frame["split"].astype(str) == name, "wind_averaging"]
263
- labels = sorted({str(value).strip() for value in rows.tolist() if str(value).strip()})
264
- report[name] = {
265
- "wind_averaging": labels,
266
- "wind_averaging_s": [wind_averaging_seconds(label) for label in labels],
267
- }
268
- return report
269
-
270
-
271
- def _synthetic_flags(frame: pd.DataFrame) -> list[bool]:
272
- if "is_synthetic" not in frame.columns:
273
- raise SchemaError(
274
- "is_synthetic is required so a synthetic row cannot be read as real"
275
- )
276
- return [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
277
-
278
-
279
- def validate_manifest(
280
- frame: pd.DataFrame,
281
- wind_min_kt: float = DEFAULT_WIND_MIN_KT,
282
- wind_max_kt: float = DEFAULT_WIND_MAX_KT,
283
- ) -> QualityReport:
284
- """Collect quality-gate failures. Callers that load data use ``require_valid``."""
285
- errors: list[str] = []
286
- missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns]
287
- if missing:
288
- return QualityReport(len(frame), 0, (f"missing required columns: {missing}",))
289
-
290
- keys = frame["sample_id"].map(_sample_key)
291
- null_id = frame["sample_id"].isna() | keys.eq("") | keys.str.lower().isin(_MISSING_TEXT)
292
- if bool(null_id.any()):
293
- errors.append("sample_id has nulls")
294
- if bool(keys.duplicated().any()):
295
- examples = keys.loc[keys.duplicated()].head(5).tolist()
296
- errors.append(f"duplicate sample_id, examples: {examples}")
297
- blank_storm = frame["storm_id"].astype(str).str.strip().str.len() == 0
298
- if frame["storm_id"].isna().any() or blank_storm.any():
299
- errors.append("storm_id has nulls")
300
- if frame["image_path"].isna().any() or (
301
- frame["image_path"].astype(str).str.strip().str.len() == 0
302
- ).any():
303
- errors.append("image_path has nulls")
304
-
305
- winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
306
- if winds.isna().any():
307
- errors.append("wind_speed_kt has non-numeric values")
308
- else:
309
- bad = (winds < wind_min_kt) | (winds > wind_max_kt)
310
- if bad.any():
311
- errors.append(
312
- f"{int(bad.sum())} wind values outside [{wind_min_kt}, {wind_max_kt}] kt"
313
- )
314
-
315
- try:
316
- recorded_wind_averaging(frame)
317
- except SchemaError as exc:
318
- errors.append(str(exc))
319
- try:
320
- _synthetic_flags(frame)
321
- except SchemaError as exc:
322
- errors.append(str(exc))
323
-
324
- n_storms = int(frame["storm_id"].nunique(dropna=True))
325
- return QualityReport(len(frame), n_storms, tuple(errors))
326
-
327
-
328
- def require_valid(frame: pd.DataFrame, **kwargs: float) -> pd.DataFrame:
329
- """Return a copy that passed every manifest gate. Raises on failure."""
330
- report = validate_manifest(frame, **kwargs)
331
- if not report.ok:
332
- raise SchemaError("; ".join(report.errors))
333
- out = frame.copy()
334
- out["storm_id"] = out["storm_id"].astype(str).str.strip()
335
- out["sample_id"] = out["sample_id"].map(_sample_key).astype(str)
336
- out["image_path"] = out["image_path"].astype(str).str.strip()
337
- out["wind_speed_kt"] = pd.to_numeric(out["wind_speed_kt"])
338
- out["wind_averaging"] = recorded_wind_averaging(out)
339
- out["is_synthetic"] = _synthetic_flags(out)
340
- # Project grouping stored on imd5_class. Not an official IMD class code.
341
- out["imd5_class"] = out["wind_speed_kt"].map(wind_to_imd5)
342
- return out
 
1
+ """Manifest schema and row-level quality gates.
2
+
3
+ Required columns are ``sample_id``, ``image_path``, ``storm_id``, and
4
+ ``wind_speed_kt``. ``require_valid`` raises ``SchemaError`` on a failed
5
+ gate. It does not warn and continue.
6
+
7
+ ``wind_averaging`` must record one period for the whole manifest, such as
8
+ ``1-min``, ``3-min``, or ``10-min``. Mixed or blank periods are rejected.
9
+ ``is_synthetic`` must be an explicit true or false on every row so a
10
+ synthetic sample cannot be read as real.
11
+
12
+ Image statistics are pixel stats. This schema has no brightness-temperature
13
+ columns. Raw digital numbers are not named ``tb``. Those names are used
14
+ only after a brightness-temperature calibration table exists.
15
+
16
+ The 17/34/48/64/91 kt bins are this project's grouping, not official IMD
17
+ classes, and they are not a warning product. ``imd5_class`` stores that
18
+ project group.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+
25
+ import pandas as pd
26
+
27
+ REQUIRED_COLUMNS = ("sample_id", "image_path", "storm_id", "wind_speed_kt")
28
+ FORBIDDEN_FEATURES = frozenset(
29
+ {"wind_speed_kt", "r34_nmi", "rmw_nmi", "imd5_class", "intensity_bin"}
30
+ )
31
+ # Project metric labels, not an IMD warning. Five names group D+DD and
32
+ # ESCS+SuCS. The edges 17/34/48/64/91 kt are this project's own grouping.
33
+ # IMD operational winds are 3-minute averages and are not these bins.
34
+ # NASA HURDAT2 labels are 1-minute winds; config data.wind_averaging is
35
+ # 1min for that dataset. Keep these tuples equal to data.imd5_edges_kt
36
+ # and data.imd5_names. The July 2024 IMD 3-minute sheet starts Extremely
37
+ # Severe at 90 kt, so 90 kt is VSCS here.
38
+ DEFAULT_EDGES_KT = (17.0, 34.0, 48.0, 64.0, 91.0)
39
+ DEFAULT_NAMES = ("D_DD", "CS", "SCS", "VSCS", "ESCS_SUCS")
40
+ DEFAULT_WIND_MIN_KT = 0.0
41
+ DEFAULT_WIND_MAX_KT = 200.0
42
+
43
+ _TRUE_TEXT = frozenset({"1", "true", "yes", "y", "t"})
44
+ _FALSE_TEXT = frozenset({"0", "false", "no", "n", "f"})
45
+ _MISSING_TEXT = frozenset({"", "nan", "none", "<na>", "nat", "null"})
46
+
47
+
48
+ class SchemaError(ValueError):
49
+ """A manifest failed a quality gate."""
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class QualityReport:
54
+ n_rows: int
55
+ n_storms: int
56
+ errors: tuple[str, ...]
57
+
58
+ @property
59
+ def ok(self) -> bool:
60
+ return not self.errors
61
+
62
+
63
+ def wind_to_imd5(
64
+ wind_kt: float,
65
+ edges: tuple[float, ...] = DEFAULT_EDGES_KT,
66
+ names: tuple[str, ...] = DEFAULT_NAMES,
67
+ ) -> str | None:
68
+ """Return this project's intensity group, or None below the lowest edge.
69
+
70
+ The names and edges are this project's grouping. They are not official IMD classes, IMD 3-minute categories, or a warning product.
71
+ """
72
+ if len(edges) != len(names):
73
+ raise ValueError("edges and names must have the same length")
74
+ if pd.isna(wind_kt) or float(wind_kt) < edges[0]:
75
+ return None
76
+ value = float(wind_kt)
77
+ for lower, upper, name in zip(edges, edges[1:], names):
78
+ if lower <= value < upper:
79
+ return name
80
+ return names[-1]
81
+
82
+
83
+ def _unpack_scalar(value: object) -> object:
84
+ """Return a Python scalar when ``value`` is a numpy scalar."""
85
+ if isinstance(value, (str, bytes, bytearray, bool)):
86
+ return value
87
+ item = getattr(value, "item", None)
88
+ if not callable(item):
89
+ return value
90
+ try:
91
+ unpacked = item()
92
+ except (TypeError, ValueError):
93
+ return value
94
+ if type(unpacked) is type(value):
95
+ return value
96
+ return unpacked
97
+
98
+
99
+ def _is_missing(value: object) -> bool:
100
+ if value is None:
101
+ return True
102
+ try:
103
+ missing = pd.isna(value)
104
+ except (TypeError, ValueError):
105
+ return False
106
+ if missing is True:
107
+ return True
108
+ return False
109
+
110
+
111
+ def _sample_key(value: object) -> str:
112
+ if isinstance(value, bool):
113
+ return "True" if value else "False"
114
+ if _is_missing(value):
115
+ return ""
116
+ if isinstance(value, str):
117
+ return value.strip()
118
+ value = _unpack_scalar(value)
119
+ if isinstance(value, bool):
120
+ return "True" if value else "False"
121
+ if _is_missing(value):
122
+ return ""
123
+ if isinstance(value, str):
124
+ return value.strip()
125
+ if isinstance(value, int) and not isinstance(value, bool):
126
+ return str(value)
127
+ if isinstance(value, float):
128
+ if value != value:
129
+ return ""
130
+ if value.is_integer():
131
+ return str(int(value))
132
+ return str(value).strip()
133
+
134
+
135
+ def parse_is_synthetic(value: object) -> bool:
136
+ """Return an explicit synthetic flag. Ambiguous values raise.
137
+
138
+ Null, blank, and unrecognized values are not treated as real data.
139
+ """
140
+ if isinstance(value, bool):
141
+ return value
142
+ if isinstance(value, str):
143
+ text = value.strip().lower()
144
+ if text in _TRUE_TEXT:
145
+ return True
146
+ if text in _FALSE_TEXT:
147
+ return False
148
+ if text in _MISSING_TEXT:
149
+ raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
150
+ try:
151
+ number = float(text)
152
+ except ValueError:
153
+ raise SchemaError(
154
+ f"is_synthetic value {value!r} is not an explicit true or false"
155
+ ) from None
156
+ return parse_is_synthetic(number)
157
+ value = _unpack_scalar(value)
158
+ if isinstance(value, bool):
159
+ return value
160
+ if _is_missing(value):
161
+ raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
162
+ if isinstance(value, str):
163
+ return parse_is_synthetic(value)
164
+ if isinstance(value, int) and not isinstance(value, bool):
165
+ if value in (0, 1):
166
+ return bool(value)
167
+ raise SchemaError(
168
+ f"is_synthetic value {value!r} is not an explicit true or false"
169
+ )
170
+ if isinstance(value, float):
171
+ if value != value or value in (float("inf"), float("-inf")):
172
+ raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
173
+ if value == 1.0:
174
+ return True
175
+ if value == 0.0:
176
+ return False
177
+ raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")
178
+
179
+
180
+ def recorded_wind_averaging(frame: pd.DataFrame) -> str:
181
+ """Return the single averaging period recorded on this manifest.
182
+
183
+ The column is required. A blank row or two different periods raises.
184
+ """
185
+ if "wind_averaging" not in frame.columns:
186
+ raise SchemaError(
187
+ "wind_averaging is required; record one period for the manifest "
188
+ "(for example 1-min, 3-min, or 10-min)"
189
+ )
190
+ if len(frame) == 0:
191
+ raise SchemaError(
192
+ "wind_averaging is required; record one period for the manifest"
193
+ )
194
+ periods: list[str] = []
195
+ for value in frame["wind_averaging"].tolist():
196
+ if isinstance(value, str):
197
+ text = value.strip()
198
+ elif _is_missing(value):
199
+ text = ""
200
+ else:
201
+ unpacked = _unpack_scalar(value)
202
+ if _is_missing(unpacked):
203
+ text = ""
204
+ else:
205
+ text = str(unpacked).strip()
206
+ if text.lower() in _MISSING_TEXT:
207
+ raise SchemaError(
208
+ "wind_averaging has nulls; record one period for every row"
209
+ )
210
+ periods.append(text)
211
+ unique = sorted(set(periods))
212
+ if len(unique) != 1:
213
+ raise SchemaError(
214
+ f"mixed wind_averaging periods {unique}; split or convert explicitly"
215
+ )
216
+ return unique[0]
217
+
218
+
219
+ # The label's duration in seconds. This is not a wind conversion factor.
220
+ _AVERAGING_SECONDS = {
221
+ "1min": 60,
222
+ "1-min": 60,
223
+ "1minute": 60,
224
+ "1-minute": 60,
225
+ "3min": 180,
226
+ "3-min": 180,
227
+ "3minute": 180,
228
+ "3-minute": 180,
229
+ "10min": 600,
230
+ "10-min": 600,
231
+ "10minute": 600,
232
+ "10-minute": 600,
233
+ }
234
+
235
+
236
+ def wind_averaging_seconds(period: object) -> int | None:
237
+ """Seconds for a 1, 3, or 10 minute label. Other labels have no duration.
238
+
239
+ ``1min`` is 60, ``3-min`` is 180, and ``10min`` is 600. Synthetic and
240
+ unknown text stay null. This does not rescale a wind speed.
241
+ """
242
+ if period is None:
243
+ return None
244
+ text = str(period).strip().lower().replace(" ", "").replace("_", "-")
245
+ if not text:
246
+ return None
247
+ return _AVERAGING_SECONDS.get(text)
248
+
249
+
250
+ def split_wind_averaging(frame: pd.DataFrame) -> dict[str, dict[str, list]]:
251
+ """``wind_averaging`` and ``wind_averaging_s`` for train, val, and test.
252
+
253
+ Each split lists the set of labels on its rows. Seconds follow the
254
+ label. A label with no known duration stores null and is not converted.
255
+ """
256
+ if "split" not in frame.columns:
257
+ raise SchemaError("split is required to record wind_averaging by split")
258
+ if "wind_averaging" not in frame.columns:
259
+ raise SchemaError("wind_averaging is required")
260
+ report: dict[str, dict[str, list]] = {}
261
+ for name in ("train", "val", "test"):
262
+ rows = frame.loc[frame["split"].astype(str) == name, "wind_averaging"]
263
+ labels = sorted({str(value).strip() for value in rows.tolist() if str(value).strip()})
264
+ report[name] = {
265
+ "wind_averaging": labels,
266
+ "wind_averaging_s": [wind_averaging_seconds(label) for label in labels],
267
+ }
268
+ return report
269
+
270
+
271
+ def _synthetic_flags(frame: pd.DataFrame) -> list[bool]:
272
+ if "is_synthetic" not in frame.columns:
273
+ raise SchemaError(
274
+ "is_synthetic is required so a synthetic row cannot be read as real"
275
+ )
276
+ return [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
277
+
278
+
279
+ def validate_manifest(
280
+ frame: pd.DataFrame,
281
+ wind_min_kt: float = DEFAULT_WIND_MIN_KT,
282
+ wind_max_kt: float = DEFAULT_WIND_MAX_KT,
283
+ ) -> QualityReport:
284
+ """Collect quality-gate failures. Callers that load data use ``require_valid``."""
285
+ errors: list[str] = []
286
+ missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns]
287
+ if missing:
288
+ return QualityReport(len(frame), 0, (f"missing required columns: {missing}",))
289
+
290
+ keys = frame["sample_id"].map(_sample_key)
291
+ null_id = frame["sample_id"].isna() | keys.eq("") | keys.str.lower().isin(_MISSING_TEXT)
292
+ if bool(null_id.any()):
293
+ errors.append("sample_id has nulls")
294
+ if bool(keys.duplicated().any()):
295
+ examples = keys.loc[keys.duplicated()].head(5).tolist()
296
+ errors.append(f"duplicate sample_id, examples: {examples}")
297
+ blank_storm = frame["storm_id"].astype(str).str.strip().str.len() == 0
298
+ if frame["storm_id"].isna().any() or blank_storm.any():
299
+ errors.append("storm_id has nulls")
300
+ if frame["image_path"].isna().any() or (
301
+ frame["image_path"].astype(str).str.strip().str.len() == 0
302
+ ).any():
303
+ errors.append("image_path has nulls")
304
+
305
+ winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
306
+ if winds.isna().any():
307
+ errors.append("wind_speed_kt has non-numeric values")
308
+ else:
309
+ bad = (winds < wind_min_kt) | (winds > wind_max_kt)
310
+ if bad.any():
311
+ errors.append(
312
+ f"{int(bad.sum())} wind values outside [{wind_min_kt}, {wind_max_kt}] kt"
313
+ )
314
+
315
+ try:
316
+ recorded_wind_averaging(frame)
317
+ except SchemaError as exc:
318
+ errors.append(str(exc))
319
+ try:
320
+ _synthetic_flags(frame)
321
+ except SchemaError as exc:
322
+ errors.append(str(exc))
323
+
324
+ n_storms = int(frame["storm_id"].nunique(dropna=True))
325
+ return QualityReport(len(frame), n_storms, tuple(errors))
326
+
327
+
328
+ def require_valid(frame: pd.DataFrame, **kwargs: float) -> pd.DataFrame:
329
+ """Return a copy that passed every manifest gate. Raises on failure."""
330
+ report = validate_manifest(frame, **kwargs)
331
+ if not report.ok:
332
+ raise SchemaError("; ".join(report.errors))
333
+ out = frame.copy()
334
+ out["storm_id"] = out["storm_id"].astype(str).str.strip()
335
+ out["sample_id"] = out["sample_id"].map(_sample_key).astype(str)
336
+ out["image_path"] = out["image_path"].astype(str).str.strip()
337
+ out["wind_speed_kt"] = pd.to_numeric(out["wind_speed_kt"])
338
+ out["wind_averaging"] = recorded_wind_averaging(out)
339
+ out["is_synthetic"] = _synthetic_flags(out)
340
+ # Project grouping stored on imd5_class. Not an official IMD class code.
341
+ out["imd5_class"] = out["wind_speed_kt"].map(wind_to_imd5)
342
+ return out
src/sequences.py CHANGED
@@ -1,171 +1,171 @@
1
- """Four-frame windows inside one split.
2
-
3
- The image tensor is infrared only. Wind, R34, and radius of maximum wind
4
- may be read as targets for the last frame. They are not channels.
5
- A previous-frame link that leaves the split cannot bring that frame in.
6
- Southern Hemisphere frames are not flipped.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- from pathlib import Path
12
-
13
- import numpy as np
14
- import pandas as pd
15
-
16
- from src.data_loader import load_image, resolve_image
17
- from src.preprocessing import NormStats, leave_unflipped, prepare_image, stack_prepared
18
-
19
- N_FRAMES = 4
20
- SIZE_LABELS = ("r34_nmi", "rmw_nmi")
21
-
22
-
23
- def size_targets_present(frame: pd.DataFrame) -> bool:
24
- """True when both size columns exist and one row has a finite pair.
25
-
26
- All-null columns are not labels. The size head stays off until then.
27
- """
28
- if any(column not in frame.columns for column in SIZE_LABELS):
29
- return False
30
- values = frame.loc[:, list(SIZE_LABELS)].apply(pd.to_numeric, errors="coerce")
31
- finite_pair = np.isfinite(values.to_numpy(dtype=np.float64)).all(axis=1)
32
- return bool(finite_pair.any())
33
-
34
-
35
- def _prev_id(value: object) -> str | None:
36
- if value is None:
37
- return None
38
- try:
39
- if pd.isna(value):
40
- return None
41
- except (TypeError, ValueError):
42
- return None
43
- text = str(value).strip()
44
- if text == "" or text.lower() in {"nan", "none", "<na>", "nat"}:
45
- return None
46
- return text
47
-
48
-
49
- def _window_stays_in_split(
50
- sample_ids: list[str], prev_ids: list[str | None], in_split: set[str]
51
- ) -> bool:
52
- """Reject a window whose previous-frame link leaves the split.
53
-
54
- A link that was cleared is ignored. A link that is still set must name
55
- the previous frame in this window, except at the first frame, where a
56
- same-split predecessor may sit just outside a sliding window.
57
- """
58
- for offset, _sample_id in enumerate(sample_ids):
59
- prev = prev_ids[offset]
60
- if prev is None:
61
- continue
62
- if prev not in in_split:
63
- return False
64
- if offset > 0 and prev != sample_ids[offset - 1]:
65
- return False
66
- return True
67
-
68
-
69
- def frame_windows(
70
- frame: pd.DataFrame, split: str, n_frames: int = N_FRAMES
71
- ) -> list[list[str]]:
72
- """Sample ids of consecutive frames, one storm, one split.
73
-
74
- ``n_frames`` is 4. A link that points outside this split rejects the
75
- window. A link that was cleared stays cleared and is not followed.
76
- """
77
- if n_frames != N_FRAMES:
78
- raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")
79
- if "split" not in frame.columns:
80
- raise ValueError("frame is missing split")
81
- rows = frame[frame["split"] == split]
82
- if rows.empty:
83
- return []
84
- order = ["timestamp", "sample_id"] if "timestamp" in rows.columns else ["sample_id"]
85
- in_split = set(rows["sample_id"].astype(str))
86
- windows: list[list[str]] = []
87
- for _storm_id, group in rows.groupby("storm_id", sort=False):
88
- ordered = group.sort_values(order, kind="mergesort")
89
- sample_ids = [str(value) for value in ordered["sample_id"].tolist()]
90
- if "prev_sample_id" in ordered.columns:
91
- prev_ids = [_prev_id(value) for value in ordered["prev_sample_id"].tolist()]
92
- else:
93
- prev_ids = [None] * len(sample_ids)
94
- for start in range(0, len(sample_ids) - n_frames + 1):
95
- chosen = sample_ids[start : start + n_frames]
96
- prev = prev_ids[start : start + n_frames]
97
- if _window_stays_in_split(chosen, prev, in_split):
98
- windows.append(chosen)
99
- return windows
100
-
101
-
102
- def _row(indexed: pd.DataFrame, sample_id: str) -> pd.Series:
103
- row = indexed.loc[sample_id]
104
- if isinstance(row, pd.DataFrame):
105
- return row.iloc[0]
106
- return row
107
-
108
-
109
- def _pair(row: pd.Series, column: str) -> float:
110
- number = pd.to_numeric(pd.Series([row[column]]), errors="coerce").iloc[0]
111
- if pd.isna(number):
112
- return float("nan")
113
- return float(number)
114
-
115
-
116
- def stack_windows(
117
- frame: pd.DataFrame,
118
- manifest_path: str | Path,
119
- split_name: str,
120
- image_size: int | str | None,
121
- stats: NormStats | None,
122
- max_missing_fraction: float,
123
- n_frames: int = N_FRAMES,
124
- wind_column: str = "wind_speed_kt",
125
- ) -> tuple[np.ndarray, np.ndarray, list[str | None], np.ndarray | None]:
126
- """Return ``(N, 4, C, H, W)`` images and last-frame targets.
127
-
128
- Size targets are returned only when :func:`size_targets_present` is true.
129
- """
130
- windows = frame_windows(frame, split_name, n_frames)
131
- if not windows:
132
- raise ValueError(f"split {split_name} has no {n_frames}-frame windows")
133
- indexed = frame.set_index(frame["sample_id"].astype(str), drop=False)
134
- use_size = size_targets_present(frame)
135
- images: list[np.ndarray] = []
136
- winds: list[float] = []
137
- labels: list[str | None] = []
138
- sizes: list[list[float]] = []
139
- for sample_ids in windows:
140
- frames: list[np.ndarray] = []
141
- for sample_id in sample_ids:
142
- row = _row(indexed, sample_id)
143
- array = load_image(resolve_image(manifest_path, str(row["image_path"])))
144
- hemisphere = None
145
- if "hemisphere" in frame.columns and not pd.isna(row["hemisphere"]):
146
- hemisphere = str(row["hemisphere"])
147
- frames.append(
148
- prepare_image(
149
- leave_unflipped(array, hemisphere),
150
- image_size,
151
- stats,
152
- max_missing_fraction,
153
- )
154
- )
155
- images.append(stack_prepared(frames))
156
- last = _row(indexed, sample_ids[-1])
157
- target_col = wind_column if wind_column in last and not pd.isna(last[wind_column]) else "wind_speed_kt"
158
- winds.append(float(last[target_col]))
159
- if "_class" in frame.columns and not pd.isna(last["_class"]):
160
- labels.append(str(last["_class"]))
161
- else:
162
- labels.append(None)
163
- if use_size:
164
- sizes.append([_pair(last, "r34_nmi"), _pair(last, "rmw_nmi")])
165
- size_array = np.asarray(sizes, dtype=np.float32) if use_size else None
166
- return (
167
- stack_prepared(images),
168
- np.asarray(winds, dtype=np.float32),
169
- labels,
170
- size_array,
171
- )
 
1
+ """Four-frame windows inside one split.
2
+
3
+ The image tensor is infrared only. Wind, R34, and radius of maximum wind
4
+ may be read as targets for the last frame. They are not channels.
5
+ A previous-frame link that leaves the split cannot bring that frame in.
6
+ Southern Hemisphere frames are not flipped.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from src.data_loader import load_image, resolve_image
17
+ from src.preprocessing import NormStats, leave_unflipped, prepare_image, stack_prepared
18
+
19
+ N_FRAMES = 4
20
+ SIZE_LABELS = ("r34_nmi", "rmw_nmi")
21
+
22
+
23
+ def size_targets_present(frame: pd.DataFrame) -> bool:
24
+ """True when both size columns exist and one row has a finite pair.
25
+
26
+ All-null columns are not labels. The size head stays off until then.
27
+ """
28
+ if any(column not in frame.columns for column in SIZE_LABELS):
29
+ return False
30
+ values = frame.loc[:, list(SIZE_LABELS)].apply(pd.to_numeric, errors="coerce")
31
+ finite_pair = np.isfinite(values.to_numpy(dtype=np.float64)).all(axis=1)
32
+ return bool(finite_pair.any())
33
+
34
+
35
+ def _prev_id(value: object) -> str | None:
36
+ if value is None:
37
+ return None
38
+ try:
39
+ if pd.isna(value):
40
+ return None
41
+ except (TypeError, ValueError):
42
+ return None
43
+ text = str(value).strip()
44
+ if text == "" or text.lower() in {"nan", "none", "<na>", "nat"}:
45
+ return None
46
+ return text
47
+
48
+
49
+ def _window_stays_in_split(
50
+ sample_ids: list[str], prev_ids: list[str | None], in_split: set[str]
51
+ ) -> bool:
52
+ """Reject a window whose previous-frame link leaves the split.
53
+
54
+ A link that was cleared is ignored. A link that is still set must name
55
+ the previous frame in this window, except at the first frame, where a
56
+ same-split predecessor may sit just outside a sliding window.
57
+ """
58
+ for offset, _sample_id in enumerate(sample_ids):
59
+ prev = prev_ids[offset]
60
+ if prev is None:
61
+ continue
62
+ if prev not in in_split:
63
+ return False
64
+ if offset > 0 and prev != sample_ids[offset - 1]:
65
+ return False
66
+ return True
67
+
68
+
69
+ def frame_windows(
70
+ frame: pd.DataFrame, split: str, n_frames: int = N_FRAMES
71
+ ) -> list[list[str]]:
72
+ """Sample ids of consecutive frames, one storm, one split.
73
+
74
+ ``n_frames`` is 4. A link that points outside this split rejects the
75
+ window. A link that was cleared stays cleared and is not followed.
76
+ """
77
+ if n_frames != N_FRAMES:
78
+ raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")
79
+ if "split" not in frame.columns:
80
+ raise ValueError("frame is missing split")
81
+ rows = frame[frame["split"] == split]
82
+ if rows.empty:
83
+ return []
84
+ order = ["timestamp", "sample_id"] if "timestamp" in rows.columns else ["sample_id"]
85
+ in_split = set(rows["sample_id"].astype(str))
86
+ windows: list[list[str]] = []
87
+ for _storm_id, group in rows.groupby("storm_id", sort=False):
88
+ ordered = group.sort_values(order, kind="mergesort")
89
+ sample_ids = [str(value) for value in ordered["sample_id"].tolist()]
90
+ if "prev_sample_id" in ordered.columns:
91
+ prev_ids = [_prev_id(value) for value in ordered["prev_sample_id"].tolist()]
92
+ else:
93
+ prev_ids = [None] * len(sample_ids)
94
+ for start in range(0, len(sample_ids) - n_frames + 1):
95
+ chosen = sample_ids[start : start + n_frames]
96
+ prev = prev_ids[start : start + n_frames]
97
+ if _window_stays_in_split(chosen, prev, in_split):
98
+ windows.append(chosen)
99
+ return windows
100
+
101
+
102
+ def _row(indexed: pd.DataFrame, sample_id: str) -> pd.Series:
103
+ row = indexed.loc[sample_id]
104
+ if isinstance(row, pd.DataFrame):
105
+ return row.iloc[0]
106
+ return row
107
+
108
+
109
+ def _pair(row: pd.Series, column: str) -> float:
110
+ number = pd.to_numeric(pd.Series([row[column]]), errors="coerce").iloc[0]
111
+ if pd.isna(number):
112
+ return float("nan")
113
+ return float(number)
114
+
115
+
116
+ def stack_windows(
117
+ frame: pd.DataFrame,
118
+ manifest_path: str | Path,
119
+ split_name: str,
120
+ image_size: int | str | None,
121
+ stats: NormStats | None,
122
+ max_missing_fraction: float,
123
+ n_frames: int = N_FRAMES,
124
+ wind_column: str = "wind_speed_kt",
125
+ ) -> tuple[np.ndarray, np.ndarray, list[str | None], np.ndarray | None]:
126
+ """Return ``(N, 4, C, H, W)`` images and last-frame targets.
127
+
128
+ Size targets are returned only when :func:`size_targets_present` is true.
129
+ """
130
+ windows = frame_windows(frame, split_name, n_frames)
131
+ if not windows:
132
+ raise ValueError(f"split {split_name} has no {n_frames}-frame windows")
133
+ indexed = frame.set_index(frame["sample_id"].astype(str), drop=False)
134
+ use_size = size_targets_present(frame)
135
+ images: list[np.ndarray] = []
136
+ winds: list[float] = []
137
+ labels: list[str | None] = []
138
+ sizes: list[list[float]] = []
139
+ for sample_ids in windows:
140
+ frames: list[np.ndarray] = []
141
+ for sample_id in sample_ids:
142
+ row = _row(indexed, sample_id)
143
+ array = load_image(resolve_image(manifest_path, str(row["image_path"])))
144
+ hemisphere = None
145
+ if "hemisphere" in frame.columns and not pd.isna(row["hemisphere"]):
146
+ hemisphere = str(row["hemisphere"])
147
+ frames.append(
148
+ prepare_image(
149
+ leave_unflipped(array, hemisphere),
150
+ image_size,
151
+ stats,
152
+ max_missing_fraction,
153
+ )
154
+ )
155
+ images.append(stack_prepared(frames))
156
+ last = _row(indexed, sample_ids[-1])
157
+ target_col = wind_column if wind_column in last and not pd.isna(last[wind_column]) else "wind_speed_kt"
158
+ winds.append(float(last[target_col]))
159
+ if "_class" in frame.columns and not pd.isna(last["_class"]):
160
+ labels.append(str(last["_class"]))
161
+ else:
162
+ labels.append(None)
163
+ if use_size:
164
+ sizes.append([_pair(last, "r34_nmi"), _pair(last, "rmw_nmi")])
165
+ size_array = np.asarray(sizes, dtype=np.float32) if use_size else None
166
+ return (
167
+ stack_prepared(images),
168
+ np.asarray(winds, dtype=np.float32),
169
+ labels,
170
+ size_array,
171
+ )
src/splits.py CHANGED
@@ -1,318 +1,318 @@
1
- """Storm-safe splits. Random frame splits are rejected.
2
-
3
- ``storm_ids_by_split`` returns the disjoint train, val, and test storm ids.
4
- A later residual-quantile coverage check can reuse that map from an assigned
5
- frame without assigning rows again.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import re
11
- from collections.abc import Iterable
12
-
13
- import numpy as np
14
- import pandas as pd
15
-
16
- from src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, wind_to_imd5
17
-
18
- _CLASS_SEQUENCES = tuple(
19
- tuple(part for part in re.split(r"[^a-z0-9]+", name.lower()) if part)
20
- for name in DEFAULT_NAMES
21
- )
22
- _COMPACT_MARKERS = ("windspeed", "windkt", "r34", "rmw", "imd5", "intensity")
23
- _LABEL_TOKENS = frozenset(
24
- {"wind", "windspeed", "windkt", "r34", "rmw", "imd5", "intensity", "class"}
25
- )
26
-
27
-
28
- class LeakageError(RuntimeError):
29
- """A split shares a storm across sides, or is a random frame split."""
30
-
31
-
32
- def _name_tokens(name: str) -> list[str]:
33
- return [part for part in re.split(r"[^a-z0-9]+", str(name).lower()) if part]
34
-
35
-
36
- def _contains_sequence(tokens: list[str], sequence: tuple[str, ...]) -> bool:
37
- width = len(sequence)
38
- if width == 0 or len(tokens) < width:
39
- return False
40
- return any(
41
- tuple(tokens[index : index + width]) == sequence
42
- for index in range(len(tokens) - width + 1)
43
- )
44
-
45
-
46
- def is_forbidden_input(name: str) -> bool:
47
- """True for a label column or a name derived from wind, size, or class.
48
-
49
- Image features such as ``pixel_mean`` and ``delta_pixel_mean`` stay allowed.
50
- """
51
- text = str(name).strip().lower()
52
- if text in {item.lower() for item in FORBIDDEN_FEATURES}:
53
- return True
54
- if text in {item.lower() for item in DEFAULT_NAMES}:
55
- return True
56
- tokens = _name_tokens(text)
57
- if any(
58
- token in _LABEL_TOKENS or token.startswith(("windspeed", "windkt", "r34", "rmw", "imd5"))
59
- for token in tokens
60
- ):
61
- return True
62
- if any(_contains_sequence(tokens, sequence) for sequence in _CLASS_SEQUENCES):
63
- return True
64
- compact = "".join(tokens)
65
- return any(marker in compact for marker in _COMPACT_MARKERS)
66
-
67
-
68
- def forbidden_input_names(names: Iterable[str]) -> list[str]:
69
- return sorted({str(name) for name in names if is_forbidden_input(str(name))})
70
-
71
-
72
- def assert_no_forbidden_inputs(names: Iterable[str], detail: str) -> None:
73
- banned = forbidden_input_names(names)
74
- if banned:
75
- raise LeakageError(f"{detail}: {banned}")
76
-
77
-
78
- def assert_no_group_leakage(*frames: pd.DataFrame, group_col: str = "storm_id") -> None:
79
- seen: dict[str, int] = {}
80
- for index, frame in enumerate(frames):
81
- if frame.empty:
82
- continue
83
- for storm_id in frame[group_col].astype(str).unique():
84
- if storm_id in seen:
85
- raise LeakageError(
86
- f"{group_col}={storm_id} is in split index {seen[storm_id]} and {index}"
87
- )
88
- seen[storm_id] = index
89
- sample_ids: list[str] = []
90
- for frame in frames:
91
- if "sample_id" in frame.columns:
92
- sample_ids.extend(frame["sample_id"].astype(str).tolist())
93
- if len(sample_ids) != len(set(sample_ids)):
94
- raise LeakageError("sample_id repeated across splits")
95
-
96
-
97
- def storm_ids_by_split(frame: pd.DataFrame) -> dict[str, frozenset[str]]:
98
- """Return disjoint storm ids for ``train``, ``val``, and ``test``.
99
-
100
- A later residual-quantile coverage check can take ``result["test"]``
101
- from an assigned frame and score those storms without assigning rows again.
102
- """
103
- if "storm_id" not in frame.columns or "split" not in frame.columns:
104
- raise LeakageError("storm_id and split are required")
105
- known = ("train", "val", "test")
106
- labels = set(frame["split"].astype(str).unique())
107
- unknown = labels - set(known)
108
- if unknown:
109
- raise LeakageError(f"unknown splits: {sorted(unknown)}")
110
- parts = [frame.loc[frame["split"].astype(str) == name] for name in known]
111
- assert_no_group_leakage(*parts)
112
- return {
113
- name: frozenset(part["storm_id"].astype(str))
114
- for name, part in zip(known, parts, strict=True)
115
- }
116
-
117
-
118
- def _storm_table(frame: pd.DataFrame) -> pd.DataFrame:
119
- rows: list[dict[str, object]] = []
120
- for storm_id, group in frame.groupby("storm_id", sort=False):
121
- if "year" in group.columns:
122
- years = pd.to_numeric(group["year"], errors="coerce").dropna().astype(int)
123
- else:
124
- years = pd.Series(dtype=int)
125
- basins = (
126
- sorted(set(group["basin"].dropna().astype(str)))
127
- if "basin" in group.columns
128
- else []
129
- )
130
- median_wind = float(pd.to_numeric(group["wind_speed_kt"]).median())
131
- rows.append(
132
- {
133
- "storm_id": str(storm_id),
134
- "year_min": int(years.min()) if len(years) else pd.NA,
135
- "year_max": int(years.max()) if len(years) else pd.NA,
136
- "basins": basins,
137
- "stratify": wind_to_imd5(median_wind) or "below",
138
- }
139
- )
140
- return pd.DataFrame(rows)
141
-
142
-
143
- def _counts(n: int, test_fraction: float, val_fraction: float) -> tuple[int, int]:
144
- if n < 3:
145
- raise LeakageError("need at least 3 storms for train/val/test")
146
- n_test = max(1, int(round(n * test_fraction)))
147
- n_val = max(1, int(round((n - n_test) * val_fraction)))
148
- if n - n_test - n_val < 1:
149
- raise LeakageError("split fractions left no training storms")
150
- return n_test, n_val
151
-
152
-
153
- def _ordered_storms(table: pd.DataFrame, seed: int) -> list[str]:
154
- """Interleave intensity bins so a slice is approximately stratified."""
155
- rng = np.random.default_rng(seed)
156
- groups = [
157
- list(rng.permutation(ids.to_numpy()))
158
- for _, ids in table.groupby("stratify")["storm_id"]
159
- ]
160
- ordered: list[str] = []
161
- while any(groups):
162
- for group in groups:
163
- if group:
164
- ordered.append(str(group.pop()))
165
- return ordered
166
-
167
-
168
- def _assignment_from_ids(
169
- table: pd.DataFrame, test_ids: set[str], val_ids: set[str]
170
- ) -> dict[str, str]:
171
- return {
172
- sid: ("test" if sid in test_ids else "val" if sid in val_ids else "train")
173
- for sid in table["storm_id"].astype(str)
174
- }
175
-
176
-
177
- def assign_storms(
178
- frame: pd.DataFrame,
179
- strategy: str,
180
- test_fraction: float = 0.2,
181
- val_fraction: float = 0.2,
182
- seed: int = 42,
183
- holdout_years: list[int] | None = None,
184
- holdout_basin: str | None = None,
185
- ) -> pd.DataFrame:
186
- """Return a copy with ``split`` in {train, val, test}. Storms are never cut."""
187
- strategy = strategy.lower().strip()
188
- if strategy in {"random", "frame", "shuffle", "random_frame"}:
189
- raise LeakageError(
190
- "random frame splits are forbidden; use storm_wise, chronological, or holdout_basin"
191
- )
192
- work = frame.copy()
193
- work["storm_id"] = work["storm_id"].astype(str)
194
- table = _storm_table(work)
195
- holdout_years = list(holdout_years or [])
196
- if strategy == "chronological":
197
- if table["year_min"].isna().any():
198
- missing = table.loc[table["year_min"].isna(), "storm_id"].tolist()
199
- raise LeakageError(f"chronological split needs a year for every storm: {missing}")
200
- if not holdout_years:
201
- years = sorted(int(year) for year in table["year_min"].astype(int).unique())
202
- n_hold = max(1, int(round(len(years) * test_fraction)))
203
- holdout_years = years[-n_hold:]
204
- held = {int(year) for year in holdout_years}
205
-
206
- def touches_year(row: pd.Series) -> bool:
207
- span = set(range(int(row.year_min), int(row.year_max) + 1))
208
- return bool(span & held)
209
-
210
- test_ids = set(table.loc[table.apply(touches_year, axis=1), "storm_id"].astype(str))
211
- pool = table[~table["storm_id"].isin(test_ids)]
212
- if pool.empty or not test_ids:
213
- raise LeakageError("chronological split produced an empty side")
214
- n_val = max(1, int(round(len(pool) * val_fraction)))
215
- if n_val >= len(pool):
216
- raise LeakageError("not enough non-holdout storms for train and val")
217
- val_ids = set(_ordered_storms(pool, seed)[:n_val])
218
- assignment = _assignment_from_ids(table, test_ids, val_ids)
219
- elif strategy == "holdout_basin":
220
- if not holdout_basin:
221
- raise LeakageError("holdout_basin strategy requires holdout_basin")
222
- test_ids = set(
223
- table.loc[
224
- table["basins"].map(lambda basins: holdout_basin in basins), "storm_id"
225
- ].astype(str)
226
- )
227
- pool = table[~table["storm_id"].isin(test_ids)]
228
- if pool.empty or not test_ids:
229
- raise LeakageError("holdout basin split produced an empty side")
230
- n_val = max(1, int(round(len(pool) * val_fraction)))
231
- if n_val >= len(pool):
232
- raise LeakageError("not enough storms outside the holdout basin for train and val")
233
- val_ids = set(_ordered_storms(pool, seed)[:n_val])
234
- assignment = _assignment_from_ids(table, test_ids, val_ids)
235
- elif strategy == "storm_wise":
236
- ordered = _ordered_storms(table, seed)
237
- n_test, n_val = _counts(len(ordered), test_fraction, val_fraction)
238
- assignment = _assignment_from_ids(
239
- table, set(ordered[:n_test]), set(ordered[n_test : n_test + n_val])
240
- )
241
- else:
242
- raise LeakageError(f"unknown split strategy: {strategy}")
243
- work["split"] = work["storm_id"].map(assignment)
244
- if work["split"].isna().any():
245
- raise LeakageError("some rows were not assigned a split")
246
- parts = [work[work["split"] == name] for name in ("train", "val", "test")]
247
- assert_no_group_leakage(*parts)
248
- return work
249
-
250
-
251
- def observation_order(frame: pd.DataFrame) -> pd.Series:
252
- """Within-storm clock. Timestamp, else NASA ``relative_time_s``, else row order.
253
-
254
- A missing value in the chosen clock falls back to row order so a partial
255
- column cannot reorder the other rows. This is not a split.
256
- """
257
- if "timestamp" in frame.columns:
258
- parsed = pd.to_datetime(frame["timestamp"], errors="coerce", utc=True)
259
- if not bool(parsed.isna().any()):
260
- return pd.Series(parsed.to_numpy(), index=frame.index)
261
- return frame["timestamp"].astype(str)
262
- if "relative_time_s" in frame.columns:
263
- values = pd.to_numeric(frame["relative_time_s"], errors="coerce")
264
- if not bool(values.isna().any()):
265
- return values
266
- return pd.Series(np.arange(len(frame)), index=frame.index)
267
-
268
-
269
- def add_previous_frame_id(frame: pd.DataFrame) -> pd.DataFrame:
270
- """Attach the previous sample inside the same storm, ordered by time.
271
-
272
- The link is not yet split-safe. Call ``null_cross_split_links`` before
273
- using it as a feature. NASA frames use ``relative_time_s`` when they
274
- have no ``timestamp``.
275
- """
276
- if "storm_id" not in frame.columns or "sample_id" not in frame.columns:
277
- raise LeakageError("storm_id and sample_id are required")
278
- out = frame.copy()
279
- out["storm_id"] = out["storm_id"].astype(str)
280
- out["sample_id"] = out["sample_id"].astype(str)
281
- out = out.assign(_order=observation_order(out))
282
- out = out.sort_values(["storm_id", "_order"], kind="mergesort")
283
- out["prev_sample_id"] = out.groupby("storm_id", sort=False)["sample_id"].shift(1)
284
- out = out.drop(columns=["_order"], errors="ignore")
285
- return out.sort_index()
286
-
287
-
288
- def _sample_split_lookup(frame: pd.DataFrame) -> pd.Series:
289
- """Map sample id strings to the split of the first row with that id."""
290
- temporary = frame.assign(_sid=frame["sample_id"].map(str))
291
- temporary = temporary.drop_duplicates("_sid")
292
- return temporary.set_index("_sid")["split"].astype(str)
293
-
294
-
295
- def null_cross_split_links(frame: pd.DataFrame) -> tuple[pd.DataFrame, int]:
296
- """Drop previous-frame ids that point outside the row's split.
297
-
298
- Returns the frame and the number of links removed. Unknown previous ids
299
- are removed as well; they can hide a filtered-out frame.
300
- """
301
- if "split" not in frame.columns or "prev_sample_id" not in frame.columns:
302
- raise LeakageError("split and prev_sample_id are required")
303
- lookup = _sample_split_lookup(frame)
304
- out = frame.copy()
305
- dropped = 0
306
- kept: list[object] = []
307
- for prev, split in zip(out["prev_sample_id"], out["split"].astype(str), strict=True):
308
- if pd.isna(prev):
309
- kept.append(pd.NA)
310
- continue
311
- key = str(prev)
312
- if key not in lookup.index or lookup.loc[key] != split:
313
- kept.append(pd.NA)
314
- dropped += 1
315
- else:
316
- kept.append(key)
317
- out["prev_sample_id"] = kept
318
- return out, dropped
 
1
+ """Storm-safe splits. Random frame splits are rejected.
2
+
3
+ ``storm_ids_by_split`` returns the disjoint train, val, and test storm ids.
4
+ A later residual-quantile coverage check can reuse that map from an assigned
5
+ frame without assigning rows again.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Iterable
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, wind_to_imd5
17
+
18
+ _CLASS_SEQUENCES = tuple(
19
+ tuple(part for part in re.split(r"[^a-z0-9]+", name.lower()) if part)
20
+ for name in DEFAULT_NAMES
21
+ )
22
+ _COMPACT_MARKERS = ("windspeed", "windkt", "r34", "rmw", "imd5", "intensity")
23
+ _LABEL_TOKENS = frozenset(
24
+ {"wind", "windspeed", "windkt", "r34", "rmw", "imd5", "intensity", "class"}
25
+ )
26
+
27
+
28
+ class LeakageError(RuntimeError):
29
+ """A split shares a storm across sides, or is a random frame split."""
30
+
31
+
32
+ def _name_tokens(name: str) -> list[str]:
33
+ return [part for part in re.split(r"[^a-z0-9]+", str(name).lower()) if part]
34
+
35
+
36
+ def _contains_sequence(tokens: list[str], sequence: tuple[str, ...]) -> bool:
37
+ width = len(sequence)
38
+ if width == 0 or len(tokens) < width:
39
+ return False
40
+ return any(
41
+ tuple(tokens[index : index + width]) == sequence
42
+ for index in range(len(tokens) - width + 1)
43
+ )
44
+
45
+
46
+ def is_forbidden_input(name: str) -> bool:
47
+ """True for a label column or a name derived from wind, size, or class.
48
+
49
+ Image features such as ``pixel_mean`` and ``delta_pixel_mean`` stay allowed.
50
+ """
51
+ text = str(name).strip().lower()
52
+ if text in {item.lower() for item in FORBIDDEN_FEATURES}:
53
+ return True
54
+ if text in {item.lower() for item in DEFAULT_NAMES}:
55
+ return True
56
+ tokens = _name_tokens(text)
57
+ if any(
58
+ token in _LABEL_TOKENS or token.startswith(("windspeed", "windkt", "r34", "rmw", "imd5"))
59
+ for token in tokens
60
+ ):
61
+ return True
62
+ if any(_contains_sequence(tokens, sequence) for sequence in _CLASS_SEQUENCES):
63
+ return True
64
+ compact = "".join(tokens)
65
+ return any(marker in compact for marker in _COMPACT_MARKERS)
66
+
67
+
68
+ def forbidden_input_names(names: Iterable[str]) -> list[str]:
69
+ return sorted({str(name) for name in names if is_forbidden_input(str(name))})
70
+
71
+
72
+ def assert_no_forbidden_inputs(names: Iterable[str], detail: str) -> None:
73
+ banned = forbidden_input_names(names)
74
+ if banned:
75
+ raise LeakageError(f"{detail}: {banned}")
76
+
77
+
78
+ def assert_no_group_leakage(*frames: pd.DataFrame, group_col: str = "storm_id") -> None:
79
+ seen: dict[str, int] = {}
80
+ for index, frame in enumerate(frames):
81
+ if frame.empty:
82
+ continue
83
+ for storm_id in frame[group_col].astype(str).unique():
84
+ if storm_id in seen:
85
+ raise LeakageError(
86
+ f"{group_col}={storm_id} is in split index {seen[storm_id]} and {index}"
87
+ )
88
+ seen[storm_id] = index
89
+ sample_ids: list[str] = []
90
+ for frame in frames:
91
+ if "sample_id" in frame.columns:
92
+ sample_ids.extend(frame["sample_id"].astype(str).tolist())
93
+ if len(sample_ids) != len(set(sample_ids)):
94
+ raise LeakageError("sample_id repeated across splits")
95
+
96
+
97
+ def storm_ids_by_split(frame: pd.DataFrame) -> dict[str, frozenset[str]]:
98
+ """Return disjoint storm ids for ``train``, ``val``, and ``test``.
99
+
100
+ A later residual-quantile coverage check can take ``result["test"]``
101
+ from an assigned frame and score those storms without assigning rows again.
102
+ """
103
+ if "storm_id" not in frame.columns or "split" not in frame.columns:
104
+ raise LeakageError("storm_id and split are required")
105
+ known = ("train", "val", "test")
106
+ labels = set(frame["split"].astype(str).unique())
107
+ unknown = labels - set(known)
108
+ if unknown:
109
+ raise LeakageError(f"unknown splits: {sorted(unknown)}")
110
+ parts = [frame.loc[frame["split"].astype(str) == name] for name in known]
111
+ assert_no_group_leakage(*parts)
112
+ return {
113
+ name: frozenset(part["storm_id"].astype(str))
114
+ for name, part in zip(known, parts, strict=True)
115
+ }
116
+
117
+
118
+ def _storm_table(frame: pd.DataFrame) -> pd.DataFrame:
119
+ rows: list[dict[str, object]] = []
120
+ for storm_id, group in frame.groupby("storm_id", sort=False):
121
+ if "year" in group.columns:
122
+ years = pd.to_numeric(group["year"], errors="coerce").dropna().astype(int)
123
+ else:
124
+ years = pd.Series(dtype=int)
125
+ basins = (
126
+ sorted(set(group["basin"].dropna().astype(str)))
127
+ if "basin" in group.columns
128
+ else []
129
+ )
130
+ median_wind = float(pd.to_numeric(group["wind_speed_kt"]).median())
131
+ rows.append(
132
+ {
133
+ "storm_id": str(storm_id),
134
+ "year_min": int(years.min()) if len(years) else pd.NA,
135
+ "year_max": int(years.max()) if len(years) else pd.NA,
136
+ "basins": basins,
137
+ "stratify": wind_to_imd5(median_wind) or "below",
138
+ }
139
+ )
140
+ return pd.DataFrame(rows)
141
+
142
+
143
+ def _counts(n: int, test_fraction: float, val_fraction: float) -> tuple[int, int]:
144
+ if n < 3:
145
+ raise LeakageError("need at least 3 storms for train/val/test")
146
+ n_test = max(1, int(round(n * test_fraction)))
147
+ n_val = max(1, int(round((n - n_test) * val_fraction)))
148
+ if n - n_test - n_val < 1:
149
+ raise LeakageError("split fractions left no training storms")
150
+ return n_test, n_val
151
+
152
+
153
+ def _ordered_storms(table: pd.DataFrame, seed: int) -> list[str]:
154
+ """Interleave intensity bins so a slice is approximately stratified."""
155
+ rng = np.random.default_rng(seed)
156
+ groups = [
157
+ list(rng.permutation(ids.to_numpy()))
158
+ for _, ids in table.groupby("stratify")["storm_id"]
159
+ ]
160
+ ordered: list[str] = []
161
+ while any(groups):
162
+ for group in groups:
163
+ if group:
164
+ ordered.append(str(group.pop()))
165
+ return ordered
166
+
167
+
168
+ def _assignment_from_ids(
169
+ table: pd.DataFrame, test_ids: set[str], val_ids: set[str]
170
+ ) -> dict[str, str]:
171
+ return {
172
+ sid: ("test" if sid in test_ids else "val" if sid in val_ids else "train")
173
+ for sid in table["storm_id"].astype(str)
174
+ }
175
+
176
+
177
+ def assign_storms(
178
+ frame: pd.DataFrame,
179
+ strategy: str,
180
+ test_fraction: float = 0.2,
181
+ val_fraction: float = 0.2,
182
+ seed: int = 42,
183
+ holdout_years: list[int] | None = None,
184
+ holdout_basin: str | None = None,
185
+ ) -> pd.DataFrame:
186
+ """Return a copy with ``split`` in {train, val, test}. Storms are never cut."""
187
+ strategy = strategy.lower().strip()
188
+ if strategy in {"random", "frame", "shuffle", "random_frame"}:
189
+ raise LeakageError(
190
+ "random frame splits are forbidden; use storm_wise, chronological, or holdout_basin"
191
+ )
192
+ work = frame.copy()
193
+ work["storm_id"] = work["storm_id"].astype(str)
194
+ table = _storm_table(work)
195
+ holdout_years = list(holdout_years or [])
196
+ if strategy == "chronological":
197
+ if table["year_min"].isna().any():
198
+ missing = table.loc[table["year_min"].isna(), "storm_id"].tolist()
199
+ raise LeakageError(f"chronological split needs a year for every storm: {missing}")
200
+ if not holdout_years:
201
+ years = sorted(int(year) for year in table["year_min"].astype(int).unique())
202
+ n_hold = max(1, int(round(len(years) * test_fraction)))
203
+ holdout_years = years[-n_hold:]
204
+ held = {int(year) for year in holdout_years}
205
+
206
+ def touches_year(row: pd.Series) -> bool:
207
+ span = set(range(int(row.year_min), int(row.year_max) + 1))
208
+ return bool(span & held)
209
+
210
+ test_ids = set(table.loc[table.apply(touches_year, axis=1), "storm_id"].astype(str))
211
+ pool = table[~table["storm_id"].isin(test_ids)]
212
+ if pool.empty or not test_ids:
213
+ raise LeakageError("chronological split produced an empty side")
214
+ n_val = max(1, int(round(len(pool) * val_fraction)))
215
+ if n_val >= len(pool):
216
+ raise LeakageError("not enough non-holdout storms for train and val")
217
+ val_ids = set(_ordered_storms(pool, seed)[:n_val])
218
+ assignment = _assignment_from_ids(table, test_ids, val_ids)
219
+ elif strategy == "holdout_basin":
220
+ if not holdout_basin:
221
+ raise LeakageError("holdout_basin strategy requires holdout_basin")
222
+ test_ids = set(
223
+ table.loc[
224
+ table["basins"].map(lambda basins: holdout_basin in basins), "storm_id"
225
+ ].astype(str)
226
+ )
227
+ pool = table[~table["storm_id"].isin(test_ids)]
228
+ if pool.empty or not test_ids:
229
+ raise LeakageError("holdout basin split produced an empty side")
230
+ n_val = max(1, int(round(len(pool) * val_fraction)))
231
+ if n_val >= len(pool):
232
+ raise LeakageError("not enough storms outside the holdout basin for train and val")
233
+ val_ids = set(_ordered_storms(pool, seed)[:n_val])
234
+ assignment = _assignment_from_ids(table, test_ids, val_ids)
235
+ elif strategy == "storm_wise":
236
+ ordered = _ordered_storms(table, seed)
237
+ n_test, n_val = _counts(len(ordered), test_fraction, val_fraction)
238
+ assignment = _assignment_from_ids(
239
+ table, set(ordered[:n_test]), set(ordered[n_test : n_test + n_val])
240
+ )
241
+ else:
242
+ raise LeakageError(f"unknown split strategy: {strategy}")
243
+ work["split"] = work["storm_id"].map(assignment)
244
+ if work["split"].isna().any():
245
+ raise LeakageError("some rows were not assigned a split")
246
+ parts = [work[work["split"] == name] for name in ("train", "val", "test")]
247
+ assert_no_group_leakage(*parts)
248
+ return work
249
+
250
+
251
+ def observation_order(frame: pd.DataFrame) -> pd.Series:
252
+ """Within-storm clock. Timestamp, else NASA ``relative_time_s``, else row order.
253
+
254
+ A missing value in the chosen clock falls back to row order so a partial
255
+ column cannot reorder the other rows. This is not a split.
256
+ """
257
+ if "timestamp" in frame.columns:
258
+ parsed = pd.to_datetime(frame["timestamp"], errors="coerce", utc=True)
259
+ if not bool(parsed.isna().any()):
260
+ return pd.Series(parsed.to_numpy(), index=frame.index)
261
+ return frame["timestamp"].astype(str)
262
+ if "relative_time_s" in frame.columns:
263
+ values = pd.to_numeric(frame["relative_time_s"], errors="coerce")
264
+ if not bool(values.isna().any()):
265
+ return values
266
+ return pd.Series(np.arange(len(frame)), index=frame.index)
267
+
268
+
269
+ def add_previous_frame_id(frame: pd.DataFrame) -> pd.DataFrame:
270
+ """Attach the previous sample inside the same storm, ordered by time.
271
+
272
+ The link is not yet split-safe. Call ``null_cross_split_links`` before
273
+ using it as a feature. NASA frames use ``relative_time_s`` when they
274
+ have no ``timestamp``.
275
+ """
276
+ if "storm_id" not in frame.columns or "sample_id" not in frame.columns:
277
+ raise LeakageError("storm_id and sample_id are required")
278
+ out = frame.copy()
279
+ out["storm_id"] = out["storm_id"].astype(str)
280
+ out["sample_id"] = out["sample_id"].astype(str)
281
+ out = out.assign(_order=observation_order(out))
282
+ out = out.sort_values(["storm_id", "_order"], kind="mergesort")
283
+ out["prev_sample_id"] = out.groupby("storm_id", sort=False)["sample_id"].shift(1)
284
+ out = out.drop(columns=["_order"], errors="ignore")
285
+ return out.sort_index()
286
+
287
+
288
+ def _sample_split_lookup(frame: pd.DataFrame) -> pd.Series:
289
+ """Map sample id strings to the split of the first row with that id."""
290
+ temporary = frame.assign(_sid=frame["sample_id"].map(str))
291
+ temporary = temporary.drop_duplicates("_sid")
292
+ return temporary.set_index("_sid")["split"].astype(str)
293
+
294
+
295
+ def null_cross_split_links(frame: pd.DataFrame) -> tuple[pd.DataFrame, int]:
296
+ """Drop previous-frame ids that point outside the row's split.
297
+
298
+ Returns the frame and the number of links removed. Unknown previous ids
299
+ are removed as well; they can hide a filtered-out frame.
300
+ """
301
+ if "split" not in frame.columns or "prev_sample_id" not in frame.columns:
302
+ raise LeakageError("split and prev_sample_id are required")
303
+ lookup = _sample_split_lookup(frame)
304
+ out = frame.copy()
305
+ dropped = 0
306
+ kept: list[object] = []
307
+ for prev, split in zip(out["prev_sample_id"], out["split"].astype(str), strict=True):
308
+ if pd.isna(prev):
309
+ kept.append(pd.NA)
310
+ continue
311
+ key = str(prev)
312
+ if key not in lookup.index or lookup.loc[key] != split:
313
+ kept.append(pd.NA)
314
+ dropped += 1
315
+ else:
316
+ kept.append(key)
317
+ out["prev_sample_id"] = kept
318
+ return out, dropped
src/tcir.py CHANGED
@@ -1,591 +1,591 @@
1
- """Build a Cloudie manifest from TCIR HDF5 files, IR1 channel only.
2
-
3
- TCIR (Chen, Chen and Lin, KDD 2018, https://doi.org/10.1145/3219819.3219926;
4
- data https://github.com/BoyoChen/TCIR) ships two HDF5 files:
5
- ``TCIR-ATLN_EPAC_WPAC.h5`` and ``TCIR-CPAC_IO_SH.h5``. Each has
6
-
7
- - ``matrix``: N x 201 x 201 x 4 float32. The README lists the channels in
8
- the order IR1, WV, VIS, PMW, so IR1 is index 0 (``IR1_INDEX``). The file
9
- has no channel attributes. On 512 random real frames per file, channel 0
10
- has a median near 275 and is warmer than channel 1 (WV, median near 238)
11
- in over 98% of frames, channel 2 is a 0 to 2.2 reflectance with many NaNs
12
- (VIS at night) and channel 3 is a rain rate. That fits the README order.
13
- IR1 comes from GridSat-B1, which stores brightness temperature in kelvin.
14
- Reports still call these "pixel stats".
15
- - ``info``: a pandas 0.15 "fixed" frame (data_set, ID, time, lon, lat, Vmax,
16
- R35_4qAVG, MSLP). Current pandas cannot read it, so ``read_info`` decodes
17
- it with h5py and a restricted unpickler that only rebuilds numpy arrays.
18
-
19
- Only channel 0 is read (an h5py hyperslab, ``matrix[a:b, :, :, 0]``). Frames
20
- keep their native 201 x 201 grid, centred on the best-track position, about
21
- 7/100 degree per pixel.
22
-
23
- Labels. TCIR documents JTWC best tracks for WPAC and HURDAT2 for ATLN and
24
- EPAC. Both are 1-minute sustained winds, so ``wind_averaging`` is ``1min``.
25
- TCIR does not document the label source for CPAC, IO or SH. Those rows carry
26
- ``label_source_documented = False`` and an ``_inferred`` label source. A
27
- cross-check against IBTrACS v04r01 (matched on time and a 0.6 degree
28
- position window) found TCIR ``Vmax`` equal to ``USA_WIND`` on 99.8% of IO
29
- and SH rows (JTWC, 1-minute) and on 92% of CPAC rows (99.5% within 5 kt;
30
- HURDAT2/CPHC, 1-minute), while the 10-minute (BoM, RSMC La Reunion, Nadi)
31
- and 3-minute (New Delhi) agency winds match 14-21% of the time. So
32
- ``wind_averaging`` is ``1min`` on every row.
33
-
34
- Southern Hemisphere storms rotate clockwise. Nothing here flips an image by
35
- default. ``hemisphere`` (N or S, from the row's latitude) is recorded per
36
- row. ``flip_southern=True`` is an explicit opt-in that mirrors S frames
37
- north-south when exporting and sets ``flipped = True`` on those rows.
38
-
39
- Frames whose IR1 is all NaN, has a NaN fraction above
40
- ``max_missing_fraction`` (0.30, the preprocessing gate), or has any finite
41
- value outside ``IR1_VALID_RANGE`` (150 to 340 K; the real files hold a few
42
- frames with pixels down to 76 K or up to 348 K) are dropped and listed with a reason in an
43
- exclusions CSV. Kept frames may still hold a few NaNs; ``ir1_nan_fraction``
44
- records how many, and ``src.preprocessing`` fills them later.
45
-
46
- TCIR has no official split inside these files, so the manifest has no
47
- ``source_split`` and never has ``split``. ``src.splits.assign_storms`` writes
48
- ``split`` by storm. MSLP and R35 are label-derived, so they stay out of the
49
- manifest.
50
-
51
- Distance to land is joined from ``tcir/audit/distance_to_land.csv`` on
52
- ``sample_id`` (``distance_to_land_km`` and ``near_land``). The training
53
- path then applies ``labels.near_land_policy`` with ``labels.open_water_km``.
54
- A sample the CSV does not list, and a listed row whose distance is blank,
55
- stay unknown. The distance is not filled with 0. NASA is not in this file;
56
- that loader has no join key (``nasa_tc/audit/README.md``).
57
- """
58
-
59
- from __future__ import annotations
60
-
61
- import argparse
62
- import io
63
- import json
64
- import pickle
65
- from collections.abc import Iterator, Sequence
66
- from pathlib import Path
67
-
68
- import numpy as np
69
- import pandas as pd
70
-
71
- from src.schema import require_valid
72
-
73
- CHANNELS = ("IR1", "WV", "VIS", "PMW") # order in the TCIR README
74
- IR1_INDEX = 0
75
- IMAGE_SIZE = 201
76
- WIND_AVERAGING = "1min"
77
- IR1_VALID_RANGE = (150.0, 340.0) # kelvin; colder or warmer than any plausible IR window value
78
- MAX_MISSING_FRACTION = 0.30 # same gate as src.preprocessing
79
- BLOCK = 256
80
- _DISTANCE_COLUMNS = ("sample_id", "distance_to_land_km", "near_land")
81
- DEFAULT_DISTANCE_CSV = Path(__file__).resolve().parents[1] / "tcir" / "audit" / "distance_to_land.csv"
82
-
83
- # data_set -> (label source, documented by TCIR)
84
- LABEL_SOURCES = {
85
- "WPAC": ("jtwc_best_track", True),
86
- "ATLN": ("hurdat2", True),
87
- "EPAC": ("hurdat2", True),
88
- # Not documented by TCIR; inferred from an IBTrACS v04r01 match (PR notes).
89
- "CPAC": ("hurdat2_inferred", False),
90
- "IO": ("jtwc_best_track_inferred", False),
91
- "SH": ("jtwc_best_track_inferred", False),
92
- }
93
- EXCLUSION_COLUMNS = [
94
- "sample_id",
95
- "storm_id",
96
- "basin",
97
- "source_file",
98
- "h5_index",
99
- "ir1_nan_fraction",
100
- "reason",
101
- ]
102
-
103
- _ALLOWED_GLOBALS = {
104
- ("numpy.core.multiarray", "_reconstruct"),
105
- ("numpy._core.multiarray", "_reconstruct"),
106
- ("numpy.core.multiarray", "scalar"),
107
- ("numpy._core.multiarray", "scalar"),
108
- ("numpy", "ndarray"),
109
- ("numpy", "dtype"),
110
- ("_codecs", "encode"), # Python 3 protocol-2 pickles of byte strings
111
- }
112
-
113
-
114
- class _NumpyOnlyUnpickler(pickle.Unpickler):
115
- def find_class(self, module: str, name: str): # noqa: ANN201
116
- if (module, name) not in _ALLOWED_GLOBALS:
117
- raise pickle.UnpicklingError(f"refusing to load {module}.{name} from TCIR info")
118
- target = "numpy._core.multiarray" if module.endswith(".multiarray") else module
119
- import importlib
120
-
121
- return getattr(importlib.import_module(target), name)
122
-
123
-
124
- def _text(value: object) -> str:
125
- return value.decode() if isinstance(value, bytes) else str(value)
126
-
127
-
128
- def _block_values(dataset) -> np.ndarray: # noqa: ANN001
129
- if dataset.dtype.kind in "fiub":
130
- return dataset[()]
131
- raw = dataset[0]
132
- data = bytes(np.asarray(raw, dtype=np.uint8)) if not isinstance(raw, bytes) else raw
133
- return _NumpyOnlyUnpickler(io.BytesIO(data), encoding="latin1").load()
134
-
135
-
136
- def read_info(path: str | Path) -> pd.DataFrame:
137
- """Decode the ``info`` frame with h5py. Adds ``h5_index`` (row in ``matrix``)."""
138
- import h5py
139
-
140
- with h5py.File(path, "r") as handle:
141
- group = handle["info"]
142
- order = [_text(name) for name in group["axis0"][()]]
143
- n_rows = int(group["axis1"].shape[0])
144
- columns: dict[str, np.ndarray] = {}
145
- for block in range(int(group.attrs["nblocks"])):
146
- items = [_text(name) for name in group[f"block{block}_items"][()]]
147
- values = np.asarray(_block_values(group[f"block{block}_values"]))
148
- if values.shape != (n_rows, len(items)):
149
- raise ValueError(f"{path}: info block{block} has shape {values.shape}")
150
- for position, item in enumerate(items):
151
- columns[item] = values[:, position]
152
- n_matrix = int(handle["matrix"].shape[0])
153
- if n_matrix != n_rows:
154
- raise ValueError(f"{path}: info has {n_rows} rows but matrix has {n_matrix}")
155
- frame = pd.DataFrame({name: columns[name] for name in order})
156
- for name in frame.columns:
157
- if frame[name].dtype == object:
158
- frame[name] = frame[name].map(_text)
159
- frame["h5_index"] = np.arange(n_rows)
160
- return frame
161
-
162
-
163
- def iter_ir1(path: str | Path, block: int = BLOCK) -> Iterator[tuple[int, np.ndarray]]:
164
- """Yield ``(start, frames)`` with frames shaped (k, 201, 201), IR1 only."""
165
- import h5py
166
-
167
- with h5py.File(path, "r") as handle:
168
- matrix = handle["matrix"]
169
- if matrix.ndim != 4 or matrix.shape[1:] != (IMAGE_SIZE, IMAGE_SIZE, len(CHANNELS)):
170
- raise ValueError(f"{path}: matrix shape {matrix.shape}, expected N x 201 x 201 x 4")
171
- for start in range(0, matrix.shape[0], block):
172
- stop = min(start + block, matrix.shape[0])
173
- yield start, np.asarray(matrix[start:stop, :, :, IR1_INDEX], dtype=np.float32)
174
-
175
-
176
- def exclusion_reason(
177
- frame: np.ndarray,
178
- max_missing_fraction: float = MAX_MISSING_FRACTION,
179
- valid_range: tuple[float, float] = IR1_VALID_RANGE,
180
- ) -> tuple[str | None, float]:
181
- """Return (reason or None, NaN fraction) for one IR1 frame."""
182
- finite = np.isfinite(frame)
183
- nan_fraction = float(1.0 - finite.mean())
184
- if not finite.any():
185
- return "ir1 all NaN", nan_fraction
186
- if nan_fraction > max_missing_fraction:
187
- return f"ir1 NaN fraction {nan_fraction:.3f} > {max_missing_fraction:.2f}", nan_fraction
188
- values = frame[finite]
189
- low, high = valid_range
190
- if float(values.min()) < low or float(values.max()) > high:
191
- return (
192
- f"ir1 value outside [{low:g}, {high:g}] K "
193
- f"(min {float(values.min()):.2f}, max {float(values.max()):.2f})",
194
- nan_fraction,
195
- )
196
- return None, nan_fraction
197
-
198
-
199
- def hemisphere_of(lat: pd.Series) -> pd.Series:
200
- return pd.Series(np.where(pd.to_numeric(lat) < 0, "S", "N"), index=lat.index)
201
-
202
-
203
- def _blank_distance(value: object) -> bool:
204
- if value is None:
205
- return True
206
- try:
207
- if pd.isna(value):
208
- return True
209
- except (TypeError, ValueError):
210
- return False
211
- return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
212
-
213
-
214
- def _near_land_token(value: object) -> str:
215
- """``true``, ``false``, or ``unknown``. A blank cell stays unknown."""
216
- if isinstance(value, (bool, np.bool_)):
217
- return "true" if bool(value) else "false"
218
- if _blank_distance(value):
219
- return "unknown"
220
- text = str(value).strip().lower()
221
- if text in {"1", "true", "yes", "y", "t"}:
222
- return "true"
223
- if text in {"0", "false", "no", "n", "f"}:
224
- return "false"
225
- if text in {"unknown", "na", "n/a"}:
226
- return "unknown"
227
- raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
228
-
229
-
230
- def _distance_km(value: object) -> float:
231
- if _blank_distance(value):
232
- return float("nan")
233
- try:
234
- number = float(value)
235
- except (TypeError, ValueError) as exc:
236
- raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
237
- if not np.isfinite(number):
238
- return float("nan")
239
- return number
240
-
241
-
242
- def read_distance_to_land(path: str | Path | None = None) -> pd.DataFrame:
243
- """``sample_id``, ``distance_to_land_km``, and ``near_land`` from the audit CSV.
244
-
245
- ``path`` defaults to ``tcir/audit/distance_to_land.csv``. Blank distances
246
- stay NaN. ``near_land`` stays ``unknown`` when the audit says so.
247
- """
248
- csv_path = DEFAULT_DISTANCE_CSV if path in (None, "", "null") else Path(path)
249
- if not csv_path.is_file():
250
- raise FileNotFoundError(
251
- f"TCIR distance table {csv_path} is missing. Nothing is downloaded."
252
- )
253
- table = pd.read_csv(csv_path)
254
- table.columns = [str(column).strip() for column in table.columns]
255
- missing = [column for column in _DISTANCE_COLUMNS if column not in table.columns]
256
- if missing:
257
- raise ValueError(f"distance_to_land.csv missing {missing}")
258
- out = pd.DataFrame(
259
- {
260
- "sample_id": table["sample_id"].astype(str).str.strip(),
261
- "distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
262
- "near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
263
- }
264
- )
265
- if out["sample_id"].duplicated().any():
266
- raise ValueError("distance_to_land.csv repeats a sample_id")
267
- return out
268
-
269
-
270
- def attach_distance_to_land(
271
- frame: pd.DataFrame, path: str | Path | None = None
272
- ) -> pd.DataFrame:
273
- """Left-join the audit distances onto ``sample_id``.
274
-
275
- A sample that is not in the CSV, or a row whose distance is blank,
276
- keeps a null distance and ``near_land`` ``unknown``. The null is not
277
- replaced with 0 km or with ``false``.
278
- """
279
- if "sample_id" not in frame.columns:
280
- raise ValueError("TCIR distance join needs sample_id")
281
- flags = read_distance_to_land(path)
282
- lookup = flags.set_index("sample_id")
283
- distance: list[float] = []
284
- near: list[str] = []
285
- for sample_id in frame["sample_id"].astype(str).tolist():
286
- if sample_id not in lookup.index:
287
- distance.append(float("nan"))
288
- near.append("unknown")
289
- continue
290
- row = lookup.loc[sample_id]
291
- if isinstance(row, pd.DataFrame):
292
- raise ValueError(f"distance_to_land.csv repeats {sample_id}")
293
- distance.append(_distance_km(row["distance_to_land_km"]))
294
- near.append(_near_land_token(row["near_land"]))
295
- out = frame.copy()
296
- out["distance_to_land_km"] = np.asarray(distance, dtype=float)
297
- out["near_land"] = near
298
- return out
299
-
300
-
301
- def orient(
302
- frame: np.ndarray, hemisphere: str, flip_southern: bool = False
303
- ) -> tuple[np.ndarray, bool]:
304
- """Return (frame, flipped). Only flips when ``flip_southern`` is set and the row is S."""
305
- if flip_southern and hemisphere == "S":
306
- return np.ascontiguousarray(frame[::-1, :]), True
307
- return frame, False
308
-
309
-
310
- def _rows(info: pd.DataFrame, source_file: str) -> pd.DataFrame:
311
- unknown = sorted(set(info["data_set"]) - set(LABEL_SOURCES))
312
- if unknown:
313
- raise ValueError(f"unknown TCIR data_set values {unknown}")
314
- stamp = pd.to_datetime(info["time"].astype(str), format="%Y%m%d%H", utc=True)
315
- lon = pd.to_numeric(info["lon"]).astype(float)
316
- rows = pd.DataFrame(
317
- {
318
- "sample_id": "tcir_" + info["ID"].astype(str) + "_" + info["time"].astype(str),
319
- "storm_id": info["ID"].astype(str),
320
- "timestamp": stamp.dt.strftime("%Y-%m-%dT%H:%M:%SZ"),
321
- "year": stamp.dt.year.astype(int),
322
- "wind_speed_kt": pd.to_numeric(info["Vmax"]).astype(float),
323
- "basin": info["data_set"].astype(str),
324
- "lat": pd.to_numeric(info["lat"]).astype(float),
325
- "lon": ((lon + 180.0) % 360.0) - 180.0,
326
- "hemisphere": hemisphere_of(info["lat"]),
327
- "source": "tcir",
328
- "source_file": source_file,
329
- "h5_index": info["h5_index"].astype(int),
330
- "sensor": "GridSat-B1",
331
- "channel": "IR1",
332
- "channel_index": IR1_INDEX,
333
- "native_height": IMAGE_SIZE,
334
- "native_width": IMAGE_SIZE,
335
- "orig_size": IMAGE_SIZE,
336
- "pixel_units": "kelvin_brightness_temperature",
337
- "wind_averaging": WIND_AVERAGING,
338
- "label_source": info["data_set"].map(lambda b: LABEL_SOURCES[b][0]),
339
- "label_source_documented": info["data_set"].map(lambda b: LABEL_SOURCES[b][1]),
340
- "center_source": "dataset_precentered",
341
- "is_synthetic": False,
342
- }
343
- )
344
- return rows
345
-
346
-
347
- class _PixelStats:
348
- def __init__(self) -> None:
349
- self.count = 0
350
- self.total = 0.0
351
- self.total_sq = 0.0
352
- self.low = np.inf
353
- self.high = -np.inf
354
-
355
- def add(self, frame: np.ndarray) -> None:
356
- values = frame[np.isfinite(frame)].astype(np.float64)
357
- if values.size:
358
- self.count += int(values.size)
359
- self.total += float(values.sum())
360
- self.total_sq += float(np.square(values).sum())
361
- self.low = min(self.low, float(values.min()))
362
- self.high = max(self.high, float(values.max()))
363
-
364
- def as_dict(self) -> dict[str, float | int]:
365
- if not self.count:
366
- return {"finite_pixels": 0}
367
- mean = self.total / self.count
368
- return {
369
- "finite_pixels": self.count,
370
- "min": round(self.low, 3),
371
- "max": round(self.high, 3),
372
- "mean": round(mean, 3),
373
- "std": round(float(np.sqrt(max(self.total_sq / self.count - mean**2, 0.0))), 3),
374
- }
375
-
376
-
377
- def build_manifest(
378
- h5_paths: Sequence[str | Path],
379
- manifest_dir: str | Path,
380
- export: bool = True,
381
- flip_southern: bool = False,
382
- max_missing_fraction: float = MAX_MISSING_FRACTION,
383
- block: int = BLOCK,
384
- distance_csv: str | Path | None = None,
385
- ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, object]]:
386
- """Return (manifest, exclusions, pixel stats).
387
-
388
- With ``export`` each kept IR1 frame is saved as ``ir1/<sample_id>.npy``
389
- under ``manifest_dir`` and ``image_path`` points there (relative), so
390
- ``src.data_loader`` can read it. Without ``export`` ``image_path`` is
391
- ``<file>#<h5_index>`` for reference only. ``distance_csv`` defaults to
392
- the committed audit table and is joined on ``sample_id``.
393
- """
394
- manifest_dir = Path(manifest_dir).resolve()
395
- image_dir = manifest_dir / "ir1"
396
- if export:
397
- image_dir.mkdir(parents=True, exist_ok=True)
398
- kept_parts, excluded_parts = [], []
399
- stats = _PixelStats()
400
- frames_with_nan = 0
401
- for h5_path in h5_paths:
402
- h5_path = Path(h5_path)
403
- rows = _rows(read_info(h5_path), h5_path.name)
404
- reasons: list[str | None] = [None] * len(rows)
405
- nan_fractions = np.zeros(len(rows))
406
- flipped = np.zeros(len(rows), dtype=bool)
407
- winds = rows["wind_speed_kt"].to_numpy()
408
- bad_wind = ~np.isfinite(winds) | (winds < 0)
409
- for start, frames in iter_ir1(h5_path, block):
410
- for offset, frame in enumerate(frames):
411
- index = start + offset
412
- reason, nan_fractions[index] = exclusion_reason(frame, max_missing_fraction)
413
- if reason is None and bad_wind[index]:
414
- reason = "wind missing or negative"
415
- reasons[index] = reason
416
- if reason is not None:
417
- continue
418
- stats.add(frame)
419
- frames_with_nan += int(nan_fractions[index] > 0)
420
- if export:
421
- out, flipped[index] = orient(frame, rows.at[index, "hemisphere"], flip_southern)
422
- np.save(image_dir / f"{rows.at[index, 'sample_id']}.npy", out.astype(np.float32))
423
- rows["ir1_nan_fraction"] = np.round(nan_fractions, 5)
424
- rows["flipped"] = flipped
425
- rows["image_path"] = (
426
- "ir1/" + rows["sample_id"] + ".npy"
427
- if export
428
- else rows["source_file"] + "#" + rows["h5_index"].astype(str)
429
- )
430
- drop = pd.Series([reason is not None for reason in reasons], index=rows.index)
431
- excluded = rows.loc[drop].assign(reason=[r for r in reasons if r is not None])
432
- kept_parts.append(rows.loc[~drop])
433
- excluded_parts.append(excluded[EXCLUSION_COLUMNS])
434
- manifest = pd.concat(kept_parts, ignore_index=True)
435
- excluded = pd.concat(excluded_parts, ignore_index=True)
436
- if "split" in manifest.columns or "source_split" in manifest.columns:
437
- raise AssertionError("TCIR manifest must not carry split or source_split")
438
- manifest = attach_distance_to_land(manifest, distance_csv)
439
- manifest = require_valid(manifest)
440
- pixel = stats.as_dict()
441
- pixel["kept_frames_with_some_nan"] = frames_with_nan
442
- return manifest, excluded, pixel
443
-
444
-
445
- def storm_split_check(
446
- frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42
447
- ) -> dict[str, object]:
448
- """Run the project splitter on the manifest and assert no storm leaks."""
449
- from src.splits import assert_no_group_leakage, assign_storms
450
-
451
- if "split" in frame.columns:
452
- raise ValueError("manifest must not carry split")
453
- assigned = assign_storms(frame, strategy, seed=seed)
454
- names = ("train", "val", "test")
455
- parts = [assigned.loc[assigned["split"] == name] for name in names]
456
- assert_no_group_leakage(*parts)
457
- return {
458
- "strategy": strategy,
459
- "rows": {name: int(len(part)) for name, part in zip(names, parts)},
460
- "storms": {name: int(part["storm_id"].nunique()) for name, part in zip(names, parts)},
461
- "leakage": "none",
462
- }
463
-
464
-
465
- def _reason_kind(reason: str) -> str:
466
- """Strip per-frame numbers so reasons can be counted."""
467
- if reason.startswith("ir1 NaN fraction"):
468
- return f"ir1 NaN fraction > {MAX_MISSING_FRACTION:.2f}"
469
- return reason.split(" (")[0]
470
-
471
-
472
- def summarize(
473
- frame: pd.DataFrame, excluded: pd.DataFrame, pixel: dict[str, object]
474
- ) -> dict[str, object]:
475
- def counts(column: str) -> dict[str, dict[str, int]]:
476
- return {
477
- str(key): {"rows": int(len(group)), "storms": int(group["storm_id"].nunique())}
478
- for key, group in frame.groupby(column)
479
- }
480
-
481
- storm_hemispheres = frame.groupby("storm_id")["hemisphere"].nunique()
482
- return {
483
- "rows": int(len(frame)),
484
- "unique_storms": int(frame["storm_id"].nunique()),
485
- "by_basin": counts("basin"),
486
- "by_hemisphere": counts("hemisphere"),
487
- "by_source_file": counts("source_file"),
488
- "storms_crossing_equator": sorted(storm_hemispheres[storm_hemispheres > 1].index.tolist()),
489
- "basin_vs_hemisphere": {
490
- f"{basin}/{hemi}": int(n)
491
- for (basin, hemi), n in frame.groupby(["basin", "hemisphere"]).size().items()
492
- },
493
- "years": [int(frame["year"].min()), int(frame["year"].max())],
494
- "wind_kt_min": float(frame["wind_speed_kt"].min()),
495
- "wind_kt_max": float(frame["wind_speed_kt"].max()),
496
- "wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
497
- "pixel_stats_ir1": pixel,
498
- "flipped_rows": int(frame["flipped"].sum()),
499
- "label_source_counts": frame["label_source"].value_counts().to_dict(),
500
- "label_source_undocumented_rows": int((~frame["label_source_documented"].astype(bool)).sum()),
501
- "wind_averaging": sorted(frame["wind_averaging"].unique()),
502
- "native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}),
503
- "has_split_column": "split" in frame.columns,
504
- "has_source_split_column": "source_split" in frame.columns,
505
- "is_synthetic": bool(frame["is_synthetic"].any()),
506
- "excluded": {
507
- "count": int(len(excluded)),
508
- "by_reason": excluded["reason"].map(_reason_kind).value_counts().to_dict(),
509
- "by_basin": excluded["basin"].value_counts().to_dict() if len(excluded) else {},
510
- },
511
- }
512
-
513
-
514
- def save_sample_png(
515
- frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path
516
- ) -> list[dict[str, object]]:
517
- """One N and one S frame side by side, as stored (no flip unless opted in)."""
518
- import matplotlib
519
-
520
- matplotlib.use("Agg")
521
- import matplotlib.pyplot as plt
522
-
523
- picks = []
524
- for hemi in ("N", "S"):
525
- subset = frame[frame["hemisphere"] == hemi]
526
- if len(subset):
527
- picks.append(subset.loc[subset["wind_speed_kt"].idxmax()])
528
- fig, axes = plt.subplots(1, len(picks), figsize=(4.2 * len(picks), 4.4), squeeze=False)
529
- info = []
530
- for ax, row in zip(axes[0], picks):
531
- image = np.load(Path(manifest_dir) / row["image_path"])
532
- shown = ax.imshow(image, cmap="gray_r")
533
- fig.colorbar(shown, ax=ax, fraction=0.046, label="IR1 pixel value")
534
- ax.set_title(
535
- f"{row['storm_id']} {row['timestamp'][:13]}Z {row['basin']}/{row['hemisphere']}\n"
536
- f"{row['wind_speed_kt']:.0f} kt (1min) | flipped={bool(row['flipped'])} | TCIR real",
537
- fontsize=8,
538
- )
539
- ax.axis("off")
540
- info.append(
541
- {
542
- "sample_id": row["sample_id"],
543
- "hemisphere": row["hemisphere"],
544
- "wind_speed_kt": float(row["wind_speed_kt"]),
545
- "shape": list(image.shape),
546
- "flipped": bool(row["flipped"]),
547
- }
548
- )
549
- Path(out).parent.mkdir(parents=True, exist_ok=True)
550
- fig.savefig(out, dpi=100, bbox_inches="tight")
551
- plt.close(fig)
552
- return info
553
-
554
-
555
- def main() -> None:
556
- parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
557
- parser.add_argument("--h5", nargs="+", required=True, help="TCIR .h5 files")
558
- parser.add_argument("--out", default="data/tcir/manifest.csv")
559
- parser.add_argument("--summary", default="reports/tcir_summary.json")
560
- parser.add_argument("--sample-png", default="reports/tcir_sample.png")
561
- parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/tcir_exclusions.csv")
562
- parser.add_argument("--no-export", action="store_true", help="do not write ir1/*.npy")
563
- parser.add_argument(
564
- "--flip-southern",
565
- action="store_true",
566
- help="opt in: mirror Southern Hemisphere frames north-south on export (default: no flip)",
567
- )
568
- args = parser.parse_args()
569
-
570
- out = Path(args.out)
571
- out.parent.mkdir(parents=True, exist_ok=True)
572
- frame, excluded, pixel = build_manifest(
573
- args.h5, out.parent, export=not args.no_export, flip_southern=args.flip_southern
574
- )
575
- exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "tcir_exclusions.csv"
576
- excluded.to_csv(exclusions_path, index=False)
577
- frame.drop(columns=["imd5_class"], errors="ignore").to_csv(out, index=False)
578
- summary = summarize(frame, excluded, pixel)
579
- summary["exclusions_file"] = str(exclusions_path)
580
- summary["storm_split_check"] = storm_split_check(frame)
581
- summary["flip_southern"] = bool(args.flip_southern)
582
- summary["manifest"] = str(out)
583
- if not args.no_export:
584
- summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
585
- Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
586
- Path(args.summary).write_text(json.dumps(summary, indent=2, default=str))
587
- print(json.dumps(summary, indent=2, default=str))
588
-
589
-
590
- if __name__ == "__main__":
591
- main()
 
1
+ """Build a Cloudie manifest from TCIR HDF5 files, IR1 channel only.
2
+
3
+ TCIR (Chen, Chen and Lin, KDD 2018, https://doi.org/10.1145/3219819.3219926;
4
+ data https://github.com/BoyoChen/TCIR) ships two HDF5 files:
5
+ ``TCIR-ATLN_EPAC_WPAC.h5`` and ``TCIR-CPAC_IO_SH.h5``. Each has
6
+
7
+ - ``matrix``: N x 201 x 201 x 4 float32. The README lists the channels in
8
+ the order IR1, WV, VIS, PMW, so IR1 is index 0 (``IR1_INDEX``). The file
9
+ has no channel attributes. On 512 random real frames per file, channel 0
10
+ has a median near 275 and is warmer than channel 1 (WV, median near 238)
11
+ in over 98% of frames, channel 2 is a 0 to 2.2 reflectance with many NaNs
12
+ (VIS at night) and channel 3 is a rain rate. That fits the README order.
13
+ IR1 comes from GridSat-B1, which stores brightness temperature in kelvin.
14
+ Reports still call these "pixel stats".
15
+ - ``info``: a pandas 0.15 "fixed" frame (data_set, ID, time, lon, lat, Vmax,
16
+ R35_4qAVG, MSLP). Current pandas cannot read it, so ``read_info`` decodes
17
+ it with h5py and a restricted unpickler that only rebuilds numpy arrays.
18
+
19
+ Only channel 0 is read (an h5py hyperslab, ``matrix[a:b, :, :, 0]``). Frames
20
+ keep their native 201 x 201 grid, centred on the best-track position, about
21
+ 7/100 degree per pixel.
22
+
23
+ Labels. TCIR documents JTWC best tracks for WPAC and HURDAT2 for ATLN and
24
+ EPAC. Both are 1-minute sustained winds, so ``wind_averaging`` is ``1min``.
25
+ TCIR does not document the label source for CPAC, IO or SH. Those rows carry
26
+ ``label_source_documented = False`` and an ``_inferred`` label source. A
27
+ cross-check against IBTrACS v04r01 (matched on time and a 0.6 degree
28
+ position window) found TCIR ``Vmax`` equal to ``USA_WIND`` on 99.8% of IO
29
+ and SH rows (JTWC, 1-minute) and on 92% of CPAC rows (99.5% within 5 kt;
30
+ HURDAT2/CPHC, 1-minute), while the 10-minute (BoM, RSMC La Reunion, Nadi)
31
+ and 3-minute (New Delhi) agency winds match 14-21% of the time. So
32
+ ``wind_averaging`` is ``1min`` on every row.
33
+
34
+ Southern Hemisphere storms rotate clockwise. Nothing here flips an image by
35
+ default. ``hemisphere`` (N or S, from the row's latitude) is recorded per
36
+ row. ``flip_southern=True`` is an explicit opt-in that mirrors S frames
37
+ north-south when exporting and sets ``flipped = True`` on those rows.
38
+
39
+ Frames whose IR1 is all NaN, has a NaN fraction above
40
+ ``max_missing_fraction`` (0.30, the preprocessing gate), or has any finite
41
+ value outside ``IR1_VALID_RANGE`` (150 to 340 K; the real files hold a few
42
+ frames with pixels down to 76 K or up to 348 K) are dropped and listed with a reason in an
43
+ exclusions CSV. Kept frames may still hold a few NaNs; ``ir1_nan_fraction``
44
+ records how many, and ``src.preprocessing`` fills them later.
45
+
46
+ TCIR has no official split inside these files, so the manifest has no
47
+ ``source_split`` and never has ``split``. ``src.splits.assign_storms`` writes
48
+ ``split`` by storm. MSLP and R35 are label-derived, so they stay out of the
49
+ manifest.
50
+
51
+ Distance to land is joined from ``tcir/audit/distance_to_land.csv`` on
52
+ ``sample_id`` (``distance_to_land_km`` and ``near_land``). The training
53
+ path then applies ``labels.near_land_policy`` with ``labels.open_water_km``.
54
+ A sample the CSV does not list, and a listed row whose distance is blank,
55
+ stay unknown. The distance is not filled with 0. NASA is not in this file;
56
+ that loader has no join key (``nasa_tc/audit/README.md``).
57
+ """
58
+
59
+ from __future__ import annotations
60
+
61
+ import argparse
62
+ import io
63
+ import json
64
+ import pickle
65
+ from collections.abc import Iterator, Sequence
66
+ from pathlib import Path
67
+
68
+ import numpy as np
69
+ import pandas as pd
70
+
71
+ from src.schema import require_valid
72
+
73
+ CHANNELS = ("IR1", "WV", "VIS", "PMW") # order in the TCIR README
74
+ IR1_INDEX = 0
75
+ IMAGE_SIZE = 201
76
+ WIND_AVERAGING = "1min"
77
+ IR1_VALID_RANGE = (150.0, 340.0) # kelvin; colder or warmer than any plausible IR window value
78
+ MAX_MISSING_FRACTION = 0.30 # same gate as src.preprocessing
79
+ BLOCK = 256
80
+ _DISTANCE_COLUMNS = ("sample_id", "distance_to_land_km", "near_land")
81
+ DEFAULT_DISTANCE_CSV = Path(__file__).resolve().parents[1] / "tcir" / "audit" / "distance_to_land.csv"
82
+
83
+ # data_set -> (label source, documented by TCIR)
84
+ LABEL_SOURCES = {
85
+ "WPAC": ("jtwc_best_track", True),
86
+ "ATLN": ("hurdat2", True),
87
+ "EPAC": ("hurdat2", True),
88
+ # Not documented by TCIR; inferred from an IBTrACS v04r01 match (PR notes).
89
+ "CPAC": ("hurdat2_inferred", False),
90
+ "IO": ("jtwc_best_track_inferred", False),
91
+ "SH": ("jtwc_best_track_inferred", False),
92
+ }
93
+ EXCLUSION_COLUMNS = [
94
+ "sample_id",
95
+ "storm_id",
96
+ "basin",
97
+ "source_file",
98
+ "h5_index",
99
+ "ir1_nan_fraction",
100
+ "reason",
101
+ ]
102
+
103
+ _ALLOWED_GLOBALS = {
104
+ ("numpy.core.multiarray", "_reconstruct"),
105
+ ("numpy._core.multiarray", "_reconstruct"),
106
+ ("numpy.core.multiarray", "scalar"),
107
+ ("numpy._core.multiarray", "scalar"),
108
+ ("numpy", "ndarray"),
109
+ ("numpy", "dtype"),
110
+ ("_codecs", "encode"), # Python 3 protocol-2 pickles of byte strings
111
+ }
112
+
113
+
114
+ class _NumpyOnlyUnpickler(pickle.Unpickler):
115
+ def find_class(self, module: str, name: str): # noqa: ANN201
116
+ if (module, name) not in _ALLOWED_GLOBALS:
117
+ raise pickle.UnpicklingError(f"refusing to load {module}.{name} from TCIR info")
118
+ target = "numpy._core.multiarray" if module.endswith(".multiarray") else module
119
+ import importlib
120
+
121
+ return getattr(importlib.import_module(target), name)
122
+
123
+
124
+ def _text(value: object) -> str:
125
+ return value.decode() if isinstance(value, bytes) else str(value)
126
+
127
+
128
+ def _block_values(dataset) -> np.ndarray: # noqa: ANN001
129
+ if dataset.dtype.kind in "fiub":
130
+ return dataset[()]
131
+ raw = dataset[0]
132
+ data = bytes(np.asarray(raw, dtype=np.uint8)) if not isinstance(raw, bytes) else raw
133
+ return _NumpyOnlyUnpickler(io.BytesIO(data), encoding="latin1").load()
134
+
135
+
136
+ def read_info(path: str | Path) -> pd.DataFrame:
137
+ """Decode the ``info`` frame with h5py. Adds ``h5_index`` (row in ``matrix``)."""
138
+ import h5py
139
+
140
+ with h5py.File(path, "r") as handle:
141
+ group = handle["info"]
142
+ order = [_text(name) for name in group["axis0"][()]]
143
+ n_rows = int(group["axis1"].shape[0])
144
+ columns: dict[str, np.ndarray] = {}
145
+ for block in range(int(group.attrs["nblocks"])):
146
+ items = [_text(name) for name in group[f"block{block}_items"][()]]
147
+ values = np.asarray(_block_values(group[f"block{block}_values"]))
148
+ if values.shape != (n_rows, len(items)):
149
+ raise ValueError(f"{path}: info block{block} has shape {values.shape}")
150
+ for position, item in enumerate(items):
151
+ columns[item] = values[:, position]
152
+ n_matrix = int(handle["matrix"].shape[0])
153
+ if n_matrix != n_rows:
154
+ raise ValueError(f"{path}: info has {n_rows} rows but matrix has {n_matrix}")
155
+ frame = pd.DataFrame({name: columns[name] for name in order})
156
+ for name in frame.columns:
157
+ if frame[name].dtype == object:
158
+ frame[name] = frame[name].map(_text)
159
+ frame["h5_index"] = np.arange(n_rows)
160
+ return frame
161
+
162
+
163
+ def iter_ir1(path: str | Path, block: int = BLOCK) -> Iterator[tuple[int, np.ndarray]]:
164
+ """Yield ``(start, frames)`` with frames shaped (k, 201, 201), IR1 only."""
165
+ import h5py
166
+
167
+ with h5py.File(path, "r") as handle:
168
+ matrix = handle["matrix"]
169
+ if matrix.ndim != 4 or matrix.shape[1:] != (IMAGE_SIZE, IMAGE_SIZE, len(CHANNELS)):
170
+ raise ValueError(f"{path}: matrix shape {matrix.shape}, expected N x 201 x 201 x 4")
171
+ for start in range(0, matrix.shape[0], block):
172
+ stop = min(start + block, matrix.shape[0])
173
+ yield start, np.asarray(matrix[start:stop, :, :, IR1_INDEX], dtype=np.float32)
174
+
175
+
176
+ def exclusion_reason(
177
+ frame: np.ndarray,
178
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
179
+ valid_range: tuple[float, float] = IR1_VALID_RANGE,
180
+ ) -> tuple[str | None, float]:
181
+ """Return (reason or None, NaN fraction) for one IR1 frame."""
182
+ finite = np.isfinite(frame)
183
+ nan_fraction = float(1.0 - finite.mean())
184
+ if not finite.any():
185
+ return "ir1 all NaN", nan_fraction
186
+ if nan_fraction > max_missing_fraction:
187
+ return f"ir1 NaN fraction {nan_fraction:.3f} > {max_missing_fraction:.2f}", nan_fraction
188
+ values = frame[finite]
189
+ low, high = valid_range
190
+ if float(values.min()) < low or float(values.max()) > high:
191
+ return (
192
+ f"ir1 value outside [{low:g}, {high:g}] K "
193
+ f"(min {float(values.min()):.2f}, max {float(values.max()):.2f})",
194
+ nan_fraction,
195
+ )
196
+ return None, nan_fraction
197
+
198
+
199
+ def hemisphere_of(lat: pd.Series) -> pd.Series:
200
+ return pd.Series(np.where(pd.to_numeric(lat) < 0, "S", "N"), index=lat.index)
201
+
202
+
203
+ def _blank_distance(value: object) -> bool:
204
+ if value is None:
205
+ return True
206
+ try:
207
+ if pd.isna(value):
208
+ return True
209
+ except (TypeError, ValueError):
210
+ return False
211
+ return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
212
+
213
+
214
+ def _near_land_token(value: object) -> str:
215
+ """``true``, ``false``, or ``unknown``. A blank cell stays unknown."""
216
+ if isinstance(value, (bool, np.bool_)):
217
+ return "true" if bool(value) else "false"
218
+ if _blank_distance(value):
219
+ return "unknown"
220
+ text = str(value).strip().lower()
221
+ if text in {"1", "true", "yes", "y", "t"}:
222
+ return "true"
223
+ if text in {"0", "false", "no", "n", "f"}:
224
+ return "false"
225
+ if text in {"unknown", "na", "n/a"}:
226
+ return "unknown"
227
+ raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
228
+
229
+
230
+ def _distance_km(value: object) -> float:
231
+ if _blank_distance(value):
232
+ return float("nan")
233
+ try:
234
+ number = float(value)
235
+ except (TypeError, ValueError) as exc:
236
+ raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
237
+ if not np.isfinite(number):
238
+ return float("nan")
239
+ return number
240
+
241
+
242
+ def read_distance_to_land(path: str | Path | None = None) -> pd.DataFrame:
243
+ """``sample_id``, ``distance_to_land_km``, and ``near_land`` from the audit CSV.
244
+
245
+ ``path`` defaults to ``tcir/audit/distance_to_land.csv``. Blank distances
246
+ stay NaN. ``near_land`` stays ``unknown`` when the audit says so.
247
+ """
248
+ csv_path = DEFAULT_DISTANCE_CSV if path in (None, "", "null") else Path(path)
249
+ if not csv_path.is_file():
250
+ raise FileNotFoundError(
251
+ f"TCIR distance table {csv_path} is missing. Nothing is downloaded."
252
+ )
253
+ table = pd.read_csv(csv_path)
254
+ table.columns = [str(column).strip() for column in table.columns]
255
+ missing = [column for column in _DISTANCE_COLUMNS if column not in table.columns]
256
+ if missing:
257
+ raise ValueError(f"distance_to_land.csv missing {missing}")
258
+ out = pd.DataFrame(
259
+ {
260
+ "sample_id": table["sample_id"].astype(str).str.strip(),
261
+ "distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
262
+ "near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
263
+ }
264
+ )
265
+ if out["sample_id"].duplicated().any():
266
+ raise ValueError("distance_to_land.csv repeats a sample_id")
267
+ return out
268
+
269
+
270
+ def attach_distance_to_land(
271
+ frame: pd.DataFrame, path: str | Path | None = None
272
+ ) -> pd.DataFrame:
273
+ """Left-join the audit distances onto ``sample_id``.
274
+
275
+ A sample that is not in the CSV, or a row whose distance is blank,
276
+ keeps a null distance and ``near_land`` ``unknown``. The null is not
277
+ replaced with 0 km or with ``false``.
278
+ """
279
+ if "sample_id" not in frame.columns:
280
+ raise ValueError("TCIR distance join needs sample_id")
281
+ flags = read_distance_to_land(path)
282
+ lookup = flags.set_index("sample_id")
283
+ distance: list[float] = []
284
+ near: list[str] = []
285
+ for sample_id in frame["sample_id"].astype(str).tolist():
286
+ if sample_id not in lookup.index:
287
+ distance.append(float("nan"))
288
+ near.append("unknown")
289
+ continue
290
+ row = lookup.loc[sample_id]
291
+ if isinstance(row, pd.DataFrame):
292
+ raise ValueError(f"distance_to_land.csv repeats {sample_id}")
293
+ distance.append(_distance_km(row["distance_to_land_km"]))
294
+ near.append(_near_land_token(row["near_land"]))
295
+ out = frame.copy()
296
+ out["distance_to_land_km"] = np.asarray(distance, dtype=float)
297
+ out["near_land"] = near
298
+ return out
299
+
300
+
301
+ def orient(
302
+ frame: np.ndarray, hemisphere: str, flip_southern: bool = False
303
+ ) -> tuple[np.ndarray, bool]:
304
+ """Return (frame, flipped). Only flips when ``flip_southern`` is set and the row is S."""
305
+ if flip_southern and hemisphere == "S":
306
+ return np.ascontiguousarray(frame[::-1, :]), True
307
+ return frame, False
308
+
309
+
310
+ def _rows(info: pd.DataFrame, source_file: str) -> pd.DataFrame:
311
+ unknown = sorted(set(info["data_set"]) - set(LABEL_SOURCES))
312
+ if unknown:
313
+ raise ValueError(f"unknown TCIR data_set values {unknown}")
314
+ stamp = pd.to_datetime(info["time"].astype(str), format="%Y%m%d%H", utc=True)
315
+ lon = pd.to_numeric(info["lon"]).astype(float)
316
+ rows = pd.DataFrame(
317
+ {
318
+ "sample_id": "tcir_" + info["ID"].astype(str) + "_" + info["time"].astype(str),
319
+ "storm_id": info["ID"].astype(str),
320
+ "timestamp": stamp.dt.strftime("%Y-%m-%dT%H:%M:%SZ"),
321
+ "year": stamp.dt.year.astype(int),
322
+ "wind_speed_kt": pd.to_numeric(info["Vmax"]).astype(float),
323
+ "basin": info["data_set"].astype(str),
324
+ "lat": pd.to_numeric(info["lat"]).astype(float),
325
+ "lon": ((lon + 180.0) % 360.0) - 180.0,
326
+ "hemisphere": hemisphere_of(info["lat"]),
327
+ "source": "tcir",
328
+ "source_file": source_file,
329
+ "h5_index": info["h5_index"].astype(int),
330
+ "sensor": "GridSat-B1",
331
+ "channel": "IR1",
332
+ "channel_index": IR1_INDEX,
333
+ "native_height": IMAGE_SIZE,
334
+ "native_width": IMAGE_SIZE,
335
+ "orig_size": IMAGE_SIZE,
336
+ "pixel_units": "kelvin_brightness_temperature",
337
+ "wind_averaging": WIND_AVERAGING,
338
+ "label_source": info["data_set"].map(lambda b: LABEL_SOURCES[b][0]),
339
+ "label_source_documented": info["data_set"].map(lambda b: LABEL_SOURCES[b][1]),
340
+ "center_source": "dataset_precentered",
341
+ "is_synthetic": False,
342
+ }
343
+ )
344
+ return rows
345
+
346
+
347
+ class _PixelStats:
348
+ def __init__(self) -> None:
349
+ self.count = 0
350
+ self.total = 0.0
351
+ self.total_sq = 0.0
352
+ self.low = np.inf
353
+ self.high = -np.inf
354
+
355
+ def add(self, frame: np.ndarray) -> None:
356
+ values = frame[np.isfinite(frame)].astype(np.float64)
357
+ if values.size:
358
+ self.count += int(values.size)
359
+ self.total += float(values.sum())
360
+ self.total_sq += float(np.square(values).sum())
361
+ self.low = min(self.low, float(values.min()))
362
+ self.high = max(self.high, float(values.max()))
363
+
364
+ def as_dict(self) -> dict[str, float | int]:
365
+ if not self.count:
366
+ return {"finite_pixels": 0}
367
+ mean = self.total / self.count
368
+ return {
369
+ "finite_pixels": self.count,
370
+ "min": round(self.low, 3),
371
+ "max": round(self.high, 3),
372
+ "mean": round(mean, 3),
373
+ "std": round(float(np.sqrt(max(self.total_sq / self.count - mean**2, 0.0))), 3),
374
+ }
375
+
376
+
377
+ def build_manifest(
378
+ h5_paths: Sequence[str | Path],
379
+ manifest_dir: str | Path,
380
+ export: bool = True,
381
+ flip_southern: bool = False,
382
+ max_missing_fraction: float = MAX_MISSING_FRACTION,
383
+ block: int = BLOCK,
384
+ distance_csv: str | Path | None = None,
385
+ ) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, object]]:
386
+ """Return (manifest, exclusions, pixel stats).
387
+
388
+ With ``export`` each kept IR1 frame is saved as ``ir1/<sample_id>.npy``
389
+ under ``manifest_dir`` and ``image_path`` points there (relative), so
390
+ ``src.data_loader`` can read it. Without ``export`` ``image_path`` is
391
+ ``<file>#<h5_index>`` for reference only. ``distance_csv`` defaults to
392
+ the committed audit table and is joined on ``sample_id``.
393
+ """
394
+ manifest_dir = Path(manifest_dir).resolve()
395
+ image_dir = manifest_dir / "ir1"
396
+ if export:
397
+ image_dir.mkdir(parents=True, exist_ok=True)
398
+ kept_parts, excluded_parts = [], []
399
+ stats = _PixelStats()
400
+ frames_with_nan = 0
401
+ for h5_path in h5_paths:
402
+ h5_path = Path(h5_path)
403
+ rows = _rows(read_info(h5_path), h5_path.name)
404
+ reasons: list[str | None] = [None] * len(rows)
405
+ nan_fractions = np.zeros(len(rows))
406
+ flipped = np.zeros(len(rows), dtype=bool)
407
+ winds = rows["wind_speed_kt"].to_numpy()
408
+ bad_wind = ~np.isfinite(winds) | (winds < 0)
409
+ for start, frames in iter_ir1(h5_path, block):
410
+ for offset, frame in enumerate(frames):
411
+ index = start + offset
412
+ reason, nan_fractions[index] = exclusion_reason(frame, max_missing_fraction)
413
+ if reason is None and bad_wind[index]:
414
+ reason = "wind missing or negative"
415
+ reasons[index] = reason
416
+ if reason is not None:
417
+ continue
418
+ stats.add(frame)
419
+ frames_with_nan += int(nan_fractions[index] > 0)
420
+ if export:
421
+ out, flipped[index] = orient(frame, rows.at[index, "hemisphere"], flip_southern)
422
+ np.save(image_dir / f"{rows.at[index, 'sample_id']}.npy", out.astype(np.float32))
423
+ rows["ir1_nan_fraction"] = np.round(nan_fractions, 5)
424
+ rows["flipped"] = flipped
425
+ rows["image_path"] = (
426
+ "ir1/" + rows["sample_id"] + ".npy"
427
+ if export
428
+ else rows["source_file"] + "#" + rows["h5_index"].astype(str)
429
+ )
430
+ drop = pd.Series([reason is not None for reason in reasons], index=rows.index)
431
+ excluded = rows.loc[drop].assign(reason=[r for r in reasons if r is not None])
432
+ kept_parts.append(rows.loc[~drop])
433
+ excluded_parts.append(excluded[EXCLUSION_COLUMNS])
434
+ manifest = pd.concat(kept_parts, ignore_index=True)
435
+ excluded = pd.concat(excluded_parts, ignore_index=True)
436
+ if "split" in manifest.columns or "source_split" in manifest.columns:
437
+ raise AssertionError("TCIR manifest must not carry split or source_split")
438
+ manifest = attach_distance_to_land(manifest, distance_csv)
439
+ manifest = require_valid(manifest)
440
+ pixel = stats.as_dict()
441
+ pixel["kept_frames_with_some_nan"] = frames_with_nan
442
+ return manifest, excluded, pixel
443
+
444
+
445
+ def storm_split_check(
446
+ frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42
447
+ ) -> dict[str, object]:
448
+ """Run the project splitter on the manifest and assert no storm leaks."""
449
+ from src.splits import assert_no_group_leakage, assign_storms
450
+
451
+ if "split" in frame.columns:
452
+ raise ValueError("manifest must not carry split")
453
+ assigned = assign_storms(frame, strategy, seed=seed)
454
+ names = ("train", "val", "test")
455
+ parts = [assigned.loc[assigned["split"] == name] for name in names]
456
+ assert_no_group_leakage(*parts)
457
+ return {
458
+ "strategy": strategy,
459
+ "rows": {name: int(len(part)) for name, part in zip(names, parts)},
460
+ "storms": {name: int(part["storm_id"].nunique()) for name, part in zip(names, parts)},
461
+ "leakage": "none",
462
+ }
463
+
464
+
465
+ def _reason_kind(reason: str) -> str:
466
+ """Strip per-frame numbers so reasons can be counted."""
467
+ if reason.startswith("ir1 NaN fraction"):
468
+ return f"ir1 NaN fraction > {MAX_MISSING_FRACTION:.2f}"
469
+ return reason.split(" (")[0]
470
+
471
+
472
+ def summarize(
473
+ frame: pd.DataFrame, excluded: pd.DataFrame, pixel: dict[str, object]
474
+ ) -> dict[str, object]:
475
+ def counts(column: str) -> dict[str, dict[str, int]]:
476
+ return {
477
+ str(key): {"rows": int(len(group)), "storms": int(group["storm_id"].nunique())}
478
+ for key, group in frame.groupby(column)
479
+ }
480
+
481
+ storm_hemispheres = frame.groupby("storm_id")["hemisphere"].nunique()
482
+ return {
483
+ "rows": int(len(frame)),
484
+ "unique_storms": int(frame["storm_id"].nunique()),
485
+ "by_basin": counts("basin"),
486
+ "by_hemisphere": counts("hemisphere"),
487
+ "by_source_file": counts("source_file"),
488
+ "storms_crossing_equator": sorted(storm_hemispheres[storm_hemispheres > 1].index.tolist()),
489
+ "basin_vs_hemisphere": {
490
+ f"{basin}/{hemi}": int(n)
491
+ for (basin, hemi), n in frame.groupby(["basin", "hemisphere"]).size().items()
492
+ },
493
+ "years": [int(frame["year"].min()), int(frame["year"].max())],
494
+ "wind_kt_min": float(frame["wind_speed_kt"].min()),
495
+ "wind_kt_max": float(frame["wind_speed_kt"].max()),
496
+ "wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
497
+ "pixel_stats_ir1": pixel,
498
+ "flipped_rows": int(frame["flipped"].sum()),
499
+ "label_source_counts": frame["label_source"].value_counts().to_dict(),
500
+ "label_source_undocumented_rows": int((~frame["label_source_documented"].astype(bool)).sum()),
501
+ "wind_averaging": sorted(frame["wind_averaging"].unique()),
502
+ "native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}),
503
+ "has_split_column": "split" in frame.columns,
504
+ "has_source_split_column": "source_split" in frame.columns,
505
+ "is_synthetic": bool(frame["is_synthetic"].any()),
506
+ "excluded": {
507
+ "count": int(len(excluded)),
508
+ "by_reason": excluded["reason"].map(_reason_kind).value_counts().to_dict(),
509
+ "by_basin": excluded["basin"].value_counts().to_dict() if len(excluded) else {},
510
+ },
511
+ }
512
+
513
+
514
+ def save_sample_png(
515
+ frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path
516
+ ) -> list[dict[str, object]]:
517
+ """One N and one S frame side by side, as stored (no flip unless opted in)."""
518
+ import matplotlib
519
+
520
+ matplotlib.use("Agg")
521
+ import matplotlib.pyplot as plt
522
+
523
+ picks = []
524
+ for hemi in ("N", "S"):
525
+ subset = frame[frame["hemisphere"] == hemi]
526
+ if len(subset):
527
+ picks.append(subset.loc[subset["wind_speed_kt"].idxmax()])
528
+ fig, axes = plt.subplots(1, len(picks), figsize=(4.2 * len(picks), 4.4), squeeze=False)
529
+ info = []
530
+ for ax, row in zip(axes[0], picks):
531
+ image = np.load(Path(manifest_dir) / row["image_path"])
532
+ shown = ax.imshow(image, cmap="gray_r")
533
+ fig.colorbar(shown, ax=ax, fraction=0.046, label="IR1 pixel value")
534
+ ax.set_title(
535
+ f"{row['storm_id']} {row['timestamp'][:13]}Z {row['basin']}/{row['hemisphere']}\n"
536
+ f"{row['wind_speed_kt']:.0f} kt (1min) | flipped={bool(row['flipped'])} | TCIR real",
537
+ fontsize=8,
538
+ )
539
+ ax.axis("off")
540
+ info.append(
541
+ {
542
+ "sample_id": row["sample_id"],
543
+ "hemisphere": row["hemisphere"],
544
+ "wind_speed_kt": float(row["wind_speed_kt"]),
545
+ "shape": list(image.shape),
546
+ "flipped": bool(row["flipped"]),
547
+ }
548
+ )
549
+ Path(out).parent.mkdir(parents=True, exist_ok=True)
550
+ fig.savefig(out, dpi=100, bbox_inches="tight")
551
+ plt.close(fig)
552
+ return info
553
+
554
+
555
+ def main() -> None:
556
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
557
+ parser.add_argument("--h5", nargs="+", required=True, help="TCIR .h5 files")
558
+ parser.add_argument("--out", default="data/tcir/manifest.csv")
559
+ parser.add_argument("--summary", default="reports/tcir_summary.json")
560
+ parser.add_argument("--sample-png", default="reports/tcir_sample.png")
561
+ parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/tcir_exclusions.csv")
562
+ parser.add_argument("--no-export", action="store_true", help="do not write ir1/*.npy")
563
+ parser.add_argument(
564
+ "--flip-southern",
565
+ action="store_true",
566
+ help="opt in: mirror Southern Hemisphere frames north-south on export (default: no flip)",
567
+ )
568
+ args = parser.parse_args()
569
+
570
+ out = Path(args.out)
571
+ out.parent.mkdir(parents=True, exist_ok=True)
572
+ frame, excluded, pixel = build_manifest(
573
+ args.h5, out.parent, export=not args.no_export, flip_southern=args.flip_southern
574
+ )
575
+ exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "tcir_exclusions.csv"
576
+ excluded.to_csv(exclusions_path, index=False)
577
+ frame.drop(columns=["imd5_class"], errors="ignore").to_csv(out, index=False)
578
+ summary = summarize(frame, excluded, pixel)
579
+ summary["exclusions_file"] = str(exclusions_path)
580
+ summary["storm_split_check"] = storm_split_check(frame)
581
+ summary["flip_southern"] = bool(args.flip_southern)
582
+ summary["manifest"] = str(out)
583
+ if not args.no_export:
584
+ summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
585
+ Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
586
+ Path(args.summary).write_text(json.dumps(summary, indent=2, default=str))
587
+ print(json.dumps(summary, indent=2, default=str))
588
+
589
+
590
+ if __name__ == "__main__":
591
+ main()
src/train.py CHANGED
The diff for this file is too large to render. See raw diff
 
src/verify_splits.py CHANGED
@@ -1,220 +1,220 @@
1
- """CLI that runs a 6-point data-leakage audit on the configured splits.
2
-
3
- The six checks are:
4
-
5
- 1. storm_wise splits keep storms whole and disjoint.
6
- 2. chronological splits keep storms whole and disjoint.
7
- 3. holdout_basin splits keep storms whole and disjoint.
8
- 4. Random / frame / shuffle strategies raise ``LeakageError``.
9
- 5. No forbidden feature name leaks into the model matrix.
10
- 6. Cross-split previous-frame links are nulled.
11
-
12
- Usage::
13
-
14
- python -m src.verify_splits --config config/config_smoke.yaml
15
-
16
- The exit code is 0 when all six checks pass. This module does not import
17
- torch and does not download imagery.
18
- """
19
-
20
- from __future__ import annotations
21
-
22
- import argparse
23
- import sys
24
- from pathlib import Path
25
-
26
- import numpy as np
27
- import pandas as pd
28
-
29
- from src.config import load_config
30
- from src.make_smoke_data import write_smoke
31
- from src.schema import require_valid
32
- from src.splits import (
33
- LeakageError,
34
- add_previous_frame_id,
35
- assert_no_forbidden_inputs,
36
- assign_storms,
37
- null_cross_split_links,
38
- storm_ids_by_split,
39
- )
40
-
41
-
42
- def _build_smoke_frame(config: dict) -> pd.DataFrame:
43
- """Return a validated manifest from the smoke config's data path."""
44
- manifest_path = Path(config["paths"]["manifest"])
45
- if not manifest_path.exists():
46
- # Generate smoke data on the fly so the audit is self-contained.
47
- out_dir = manifest_path.parent
48
- write_smoke(out_dir, seed=config.get("project", {}).get("seed", 7))
49
- frame = pd.read_csv(manifest_path)
50
- return require_valid(frame)
51
-
52
-
53
- def _assert_disjoint(assigned: pd.DataFrame) -> dict[str, frozenset[str]]:
54
- """Verify that storm-id sets across splits are disjoint."""
55
- groups = storm_ids_by_split(assigned)
56
- assert groups["train"], "train is empty"
57
- assert groups["val"], "val is empty"
58
- assert groups["test"], "test is empty"
59
- assert groups["train"].isdisjoint(groups["val"]), "train ∩ val is non-empty"
60
- assert groups["train"].isdisjoint(groups["test"]), "train ∩ test is non-empty"
61
- assert groups["val"].isdisjoint(groups["test"]), "val ∩ test is non-empty"
62
- # Every storm is in exactly one split.
63
- counts = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()
64
- assert int(counts.max()) == 1, "a storm appears in more than one split"
65
- return groups
66
-
67
-
68
- def _run_strategy(frame: pd.DataFrame, strategy: str, config: dict) -> None:
69
- """Check that a strategy assigns splits correctly."""
70
- split_cfg = dict(config.get("split", {}))
71
- kwargs: dict = {
72
- "test_fraction": float(split_cfg.get("test_fraction", 0.2)),
73
- "val_fraction": float(split_cfg.get("val_fraction", 0.2)),
74
- "seed": int(split_cfg.get("seed", 42)),
75
- }
76
- if strategy == "chronological":
77
- holdout_years = [int(y) for y in (split_cfg.get("holdout_years") or [])]
78
- if not holdout_years:
79
- # Use at least one year for the audit.
80
- if "year" in frame.columns:
81
- years = sorted(frame["year"].dropna().unique())
82
- holdout_years = [int(years[-1])] if years else [2021]
83
- else:
84
- holdout_years = [2021]
85
- kwargs["holdout_years"] = holdout_years
86
- if strategy == "holdout_basin":
87
- holdout_basin = split_cfg.get("holdout_basin") or None
88
- if not holdout_basin:
89
- if "basin" in frame.columns:
90
- basins = sorted(frame["basin"].dropna().unique())
91
- holdout_basin = basins[0] if basins else "NIO"
92
- else:
93
- holdout_basin = "NIO"
94
- kwargs["holdout_basin"] = holdout_basin
95
-
96
- assigned = assign_storms(frame, strategy, **kwargs)
97
- # Deterministic: same call same result.
98
- again = assign_storms(frame, strategy, **kwargs)
99
- assert assigned["split"].tolist() == again["split"].tolist(), (
100
- f"{strategy}: non-deterministic assignment"
101
- )
102
- _assert_disjoint(assigned)
103
-
104
-
105
- def audit(config: dict) -> list[str]:
106
- """Run the 6-point leakage audit. Returns a list of failure messages."""
107
- frame = _build_smoke_frame(config)
108
- failures: list[str] = []
109
-
110
- # --- Check 1: storm_wise ---
111
- try:
112
- _run_strategy(frame, "storm_wise", config)
113
- print(" [PASS] 1. storm_wise splits are disjoint")
114
- except Exception as exc:
115
- failures.append(f"1. storm_wise: {exc}")
116
- print(f" [FAIL] 1. storm_wise: {exc}")
117
-
118
- # --- Check 2: chronological ---
119
- try:
120
- _run_strategy(frame, "chronological", config)
121
- print(" [PASS] 2. chronological splits are disjoint")
122
- except Exception as exc:
123
- failures.append(f"2. chronological: {exc}")
124
- print(f" [FAIL] 2. chronological: {exc}")
125
-
126
- # --- Check 3: holdout_basin ---
127
- try:
128
- _run_strategy(frame, "holdout_basin", config)
129
- print(" [PASS] 3. holdout_basin splits are disjoint")
130
- except Exception as exc:
131
- failures.append(f"3. holdout_basin: {exc}")
132
- print(f" [FAIL] 3. holdout_basin: {exc}")
133
-
134
- # --- Check 4: random splits raise LeakageError ---
135
- random_ok = True
136
- for name in ("random", "frame", "shuffle", "random_frame"):
137
- try:
138
- assign_storms(frame, name)
139
- failures.append(f"4. {name} did not raise LeakageError")
140
- random_ok = False
141
- except LeakageError:
142
- pass
143
- except Exception as exc:
144
- failures.append(f"4. {name} raised unexpected {type(exc).__name__}: {exc}")
145
- random_ok = False
146
- if random_ok:
147
- print(" [PASS] 4. Random splits raise LeakageError")
148
- else:
149
- print(" [FAIL] 4. Random splits did not all raise LeakageError")
150
-
151
- # --- Check 5: no forbidden features in model matrix ---
152
- try:
153
- from src.features import FeatureSpec
154
-
155
- feature_names = list(FeatureSpec().feature_names())
156
- assert_no_forbidden_inputs(feature_names, "model features")
157
- print(" [PASS] 5. No forbidden features in default feature set")
158
- except LeakageError as exc:
159
- failures.append(f"5. forbidden features: {exc}")
160
- print(f" [FAIL] 5. {exc}")
161
- except Exception as exc:
162
- failures.append(f"5. feature check error: {exc}")
163
- print(f" [FAIL] 5. {exc}")
164
-
165
- # --- Check 6: cross-split links are nulled ---
166
- try:
167
- split_cfg = dict(config.get("split", {}))
168
- assigned = assign_storms(
169
- frame,
170
- "storm_wise",
171
- test_fraction=float(split_cfg.get("test_fraction", 0.2)),
172
- val_fraction=float(split_cfg.get("val_fraction", 0.2)),
173
- seed=int(split_cfg.get("seed", 42)),
174
- )
175
- linked = add_previous_frame_id(assigned)
176
- linked["split"] = assigned.loc[linked.index, "split"]
177
- # Artificially set a cross-split link.
178
- train_ids = linked.loc[linked["split"] == "train", "sample_id"].tolist()
179
- test_ids = linked.loc[linked["split"] == "test", "sample_id"].tolist()
180
- if train_ids and test_ids:
181
- dirty = linked.copy()
182
- dirty.loc[dirty["sample_id"] == train_ids[0], "prev_sample_id"] = test_ids[0]
183
- cleaned, dropped = null_cross_split_links(dirty)
184
- assert dropped >= 1, "cross-split link was not removed"
185
- assert pd.isna(
186
- cleaned.loc[cleaned["sample_id"] == train_ids[0], "prev_sample_id"]
187
- ).all(), "cross-split link survived cleaning"
188
- print(" [PASS] 6. Cross-split previous-frame links are nulled")
189
- except Exception as exc:
190
- failures.append(f"6. cross-split links: {exc}")
191
- print(f" [FAIL] 6. {exc}")
192
-
193
- return failures
194
-
195
-
196
- def main() -> None:
197
- parser = argparse.ArgumentParser(
198
- description="Run a 6-point data-leakage audit on the split strategy."
199
- )
200
- parser.add_argument(
201
- "--config",
202
- type=str,
203
- default="config/config_smoke.yaml",
204
- help="Path to YAML config file.",
205
- )
206
- args = parser.parse_args()
207
- config = load_config(args.config)
208
- print(f"Running 6-point leakage audit with {args.config}")
209
- failures = audit(config)
210
- if failures:
211
- print(f"\n{len(failures)} check(s) failed:")
212
- for msg in failures:
213
- print(f" - {msg}")
214
- sys.exit(1)
215
- else:
216
- print("\nAll 6 checks passed.")
217
-
218
-
219
- if __name__ == "__main__":
220
- main()
 
1
+ """CLI that runs a 6-point data-leakage audit on the configured splits.
2
+
3
+ The six checks are:
4
+
5
+ 1. storm_wise splits keep storms whole and disjoint.
6
+ 2. chronological splits keep storms whole and disjoint.
7
+ 3. holdout_basin splits keep storms whole and disjoint.
8
+ 4. Random / frame / shuffle strategies raise ``LeakageError``.
9
+ 5. No forbidden feature name leaks into the model matrix.
10
+ 6. Cross-split previous-frame links are nulled.
11
+
12
+ Usage::
13
+
14
+ python -m src.verify_splits --config config/config_smoke.yaml
15
+
16
+ The exit code is 0 when all six checks pass. This module does not import
17
+ torch and does not download imagery.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from src.config import load_config
30
+ from src.make_smoke_data import write_smoke
31
+ from src.schema import require_valid
32
+ from src.splits import (
33
+ LeakageError,
34
+ add_previous_frame_id,
35
+ assert_no_forbidden_inputs,
36
+ assign_storms,
37
+ null_cross_split_links,
38
+ storm_ids_by_split,
39
+ )
40
+
41
+
42
+ def _build_smoke_frame(config: dict) -> pd.DataFrame:
43
+ """Return a validated manifest from the smoke config's data path."""
44
+ manifest_path = Path(config["paths"]["manifest"])
45
+ if not manifest_path.exists():
46
+ # Generate smoke data on the fly so the audit is self-contained.
47
+ out_dir = manifest_path.parent
48
+ write_smoke(out_dir, seed=config.get("project", {}).get("seed", 7))
49
+ frame = pd.read_csv(manifest_path)
50
+ return require_valid(frame)
51
+
52
+
53
+ def _assert_disjoint(assigned: pd.DataFrame) -> dict[str, frozenset[str]]:
54
+ """Verify that storm-id sets across splits are disjoint."""
55
+ groups = storm_ids_by_split(assigned)
56
+ assert groups["train"], "train is empty"
57
+ assert groups["val"], "val is empty"
58
+ assert groups["test"], "test is empty"
59
+ assert groups["train"].isdisjoint(groups["val"]), "train ∩ val is non-empty"
60
+ assert groups["train"].isdisjoint(groups["test"]), "train ∩ test is non-empty"
61
+ assert groups["val"].isdisjoint(groups["test"]), "val ∩ test is non-empty"
62
+ # Every storm is in exactly one split.
63
+ counts = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()
64
+ assert int(counts.max()) == 1, "a storm appears in more than one split"
65
+ return groups
66
+
67
+
68
+ def _run_strategy(frame: pd.DataFrame, strategy: str, config: dict) -> None:
69
+ """Check that a strategy assigns splits correctly."""
70
+ split_cfg = dict(config.get("split", {}))
71
+ kwargs: dict = {
72
+ "test_fraction": float(split_cfg.get("test_fraction", 0.2)),
73
+ "val_fraction": float(split_cfg.get("val_fraction", 0.2)),
74
+ "seed": int(split_cfg.get("seed", 42)),
75
+ }
76
+ if strategy == "chronological":
77
+ holdout_years = [int(y) for y in (split_cfg.get("holdout_years") or [])]
78
+ if not holdout_years:
79
+ # Use at least one year for the audit.
80
+ if "year" in frame.columns:
81
+ years = sorted(frame["year"].dropna().unique())
82
+ holdout_years = [int(years[-1])] if years else [2021]
83
+ else:
84
+ holdout_years = [2021]
85
+ kwargs["holdout_years"] = holdout_years
86
+ if strategy == "holdout_basin":
87
+ holdout_basin = split_cfg.get("holdout_basin") or None
88
+ if not holdout_basin:
89
+ if "basin" in frame.columns:
90
+ basins = sorted(frame["basin"].dropna().unique())
91
+ holdout_basin = basins[0] if basins else "NIO"
92
+ else:
93
+ holdout_basin = "NIO"
94
+ kwargs["holdout_basin"] = holdout_basin
95
+
96
+ assigned = assign_storms(frame, strategy, **kwargs)
97
+ # Deterministic: same call same result.
98
+ again = assign_storms(frame, strategy, **kwargs)
99
+ assert assigned["split"].tolist() == again["split"].tolist(), (
100
+ f"{strategy}: non-deterministic assignment"
101
+ )
102
+ _assert_disjoint(assigned)
103
+
104
+
105
+ def audit(config: dict) -> list[str]:
106
+ """Run the 6-point leakage audit. Returns a list of failure messages."""
107
+ frame = _build_smoke_frame(config)
108
+ failures: list[str] = []
109
+
110
+ # --- Check 1: storm_wise ---
111
+ try:
112
+ _run_strategy(frame, "storm_wise", config)
113
+ print(" [PASS] 1. storm_wise splits are disjoint")
114
+ except Exception as exc:
115
+ failures.append(f"1. storm_wise: {exc}")
116
+ print(f" [FAIL] 1. storm_wise: {exc}")
117
+
118
+ # --- Check 2: chronological ---
119
+ try:
120
+ _run_strategy(frame, "chronological", config)
121
+ print(" [PASS] 2. chronological splits are disjoint")
122
+ except Exception as exc:
123
+ failures.append(f"2. chronological: {exc}")
124
+ print(f" [FAIL] 2. chronological: {exc}")
125
+
126
+ # --- Check 3: holdout_basin ---
127
+ try:
128
+ _run_strategy(frame, "holdout_basin", config)
129
+ print(" [PASS] 3. holdout_basin splits are disjoint")
130
+ except Exception as exc:
131
+ failures.append(f"3. holdout_basin: {exc}")
132
+ print(f" [FAIL] 3. holdout_basin: {exc}")
133
+
134
+ # --- Check 4: random splits raise LeakageError ---
135
+ random_ok = True
136
+ for name in ("random", "frame", "shuffle", "random_frame"):
137
+ try:
138
+ assign_storms(frame, name)
139
+ failures.append(f"4. {name} did not raise LeakageError")
140
+ random_ok = False
141
+ except LeakageError:
142
+ pass
143
+ except Exception as exc:
144
+ failures.append(f"4. {name} raised unexpected {type(exc).__name__}: {exc}")
145
+ random_ok = False
146
+ if random_ok:
147
+ print(" [PASS] 4. Random splits raise LeakageError")
148
+ else:
149
+ print(" [FAIL] 4. Random splits did not all raise LeakageError")
150
+
151
+ # --- Check 5: no forbidden features in model matrix ---
152
+ try:
153
+ from src.features import FeatureSpec
154
+
155
+ feature_names = list(FeatureSpec().feature_names())
156
+ assert_no_forbidden_inputs(feature_names, "model features")
157
+ print(" [PASS] 5. No forbidden features in default feature set")
158
+ except LeakageError as exc:
159
+ failures.append(f"5. forbidden features: {exc}")
160
+ print(f" [FAIL] 5. {exc}")
161
+ except Exception as exc:
162
+ failures.append(f"5. feature check error: {exc}")
163
+ print(f" [FAIL] 5. {exc}")
164
+
165
+ # --- Check 6: cross-split links are nulled ---
166
+ try:
167
+ split_cfg = dict(config.get("split", {}))
168
+ assigned = assign_storms(
169
+ frame,
170
+ "storm_wise",
171
+ test_fraction=float(split_cfg.get("test_fraction", 0.2)),
172
+ val_fraction=float(split_cfg.get("val_fraction", 0.2)),
173
+ seed=int(split_cfg.get("seed", 42)),
174
+ )
175
+ linked = add_previous_frame_id(assigned)
176
+ linked["split"] = assigned.loc[linked.index, "split"]
177
+ # Artificially set a cross-split link.
178
+ train_ids = linked.loc[linked["split"] == "train", "sample_id"].tolist()
179
+ test_ids = linked.loc[linked["split"] == "test", "sample_id"].tolist()
180
+ if train_ids and test_ids:
181
+ dirty = linked.copy()
182
+ dirty.loc[dirty["sample_id"] == train_ids[0], "prev_sample_id"] = test_ids[0]
183
+ cleaned, dropped = null_cross_split_links(dirty)
184
+ assert dropped >= 1, "cross-split link was not removed"
185
+ assert pd.isna(
186
+ cleaned.loc[cleaned["sample_id"] == train_ids[0], "prev_sample_id"]
187
+ ).all(), "cross-split link survived cleaning"
188
+ print(" [PASS] 6. Cross-split previous-frame links are nulled")
189
+ except Exception as exc:
190
+ failures.append(f"6. cross-split links: {exc}")
191
+ print(f" [FAIL] 6. {exc}")
192
+
193
+ return failures
194
+
195
+
196
+ def main() -> None:
197
+ parser = argparse.ArgumentParser(
198
+ description="Run a 6-point data-leakage audit on the split strategy."
199
+ )
200
+ parser.add_argument(
201
+ "--config",
202
+ type=str,
203
+ default="config/config_smoke.yaml",
204
+ help="Path to YAML config file.",
205
+ )
206
+ args = parser.parse_args()
207
+ config = load_config(args.config)
208
+ print(f"Running 6-point leakage audit with {args.config}")
209
+ failures = audit(config)
210
+ if failures:
211
+ print(f"\n{len(failures)} check(s) failed:")
212
+ for msg in failures:
213
+ print(f" - {msg}")
214
+ sys.exit(1)
215
+ else:
216
+ print("\nAll 6 checks passed.")
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()