fix: upload synced space/bundle to Space root
Browse filesFiles changed (33)
- config/config.yaml+233-233
- config/config_incyde.yaml+201-201
- config/config_incyde_224.yamlAdded+264
- config/config_incyde_safe.yamlAdded+264
- config/config_nasa_safe.yamlAdded+264
- config/config_smoke.yaml+196-196
- config/incyde_cpu.yaml+41-41
- src/__init__.py+6-6
- src/baselines.py
- src/cache_frames.py+72-72
- src/calibration.py+345-345
- src/config.py+68-68
- src/data_loader.py+102-102
- src/device.py+390-390
- src/evaluate.py
- src/features.py+899-899
- src/incyde.py+778-778
- src/inference.py
- src/labels.py+216-216
- src/make_smoke_data.py+153-153
- src/metrics.py+174-174
- src/model.py+262-262
- src/model_access.py+26-26
- src/nasa_tc.py+360-360
- src/plots.py+109-109
- src/preprocessing.py+314-314
- src/reproducibility.py+46-46
- src/schema.py+342-342
- src/sequences.py+171-171
- src/splits.py+318-318
- src/tcir.py+591-591
- src/train.py
- src/verify_splits.py+220-220
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233project:name: cyclone-intensity-estimationseed: 42honesty: >No trained weights are shipped. Smoke images are synthetic.This is not an operational forecast or warning system.Best-track labels are noisy, and agreement with them is not ground truth.No survey or smoke number is a result of this project.paths:manifest: data/manifest.csvartifacts: artifactsreports: reportscheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cache# Extracted Cropped_cyclone_data directory. This file does not download it.incyde_root: data/incyde# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: nasa# null or native keeps each chip's height and width. NASA TorchGeo chips# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer# resizes the deep model to that square. Classical features stay native.image_size: nativechannels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# NASA TropicalCyclone labels are HURDAT2 maximum sustained wind, a# 1-minute average. Do not mix this with 10-minute winds.wind_averaging: 1min# Project bins for error tables. Not an IMD warning, and not the IMD# 3-minute scale. IMD uses 3-minute winds. These edges are this project's# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,# and 91 kt and above ESCS_SUCS.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]# International knot. Used only to display a second unit.kt_to_kmh: 1.852# letterbox pads to a square before the checkpoint resize. stretch is the old path.resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.labels:# Training target for TCIR, NASA, and INCYDE. Raw knots stay on wind_speed_kt.label_column: wind_kt_3min# Derived at-sea factor, not a WMO constant. See docs/TRAINING.md.wind_1min_to_3min: 0.93# flag: still multiply near-land 1-minute rows and set conversion_exposure_flag.# raw: leave those rows at the 1-minute label.near_land_policy: flag# The factor is for open water farther offshore than this, in kilometres.open_water_km: 20incyde:# null uses incyde/audit/storm_split.csv and exclusions.csv.manifest_csv: nullstorm_split_csv: nullexclusions_csv: nullarchive: nulldrop_qc_flags: []n_folds: 5cv_val_fold: 0cv_seed: 42# Optional storm_id,fold file. When set, it replaces the seeded folds.cv_folds_csv: null# null uses incyde/audit/frame_flags.csv. Unknown cells stay unknown.frame_flags_csv: null# When true, also report validation metrics on explicit on_fix frames.# The overall validation metrics stay the full validation split.on_fix_only_eval: falsesplit:strategy: storm_wisetest_fraction: 0.2val_fraction: 0.2holdout_years: []holdout_basin: nullseed: 42model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20# Used when model.name is convlstm. The sequence length stays 4.n_frames: 4hidden: 16train:batch_size: 16epochs: 20lr: 0.001weight_decay: 0.0001patience: 5# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.device: automax_steps: nullgrad_accum_steps: 1num_workers: 2# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.device_parity_tol: 0.05class_loss_weight: 0.1# Applied only when r34_nmi and rmw_nmi exist on the train split.size_loss_weight: 0.1# none leaves Smooth L1 unweighted. The other modes reweight the five# project bins on the 3-minute target, using train originals only.loss_weighting: none# Draw train rows with inverse-frequency weights so each occurring bin# has the same expected count. Off by default.balanced_sampling: falsepredict:# Review flag, not a warning threshold.advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]# Image mean must sit within this many training standard deviations.training_mean_width: 3# Same storm, resized, should stay inside this knot span.scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75# Approximate public reference points, not Survey of India boundaries.coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binfeatures:# Name distributional stats tb_* only when a calibration table was applied.calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 80seed: 42baselines:n_splits: 3seed: 42# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 5svr_c: 1.0svc_c: 1.0rf_estimators: 200rf_max_depth: 6xgb_estimators: 80xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 1000# Grouped CV. train folds the training storms only. train_val folds# train and val together and never includes test. The group column stays# intact inside a fold. cv_collapse_rare remaps a stratify label that# sits in fewer groups than n_splits, for fold assignment only.cv_pool: traincv_group_column: storm_idcv_collapse_rare: falsecv_assign: stratified123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233project:name: cyclone-intensity-estimationseed: 42honesty: >No trained weights are shipped. Smoke images are synthetic.This is not an operational forecast or warning system.Best-track labels are noisy, and agreement with them is not ground truth.No survey or smoke number is a result of this project.paths:manifest: data/manifest.csvartifacts: artifactsreports: reportscheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cache# Extracted Cropped_cyclone_data directory. This file does not download it.incyde_root: data/incyde# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: nasa# null or native keeps each chip's height and width. NASA TorchGeo chips# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer# resizes the deep model to that square. Classical features stay native.image_size: nativechannels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# NASA TropicalCyclone labels are HURDAT2 maximum sustained wind, a# 1-minute average. Do not mix this with 10-minute winds.wind_averaging: 1min# Project bins for error tables. Not an IMD warning, and not the IMD# 3-minute scale. IMD uses 3-minute winds. These edges are this project's# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,# and 91 kt and above ESCS_SUCS.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]# International knot. Used only to display a second unit.kt_to_kmh: 1.852# letterbox pads to a square before the checkpoint resize. stretch is the old path.resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.labels:# Training target for TCIR, NASA, and INCYDE. Raw knots stay on wind_speed_kt.label_column: wind_kt_3min# Derived at-sea factor, not a WMO constant. See docs/TRAINING.md.wind_1min_to_3min: 0.93# flag: still multiply near-land 1-minute rows and set conversion_exposure_flag.# raw: leave those rows at the 1-minute label.near_land_policy: flag# The factor is for open water farther offshore than this, in kilometres.open_water_km: 20incyde:# null uses incyde/audit/storm_split.csv and exclusions.csv.manifest_csv: nullstorm_split_csv: nullexclusions_csv: nullarchive: nulldrop_qc_flags: []n_folds: 5cv_val_fold: 0cv_seed: 42# Optional storm_id,fold file. When set, it replaces the seeded folds.cv_folds_csv: null# null uses incyde/audit/frame_flags.csv. Unknown cells stay unknown.frame_flags_csv: null# When true, also report validation metrics on explicit on_fix frames.# The overall validation metrics stay the full validation split.on_fix_only_eval: falsesplit:strategy: storm_wisetest_fraction: 0.2val_fraction: 0.2holdout_years: []holdout_basin: nullseed: 42model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20# Used when model.name is convlstm. The sequence length stays 4.n_frames: 4hidden: 16train:batch_size: 16epochs: 20lr: 0.001weight_decay: 0.0001patience: 5# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.device: automax_steps: nullgrad_accum_steps: 1num_workers: 2# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.device_parity_tol: 0.05class_loss_weight: 0.1# Applied only when r34_nmi and rmw_nmi exist on the train split.size_loss_weight: 0.1# none leaves Smooth L1 unweighted. The other modes reweight the five# project bins on the 3-minute target, using train originals only.loss_weighting: none# Draw train rows with inverse-frequency weights so each occurring bin# has the same expected count. Off by default.balanced_sampling: falsepredict:# Review flag, not a warning threshold.advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]# Image mean must sit within this many training standard deviations.training_mean_width: 3# Same storm, resized, should stay inside this knot span.scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75# Approximate public reference points, not Survey of India boundaries.coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binfeatures:# Name distributional stats tb_* only when a calibration table was applied.calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 80seed: 42baselines:n_splits: 3seed: 42# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 5svr_c: 1.0svc_c: 1.0rf_estimators: 200rf_max_depth: 6xgb_estimators: 80xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 1000# Grouped CV. train folds the training storms only. train_val folds# train and val together and never includes test. The group column stays# intact inside a fold. cv_collapse_rare remaps a stratify label that# sits in fewer groups than n_splits, for fold assignment only.cv_pool: traincv_group_column: storm_idcv_collapse_rare: falsecv_assign: stratified
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201project:name: cyclone-intensity-estimationseed: 42honesty: >No trained weights are shipped. Smoke images are synthetic.This is not an operational forecast or warning system.Best-track labels are noisy, and agreement with them is not ground truth.No survey or smoke number is a result of this project.paths:manifest: data/incyde/manifest.csvartifacts: artifactsreports: reportscheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cache# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: incyde# null or native keeps each chip's height and width. NASA TorchGeo chips# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer# resizes the deep model to that square. Classical features stay native.image_size: nativechannels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# Raw IMD 3-minute sustained winds from the INCYDE labels CSV.# Do not convert them to 1-minute. wind_averaging_s is 180 on every row.wind_averaging: 3-min# Project bins for error tables. Not an IMD warning, and not the IMD# 3-minute scale. IMD uses 3-minute winds. These edges are this project's# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,# and 91 kt and above ESCS_SUCS.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]# International knot. Used only to display a second unit.kt_to_kmh: 1.852# letterbox pads to a square before the checkpoint resize. stretch is the old path.resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.split:strategy: recordedtest_fraction: 0.2val_fraction: 0.2holdout_years: []holdout_basin: nullseed: 42model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20# Used when model.name is convlstm. The sequence length stays 4.n_frames: 4hidden: 16train:batch_size: 16epochs: 20lr: 0.001weight_decay: 0.0001patience: 5# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.device: automax_steps: nullgrad_accum_steps: 1num_workers: 2# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.device_parity_tol: 0.05class_loss_weight: 0.1# Applied only when r34_nmi and rmw_nmi exist on the train split.size_loss_weight: 0.1predict:# Review flag, not a warning threshold.advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]# Image mean must sit within this many training standard deviations.training_mean_width: 3# Same storm, resized, should stay inside this knot span.scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75# Approximate public reference points, not Survey of India boundaries.coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binfeatures:# Name distributional stats tb_* only when a calibration table was applied.calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 80seed: 42baselines:# Five folds, seed 42, groups dealt round-robin. The file# results/incyde_baselines/cv_folds.csv is storm_id,fold for train+val# only, and each cooccurrence_group stays in one fold.n_splits: 5seed: 42# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 5svr_c: 1.0svc_c: 1.0rf_estimators: 200rf_max_depth: 6xgb_estimators: 80xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 1000# Grouped CV. train folds the training storms only. train_val folds# train and val together and never includes test. The group column stays# intact inside a fold. cv_collapse_rare remaps a stratify label that# sits in fewer groups than n_splits, for fold assignment only.cv_pool: train_valcv_group_column: cv_groupcv_collapse_rare: falsecv_assign: round_robin123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201project:name: cyclone-intensity-estimationseed: 42honesty: >No trained weights are shipped. Smoke images are synthetic.This is not an operational forecast or warning system.Best-track labels are noisy, and agreement with them is not ground truth.No survey or smoke number is a result of this project.paths:manifest: data/incyde/manifest.csvartifacts: artifactsreports: reportscheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cache# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: incyde# null or native keeps each chip's height and width. NASA TorchGeo chips# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer# resizes the deep model to that square. Classical features stay native.image_size: nativechannels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# Raw IMD 3-minute sustained winds from the INCYDE labels CSV.# Do not convert them to 1-minute. wind_averaging_s is 180 on every row.wind_averaging: 3-min# Project bins for error tables. Not an IMD warning, and not the IMD# 3-minute scale. IMD uses 3-minute winds. These edges are this project's# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,# and 91 kt and above ESCS_SUCS.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]# International knot. Used only to display a second unit.kt_to_kmh: 1.852# letterbox pads to a square before the checkpoint resize. stretch is the old path.resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.split:strategy: recordedtest_fraction: 0.2val_fraction: 0.2holdout_years: []holdout_basin: nullseed: 42model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20# Used when model.name is convlstm. The sequence length stays 4.n_frames: 4hidden: 16train:batch_size: 16epochs: 20lr: 0.001weight_decay: 0.0001patience: 5# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.device: automax_steps: nullgrad_accum_steps: 1num_workers: 2# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.device_parity_tol: 0.05class_loss_weight: 0.1# Applied only when r34_nmi and rmw_nmi exist on the train split.size_loss_weight: 0.1predict:# Review flag, not a warning threshold.advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]# Image mean must sit within this many training standard deviations.training_mean_width: 3# Same storm, resized, should stay inside this knot span.scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75# Approximate public reference points, not Survey of India boundaries.coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binfeatures:# Name distributional stats tb_* only when a calibration table was applied.calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 80seed: 42baselines:# Five folds, seed 42, groups dealt round-robin. The file# results/incyde_baselines/cv_folds.csv is storm_id,fold for train+val# only, and each cooccurrence_group stays in one fold.n_splits: 5seed: 42# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 5svr_c: 1.0svc_c: 1.0rf_estimators: 200rf_max_depth: 6xgb_estimators: 80xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 1000# Grouped CV. train folds the training storms only. train_val folds# train and val together and never includes test. The group column stays# intact inside a fold. cv_collapse_rare remaps a stratify label that# sits in fewer groups than n_splits, for fold assignment only.cv_pool: train_valcv_group_column: cv_groupcv_collapse_rare: falsecv_assign: round_robin
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264baselines: bootstrap_resamples: 1000 classification_models: - mean - persistence - logreg - knn - rf - xgboost - svc cv_assign: stratified cv_collapse_rare: false cv_group_column: storm_id cv_pool: train knn_neighbors: 5 max_iter: 1000 n_splits: 3 per_storm_breakdown: true regression_models: - mean - persistence - ridge - lr - knn - rf - xgboost - svr rf_estimators: 200 rf_max_depth: 6 ridge_alpha: 1.0 seed: 42 svc_c: 1.0 svr_c: 1.0 use_smote: true xgb_estimators: 80 xgb_learning_rate: 0.1 xgb_max_depth: 3data: channels: 1 dataset: nasa grouping_note: 'Intensity category is this project''s grouping on the configured knot bins. It is not an official IMD class.
' image_size: 224 imd5_edges_kt: - 17 - 34 - 48 - 64 - 91 imd5_names: - D_DD - CS - SCS - VSCS - ESCS_SUCS kt_to_kmh: 1.852 max_missing_fraction: 0.3 normalize: zscore pad: median plausible_wind_kt: - 0 - 200 resize: letterbox wind_averaging: 1minfeatures: calibrated: false cdo_outer_fraction: 0.35 cold_thresholds: - 200 - 210 - 220 - 230 - 240 dav_annulus_width_fraction: 0.08 dav_radii_fractions: - 0.15 - 0.3 - 0.45 - 0.6 eye_contrast_min: 2.0 eye_radius_fraction: 0.12 glcm_distance: 1 glcm_levels: 16 radial_bins: 8 selection: correlation_threshold: 0.95 max_features: 25 method: correlation_rf n_estimators: 80 seed: 42forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binincyde: archive: null cv_folds_csv: null cv_seed: 42 cv_val_fold: 0 drop_qc_flags: [] exclusions_csv: null frame_flags_csv: null manifest_csv: null n_folds: 5 on_fix_only_eval: false storm_split_csv: nulllabels: label_column: wind_kt_3min near_land_policy: flag open_water_km: 20 wind_1min_to_3min: 0.93model: dropout: 0.3 hidden: 16 mc_samples: 20 n_frames: 4 name: simple_cnn pretrained: falsepaths: artifacts: artifacts checkpoint_name: checkpoint.pt frame_cache: artifacts/frame_cache hf_model_repo: null incyde_root: data/incyde manifest: data/manifest.csv nasa_root: data/nasa_tc reports: reports run_id: null run_records: artifacts/run_records runs: artifacts/runs tcir_files: [] tcir_manifest_dir: data/tcirpredict: advisory_jump_kt: 20 coast: - lat: 21.64 lon: 69.61 name: Gujarat - lat: 18.94 lon: 72.84 name: Maharashtra - lat: 15.49 lon: 73.83 name: Goa - lat: 12.91 lon: 74.86 name: Karnataka - lat: 9.93 lon: 76.26 name: Kerala - lat: 13.08 lon: 80.27 name: Tamil Nadu - lat: 11.94 lon: 79.83 name: Puducherry - lat: 17.69 lon: 83.22 name: Andhra Pradesh - lat: 19.81 lon: 85.83 name: Odisha - lat: 21.63 lon: 87.51 name: West Bengal - lat: 11.67 lon: 92.74 name: Andaman and Nicobar Islands - lat: 10.57 lon: 72.64 name: Lakshadweep - lat: 20.42 lon: 72.83 name: Dadra and Nagar Haveli and Daman and Diu coast_reference_note: 'Reference points are approximate coastal coordinates, not a shoreline survey and not a landfall forecast.
' coastal_count: 3 coastal_heading: nearest Indian coastal states to the current position confidence: coverage_label: real-data coverage recorded gate_weight: 0.4 interval_scale_kt: 30 interval_weight: 0.2 mc_std_scale_kt: 15 mc_weight: 0.4 uncalibrated_label: uncalibrated earth_radius_km: 6371.0 gate: cold_radius_fraction: 0.45 cold_tail_fraction: 0.25 cold_value: auto concentration_reference: 0.75 eye_radius_fraction: 0.12 eyewall_outer_fraction: 0.32 grayscale_tolerance: 0.08 max_dropout_std_kt: 50 min_cold_concentration: 0.36 min_std: 0.02 min_symmetry: 0.45 min_wall_contrast: 0.45 outer_inner_fraction: 0.55 outer_outer_fraction: 0.95 radial_bins: 8 refusal: not a tropical cyclone IR image held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out storm check. There is no model output. This is not a forecast.
' landfall_note: not a landfall forecast latitude_keys: - latitude - lat longitude_keys: - longitude - lon no_run_record_refusal: 'This checkpoint has no matching real-data run record. There is no model output. This is not a forecast.
' no_run_record_review: no matching real-data run record operational_disclaimer: This is not an operational forecast. scale_tolerance_kt: 1.0 sklearn_features: - symmetry - cold_concentration - wall_contrast - eye_contrast training_mean_width: 3project: honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not an operational forecast or warning system. Best-track labels are noisy, and agreement with them is not ground truth. No survey or smoke number is a result of this project.
' name: cyclone-intensity-estimation seed: 42split: holdout_basin: null holdout_years: [] seed: 42 strategy: storm_wise test_fraction: 0.2 val_fraction: 0.2train: balanced_sampling: false batch_size: 16 class_loss_weight: 0.1 device: auto device_parity_tol: 0.05 epochs: 20 grad_accum_steps: 1 loss_weighting: none lr: 0.001 max_steps: null num_workers: 2 patience: 5 size_loss_weight: 0.1 weight_decay: 0.0001123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264baselines: bootstrap_resamples: 1000 classification_models: - mean - persistence - logreg - knn - rf - xgboost - svc cv_assign: stratified cv_collapse_rare: false cv_group_column: storm_id cv_pool: train knn_neighbors: 5 max_iter: 1000 n_splits: 3 per_storm_breakdown: true regression_models: - mean - persistence - ridge - lr - knn - rf - xgboost - svr rf_estimators: 200 rf_max_depth: 6 ridge_alpha: 1.0 seed: 42 svc_c: 1.0 svr_c: 1.0 use_smote: true xgb_estimators: 80 xgb_learning_rate: 0.1 xgb_max_depth: 3data: channels: 1 dataset: nasa grouping_note: 'Intensity category is this project''s grouping on the configured knot bins. It is not an official IMD class.
' image_size: 224 imd5_edges_kt: - 17 - 34 - 48 - 64 - 91 imd5_names: - D_DD - CS - SCS - VSCS - ESCS_SUCS kt_to_kmh: 1.852 max_missing_fraction: 0.3 normalize: zscore pad: median plausible_wind_kt: - 0 - 200 resize: letterbox wind_averaging: 1minfeatures: calibrated: false cdo_outer_fraction: 0.35 cold_thresholds: - 200 - 210 - 220 - 230 - 240 dav_annulus_width_fraction: 0.08 dav_radii_fractions: - 0.15 - 0.3 - 0.45 - 0.6 eye_contrast_min: 2.0 eye_radius_fraction: 0.12 glcm_distance: 1 glcm_levels: 16 radial_bins: 8 selection: correlation_threshold: 0.95 max_features: 25 method: correlation_rf n_estimators: 80 seed: 42forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binincyde: archive: null cv_folds_csv: null cv_seed: 42 cv_val_fold: 0 drop_qc_flags: [] exclusions_csv: null frame_flags_csv: null manifest_csv: null n_folds: 5 on_fix_only_eval: false storm_split_csv: nulllabels: label_column: wind_kt_3min near_land_policy: flag open_water_km: 20 wind_1min_to_3min: 0.93model: dropout: 0.3 hidden: 16 mc_samples: 20 n_frames: 4 name: simple_cnn pretrained: falsepaths: artifacts: artifacts checkpoint_name: checkpoint.pt frame_cache: artifacts/frame_cache hf_model_repo: null incyde_root: data/incyde/Cropped_cyclone_data manifest: data/manifest.csv nasa_root: data/nasa_tc reports: reports run_id: null run_records: artifacts/run_records runs: artifacts/runs tcir_files: [] tcir_manifest_dir: data/tcirpredict: advisory_jump_kt: 20 coast: - lat: 21.64 lon: 69.61 name: Gujarat - lat: 18.94 lon: 72.84 name: Maharashtra - lat: 15.49 lon: 73.83 name: Goa - lat: 12.91 lon: 74.86 name: Karnataka - lat: 9.93 lon: 76.26 name: Kerala - lat: 13.08 lon: 80.27 name: Tamil Nadu - lat: 11.94 lon: 79.83 name: Puducherry - lat: 17.69 lon: 83.22 name: Andhra Pradesh - lat: 19.81 lon: 85.83 name: Odisha - lat: 21.63 lon: 87.51 name: West Bengal - lat: 11.67 lon: 92.74 name: Andaman and Nicobar Islands - lat: 10.57 lon: 72.64 name: Lakshadweep - lat: 20.42 lon: 72.83 name: Dadra and Nagar Haveli and Daman and Diu coast_reference_note: 'Reference points are approximate coastal coordinates, not a shoreline survey and not a landfall forecast.
' coastal_count: 3 coastal_heading: nearest Indian coastal states to the current position confidence: coverage_label: real-data coverage recorded gate_weight: 0.4 interval_scale_kt: 30 interval_weight: 0.2 mc_std_scale_kt: 15 mc_weight: 0.4 uncalibrated_label: uncalibrated earth_radius_km: 6371.0 gate: cold_radius_fraction: 0.45 cold_tail_fraction: 0.25 cold_value: auto concentration_reference: 0.75 eye_radius_fraction: 0.12 eyewall_outer_fraction: 0.32 grayscale_tolerance: 0.08 max_dropout_std_kt: 50 min_cold_concentration: 0.36 min_std: 0.02 min_symmetry: 0.45 min_wall_contrast: 0.45 outer_inner_fraction: 0.55 outer_outer_fraction: 0.95 radial_bins: 8 refusal: not a tropical cyclone IR image held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out storm check. There is no model output. This is not a forecast.
' landfall_note: not a landfall forecast latitude_keys: - latitude - lat longitude_keys: - longitude - lon no_run_record_refusal: 'This checkpoint has no matching real-data run record. There is no model output. This is not a forecast.
' no_run_record_review: no matching real-data run record operational_disclaimer: This is not an operational forecast. scale_tolerance_kt: 1.0 sklearn_features: - symmetry - cold_concentration - wall_contrast - eye_contrast training_mean_width: 3project: honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not an operational forecast or warning system. Best-track labels are noisy, and agreement with them is not ground truth. No survey or smoke number is a result of this project.
' name: cyclone-intensity-estimation seed: 42split: holdout_basin: null holdout_years: [] seed: 42 strategy: storm_wise test_fraction: 0.2 val_fraction: 0.2train: balanced_sampling: false batch_size: 8 class_loss_weight: 0.1 device: auto device_parity_tol: 0.05 epochs: 20 grad_accum_steps: 2 loss_weighting: none lr: 0.001 max_steps: null num_workers: 0 patience: 5 size_loss_weight: 0.1 weight_decay: 0.0001123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264baselines: bootstrap_resamples: 1000 classification_models: - mean - persistence - logreg - knn - rf - xgboost - svc cv_assign: stratified cv_collapse_rare: false cv_group_column: storm_id cv_pool: train knn_neighbors: 5 max_iter: 1000 n_splits: 3 per_storm_breakdown: true regression_models: - mean - persistence - ridge - lr - knn - rf - xgboost - svr rf_estimators: 200 rf_max_depth: 6 ridge_alpha: 1.0 seed: 42 svc_c: 1.0 svr_c: 1.0 use_smote: true xgb_estimators: 80 xgb_learning_rate: 0.1 xgb_max_depth: 3data: channels: 1 dataset: nasa grouping_note: 'Intensity category is this project''s grouping on the configured knot bins. It is not an official IMD class.
' image_size: native imd5_edges_kt: - 17 - 34 - 48 - 64 - 91 imd5_names: - D_DD - CS - SCS - VSCS - ESCS_SUCS kt_to_kmh: 1.852 max_missing_fraction: 0.3 normalize: zscore pad: median plausible_wind_kt: - 0 - 200 resize: letterbox wind_averaging: 1minfeatures: calibrated: false cdo_outer_fraction: 0.35 cold_thresholds: - 200 - 210 - 220 - 230 - 240 dav_annulus_width_fraction: 0.08 dav_radii_fractions: - 0.15 - 0.3 - 0.45 - 0.6 eye_contrast_min: 2.0 eye_radius_fraction: 0.12 glcm_distance: 1 glcm_levels: 16 radial_bins: 8 selection: correlation_threshold: 0.95 max_features: 25 method: correlation_rf n_estimators: 80 seed: 42forbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_binincyde: archive: null cv_folds_csv: null cv_seed: 42 cv_val_fold: 0 drop_qc_flags: [] exclusions_csv: null frame_flags_csv: null manifest_csv: null n_folds: 5 on_fix_only_eval: false storm_split_csv: nulllabels: label_column: wind_kt_3min near_land_policy: flag open_water_km: 20 wind_1min_to_3min: 0.93model: dropout: 0.3 hidden: 16 mc_samples: 20 n_frames: 4 name: simple_cnn pretrained: falsepaths: artifacts: artifacts checkpoint_name: checkpoint.pt frame_cache: artifacts/frame_cache hf_model_repo: null incyde_root: data/incyde manifest: data/manifest.csv nasa_root: data/nasa_tc reports: reports run_id: null run_records: artifacts/run_records runs: artifacts/runs tcir_files: [] tcir_manifest_dir: data/tcirpredict: advisory_jump_kt: 20 coast: - lat: 21.64 lon: 69.61 name: Gujarat - lat: 18.94 lon: 72.84 name: Maharashtra - lat: 15.49 lon: 73.83 name: Goa - lat: 12.91 lon: 74.86 name: Karnataka - lat: 9.93 lon: 76.26 name: Kerala - lat: 13.08 lon: 80.27 name: Tamil Nadu - lat: 11.94 lon: 79.83 name: Puducherry - lat: 17.69 lon: 83.22 name: Andhra Pradesh - lat: 19.81 lon: 85.83 name: Odisha - lat: 21.63 lon: 87.51 name: West Bengal - lat: 11.67 lon: 92.74 name: Andaman and Nicobar Islands - lat: 10.57 lon: 72.64 name: Lakshadweep - lat: 20.42 lon: 72.83 name: Dadra and Nagar Haveli and Daman and Diu coast_reference_note: 'Reference points are approximate coastal coordinates, not a shoreline survey and not a landfall forecast.
' coastal_count: 3 coastal_heading: nearest Indian coastal states to the current position confidence: coverage_label: real-data coverage recorded gate_weight: 0.4 interval_scale_kt: 30 interval_weight: 0.2 mc_std_scale_kt: 15 mc_weight: 0.4 uncalibrated_label: uncalibrated earth_radius_km: 6371.0 gate: cold_radius_fraction: 0.45 cold_tail_fraction: 0.25 cold_value: auto concentration_reference: 0.75 eye_radius_fraction: 0.12 eyewall_outer_fraction: 0.32 grayscale_tolerance: 0.08 max_dropout_std_kt: 50 min_cold_concentration: 0.36 min_std: 0.02 min_symmetry: 0.45 min_wall_contrast: 0.45 outer_inner_fraction: 0.55 outer_outer_fraction: 0.95 radial_bins: 8 refusal: not a tropical cyclone IR image held_out_refusal: 'This checkpoint''s real-data run record has not passed the held-out storm check. There is no model output. This is not a forecast.
' landfall_note: not a landfall forecast latitude_keys: - latitude - lat longitude_keys: - longitude - lon no_run_record_refusal: 'This checkpoint has no matching real-data run record. There is no model output. This is not a forecast.
' no_run_record_review: no matching real-data run record operational_disclaimer: This is not an operational forecast. scale_tolerance_kt: 1.0 sklearn_features: - symmetry - cold_concentration - wall_contrast - eye_contrast training_mean_width: 3project: honesty: 'No trained weights are shipped. Smoke images are synthetic. This is not an operational forecast or warning system. Best-track labels are noisy, and agreement with them is not ground truth. No survey or smoke number is a result of this project.
' name: cyclone-intensity-estimation seed: 42split: holdout_basin: null holdout_years: [] seed: 42 strategy: storm_wise test_fraction: 0.2 val_fraction: 0.2train: balanced_sampling: false batch_size: 8 class_loss_weight: 0.1 device: auto device_parity_tol: 0.05 epochs: 20 grad_accum_steps: 2 loss_weighting: none lr: 0.001 max_steps: null num_workers: 0 patience: 5 size_loss_weight: 0.1 weight_decay: 0.0001123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196project:name: cyclone-intensity-estimation-smokeseed: 7honesty: >Smoke images are synthetic. Metrics from this config are a softwarecheck, not a scientific result and not a forecast.paths:manifest: data/smoke/manifest.csvartifacts: artifacts/smokereports: reports/smokecheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cacheincyde_root: data/incyde# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: smoke# Small square so the software check stays fast. The NASA config uses native.image_size: 64channels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# Smoke labels are synthetic. They are not HURDAT2 1-minute winds.wind_averaging: synthetic# Same project bins as config.yaml. IMD itself uses 3-minute winds.# 17/34/48/64/91 kt is this project's grouping, not that IMD scale.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]kt_to_kmh: 1.852resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.labels:label_column: wind_kt_3minwind_1min_to_3min: 0.93near_land_policy: flagopen_water_km: 20incyde:manifest_csv: nullstorm_split_csv: nullexclusions_csv: nullarchive: nulldrop_qc_flags: []n_folds: 5cv_val_fold: 0cv_seed: 42cv_folds_csv: nullframe_flags_csv: nullon_fix_only_eval: falsesplit:strategy: storm_wisetest_fraction: 0.2val_fraction: 0.2holdout_years: [2021]holdout_basin: NIOseed: 7model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20n_frames: 4hidden: 8train:batch_size: 8epochs: 2lr: 0.001weight_decay: 0.0001patience: 1device: automax_steps: nullgrad_accum_steps: 1num_workers: 2device_parity_tol: 0.05class_loss_weight: 0.1size_loss_weight: 0.1loss_weighting: nonebalanced_sampling: falsepredict:advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]training_mean_width: 3scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}features:calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 20seed: 7baselines:n_splits: 2seed: 7# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 3svr_c: 1.0svc_c: 1.0rf_estimators: 20rf_max_depth: 4xgb_estimators: 20xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 400cv_pool: traincv_group_column: storm_idcv_collapse_rare: falsecv_assign: stratifiedforbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_bin123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196project:name: cyclone-intensity-estimation-smokeseed: 7honesty: >Smoke images are synthetic. Metrics from this config are a softwarecheck, not a scientific result and not a forecast.paths:manifest: data/smoke/manifest.csvartifacts: artifacts/smokereports: reports/smokecheckpoint_name: checkpoint.ptrun_records: artifacts/run_recordsruns: artifacts/runsnasa_root: data/nasa_tctcir_files: []tcir_manifest_dir: data/tcirframe_cache: artifacts/frame_cacheincyde_root: data/incyde# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.run_id: nullhf_model_repo: nulldata:dataset: smoke# Small square so the software check stays fast. The NASA config uses native.image_size: 64channels: 1normalize: zscoremax_missing_fraction: 0.30plausible_wind_kt: [0, 200]# Smoke labels are synthetic. They are not HURDAT2 1-minute winds.wind_averaging: synthetic# Same project bins as config.yaml. IMD itself uses 3-minute winds.# 17/34/48/64/91 kt is this project's grouping, not that IMD scale.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]kt_to_kmh: 1.852resize: letterboxpad: mediangrouping_note: >Intensity category is this project's grouping on the configured knot bins.It is not an official IMD class.labels:label_column: wind_kt_3minwind_1min_to_3min: 0.93near_land_policy: flagopen_water_km: 20incyde:manifest_csv: nullstorm_split_csv: nullexclusions_csv: nullarchive: nulldrop_qc_flags: []n_folds: 5cv_val_fold: 0cv_seed: 42cv_folds_csv: nullframe_flags_csv: nullon_fix_only_eval: falsesplit:strategy: storm_wisetest_fraction: 0.2val_fraction: 0.2holdout_years: [2021]holdout_basin: NIOseed: 7model:name: simple_cnnpretrained: falsedropout: 0.3mc_samples: 20n_frames: 4hidden: 8train:batch_size: 8epochs: 2lr: 0.001weight_decay: 0.0001patience: 1device: automax_steps: nullgrad_accum_steps: 1num_workers: 2device_parity_tol: 0.05class_loss_weight: 0.1size_loss_weight: 0.1loss_weighting: nonebalanced_sampling: falsepredict:advisory_jump_kt: 20operational_disclaimer: "This is not an operational forecast."no_run_record_review: "no matching real-data run record"no_run_record_refusal: >This checkpoint has no matching real-data run record.There is no model output. This is not a forecast.held_out_refusal: >This checkpoint's real-data run record has not passed the held-outstorm check. There is no model output. This is not a forecast.landfall_note: "not a landfall forecast"coast_reference_note: >Reference points are approximate coastal coordinates, not a shorelinesurvey and not a landfall forecast.coastal_heading: "nearest Indian coastal states to the current position"coastal_count: 3earth_radius_km: 6371.0latitude_keys: [latitude, lat]longitude_keys: [longitude, lon]training_mean_width: 3scale_tolerance_kt: 1.0sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]confidence:uncalibrated_label: uncalibratedcoverage_label: "real-data coverage recorded"gate_weight: 0.4mc_weight: 0.4interval_weight: 0.2mc_std_scale_kt: 15interval_scale_kt: 30gate:refusal: "not a tropical cyclone IR image"grayscale_tolerance: 0.08min_std: 0.02min_symmetry: 0.45min_cold_concentration: 0.36cold_radius_fraction: 0.45cold_tail_fraction: 0.25eye_radius_fraction: 0.12eyewall_outer_fraction: 0.32outer_inner_fraction: 0.55outer_outer_fraction: 0.95min_wall_contrast: 0.45radial_bins: 8cold_value: automax_dropout_std_kt: 50concentration_reference: 0.75coast:- {name: Gujarat, lat: 21.64, lon: 69.61}- {name: Maharashtra, lat: 18.94, lon: 72.84}- {name: Goa, lat: 15.49, lon: 73.83}- {name: Karnataka, lat: 12.91, lon: 74.86}- {name: Kerala, lat: 9.93, lon: 76.26}- {name: Tamil Nadu, lat: 13.08, lon: 80.27}- {name: Puducherry, lat: 11.94, lon: 79.83}- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}- {name: Odisha, lat: 19.81, lon: 85.83}- {name: West Bengal, lat: 21.63, lon: 87.51}- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}- {name: Lakshadweep, lat: 10.57, lon: 72.64}- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}features:calibrated: falsecold_thresholds: [200, 210, 220, 230, 240]radial_bins: 8eye_radius_fraction: 0.12cdo_outer_fraction: 0.35eye_contrast_min: 2.0dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]dav_annulus_width_fraction: 0.08glcm_levels: 16glcm_distance: 1selection:correlation_threshold: 0.95max_features: 25method: correlation_rfn_estimators: 20seed: 7baselines:n_splits: 2seed: 7# Validation per-class intervals. Each resample draws storms with replacement.# The generator seed is baselines.seed. Rows are not resampled.bootstrap_resamples: 1000# List each storm inside a class that has fewer than 3 storms.per_storm_breakdown: trueregression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]use_smote: trueridge_alpha: 1.0knn_neighbors: 3svr_c: 1.0svc_c: 1.0rf_estimators: 20rf_max_depth: 4xgb_estimators: 20xgb_max_depth: 3xgb_learning_rate: 0.1max_iter: 400cv_pool: traincv_group_column: storm_idcv_collapse_rare: falsecv_assign: stratifiedforbidden_features:- wind_speed_kt- r34_nmi- rmw_nmi- imd5_class- intensity_bin
1234567891011121314151617181920212223242526272829303132333435363738394041# INCYDE CPU model v0.1 (SimpleCNN). Used by scripts/incyde_cpu/*.# Device-neutral: device auto picks xpu, then cuda, then cpu (GPU needs CLOUDIE_ALLOW_GPU=1).project:seed: 42labels:# Standard: IMD 3-minute sustained wind. INCYDE labels are used unchanged.# 1-minute sources (TCIR, NASA) are converted with ONE factor:# 0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, at-sea exposure# (Harper, Kepert & Ginger 2010). Derived, NOT a WMO constant.# Pending Researchy's verification.one_to_three_min_factor: 0.93one_to_three_min_factor_status: derived_pending_verification# Rows whose centre is within this distance of land are flagged (near_land).near_land_km: 20# false: near-land TCIR rows are left out of pretraining instead of converted.pretrain_keep_near_land: falsedata:image_size: 96# Main's project bins (src/schema.py). Not official IMD classes.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]model:name: simple_cnndropout: 0.3channels: 1train:device: autobatch_size: 64epochs: 30lr: 0.001weight_decay: 0.0001patience: 6class_loss_weight: 0.5num_workers: 0cv:n_folds: 5seed: 42augment:rot_180: truemasked_rotation: trueflips: false1234567891011121314151617181920212223242526272829303132333435363738394041# INCYDE CPU model v0.1 (SimpleCNN). Used by scripts/incyde_cpu/*.# Device-neutral: device auto picks xpu, then cuda, then cpu (GPU needs CLOUDIE_ALLOW_GPU=1).project:seed: 42labels:# Standard: IMD 3-minute sustained wind. INCYDE labels are used unchanged.# 1-minute sources (TCIR, NASA) are converted with ONE factor:# 0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, at-sea exposure# (Harper, Kepert & Ginger 2010). Derived, NOT a WMO constant.# Pending Researchy's verification.one_to_three_min_factor: 0.93one_to_three_min_factor_status: derived_pending_verification# Rows whose centre is within this distance of land are flagged (near_land).near_land_km: 20# false: near-land TCIR rows are left out of pretraining instead of converted.pretrain_keep_near_land: falsedata:image_size: 96# Main's project bins (src/schema.py). Not official IMD classes.imd5_edges_kt: [17, 34, 48, 64, 91]imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]model:name: simple_cnndropout: 0.3channels: 1train:device: autobatch_size: 64epochs: 30lr: 0.001weight_decay: 0.0001patience: 6class_loss_weight: 0.5num_workers: 0cv:n_folds: 5seed: 42augment:rot_180: truemasked_rotation: trueflips: false
123456"""Tropical cyclone intensity estimation framework.No trained weights are shipped. This is not a warning system."""__version__ = "0.2.0"123456"""Tropical cyclone intensity estimation framework.No trained weights are shipped. This is not a warning system."""__version__ = "0.2.0"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Write fp16 ``.npy`` frames and an index CSV for one dataset.Training reads this cache when ``paths.frame_cache/<dataset>/index.csv``exists and otherwise reads the source files. Nothing is downloaded.Workers then load a small array instead of decoding the source.``python -m src.cache_frames --dataset nasa``"""from __future__ import annotationsimport argparseimport refrom pathlib import Pathimport numpy as npimport pandas as pd_SAMPLE_CHARS = re.compile(r"[^A-Za-z0-9._-]+")def _safe_name(sample_id: str) -> str:cleaned = _SAMPLE_CHARS.sub("_", sample_id.strip())return cleaned or "frame"def cache_dataset(dataset: str, config: dict) -> Path:"""Read one local dataset and write fp16 frames plus ``index.csv``."""from src.data_loader import load_imagefrom src.train import load_training_framename = str(dataset).strip().lower()root = Path(config["paths"]["frame_cache"])frame, _excluded = load_training_frame(name, config)dest_dir = root / name / "frames"dest_dir.mkdir(parents=True, exist_ok=True)rows: list[dict[str, str]] = []for row in frame.itertuples(index=False):array = np.asarray(load_image(row.image_path), dtype=np.float16)path = dest_dir / f"{_safe_name(str(row.sample_id))}.npy"np.save(path, array)rows.append({"sample_id": str(row.sample_id),"cache_path": path.resolve().as_posix(),"source_path": str(row.image_path),"dataset": name,"dtype": "float16",})index = root / name / "index.csv"pd.DataFrame(rows).to_csv(index, index=False)print(f"Wrote {index} ({len(rows)} fp16 frames). Not a model result.")return indexdef main(argv: list[str] | None = None) -> Path:"""``python -m src.cache_frames --config config/config.yaml --dataset nasa``."""from src.config import load_configfrom src.train import _DATASETSparser = argparse.ArgumentParser(description="Cache one dataset as fp16 npy frames. Does not download imagery.")parser.add_argument("--config", type=Path, default=Path("config/config.yaml"))parser.add_argument("--dataset", required=True, choices=_DATASETS)args = parser.parse_args(argv)return cache_dataset(args.dataset, load_config(args.config))if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Write fp16 ``.npy`` frames and an index CSV for one dataset.Training reads this cache when ``paths.frame_cache/<dataset>/index.csv``exists and otherwise reads the source files. Nothing is downloaded.Workers then load a small array instead of decoding the source.``python -m src.cache_frames --dataset nasa``"""from __future__ import annotationsimport argparseimport refrom pathlib import Pathimport numpy as npimport pandas as pd_SAMPLE_CHARS = re.compile(r"[^A-Za-z0-9._-]+")def _safe_name(sample_id: str) -> str:cleaned = _SAMPLE_CHARS.sub("_", sample_id.strip())return cleaned or "frame"def cache_dataset(dataset: str, config: dict) -> Path:"""Read one local dataset and write fp16 frames plus ``index.csv``."""from src.data_loader import load_imagefrom src.train import load_training_framename = str(dataset).strip().lower()root = Path(config["paths"]["frame_cache"])frame, _excluded = load_training_frame(name, config)dest_dir = root / name / "frames"dest_dir.mkdir(parents=True, exist_ok=True)rows: list[dict[str, str]] = []for row in frame.itertuples(index=False):array = np.asarray(load_image(row.image_path), dtype=np.float16)path = dest_dir / f"{_safe_name(str(row.sample_id))}.npy"np.save(path, array)rows.append({"sample_id": str(row.sample_id),"cache_path": path.resolve().as_posix(),"source_path": str(row.image_path),"dataset": name,"dtype": "float16",})index = root / name / "index.csv"pd.DataFrame(rows).to_csv(index, index=False)print(f"Wrote {index} ({len(rows)} fp16 frames). Not a model result.")return indexdef main(argv: list[str] | None = None) -> Path:"""``python -m src.cache_frames --config config/config.yaml --dataset nasa``."""from src.config import load_configfrom src.train import _DATASETSparser = argparse.ArgumentParser(description="Cache one dataset as fp16 npy frames. Does not download imagery.")parser.add_argument("--config", type=Path, default=Path("config/config.yaml"))parser.add_argument("--dataset", required=True, choices=_DATASETS)args = parser.parse_args(argv)return cache_dataset(args.dataset, load_config(args.config))if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345"""Torch-free calibration diagnostics for uncertainty intervals.Compares raw MC Dropout intervals with validation-fit scaled conformalintervals. Computes MACE, ENCE, 90% coverage and width, and Spearmanrank correlation between predicted uncertainty and absolute error.This module does **not** import torch. All inputs are NumPy arrays.Terminology------------ *Raw MC*: central percentile interval from MC-dropout samples.- *Scaled conformal*: MC-dropout intervals whose half-widths are rescaledby a single scalar fit on validation residuals so that empirical coveragematches the nominal level on the validation set."""from __future__ import annotationsimport mathfrom dataclasses import dataclass, fieldimport numpy as np# ---------------------------------------------------------------------------# Data containers# ---------------------------------------------------------------------------@dataclass(frozen=True)class IntervalResult:"""Coverage and width for one interval method at one nominal level."""nominal: floatempirical_coverage: floatmean_width_kt: floatmedian_width_kt: floatn: int@dataclass(frozen=True)class CalibrationReport:"""Full calibration comparison between raw MC and scaled conformal."""# Per-level resultsraw_mc: dict[str, IntervalResult] = field(default_factory=dict)scaled_conformal: dict[str, IntervalResult] = field(default_factory=dict)# Aggregate scalar metricsmace: float = float("nan")ence: float = float("nan")coverage_90_raw: float = float("nan")width_90_raw_kt: float = float("nan")coverage_90_scaled: float = float("nan")width_90_scaled_kt: float = float("nan")spearman_rho: float = float("nan")spearman_p: float = float("nan")def to_dict(self) -> dict:"""Serialize to a plain dict for JSON output."""out: dict = {"mace": _safe_float(self.mace),"ence": _safe_float(self.ence),"spearman_rho": _safe_float(self.spearman_rho),"spearman_p": _safe_float(self.spearman_p),"coverage_90_raw": _safe_float(self.coverage_90_raw),"width_90_raw_kt": _safe_float(self.width_90_raw_kt),"coverage_90_scaled": _safe_float(self.coverage_90_scaled),"width_90_scaled_kt": _safe_float(self.width_90_scaled_kt),}for label, bucket in (("raw_mc", self.raw_mc), ("scaled_conformal", self.scaled_conformal)):out[label] = {key: {"nominal": result.nominal,"empirical_coverage": result.empirical_coverage,"mean_width_kt": result.mean_width_kt,"median_width_kt": result.median_width_kt,"n": result.n,}for key, result in bucket.items()}return outdef _safe_float(value: float) -> float | None:"""Return None for nan/inf so JSON serialization works."""if not np.isfinite(value):return Nonereturn float(value)# ---------------------------------------------------------------------------# Low-level interval helpers (no torch)# ---------------------------------------------------------------------------def _mc_intervals(samples: np.ndarray, level: float) -> tuple[np.ndarray, np.ndarray]:"""Central percentile interval from MC-dropout draws.Parameters----------samples : array, shape (n_draws, n_rows)level : float in (0, 1)Returns-------lower, upper : arrays of shape (n_rows,)"""draws = np.asarray(samples, dtype=np.float64)if draws.ndim != 2 or draws.shape[0] < 2:raise ValueError("samples must have shape (n_draws, n_rows) with >= 2 draws")alpha = (1.0 - level) / 2.0lower = np.quantile(draws, alpha, axis=0, method="linear")upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")return np.asarray(lower, np.float64), np.asarray(upper, np.float64)def _coverage_and_width(y_true: np.ndarray,lower: np.ndarray,upper: np.ndarray,) -> tuple[float, float, float]:"""Empirical coverage, mean width, median width."""covered = (y_true >= lower) & (y_true <= upper)widths = upper - lowerreturn float(np.mean(covered)), float(np.mean(widths)), float(np.median(widths))def _fit_conformal_scale(y_true_val: np.ndarray,mc_samples_val: np.ndarray,level: float,) -> float:"""Fit a single multiplicative scalar on validation residuals.The scalar *s* is chosen so that the rescaled MC intervals (center ± s·hw)achieve exactly the requested coverage on the validation set, usingconformalized quantile regression with a single global scale."""draws = np.asarray(mc_samples_val, dtype=np.float64)means = draws.mean(axis=0)lower, upper = _mc_intervals(draws, level)half_widths = (upper - lower) / 2.0# Avoid division by zero for constant predictions.half_widths = np.maximum(half_widths, 1e-12)conformity_scores = np.abs(y_true_val - means) / half_widths# The conformal quantile: the smallest s such that coverage >= level.quantile = np.quantile(conformity_scores, level, method="higher")return float(quantile)def _scaled_intervals(mc_samples: np.ndarray, scale: float, level: float) -> tuple[np.ndarray, np.ndarray]:"""Apply conformal scale to MC intervals."""draws = np.asarray(mc_samples, dtype=np.float64)means = draws.mean(axis=0)lower_raw, upper_raw = _mc_intervals(draws, level)half_widths = (upper_raw - lower_raw) / 2.0lower = means - scale * half_widthsupper = means + scale * half_widthsreturn lower, upper# ---------------------------------------------------------------------------# Aggregate calibration metrics# ---------------------------------------------------------------------------def compute_mace(y_true: np.ndarray,mc_samples: np.ndarray,n_bins: int = 10,) -> float:"""Mean Absolute Calibration Error (MACE).Evaluates the raw MC intervals at ``n_bins`` equally spaced nominallevels from 0.1 to 0.9 and returns the mean absolute gap betweennominal and empirical coverage."""levels = np.linspace(0.1, 0.9, n_bins)gaps: list[float] = []for level in levels:lower, upper = _mc_intervals(mc_samples, float(level))cov, _, _ = _coverage_and_width(y_true, lower, upper)gaps.append(abs(cov - float(level)))return float(np.mean(gaps))def compute_ence(y_true: np.ndarray,mc_samples: np.ndarray,n_bins: int = 10,) -> float:"""Expected Normalized Calibration Error (ENCE).Groups rows by predicted uncertainty (MC std), computes per-bin RMSE andmean predicted std, then averages the relative gap."""draws = np.asarray(mc_samples, dtype=np.float64)pred_mean = draws.mean(axis=0)pred_std = draws.std(axis=0, ddof=0)n = len(y_true)if n < n_bins:n_bins = max(1, n)order = np.argsort(pred_std)bin_edges = np.array_split(order, n_bins)ence_terms: list[float] = []for indices in bin_edges:if len(indices) == 0:continuermse = float(np.sqrt(np.mean((y_true[indices] - pred_mean[indices]) ** 2)))mean_std = float(np.mean(pred_std[indices]))if mean_std > 0:ence_terms.append(abs(rmse - mean_std) / mean_std)else:ence_terms.append(0.0 if rmse == 0 else float("inf"))return float(np.mean(ence_terms)) if ence_terms else float("nan")def compute_spearman(y_true: np.ndarray,mc_samples: np.ndarray,) -> tuple[float, float]:"""Spearman ρ between predicted uncertainty (MC std) and |error|.A higher ρ means the model's uncertainty tracks its actual errors."""draws = np.asarray(mc_samples, dtype=np.float64)pred_mean = draws.mean(axis=0)pred_std = draws.std(axis=0, ddof=0)abs_error = np.abs(y_true - pred_mean)if pred_std.std() == 0 or abs_error.std() == 0:return 0.0, 1.0try:from scipy import stats as sp_statsresult = sp_stats.spearmanr(pred_std, abs_error)return float(result.statistic), float(result.pvalue)except ImportError:import pandas as pdrho = float(pd.Series(pred_std).corr(pd.Series(abs_error), method="spearman"))n = len(pred_std)if n > 2 and abs(rho) < 1.0:t_stat = rho * np.sqrt((n - 2) / (1.0 - rho**2))pval = float(2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(t_stat) / np.sqrt(2)))))else:pval = 0.0 if abs(rho) == 1.0 else 1.0return rho, pval# ---------------------------------------------------------------------------# Main calibration comparison# ---------------------------------------------------------------------------NOMINAL_LEVELS = (0.50, 0.80, 0.90, 0.95)def compare_calibration(y_true_val: np.ndarray,mc_samples_val: np.ndarray,y_true_test: np.ndarray,mc_samples_test: np.ndarray,levels: tuple[float, ...] = NOMINAL_LEVELS,) -> CalibrationReport:"""Compare raw MC Dropout vs validation-fit scaled conformal intervals.Parameters----------y_true_val, mc_samples_valValidation ground truth and MC draws (n_draws, n_val).y_true_test, mc_samples_testTest ground truth and MC draws (n_draws, n_test).levelsNominal coverage levels to evaluate.Returns-------CalibrationReport"""y_val = np.asarray(y_true_val, dtype=np.float64).ravel()y_test = np.asarray(y_true_test, dtype=np.float64).ravel()mc_val = np.asarray(mc_samples_val, dtype=np.float64)mc_test = np.asarray(mc_samples_test, dtype=np.float64)if mc_val.ndim != 2 or mc_val.shape[0] < 2:raise ValueError("mc_samples_val must have shape (n_draws, n_val)")if mc_test.ndim != 2 or mc_test.shape[0] < 2:raise ValueError("mc_samples_test must have shape (n_draws, n_test)")if mc_val.shape[1] != y_val.size:raise ValueError("mc_samples_val columns must match y_true_val length")if mc_test.shape[1] != y_test.size:raise ValueError("mc_samples_test columns must match y_true_test length")raw_results: dict[str, IntervalResult] = {}scaled_results: dict[str, IntervalResult] = {}for level in levels:key = f"{level:.2f}"# Raw MC on testraw_lo, raw_hi = _mc_intervals(mc_test, level)cov_r, mw_r, mdw_r = _coverage_and_width(y_test, raw_lo, raw_hi)raw_results[key] = IntervalResult(nominal=level,empirical_coverage=cov_r,mean_width_kt=mw_r,median_width_kt=mdw_r,n=y_test.size,)# Scaled conformal on test (scale fit on val)scale = _fit_conformal_scale(y_val, mc_val, level)sc_lo, sc_hi = _scaled_intervals(mc_test, scale, level)cov_s, mw_s, mdw_s = _coverage_and_width(y_test, sc_lo, sc_hi)scaled_results[key] = IntervalResult(nominal=level,empirical_coverage=cov_s,mean_width_kt=mw_s,median_width_kt=mdw_s,n=y_test.size,)# Aggregate metrics on test set using raw MCmace = compute_mace(y_test, mc_test)ence = compute_ence(y_test, mc_test)rho, pval = compute_spearman(y_test, mc_test)cov_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coveragew_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_ktcov_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coveragew_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_ktreturn CalibrationReport(raw_mc=raw_results,scaled_conformal=scaled_results,mace=mace,ence=ence,coverage_90_raw=cov_90_raw,width_90_raw_kt=w_90_raw,coverage_90_scaled=cov_90_sc,width_90_scaled_kt=w_90_sc,spearman_rho=rho,spearman_p=pval,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345"""Torch-free calibration diagnostics for uncertainty intervals.Compares raw MC Dropout intervals with validation-fit scaled conformalintervals. Computes MACE, ENCE, 90% coverage and width, and Spearmanrank correlation between predicted uncertainty and absolute error.This module does **not** import torch. All inputs are NumPy arrays.Terminology------------ *Raw MC*: central percentile interval from MC-dropout samples.- *Scaled conformal*: MC-dropout intervals whose half-widths are rescaledby a single scalar fit on validation residuals so that empirical coveragematches the nominal level on the validation set."""from __future__ import annotationsimport mathfrom dataclasses import dataclass, fieldimport numpy as np# ---------------------------------------------------------------------------# Data containers# ---------------------------------------------------------------------------@dataclass(frozen=True)class IntervalResult:"""Coverage and width for one interval method at one nominal level."""nominal: floatempirical_coverage: floatmean_width_kt: floatmedian_width_kt: floatn: int@dataclass(frozen=True)class CalibrationReport:"""Full calibration comparison between raw MC and scaled conformal."""# Per-level resultsraw_mc: dict[str, IntervalResult] = field(default_factory=dict)scaled_conformal: dict[str, IntervalResult] = field(default_factory=dict)# Aggregate scalar metricsmace: float = float("nan")ence: float = float("nan")coverage_90_raw: float = float("nan")width_90_raw_kt: float = float("nan")coverage_90_scaled: float = float("nan")width_90_scaled_kt: float = float("nan")spearman_rho: float = float("nan")spearman_p: float = float("nan")def to_dict(self) -> dict:"""Serialize to a plain dict for JSON output."""out: dict = {"mace": _safe_float(self.mace),"ence": _safe_float(self.ence),"spearman_rho": _safe_float(self.spearman_rho),"spearman_p": _safe_float(self.spearman_p),"coverage_90_raw": _safe_float(self.coverage_90_raw),"width_90_raw_kt": _safe_float(self.width_90_raw_kt),"coverage_90_scaled": _safe_float(self.coverage_90_scaled),"width_90_scaled_kt": _safe_float(self.width_90_scaled_kt),}for label, bucket in (("raw_mc", self.raw_mc), ("scaled_conformal", self.scaled_conformal)):out[label] = {key: {"nominal": result.nominal,"empirical_coverage": result.empirical_coverage,"mean_width_kt": result.mean_width_kt,"median_width_kt": result.median_width_kt,"n": result.n,}for key, result in bucket.items()}return outdef _safe_float(value: float) -> float | None:"""Return None for nan/inf so JSON serialization works."""if not np.isfinite(value):return Nonereturn float(value)# ---------------------------------------------------------------------------# Low-level interval helpers (no torch)# ---------------------------------------------------------------------------def _mc_intervals(samples: np.ndarray, level: float) -> tuple[np.ndarray, np.ndarray]:"""Central percentile interval from MC-dropout draws.Parameters----------samples : array, shape (n_draws, n_rows)level : float in (0, 1)Returns-------lower, upper : arrays of shape (n_rows,)"""draws = np.asarray(samples, dtype=np.float64)if draws.ndim != 2 or draws.shape[0] < 2:raise ValueError("samples must have shape (n_draws, n_rows) with >= 2 draws")alpha = (1.0 - level) / 2.0lower = np.quantile(draws, alpha, axis=0, method="linear")upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")return np.asarray(lower, np.float64), np.asarray(upper, np.float64)def _coverage_and_width(y_true: np.ndarray,lower: np.ndarray,upper: np.ndarray,) -> tuple[float, float, float]:"""Empirical coverage, mean width, median width."""covered = (y_true >= lower) & (y_true <= upper)widths = upper - lowerreturn float(np.mean(covered)), float(np.mean(widths)), float(np.median(widths))def _fit_conformal_scale(y_true_val: np.ndarray,mc_samples_val: np.ndarray,level: float,) -> float:"""Fit a single multiplicative scalar on validation residuals.The scalar *s* is chosen so that the rescaled MC intervals (center ± s·hw)achieve exactly the requested coverage on the validation set, usingconformalized quantile regression with a single global scale."""draws = np.asarray(mc_samples_val, dtype=np.float64)means = draws.mean(axis=0)lower, upper = _mc_intervals(draws, level)half_widths = (upper - lower) / 2.0# Avoid division by zero for constant predictions.half_widths = np.maximum(half_widths, 1e-12)conformity_scores = np.abs(y_true_val - means) / half_widths# The conformal quantile: the smallest s such that coverage >= level.quantile = np.quantile(conformity_scores, level, method="higher")return float(quantile)def _scaled_intervals(mc_samples: np.ndarray, scale: float, level: float) -> tuple[np.ndarray, np.ndarray]:"""Apply conformal scale to MC intervals."""draws = np.asarray(mc_samples, dtype=np.float64)means = draws.mean(axis=0)lower_raw, upper_raw = _mc_intervals(draws, level)half_widths = (upper_raw - lower_raw) / 2.0lower = means - scale * half_widthsupper = means + scale * half_widthsreturn lower, upper# ---------------------------------------------------------------------------# Aggregate calibration metrics# ---------------------------------------------------------------------------def compute_mace(y_true: np.ndarray,mc_samples: np.ndarray,n_bins: int = 10,) -> float:"""Mean Absolute Calibration Error (MACE).Evaluates the raw MC intervals at ``n_bins`` equally spaced nominallevels from 0.1 to 0.9 and returns the mean absolute gap betweennominal and empirical coverage."""levels = np.linspace(0.1, 0.9, n_bins)gaps: list[float] = []for level in levels:lower, upper = _mc_intervals(mc_samples, float(level))cov, _, _ = _coverage_and_width(y_true, lower, upper)gaps.append(abs(cov - float(level)))return float(np.mean(gaps))def compute_ence(y_true: np.ndarray,mc_samples: np.ndarray,n_bins: int = 10,) -> float:"""Expected Normalized Calibration Error (ENCE).Groups rows by predicted uncertainty (MC std), computes per-bin RMSE andmean predicted std, then averages the relative gap."""draws = np.asarray(mc_samples, dtype=np.float64)pred_mean = draws.mean(axis=0)pred_std = draws.std(axis=0, ddof=0)n = len(y_true)if n < n_bins:n_bins = max(1, n)order = np.argsort(pred_std)bin_edges = np.array_split(order, n_bins)ence_terms: list[float] = []for indices in bin_edges:if len(indices) == 0:continuermse = float(np.sqrt(np.mean((y_true[indices] - pred_mean[indices]) ** 2)))mean_std = float(np.mean(pred_std[indices]))if mean_std > 0:ence_terms.append(abs(rmse - mean_std) / mean_std)else:ence_terms.append(0.0 if rmse == 0 else float("inf"))return float(np.mean(ence_terms)) if ence_terms else float("nan")def compute_spearman(y_true: np.ndarray,mc_samples: np.ndarray,) -> tuple[float, float]:"""Spearman ρ between predicted uncertainty (MC std) and |error|.A higher ρ means the model's uncertainty tracks its actual errors."""draws = np.asarray(mc_samples, dtype=np.float64)pred_mean = draws.mean(axis=0)pred_std = draws.std(axis=0, ddof=0)abs_error = np.abs(y_true - pred_mean)if pred_std.std() == 0 or abs_error.std() == 0:return 0.0, 1.0try:from scipy import stats as sp_statsresult = sp_stats.spearmanr(pred_std, abs_error)return float(result.statistic), float(result.pvalue)except ImportError:import pandas as pdrho = float(pd.Series(pred_std).corr(pd.Series(abs_error), method="spearman"))n = len(pred_std)if n > 2 and abs(rho) < 1.0:t_stat = rho * np.sqrt((n - 2) / (1.0 - rho**2))pval = float(2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(t_stat) / np.sqrt(2)))))else:pval = 0.0 if abs(rho) == 1.0 else 1.0return rho, pval# ---------------------------------------------------------------------------# Main calibration comparison# ---------------------------------------------------------------------------NOMINAL_LEVELS = (0.50, 0.80, 0.90, 0.95)def compare_calibration(y_true_val: np.ndarray,mc_samples_val: np.ndarray,y_true_test: np.ndarray,mc_samples_test: np.ndarray,levels: tuple[float, ...] = NOMINAL_LEVELS,) -> CalibrationReport:"""Compare raw MC Dropout vs validation-fit scaled conformal intervals.Parameters----------y_true_val, mc_samples_valValidation ground truth and MC draws (n_draws, n_val).y_true_test, mc_samples_testTest ground truth and MC draws (n_draws, n_test).levelsNominal coverage levels to evaluate.Returns-------CalibrationReport"""y_val = np.asarray(y_true_val, dtype=np.float64).ravel()y_test = np.asarray(y_true_test, dtype=np.float64).ravel()mc_val = np.asarray(mc_samples_val, dtype=np.float64)mc_test = np.asarray(mc_samples_test, dtype=np.float64)if mc_val.ndim != 2 or mc_val.shape[0] < 2:raise ValueError("mc_samples_val must have shape (n_draws, n_val)")if mc_test.ndim != 2 or mc_test.shape[0] < 2:raise ValueError("mc_samples_test must have shape (n_draws, n_test)")if mc_val.shape[1] != y_val.size:raise ValueError("mc_samples_val columns must match y_true_val length")if mc_test.shape[1] != y_test.size:raise ValueError("mc_samples_test columns must match y_true_test length")raw_results: dict[str, IntervalResult] = {}scaled_results: dict[str, IntervalResult] = {}for level in levels:key = f"{level:.2f}"# Raw MC on testraw_lo, raw_hi = _mc_intervals(mc_test, level)cov_r, mw_r, mdw_r = _coverage_and_width(y_test, raw_lo, raw_hi)raw_results[key] = IntervalResult(nominal=level,empirical_coverage=cov_r,mean_width_kt=mw_r,median_width_kt=mdw_r,n=y_test.size,)# Scaled conformal on test (scale fit on val)scale = _fit_conformal_scale(y_val, mc_val, level)sc_lo, sc_hi = _scaled_intervals(mc_test, scale, level)cov_s, mw_s, mdw_s = _coverage_and_width(y_test, sc_lo, sc_hi)scaled_results[key] = IntervalResult(nominal=level,empirical_coverage=cov_s,mean_width_kt=mw_s,median_width_kt=mdw_s,n=y_test.size,)# Aggregate metrics on test set using raw MCmace = compute_mace(y_test, mc_test)ence = compute_ence(y_test, mc_test)rho, pval = compute_spearman(y_test, mc_test)cov_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coveragew_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_ktcov_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coveragew_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_ktreturn CalibrationReport(raw_mc=raw_results,scaled_conformal=scaled_results,mace=mace,ence=ence,coverage_90_raw=cov_90_raw,width_90_raw_kt=w_90_raw,coverage_90_scaled=cov_90_sc,width_90_scaled_kt=w_90_sc,spearman_rho=rho,spearman_p=pval,)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""YAML config loader. Training and baselines must read hyperparameters from here."""from __future__ import annotationsfrom pathlib import Pathimport yamldef load_config(path: str | Path) -> dict:with Path(path).open(encoding="utf-8") as handle:raw = yaml.safe_load(handle)if not isinstance(raw, dict):raise ValueError("config root must be a mapping")return rawdef parse_image_size(value: object) -> int | None:"""Square side to resize to, or None to keep the chip's height and width.``None`` and the string ``native`` do not resize. An integer resizes tothat square. NASA TorchGeo chips are 366 by 366 and TCIR chips are 201by 201; this function does not assume either size and does not downloadimagery."""if value is None:return Noneif isinstance(value, str):text = value.strip().lower()if text in {"native", "null", "none"}:return Noneif not text:raise ValueError("data.image_size is blank")try:value = int(text)except ValueError as exc:raise ValueError("data.image_size must be native or a positive integer") from excif isinstance(value, bool) or not isinstance(value, (int, float)):raise ValueError(f"data.image_size must be native or a positive integer, got {value!r}")size = int(value)if size < 1 or float(value) != float(size):raise ValueError("data.image_size must be native or a positive integer")return sizedef image_sizes_match(left: object, right: object) -> bool:"""True when both sides resize to the same square, or both stay native."""return parse_image_size(left) == parse_image_size(right)def checkpoint_path(config: dict, root: str | Path | None = None) -> Path:"""Path of the deep-model checkpoint named in ``paths``.``paths.artifacts`` is the directory. ``paths.checkpoint_name`` is afile name, not a directory. ``root`` prefixes a relative path."""artifacts = Path(config["paths"]["artifacts"])name = str(config["paths"]["checkpoint_name"])if not name or name != Path(name).name:raise ValueError("paths.checkpoint_name must be a file name, not a path")path = artifacts / nameif root is not None and not path.is_absolute():path = Path(root) / pathreturn path1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""YAML config loader. Training and baselines must read hyperparameters from here."""from __future__ import annotationsfrom pathlib import Pathimport yamldef load_config(path: str | Path) -> dict:with Path(path).open(encoding="utf-8") as handle:raw = yaml.safe_load(handle)if not isinstance(raw, dict):raise ValueError("config root must be a mapping")return rawdef parse_image_size(value: object) -> int | None:"""Square side to resize to, or None to keep the chip's height and width.``None`` and the string ``native`` do not resize. An integer resizes tothat square. NASA TorchGeo chips are 366 by 366 and TCIR chips are 201by 201; this function does not assume either size and does not downloadimagery."""if value is None:return Noneif isinstance(value, str):text = value.strip().lower()if text in {"native", "null", "none"}:return Noneif not text:raise ValueError("data.image_size is blank")try:value = int(text)except ValueError as exc:raise ValueError("data.image_size must be native or a positive integer") from excif isinstance(value, bool) or not isinstance(value, (int, float)):raise ValueError(f"data.image_size must be native or a positive integer, got {value!r}")size = int(value)if size < 1 or float(value) != float(size):raise ValueError("data.image_size must be native or a positive integer")return sizedef image_sizes_match(left: object, right: object) -> bool:"""True when both sides resize to the same square, or both stay native."""return parse_image_size(left) == parse_image_size(right)def checkpoint_path(config: dict, root: str | Path | None = None) -> Path:"""Path of the deep-model checkpoint named in ``paths``.``paths.artifacts`` is the directory. ``paths.checkpoint_name`` is afile name, not a directory. ``root`` prefixes a relative path."""artifacts = Path(config["paths"]["artifacts"])name = str(config["paths"]["checkpoint_name"])if not name or name != Path(name).name:raise ValueError("paths.checkpoint_name must be a file name, not a path")path = artifacts / nameif root is not None and not path.is_absolute():path = Path(root) / pathreturn path
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Manifest loading. Image paths are relative to the manifest directory."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport pandas as pdfrom PIL import Imagefrom src.preprocessing import (MAX_MISSING_FRACTION,NormStats,prepare_image,stack_prepared,)from src.schema import require_validdef load_manifest(path: str | Path) -> pd.DataFrame:frame = pd.read_csv(path)return require_valid(frame)def resolve_image(manifest_path: str | Path, image_path: str) -> Path:candidate = Path(image_path)if candidate.is_absolute():return candidatereturn Path(manifest_path).parent / candidatedef load_image(path: str | Path) -> np.ndarray:file_path = Path(path)if not file_path.is_file():raise FileNotFoundError(file_path)if file_path.suffix == ".npy":return np.load(file_path)return np.asarray(Image.open(file_path), dtype=np.float32)def apply_frame_cache(frame: pd.DataFrame, dataset: str, cache_root: str | Path | None) -> pd.DataFrame:"""Point rows at cached fp16 ``.npy`` files when that dataset's index exists.A missing cache leaves ``image_path`` unchanged. A sample that is notin the index, or whose file is gone, keeps its source path."""if cache_root in (None, "", "null"):return frameindex = Path(cache_root) / str(dataset).strip().lower() / "index.csv"if not index.is_file():return framecached = pd.read_csv(index)if "sample_id" not in cached.columns or "cache_path" not in cached.columns:raise ValueError(f"frame cache index {index} needs sample_id and cache_path")mapping = {str(sample): str(path)for sample, path in zip(cached["sample_id"], cached["cache_path"], strict=False)}out = frame.copy()paths: list[str] = []replaced = 0for sample_id, image_path in zip(out["sample_id"].astype(str), out["image_path"].astype(str)):candidate = mapping.get(sample_id)if candidate and Path(candidate).is_file():paths.append(str(Path(candidate).resolve()))if paths[-1] != str(Path(image_path).resolve()):replaced += 1else:paths.append(image_path)out["image_path"] = pathsif replaced:print(f"{dataset} frame cache supplied {replaced} fp16 frames from {index}")return outdef prepare_split(frame: pd.DataFrame,manifest_path: str | Path,split: str,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> tuple[np.ndarray, np.ndarray]:"""Load one split. ``stats`` must already have been fit on train.``image_size`` comes from ``data.image_size``. ``native`` keeps eachchip's height and width, and those chips must already share a shape."""rows = frame[frame["split"] == split]images = []winds = []for row in rows.itertuples(index=False):path = resolve_image(manifest_path, row.image_path)images.append(prepare_image(load_image(path), image_size, stats, max_missing_fraction))winds.append(float(row.wind_speed_kt))if not images:raise ValueError(f"split {split} has no rows")return stack_prepared(images), np.asarray(winds, dtype=np.float32)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Manifest loading. Image paths are relative to the manifest directory."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport pandas as pdfrom PIL import Imagefrom src.preprocessing import (MAX_MISSING_FRACTION,NormStats,prepare_image,stack_prepared,)from src.schema import require_validdef load_manifest(path: str | Path) -> pd.DataFrame:frame = pd.read_csv(path)return require_valid(frame)def resolve_image(manifest_path: str | Path, image_path: str) -> Path:candidate = Path(image_path)if candidate.is_absolute():return candidatereturn Path(manifest_path).parent / candidatedef load_image(path: str | Path) -> np.ndarray:file_path = Path(path)if not file_path.is_file():raise FileNotFoundError(file_path)if file_path.suffix == ".npy":return np.load(file_path)return np.asarray(Image.open(file_path), dtype=np.float32)def apply_frame_cache(frame: pd.DataFrame, dataset: str, cache_root: str | Path | None) -> pd.DataFrame:"""Point rows at cached fp16 ``.npy`` files when that dataset's index exists.A missing cache leaves ``image_path`` unchanged. A sample that is notin the index, or whose file is gone, keeps its source path."""if cache_root in (None, "", "null"):return frameindex = Path(cache_root) / str(dataset).strip().lower() / "index.csv"if not index.is_file():return framecached = pd.read_csv(index)if "sample_id" not in cached.columns or "cache_path" not in cached.columns:raise ValueError(f"frame cache index {index} needs sample_id and cache_path")mapping = {str(sample): str(path)for sample, path in zip(cached["sample_id"], cached["cache_path"], strict=False)}out = frame.copy()paths: list[str] = []replaced = 0for sample_id, image_path in zip(out["sample_id"].astype(str), out["image_path"].astype(str)):candidate = mapping.get(sample_id)if candidate and Path(candidate).is_file():paths.append(str(Path(candidate).resolve()))if paths[-1] != str(Path(image_path).resolve()):replaced += 1else:paths.append(image_path)out["image_path"] = pathsif replaced:print(f"{dataset} frame cache supplied {replaced} fp16 frames from {index}")return outdef prepare_split(frame: pd.DataFrame,manifest_path: str | Path,split: str,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> tuple[np.ndarray, np.ndarray]:"""Load one split. ``stats`` must already have been fit on train.``image_size`` comes from ``data.image_size``. ``native`` keeps eachchip's height and width, and those chips must already share a shape."""rows = frame[frame["split"] == split]images = []winds = []for row in rows.itertuples(index=False):path = resolve_image(manifest_path, row.image_path)images.append(prepare_image(load_image(path), image_size, stats, max_missing_fraction))winds.append(float(row.wind_speed_kt))if not images:raise ValueError(f"split {split} has no rows")return stack_prepared(images), np.asarray(winds, dtype=np.float32)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390"""Device selection and mixed precision for native PyTorch.The order is XPU, then CUDA, then CPU. XPU means ``torch.xpu`` in anofficial PyTorch build (2.5 or newer; 2.15 is the pinned Windows wheel).This module does not import or call the archived IPEX package.``CLOUDIE_ALLOW_GPU=1`` is required for XPU and CUDA alike. An explicitaccelerator without that gate is refused. Auto falls back to CPU andlogs the reason. CPU stays fp32. CUDA fp16 is the only path that usesGradScaler. XPU uses bf16 autocast when native bf16 is supported, andfp32 otherwise. ``cudnn.benchmark`` is not enabled."""from __future__ import annotationsimport inspectimport loggingimport mathimport osfrom collections.abc import Iteratorfrom contextlib import contextmanager, nullcontextfrom dataclasses import dataclassLOGGER = logging.getLogger("src.device")DEVICE_CHOICES = ("auto", "xpu", "cuda", "cpu")GPU_DEVICES = ("xpu", "cuda")GPU_GATE = "CLOUDIE_ALLOW_GPU"def _torch():import torchreturn torchdef accelerator_available(torch_module, name: str) -> bool:"""True when this torch build can see ``name``. Missing XPU attributes are false."""if name == "cpu":return Trueif name == "xpu":xpu = getattr(torch_module, "xpu", None)checker = getattr(xpu, "is_available", None) if xpu is not None else Noneif not callable(checker):return Falsetry:return bool(checker())except Exception:return Falseif name == "cuda":try:return bool(torch_module.cuda.is_available())except Exception:return Falsereturn Falsedef xpu_native_bf16(torch_module) -> bool:"""True when native XPU bf16 is supported.Uses ``torch.xpu.is_bf16_supported(including_emulation=False)`` whenthat parameter exists, so emulated bf16 does not select the autocastpath. Older builds without the function, or whose call fails, stayon fp32. A build that has the function but not the parameter iscalled with no arguments."""xpu = getattr(torch_module, "xpu", None)checker = getattr(xpu, "is_bf16_supported", None) if xpu is not None else Noneif not callable(checker):return Falsetry:parameters = inspect.signature(checker).parametershas_kwarg = "including_emulation" in parametersexcept (TypeError, ValueError):has_kwarg = Falsetry:if has_kwarg:return bool(checker(including_emulation=False))return bool(checker())except TypeError:try:return bool(checker())except Exception:return Falseexcept Exception:return False@dataclass(frozen=True)class AmpPolicy:"""How one device runs the forward and the backward."""precision: strautocast_device: str | Nonedtype: object | Noneuse_grad_scaler: booldef amp_policy_for(device, torch_module=None) -> AmpPolicy:"""fp16+GradScaler on CUDA, native bf16 on XPU, fp32 everywhere else.GradScaler is never constructed for XPU or CPU. A missing native bf16on XPU falls back to fp32 with no autocast."""torch_module = torch_module or _torch()kind = device.type if hasattr(device, "type") else str(device)if kind == "cuda":return AmpPolicy("fp16", "cuda", torch_module.float16, True)if kind == "xpu":if xpu_native_bf16(torch_module):return AmpPolicy("bf16", "xpu", torch_module.bfloat16, False)return AmpPolicy("fp32", None, None, False)return AmpPolicy("fp32", None, None, False)@contextmanagerdef autocast_context(policy: AmpPolicy) -> Iterator[None]:"""Enter ``torch.autocast`` for the policy, or do nothing for fp32."""if policy.autocast_device is None or policy.dtype is None:with nullcontext():yieldreturntorch_module = _torch()with torch_module.autocast(policy.autocast_device, dtype=policy.dtype):yielddef make_grad_scaler(policy: AmpPolicy):"""A CUDA fp16 GradScaler, or None. XPU and CPU never get one."""if not policy.use_grad_scaler:return Noneif policy.precision != "fp16" or policy.autocast_device != "cuda":raise RuntimeError("GradScaler is used only for cuda fp16")torch_module = _torch()scaler_cls = getattr(getattr(torch_module, "amp", None), "GradScaler", None)if scaler_cls is not None:try:return scaler_cls("cuda")except TypeError:passreturn torch_module.cuda.amp.GradScaler()def resolve_device(name: str):"""Pick a ``torch.device``. Auto order is xpu, cuda, cpu.Explicit xpu or cuda without ``CLOUDIE_ALLOW_GPU=1`` raises. Autothat would have picked an accelerator falls back to cpu and logs why."""choice = str(name).strip().lower()if choice not in DEVICE_CHOICES:raise ValueError("device must be auto, xpu, cuda, or cpu")torch_module = _torch()if choice == "auto":if accelerator_available(torch_module, "xpu"):picked = "xpu"elif accelerator_available(torch_module, "cuda"):picked = "cuda"else:picked = "cpu"if picked != "cpu" and os.environ.get(GPU_GATE) != "1":message = (f"Refusing auto-picked device {picked} because {GPU_GATE} is not 1. ""Falling back to cpu. An XPU or GPU run needs misty wind's approval. "f"Set {GPU_GATE}=1 only after that approval.")LOGGER.warning(message)print(message)return torch_module.device("cpu")choice = pickedif choice in GPU_DEVICES and os.environ.get(GPU_GATE) != "1":raise RuntimeError(f"Refusing device {choice}. An XPU or GPU run needs misty wind's approval. "f"Set {GPU_GATE}=1 only after that approval.")if choice == "xpu" and not accelerator_available(torch_module, "xpu"):raise RuntimeError("device xpu was approved but XPU is not available")if choice == "cuda" and not accelerator_available(torch_module, "cuda"):raise RuntimeError("device cuda was approved but CUDA is not available")try:return torch_module.device(choice)except RuntimeError as exc:raise RuntimeError(f"device {choice} is not supported by this torch build") from excdef reset_peak_memory(device) -> None:"""Clear the allocator peak for the device that tracks it. CPU is a no-op."""torch_module = _torch()if getattr(device, "type", None) == "cuda":reset = getattr(torch_module.cuda, "reset_peak_memory_stats", None)if callable(reset):try:reset()except Exception:returnif getattr(device, "type", None) == "xpu":xpu = getattr(torch_module, "xpu", None)reset = getattr(xpu, "reset_peak_memory_stats", None) if xpu is not None else Noneif callable(reset):try:reset()except Exception:returndef peak_memory_bytes(device) -> int | None:"""Peak bytes from XPU or CUDA, or null when the device does not report it.XPU peak memory is trustworthy on the torch 2.15 line. Older buildsmay return a number that is not the true peak; the value is stillwhatever ``max_memory_allocated`` reports."""torch_module = _torch()kind = getattr(device, "type", None)if kind == "xpu":xpu = getattr(torch_module, "xpu", None)reader = getattr(xpu, "max_memory_allocated", None) if xpu is not None else Noneif not callable(reader):return Nonetry:return int(reader())except Exception:return Noneif kind == "cuda":reader = getattr(torch_module.cuda, "max_memory_allocated", None)if not callable(reader):return Nonetry:return int(reader())except Exception:return Nonereturn Nonedef _jsonable(value):if value is None or isinstance(value, (str, int, float, bool)):if isinstance(value, float) and not math.isfinite(value):return Nonereturn valueif isinstance(value, (list, tuple)):return [_jsonable(item) for item in value]return str(value)def xpu_device_properties(device) -> dict | None:"""``torch.xpu.get_device_properties`` as a JSON object, or null off XPU."""if getattr(device, "type", None) != "xpu":return Nonetorch_module = _torch()xpu = getattr(torch_module, "xpu", None)getter = getattr(xpu, "get_device_properties", None) if xpu is not None else Noneif not callable(getter):return Noneindex = 0current = getattr(xpu, "current_device", None)if callable(current):try:index = int(current())except Exception:index = 0try:props = getter(index)except Exception:return Noneif hasattr(props, "_asdict"):raw = dict(props._asdict())else:raw = {}for key in dir(props):if key.startswith("_"):continuetry:value = getattr(props, key)except Exception:continueif callable(value):continueraw[key] = valuereturn {str(key): _jsonable(value) for key, value in raw.items()}def parity_verdict(output_max_abs: float,loss_max_abs: float,tolerance: float,reference_scale: float,) -> dict:"""Decide whether a device-versus-CPU gap is inside the tolerance.``tolerance`` is a fraction. The allowed absolute gap is``tolerance * max(1, reference_scale)``. The floor of 1 keeps a smallbf16-versus-fp32 drift from failing when the CPU output is near zero.A larger wind head may move by that fraction of its magnitude.This does not convert physical units. It only compares two forwards."""if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):raise ValueError("device_parity_tol must be a finite number >= 0")if not math.isfinite(float(tolerance)) or float(tolerance) < 0:raise ValueError("device_parity_tol must be a finite number >= 0")output = float(output_max_abs)loss = float(loss_max_abs)if not math.isfinite(output) or not math.isfinite(loss):worst = float("inf")else:worst = max(output, loss)scale = float(reference_scale)if not math.isfinite(scale) or scale < 1.0:scale = 1.0limit = float(tolerance) * scalereturn {"output_max_abs": output,"loss_max_abs": loss,"max_abs_diff": worst,"reference_scale": scale,"tolerance": float(tolerance),"limit": limit,"ok": bool(worst <= limit),}def warn_if_parity_failed(result: dict) -> None:"""Loud warning when the seeded forward disagrees. Training still continues."""if result.get("ok"):returnmessage = ("WARNING: device parity check failed. "f"max abs diff {result['max_abs_diff']:.6g} exceeds limit {result['limit']:.6g} "f"(tolerance {result['tolerance']:.6g}, scale {result['reference_scale']:.6g}). ""device_parity_ok is false. Training continues. This is not a forecast.")LOGGER.warning(message)print(message)def seeded_parity_batch(batch_size: int, channels: int, side: int, seed: int = 0, n_frames: int = 1):"""One fixed CPU batch. The same tensors are copied onto the device."""torch_module = _torch()generator = torch_module.Generator(device="cpu")generator.manual_seed(int(seed))if n_frames > 1:images = torch_module.randn(int(batch_size), int(n_frames), int(channels), int(side), int(side), generator=generator)else:images = torch_module.randn(int(batch_size), int(channels), int(side), int(side), generator=generator)winds = torch_module.rand(int(batch_size), 1, generator=generator)return images, windsdef _forward_wind_loss(model, images, winds):import torch.nn.functional as Ftorch_module = _torch()was_training = model.trainingmodel.eval()try:with torch_module.no_grad():output = model(images)wind = output[0] if isinstance(output, tuple) else outputloss = F.smooth_l1_loss(wind.float().view(-1), winds.float().view(-1))return wind.detach().float().cpu(), loss.detach().float().cpu()finally:model.train(was_training)def compare_model_parity(model, images, winds, device, tolerance: float, *, policy=None) -> dict:"""Run one forward on ``device`` and on CPU. Record the max absolute gap.The training model is copied. Its weights are not updated. The devicecopy uses the same autocast policy as training when one is passed."""import copycpu_model = copy.deepcopy(model).to("cpu").eval()device_model = copy.deepcopy(model).to(device).eval()cpu_wind, cpu_loss = _forward_wind_loss(cpu_model, images, winds)if policy is None:policy = amp_policy_for(device)with autocast_context(policy):dev_wind, dev_loss = _forward_wind_loss(device_model, images.to(device), winds.to(device))output_diff = float((dev_wind - cpu_wind).abs().max())loss_diff = abs(float(dev_loss) - float(cpu_loss))scale = max(1.0, float(cpu_wind.abs().max()), abs(float(cpu_loss)))result = parity_verdict(output_diff, loss_diff, float(tolerance), scale)warn_if_parity_failed(result)return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390"""Device selection and mixed precision for native PyTorch.The order is XPU, then CUDA, then CPU. XPU means ``torch.xpu`` in anofficial PyTorch build (2.5 or newer; 2.15 is the pinned Windows wheel).This module does not import or call the archived IPEX package.``CLOUDIE_ALLOW_GPU=1`` is required for XPU and CUDA alike. An explicitaccelerator without that gate is refused. Auto falls back to CPU andlogs the reason. CPU stays fp32. CUDA fp16 is the only path that usesGradScaler. XPU uses bf16 autocast when native bf16 is supported, andfp32 otherwise. ``cudnn.benchmark`` is not enabled."""from __future__ import annotationsimport inspectimport loggingimport mathimport osfrom collections.abc import Iteratorfrom contextlib import contextmanager, nullcontextfrom dataclasses import dataclassLOGGER = logging.getLogger("src.device")DEVICE_CHOICES = ("auto", "xpu", "cuda", "cpu")GPU_DEVICES = ("xpu", "cuda")GPU_GATE = "CLOUDIE_ALLOW_GPU"def _torch():import torchreturn torchdef accelerator_available(torch_module, name: str) -> bool:"""True when this torch build can see ``name``. Missing XPU attributes are false."""if name == "cpu":return Trueif name == "xpu":xpu = getattr(torch_module, "xpu", None)checker = getattr(xpu, "is_available", None) if xpu is not None else Noneif not callable(checker):return Falsetry:return bool(checker())except Exception:return Falseif name == "cuda":try:return bool(torch_module.cuda.is_available())except Exception:return Falsereturn Falsedef xpu_native_bf16(torch_module) -> bool:"""True when native XPU bf16 is supported.Uses ``torch.xpu.is_bf16_supported(including_emulation=False)`` whenthat parameter exists, so emulated bf16 does not select the autocastpath. Older builds without the function, or whose call fails, stayon fp32. A build that has the function but not the parameter iscalled with no arguments."""xpu = getattr(torch_module, "xpu", None)checker = getattr(xpu, "is_bf16_supported", None) if xpu is not None else Noneif not callable(checker):return Falsetry:parameters = inspect.signature(checker).parametershas_kwarg = "including_emulation" in parametersexcept (TypeError, ValueError):has_kwarg = Falsetry:if has_kwarg:return bool(checker(including_emulation=False))return bool(checker())except TypeError:try:return bool(checker())except Exception:return Falseexcept Exception:return False@dataclass(frozen=True)class AmpPolicy:"""How one device runs the forward and the backward."""precision: strautocast_device: str | Nonedtype: object | Noneuse_grad_scaler: booldef amp_policy_for(device, torch_module=None) -> AmpPolicy:"""fp16+GradScaler on CUDA, native bf16 on XPU, fp32 everywhere else.GradScaler is never constructed for XPU or CPU. A missing native bf16on XPU falls back to fp32 with no autocast."""torch_module = torch_module or _torch()kind = device.type if hasattr(device, "type") else str(device)if kind == "cuda":return AmpPolicy("fp16", "cuda", torch_module.float16, True)if kind == "xpu":if xpu_native_bf16(torch_module):return AmpPolicy("bf16", "xpu", torch_module.bfloat16, False)return AmpPolicy("fp32", None, None, False)return AmpPolicy("fp32", None, None, False)@contextmanagerdef autocast_context(policy: AmpPolicy) -> Iterator[None]:"""Enter ``torch.autocast`` for the policy, or do nothing for fp32."""if policy.autocast_device is None or policy.dtype is None:with nullcontext():yieldreturntorch_module = _torch()with torch_module.autocast(policy.autocast_device, dtype=policy.dtype):yielddef make_grad_scaler(policy: AmpPolicy):"""A CUDA fp16 GradScaler, or None. XPU and CPU never get one."""if not policy.use_grad_scaler:return Noneif policy.precision != "fp16" or policy.autocast_device != "cuda":raise RuntimeError("GradScaler is used only for cuda fp16")torch_module = _torch()scaler_cls = getattr(getattr(torch_module, "amp", None), "GradScaler", None)if scaler_cls is not None:try:return scaler_cls("cuda")except TypeError:passreturn torch_module.cuda.amp.GradScaler()def resolve_device(name: str):"""Pick a ``torch.device``. Auto order is xpu, cuda, cpu.Explicit xpu or cuda without ``CLOUDIE_ALLOW_GPU=1`` raises. Autothat would have picked an accelerator falls back to cpu and logs why."""choice = str(name).strip().lower()if choice not in DEVICE_CHOICES:raise ValueError("device must be auto, xpu, cuda, or cpu")torch_module = _torch()if choice == "auto":if accelerator_available(torch_module, "xpu"):picked = "xpu"elif accelerator_available(torch_module, "cuda"):picked = "cuda"else:picked = "cpu"if picked != "cpu" and os.environ.get(GPU_GATE) != "1":message = (f"Refusing auto-picked device {picked} because {GPU_GATE} is not 1. ""Falling back to cpu. An XPU or GPU run needs misty wind's approval. "f"Set {GPU_GATE}=1 only after that approval.")LOGGER.warning(message)print(message)return torch_module.device("cpu")choice = pickedif choice in GPU_DEVICES and os.environ.get(GPU_GATE) != "1":raise RuntimeError(f"Refusing device {choice}. An XPU or GPU run needs misty wind's approval. "f"Set {GPU_GATE}=1 only after that approval.")if choice == "xpu" and not accelerator_available(torch_module, "xpu"):raise RuntimeError("device xpu was approved but XPU is not available")if choice == "cuda" and not accelerator_available(torch_module, "cuda"):raise RuntimeError("device cuda was approved but CUDA is not available")try:return torch_module.device(choice)except RuntimeError as exc:raise RuntimeError(f"device {choice} is not supported by this torch build") from excdef reset_peak_memory(device) -> None:"""Clear the allocator peak for the device that tracks it. CPU is a no-op."""torch_module = _torch()if getattr(device, "type", None) == "cuda":reset = getattr(torch_module.cuda, "reset_peak_memory_stats", None)if callable(reset):try:reset()except Exception:returnif getattr(device, "type", None) == "xpu":xpu = getattr(torch_module, "xpu", None)reset = getattr(xpu, "reset_peak_memory_stats", None) if xpu is not None else Noneif callable(reset):try:reset()except Exception:returndef peak_memory_bytes(device) -> int | None:"""Peak bytes from XPU or CUDA, or null when the device does not report it.XPU peak memory is trustworthy on the torch 2.15 line. Older buildsmay return a number that is not the true peak; the value is stillwhatever ``max_memory_allocated`` reports."""torch_module = _torch()kind = getattr(device, "type", None)if kind == "xpu":xpu = getattr(torch_module, "xpu", None)reader = getattr(xpu, "max_memory_allocated", None) if xpu is not None else Noneif not callable(reader):return Nonetry:return int(reader())except Exception:return Noneif kind == "cuda":reader = getattr(torch_module.cuda, "max_memory_allocated", None)if not callable(reader):return Nonetry:return int(reader())except Exception:return Nonereturn Nonedef _jsonable(value):if value is None or isinstance(value, (str, int, float, bool)):if isinstance(value, float) and not math.isfinite(value):return Nonereturn valueif isinstance(value, (list, tuple)):return [_jsonable(item) for item in value]return str(value)def xpu_device_properties(device) -> dict | None:"""``torch.xpu.get_device_properties`` as a JSON object, or null off XPU."""if getattr(device, "type", None) != "xpu":return Nonetorch_module = _torch()xpu = getattr(torch_module, "xpu", None)getter = getattr(xpu, "get_device_properties", None) if xpu is not None else Noneif not callable(getter):return Noneindex = 0current = getattr(xpu, "current_device", None)if callable(current):try:index = int(current())except Exception:index = 0try:props = getter(index)except Exception:return Noneif hasattr(props, "_asdict"):raw = dict(props._asdict())else:raw = {}for key in dir(props):if key.startswith("_"):continuetry:value = getattr(props, key)except Exception:continueif callable(value):continueraw[key] = valuereturn {str(key): _jsonable(value) for key, value in raw.items()}def parity_verdict(output_max_abs: float,loss_max_abs: float,tolerance: float,reference_scale: float,) -> dict:"""Decide whether a device-versus-CPU gap is inside the tolerance.``tolerance`` is a fraction. The allowed absolute gap is``tolerance * max(1, reference_scale)``. The floor of 1 keeps a smallbf16-versus-fp32 drift from failing when the CPU output is near zero.A larger wind head may move by that fraction of its magnitude.This does not convert physical units. It only compares two forwards."""if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):raise ValueError("device_parity_tol must be a finite number >= 0")if not math.isfinite(float(tolerance)) or float(tolerance) < 0:raise ValueError("device_parity_tol must be a finite number >= 0")output = float(output_max_abs)loss = float(loss_max_abs)if not math.isfinite(output) or not math.isfinite(loss):worst = float("inf")else:worst = max(output, loss)scale = float(reference_scale)if not math.isfinite(scale) or scale < 1.0:scale = 1.0limit = float(tolerance) * scalereturn {"output_max_abs": output,"loss_max_abs": loss,"max_abs_diff": worst,"reference_scale": scale,"tolerance": float(tolerance),"limit": limit,"ok": bool(worst <= limit),}def warn_if_parity_failed(result: dict) -> None:"""Loud warning when the seeded forward disagrees. Training still continues."""if result.get("ok"):returnmessage = ("WARNING: device parity check failed. "f"max abs diff {result['max_abs_diff']:.6g} exceeds limit {result['limit']:.6g} "f"(tolerance {result['tolerance']:.6g}, scale {result['reference_scale']:.6g}). ""device_parity_ok is false. Training continues. This is not a forecast.")LOGGER.warning(message)print(message)def seeded_parity_batch(batch_size: int, channels: int, side: int, seed: int = 0, n_frames: int = 1):"""One fixed CPU batch. The same tensors are copied onto the device."""torch_module = _torch()generator = torch_module.Generator(device="cpu")generator.manual_seed(int(seed))if n_frames > 1:images = torch_module.randn(int(batch_size), int(n_frames), int(channels), int(side), int(side), generator=generator)else:images = torch_module.randn(int(batch_size), int(channels), int(side), int(side), generator=generator)winds = torch_module.rand(int(batch_size), 1, generator=generator)return images, windsdef _forward_wind_loss(model, images, winds):import torch.nn.functional as Ftorch_module = _torch()was_training = model.trainingmodel.eval()try:with torch_module.no_grad():output = model(images)wind = output[0] if isinstance(output, tuple) else outputloss = F.smooth_l1_loss(wind.float().view(-1), winds.float().view(-1))return wind.detach().float().cpu(), loss.detach().float().cpu()finally:model.train(was_training)def compare_model_parity(model, images, winds, device, tolerance: float, *, policy=None) -> dict:"""Run one forward on ``device`` and on CPU. Record the max absolute gap.The training model is copied. Its weights are not updated. The devicecopy uses the same autocast policy as training when one is passed."""import copycpu_model = copy.deepcopy(model).to("cpu").eval()device_model = copy.deepcopy(model).to(device).eval()cpu_wind, cpu_loss = _forward_wind_loss(cpu_model, images, winds)if policy is None:policy = amp_policy_for(device)with autocast_context(policy):dev_wind, dev_loss = _forward_wind_loss(device_model, images.to(device), winds.to(device))output_diff = float((dev_wind - cpu_wind).abs().max())loss_diff = abs(float(dev_loss) - float(cpu_loss))scale = max(1.0, float(cpu_wind.abs().max()), abs(float(cpu_loss)))result = parity_verdict(output_diff, loss_diff, float(tolerance), scale)warn_if_parity_failed(result)return result
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899"""Physically motivated image features for classical intensity baselines.Distributional statistics are called ``tb_*`` only when the caller has set``features.calibrated``. Otherwise they are ``pixel_*``. Nothing here convertsdigital numbers to brightness temperature.The simplified DAV terms are the circular variance of the angle between theimage gradient and the radial direction, at fixed fractions of the crophalf-width. That is not operational deviation-angle variance: there is noradius search, no flight-level wind, and no agency radius product.Radial, eye, and DAV features assume the storm is already near the imagecenter. This module does not recenter with a best-track fix.Temporal deltas use the previous frame of the same storm after cross-splitlinks have been removed. Wind, R34, RMW, and class labels are not features.Crop height and width are the array shape. ``data.image_size`` may be``native`` or a square resize for the deep model. It is not applied here.Feature selection calls``storm_ids_by_split`` and fits only the training storms."""from __future__ import annotationsimport jsonimport loggingfrom dataclasses import dataclassfrom pathlib import Pathimport numpy as npimport pandas as pdfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.feature_selection import RFEfrom sklearn.impute import SimpleImputerfrom src.data_loader import load_image, resolve_imagefrom src.preprocessing import MAX_MISSING_FRACTION, as_channel_first, missing_fractionfrom src.schema import FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5from src.splits import (LeakageError,add_previous_frame_id,assert_no_forbidden_inputs,null_cross_split_links,storm_ids_by_split,)logger = logging.getLogger(__name__)GLCM_NAMES = ("glcm_contrast","glcm_dissimilarity","glcm_homogeneity","glcm_energy","glcm_correlation","glcm_asm",)HAAR_NAMES = ("haar_energy_ll","haar_energy_lh","haar_energy_hl","haar_energy_hh",)EYE_NAMES = ("eye_center_mean","cdo_annulus_mean","eye_cdo_contrast","eye_present",)@dataclass(frozen=True)class FeatureSpec:"""Geometry of one feature vector. Thresholds are in image units."""calibrated: bool = Falsecold_thresholds: tuple[float, ...] = (200.0, 210.0, 220.0, 230.0, 240.0)radial_bins: int = 8eye_radius_fraction: float = 0.12cdo_outer_fraction: float = 0.35eye_contrast_min: float = 2.0dav_radii_fractions: tuple[float, ...] = (0.15, 0.30, 0.45, 0.60)dav_annulus_width_fraction: float = 0.08glcm_levels: int = 16glcm_distance: int = 1def __post_init__(self) -> None:if not self.cold_thresholds:raise ValueError("cold_thresholds must not be empty")if self.radial_bins < 2:raise ValueError("radial_bins must be at least 2")if not 0 < self.eye_radius_fraction < self.cdo_outer_fraction <= 1:raise ValueError("eye radius must sit inside the CDO annulus")if self.eye_contrast_min < 0:raise ValueError("eye_contrast_min must be >= 0")if any(not 0 < radius < 1 for radius in self.dav_radii_fractions):raise ValueError("DAV radii must be fractions of the half-width")if not 0 < self.dav_annulus_width_fraction < 0.5:raise ValueError("DAV annulus width fraction is out of range")if not 8 <= self.glcm_levels <= 32:raise ValueError("glcm_levels must be between 8 and 32")if self.glcm_distance < 1:raise ValueError("glcm_distance must be >= 1")@propertydef prefix(self) -> str:return "tb" if self.calibrated else "pixel"@classmethoddef from_config(cls, config: dict) -> FeatureSpec:raw = config.get("features")if not isinstance(raw, dict):raise KeyError("config features is required")required = ("calibrated","cold_thresholds","radial_bins","eye_radius_fraction","cdo_outer_fraction","eye_contrast_min","dav_radii_fractions","dav_annulus_width_fraction","glcm_levels","glcm_distance",)missing = [key for key in required if key not in raw]if missing:raise KeyError(f"config features missing {missing}")return cls(calibrated=bool(raw["calibrated"]),cold_thresholds=tuple(float(value) for value in raw["cold_thresholds"]),radial_bins=int(raw["radial_bins"]),eye_radius_fraction=float(raw["eye_radius_fraction"]),cdo_outer_fraction=float(raw["cdo_outer_fraction"]),eye_contrast_min=float(raw["eye_contrast_min"]),dav_radii_fractions=tuple(float(value) for value in raw["dav_radii_fractions"]),dav_annulus_width_fraction=float(raw["dav_annulus_width_fraction"]),glcm_levels=int(raw["glcm_levels"]),glcm_distance=int(raw["glcm_distance"]),)def feature_groups(self) -> dict[str, tuple[str, ...]]:"""Feature names by group.``pixel_stats`` are order statistics of the stored image values.They are not brightness temperature unless ``calibrated`` is set,in which case the same slots use the ``tb_`` prefix.``dav_simplified`` is gradient-angle variance, not operational DAV."""prefix = self.prefixreturn {"pixel_stats": (f"{prefix}_min",f"{prefix}_max",f"{prefix}_mean",f"{prefix}_std",f"{prefix}_p10",f"{prefix}_p25",f"{prefix}_p50",f"{prefix}_p75",f"{prefix}_p90",f"{prefix}_iqr",),"cold_cloud": tuple(f"cold_frac_{_token(threshold)}" for threshold in self.cold_thresholds),"radial": tuple(f"radial_mean_{index:02d}" for index in range(self.radial_bins)),"eye_cdo": EYE_NAMES,"dav_simplified": tuple(f"dav_simplified_r{index:02d}" for index in range(len(self.dav_radii_fractions))),"glcm": GLCM_NAMES,"haar": HAAR_NAMES,"temporal": ("has_prev",f"delta_{prefix}_mean",f"delta_{prefix}_min","delta_cold_primary","delta_eye_cdo_contrast","delta_radial_mean_00",),}def image_feature_names(self) -> tuple[str, ...]:groups = self.feature_groups()names: list[str] = []for key in ("pixel_stats","cold_cloud","radial","eye_cdo","dav_simplified","glcm","haar",):names.extend(groups[key])return tuple(names)def feature_names(self) -> tuple[str, ...]:return self.image_feature_names() + self.feature_groups()["temporal"]@dataclass(frozen=True)class FeatureSelection:names: tuple[str, ...]source_split: strimportances: dict[str, float]dropped_variance: tuple[str, ...]dropped_correlation: tuple[str, ...]train_storms: frozenset[str] = frozenset()def _token(value: float) -> str:number = float(value)if number.is_integer():return str(int(number))return str(number).replace("-", "m").replace(".", "p")def _single_channel(image: np.ndarray) -> np.ndarray:return as_channel_first(image)[0]def _finite_fill(image: np.ndarray) -> np.ndarray:filled = np.array(image, dtype=np.float64, copy=True)finite = np.isfinite(filled)fill = float(np.median(filled[finite])) if finite.any() else 0.0filled[~finite] = fillreturn filleddef _distribution(image: np.ndarray, prefix: str) -> dict[str, float]:finite = image[np.isfinite(image)]if finite.size == 0:keys = ("min","max","mean","std","p10","p25","p50","p75","p90","iqr",)return {f"{prefix}_{key}": float("nan") for key in keys}percentiles = np.percentile(finite, [10, 25, 50, 75, 90])return {f"{prefix}_min": float(finite.min()),f"{prefix}_max": float(finite.max()),f"{prefix}_mean": float(finite.mean()),f"{prefix}_std": float(finite.std()),f"{prefix}_p10": float(percentiles[0]),f"{prefix}_p25": float(percentiles[1]),f"{prefix}_p50": float(percentiles[2]),f"{prefix}_p75": float(percentiles[3]),f"{prefix}_p90": float(percentiles[4]),f"{prefix}_iqr": float(percentiles[3] - percentiles[1]),}def _cold_coverage(image: np.ndarray, thresholds: tuple[float, ...]) -> dict[str, float]:finite = image[np.isfinite(image)]out: dict[str, float] = {}for threshold in thresholds:key = f"cold_frac_{_token(threshold)}"if finite.size == 0:out[key] = float("nan")else:out[key] = float(np.mean(finite < threshold))return outdef _radial_and_eye(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:height, width = image.shapeyy, xx = np.mgrid[0:height, 0:width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0radius = np.hypot(yy - center_y, xx - center_x)max_radius = max(float(radius.max()), 1e-6)edges = np.linspace(0.0, max_radius + 1e-6, spec.radial_bins + 1)out: dict[str, float] = {}for index in range(spec.radial_bins):mask = (radius >= edges[index]) & (radius < edges[index + 1]) & np.isfinite(image)out[f"radial_mean_{index:02d}"] = (float(image[mask].mean()) if mask.any() else float("nan"))half = min(height, width) / 2.0eye = radius <= spec.eye_radius_fraction * halfannulus = (radius > spec.eye_radius_fraction * half) & (radius <= spec.cdo_outer_fraction * half)eye_values = image[eye & np.isfinite(image)]annulus_values = image[annulus & np.isfinite(image)]eye_mean = float(eye_values.mean()) if eye_values.size else float("nan")annulus_mean = float(annulus_values.mean()) if annulus_values.size else float("nan")contrast = eye_mean - annulus_meaneye_present = (0.0if not np.isfinite(contrast)else float(contrast >= spec.eye_contrast_min))out["eye_center_mean"] = eye_meanout["cdo_annulus_mean"] = annulus_meanout["eye_cdo_contrast"] = float(contrast)out["eye_present"] = eye_presentreturn outdef _deviation_angle_variance(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:"""Circular variance of gradient angle minus radial angle. Not operational DAV."""height, width = image.shapeyy, xx = np.mgrid[0:height, 0:width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0dy = yy - center_ydx = xx - center_xradius = np.hypot(dy, dx)half = min(height, width) / 2.0gradient_y, gradient_x = np.gradient(image)magnitude = np.hypot(gradient_y, gradient_x)radial_angle = np.arctan2(dy, dx)gradient_angle = np.arctan2(gradient_y, gradient_x)deviation = np.arctan2(np.sin(gradient_angle - radial_angle),np.cos(gradient_angle - radial_angle),)# Keep the ring at least two pixels thick. On a small crop the fractional# width can otherwise fall between grid points and the statistic is empty.width_px = max(spec.dav_annulus_width_fraction * half, 2.0)out: dict[str, float] = {}for index, fraction in enumerate(spec.dav_radii_fractions):radius_px = fraction * halfannulus = (radius >= radius_px - width_px / 2.0) & (radius <= radius_px + width_px / 2.0)# A zero gradient has no direction. arctan2(0, 0) is 0 and would# look like a full circle of disagreement.selected = deviation[annulus & (magnitude > 1e-6)]if selected.size < 8:out[f"dav_simplified_r{index:02d}"] = float("nan")continuemean_vector = np.exp(1j * selected).mean()out[f"dav_simplified_r{index:02d}"] = float(1.0 - np.abs(mean_vector))return outdef _pair_counts(bins: np.ndarray, valid: np.ndarray, dy: int, dx: int, levels: int) -> np.ndarray | None:height, width = bins.shapeif abs(dy) >= height or abs(dx) >= width:return Noneif dy >= 0:src_y, dst_y = slice(0, height - dy), slice(dy, height)else:src_y, dst_y = slice(-dy, height), slice(0, height + dy)if dx >= 0:src_x, dst_x = slice(0, width - dx), slice(dx, width)else:src_x, dst_x = slice(-dx, width), slice(0, width + dx)mask = valid[src_y, src_x] & valid[dst_y, dst_x]if not mask.any():return Nonesource = bins[src_y, src_x][mask].ravel()dest = bins[dst_y, dst_x][mask].ravel()flat = source.astype(np.int64) * levels + dest.astype(np.int64)counts = np.bincount(flat, minlength=levels * levels).reshape(levels, levels)total = float(counts.sum())if total <= 0:return Nonereturn counts.astype(np.float64) / totaldef _haralick(probs: np.ndarray) -> dict[str, float]:levels = probs.shape[0]rows, cols = np.indices((levels, levels))contrast = float(((rows - cols) ** 2 * probs).sum())dissimilarity = float((np.abs(rows - cols) * probs).sum())homogeneity = float((probs / (1.0 + (rows - cols) ** 2)).sum())asm = float((probs**2).sum())energy = float(np.sqrt(asm))mean_i = float((rows * probs).sum())mean_j = float((cols * probs).sum())std_i = float(np.sqrt(((rows - mean_i) ** 2 * probs).sum()))std_j = float(np.sqrt(((cols - mean_j) ** 2 * probs).sum()))if std_i < 1e-12 or std_j < 1e-12:correlation = 0.0else:correlation = float(((rows - mean_i) * (cols - mean_j) * probs).sum() / (std_i * std_j))return {"glcm_contrast": contrast,"glcm_dissimilarity": dissimilarity,"glcm_homogeneity": homogeneity,"glcm_energy": energy,"glcm_correlation": correlation,"glcm_asm": asm,}def _glcm_features(image: np.ndarray, levels: int, distance: int) -> dict[str, float]:height, width = image.shapeempty = {name: float("nan") for name in GLCM_NAMES}if height <= distance or width <= distance:return emptyfinite = image[np.isfinite(image)]if finite.size == 0:return emptylow = float(finite.min())high = float(finite.max())if high - low < 1e-6:bins = np.zeros(image.shape, dtype=np.int32)else:scaled = np.clip((image - low) / (high - low), 0.0, 1.0)bins = np.minimum((scaled * levels).astype(np.int32), levels - 1)valid = np.isfinite(image)offsets = ((0, distance),(-distance, distance),(-distance, 0),(-distance, -distance),)collected = []for dy, dx in offsets:probs = _pair_counts(bins, valid, dy, dx, levels)if probs is not None:collected.append(_haralick(probs))if not collected:return emptyreturn {name: float(np.mean([item[name] for item in collected])) for name in GLCM_NAMES}def _haar_energies(image: np.ndarray) -> dict[str, float]:band = imageif band.shape[0] % 2:band = band[:-1, :]if band.shape[1] % 2:band = band[:, :-1]if min(band.shape) < 2:return {name: float("nan") for name in HAAR_NAMES}even_even = band[0::2, 0::2]even_odd = band[0::2, 1::2]odd_even = band[1::2, 0::2]odd_odd = band[1::2, 1::2]low_low = (even_even + even_odd + odd_even + odd_odd) / 4.0low_high = (even_even + odd_even - even_odd - odd_odd) / 4.0high_low = (even_even - odd_even + even_odd - odd_odd) / 4.0high_high = (even_even - odd_even - even_odd + odd_odd) / 4.0energies = {"haar_energy_ll": float(np.mean(low_low**2)),"haar_energy_lh": float(np.mean(low_high**2)),"haar_energy_hl": float(np.mean(high_low**2)),"haar_energy_hh": float(np.mean(high_high**2)),}total = sum(energies.values())if total <= 1e-12:return {name: 0.0 for name in HAAR_NAMES}return {name: value / total for name, value in energies.items()}def native_shape(image: np.ndarray) -> tuple[int, int]:"""Height and width of one crop. This is not ``data.image_size``."""channel = _single_channel(image)return int(channel.shape[0]), int(channel.shape[1])def extract_image_features(image: np.ndarray,spec: FeatureSpec,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> dict[str, float]:"""Features of one centered IR crop. The label is not an input.The crop is not resized. Callers that need the crop size use``native_shape``, which reads the array. ``data.image_size`` is not applied."""channel = _single_channel(image)fraction = missing_fraction(channel)if fraction > max_missing_fraction:raise ValueError(f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}")if not np.isfinite(channel).any():raise ValueError("image has no finite pixels")dense = _finite_fill(channel)features: dict[str, float] = {}features.update(_distribution(channel, spec.prefix))features.update(_cold_coverage(channel, spec.cold_thresholds))features.update(_radial_and_eye(channel, spec))features.update(_deviation_angle_variance(dense, spec))features.update(_glcm_features(dense, spec.glcm_levels, spec.glcm_distance))features.update(_haar_energies(dense))expected = spec.image_feature_names()missing = [name for name in expected if name not in features]if missing:raise RuntimeError(f"feature extractor omitted {missing}")return {name: float(features[name]) for name in expected}def _temporal_defaults(spec: FeatureSpec) -> dict[str, float]:prefix = spec.prefixreturn {"has_prev": 0.0,f"delta_{prefix}_mean": float("nan"),f"delta_{prefix}_min": float("nan"),"delta_cold_primary": float("nan"),"delta_eye_cdo_contrast": float("nan"),"delta_radial_mean_00": float("nan"),}# Optional frame labels. Copied when the manifest has them. Not model features._CARRIED_COLUMNS = ("timestamp","relative_time_s","source_split","wind_averaging","wind_averaging_s","on_fix","near_land","distance_to_land_km","cv_group",)def _extract_path(task: tuple[str, FeatureSpec, float]) -> dict[str, float]:"""Load one image and return its feature dict. Used by the worker pool."""path, spec, max_missing_fraction = taskreturn extract_image_features(load_image(path), spec, max_missing_fraction)def _spec_fingerprint(spec: FeatureSpec, max_missing_fraction: float) -> str:"""Identity of the extractor settings stored next to an image checkpoint."""payload = {"calibrated": bool(spec.calibrated),"cold_thresholds": [float(value) for value in spec.cold_thresholds],"radial_bins": int(spec.radial_bins),"eye_radius_fraction": float(spec.eye_radius_fraction),"cdo_outer_fraction": float(spec.cdo_outer_fraction),"eye_contrast_min": float(spec.eye_contrast_min),"dav_radii_fractions": [float(value) for value in spec.dav_radii_fractions],"dav_annulus_width_fraction": float(spec.dav_annulus_width_fraction),"glcm_levels": int(spec.glcm_levels),"glcm_distance": int(spec.glcm_distance),"max_missing_fraction": float(max_missing_fraction),}return json.dumps(payload, sort_keys=True)def _checkpoint_spec_path(path: Path) -> Path:return path.with_suffix(path.suffix + ".spec.json")def _image_checkpoint_rows(path: Path, spec: FeatureSpec, max_missing_fraction: float) -> dict[str, dict[str, float]]:if not path.is_file():return {}spec_path = _checkpoint_spec_path(path)if not spec_path.is_file():return {}saved_spec = json.loads(spec_path.read_text(encoding="utf-8"))if saved_spec.get("fingerprint") != _spec_fingerprint(spec, max_missing_fraction):return {}saved = pd.read_csv(path)if "sample_id" not in saved.columns:return {}rows: dict[str, dict[str, float]] = {}for record in saved.to_dict(orient="records"):sample_id = str(record.pop("sample_id"))rows[sample_id] = recordreturn rowsdef _write_image_checkpoint(path: Path,rows: dict[str, dict[str, float]],spec: FeatureSpec,max_missing_fraction: float,) -> None:records = [{"sample_id": sample_id, **features} for sample_id, features in rows.items()]path.parent.mkdir(parents=True, exist_ok=True)pd.DataFrame(records).to_csv(path, index=False)_checkpoint_spec_path(path).write_text(json.dumps({"fingerprint": _spec_fingerprint(spec, max_missing_fraction)},indent=2,sort_keys=True,)+ "\n",encoding="utf-8",)def extract_feature_table(frame: pd.DataFrame,manifest_path: str,spec: FeatureSpec,max_missing_fraction: float = MAX_MISSING_FRACTION,workers: int = 1,image_checkpoint: str | Path | None = None,) -> tuple[pd.DataFrame, int]:"""Extract features and same-split temporal deltas.Previous-frame ids are recomputed from ``storm_id`` and the observationclock (``timestamp``, else NASA ``relative_time_s``), then any link thatcrosses ``split`` is dropped before the delta is taken. ``workers`` above1 only parallelizes the per-image extract. It does not change the values.``image_checkpoint``, when set, stores per-image features so a restartedrun does not re-read frames that already finished. Temporal deltas arestill computed after every frame in this call has image features."""if "split" not in frame.columns:raise LeakageError("feature extraction requires a split column")if workers < 1:raise ValueError("workers must be at least 1")linked = add_previous_frame_id(frame)linked, dropped = null_cross_split_links(linked)rows_in = linked.to_dict(orient="records")tasks = [(str(resolve_image(manifest_path, str(row["image_path"]))), spec, max_missing_fraction)for row in rows_in]expected = spec.image_feature_names()checkpoint = Path(image_checkpoint) if image_checkpoint else Nonestored = (_image_checkpoint_rows(checkpoint, spec, max_missing_fraction) if checkpoint else {})extracted: list[dict[str, float] | None] = [None] * len(rows_in)pending: list[int] = []for index, row in enumerate(rows_in):sample_id = str(row["sample_id"])cached = stored.get(sample_id)if cached is not None and all(name in cached for name in expected):extracted[index] = {name: float(cached[name]) for name in expected}else:pending.append(index)if pending:logger.info("Extracting %s images (%s already cached)", len(pending), len(rows_in) - len(pending))def _finish(index: int) -> tuple[int, dict[str, float]]:return index, _extract_path(tasks[index])batch = 200if workers == 1:for start in range(0, len(pending), batch):chunk = pending[start : start + batch]for index in chunk:_index, features = _finish(index)extracted[_index] = featuresstored[str(rows_in[_index]["sample_id"])] = featuresif checkpoint:_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))else:from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=workers) as pool:for start in range(0, len(pending), batch):chunk = pending[start : start + batch]for index, features in pool.map(_finish, chunk):extracted[index] = featuresstored[str(rows_in[index]["sample_id"])] = featuresif checkpoint:_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))if any(item is None for item in extracted):raise RuntimeError("image feature extraction left a row empty")cache: dict[str, tuple[str, dict[str, float]]] = {}packed: list[tuple[dict[str, object], dict[str, float]]] = []for row, image_features in zip(rows_in, extracted, strict=True):sample_id = str(row["sample_id"])cache[sample_id] = (str(row["split"]), image_features)packed.append((row, image_features))prefix = spec.prefixcold_key = f"cold_frac_{_token(spec.cold_thresholds[0])}"rows: list[dict[str, object]] = []for row, image_features in packed:temporal = _temporal_defaults(spec)prev = row.get("prev_sample_id")if not pd.isna(prev) and str(prev) in cache:prev_split, previous = cache[str(prev)]if prev_split != str(row["split"]):raise LeakageError(f"temporal feature for {row['sample_id']} crossed a split")temporal["has_prev"] = 1.0temporal[f"delta_{prefix}_mean"] = (image_features[f"{prefix}_mean"] - previous[f"{prefix}_mean"])temporal[f"delta_{prefix}_min"] = (image_features[f"{prefix}_min"] - previous[f"{prefix}_min"])temporal["delta_cold_primary"] = image_features[cold_key] - previous[cold_key]temporal["delta_eye_cdo_contrast"] = (image_features["eye_cdo_contrast"] - previous["eye_cdo_contrast"])temporal["delta_radial_mean_00"] = (image_features["radial_mean_00"] - previous["radial_mean_00"])klass = row.get("imd5_class")if pd.isna(klass):klass = wind_to_imd5(float(row["wind_speed_kt"]))built: dict[str, object] = {"sample_id": str(row["sample_id"]),"storm_id": str(row["storm_id"]),"split": str(row["split"]),"wind_speed_kt": float(row["wind_speed_kt"]),"imd5_class": klass,}if "is_synthetic" in row:built["is_synthetic"] = parse_is_synthetic(row["is_synthetic"])for column in _CARRIED_COLUMNS:if column in row:built[column] = row[column]built.update(image_features)built.update(temporal)rows.append(built)table = pd.DataFrame(rows)assert_no_forbidden_inputs(spec.feature_names(), "feature names include labels")return table, droppeddef model_matrix(frame: pd.DataFrame, names: tuple[str, ...] | list[str]) -> np.ndarray:"""Numeric feature matrix. Raises if a label column is requested."""assert_no_forbidden_inputs(names, "forbidden features in model matrix")missing = [name for name in names if name not in frame.columns]if missing:raise KeyError(f"missing feature columns: {missing}")return frame.loc[:, list(names)].to_numpy(dtype=np.float64)def _impute_matrix(values: np.ndarray) -> np.ndarray:imputer = SimpleImputer(strategy="median", keep_empty_features=True)filled = imputer.fit_transform(values)return np.where(np.isfinite(filled), filled, 0.0)def _training_view(frame: pd.DataFrame, target: np.ndarray) -> tuple[pd.DataFrame, np.ndarray, frozenset[str]]:"""Rows whose storm is in the train side of ``storm_ids_by_split``.Val and test rows stay in ``frame`` so a caller can pass a full manifest,and they are dropped before any selection statistic is computed. A stormthat sits in two splits raises ``LeakageError``."""if "storm_id" not in frame.columns or "split" not in frame.columns:raise LeakageError("feature selection requires storm_id and split")y = np.asarray(target, dtype=np.float64).ravel()if len(y) != len(frame):raise ValueError("target must align with the selection frame")groups = storm_ids_by_split(frame)train_ids = groups["train"]if not train_ids:raise LeakageError("feature selection needs at least one training storm")mask = frame["storm_id"].astype(str).isin(train_ids).to_numpy()mask = mask & (frame["split"].astype(str) == "train").to_numpy()train = frame.loc[mask].reset_index(drop=True)if train.empty:raise LeakageError("feature selection needs at least one training storm")return train, y[mask], train_idsdef select_features(frame: pd.DataFrame,feature_names: tuple[str, ...] | list[str],target: np.ndarray,*,source_split: str,correlation_threshold: float = 0.95,max_features: int = 25,method: str = "correlation_rf",n_estimators: int = 40,seed: int = 42,) -> FeatureSelection:"""Fit a correlation filter and RF importance or RFE on train storms.Correlation filtering does not look at the label. Forest importance andRFE do. Both see only the storms ``storm_ids_by_split`` assigns to train.Changing val or test rows does not change the returned names."""if source_split != "train":raise LeakageError("feature selection is allowed on the train split only")names = tuple(feature_names)assert_no_forbidden_inputs(names, "forbidden features in selection")train, y, train_storms = _training_view(frame, target)if len(train) < 5:raise ValueError("feature selection needs at least 5 training rows")method = method.lower().strip()if method not in {"correlation_rf", "rfe", "none"}:raise ValueError(f"unknown selection method: {method}")values = _impute_matrix(model_matrix(train, names))variance = values.var(axis=0)kept_mask = variance > 1e-8dropped_variance = tuple(name for name, keep in zip(names, kept_mask, strict=True) if not keep)kept_names = [name for name, keep in zip(names, kept_mask, strict=True) if keep]kept_values = values[:, kept_mask]if not kept_names:raise ValueError("every candidate feature was constant on the train split")dropped_correlation: list[str] = []if method in {"correlation_rf", "rfe", "none"} and len(kept_names) > 1:corr = np.corrcoef(kept_values, rowvar=False)corr = np.where(np.isfinite(corr), corr, 0.0)drop_flags = np.zeros(len(kept_names), dtype=bool)for left in range(len(kept_names)):if drop_flags[left]:continuefor right in range(left + 1, len(kept_names)):if drop_flags[right]:continueif abs(corr[left, right]) > correlation_threshold:drop_flags[right] = Truedropped_correlation.append(kept_names[right])kept_names = [name for name, drop in zip(kept_names, drop_flags, strict=True) if not drop]kept_values = kept_values[:, ~drop_flags]cap = max(1, int(max_features))if method == "none":chosen = kept_names[:cap]importances: dict[str, float] = {}elif method == "correlation_rf":rank_cap = cap if len(kept_names) > cap else len(kept_names)ranked, importances = _rank_by_forest(kept_values, y, kept_names, rank_cap, n_estimators, seed)chosen = ranked if len(kept_names) > cap else kept_nameselse:chosen, importances = _rank_by_rfe(kept_values, y, kept_names, min(cap, len(kept_names)), n_estimators, seed)return FeatureSelection(names=tuple(chosen),source_split=source_split,importances=importances,dropped_variance=dropped_variance,dropped_correlation=tuple(dropped_correlation),train_storms=train_storms,)def _rank_by_forest(values: np.ndarray,target: np.ndarray,names: list[str],cap: int,n_estimators: int,seed: int,) -> tuple[list[str], dict[str, float]]:forest = RandomForestRegressor(n_estimators=max(10, int(n_estimators)),max_depth=4,random_state=seed,n_jobs=1,)forest.fit(values, target)importance = np.asarray(forest.feature_importances_, dtype=np.float64)order = sorted(range(len(names)),key=lambda index: (-importance[index], names[index]),)chosen = [names[index] for index in order[:cap]]return chosen, {names[index]: float(importance[index]) for index in order}def _rank_by_rfe(values: np.ndarray,target: np.ndarray,names: list[str],cap: int,n_estimators: int,seed: int,) -> tuple[list[str], dict[str, float]]:forest = RandomForestRegressor(n_estimators=max(10, int(n_estimators)),max_depth=4,random_state=seed,n_jobs=1,)step = max(1, len(names) // 10)selector = RFE(forest,n_features_to_select=max(1, min(cap, len(names))),step=step,)selector.fit(values, target)ranking = np.asarray(selector.ranking_)chosen = [name for name, keep in zip(names, selector.support_, strict=True) if keep]importance = {name: float(1.0 / rank) for name, rank in zip(names, ranking, strict=True)}return chosen, importance123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899"""Physically motivated image features for classical intensity baselines.Distributional statistics are called ``tb_*`` only when the caller has set``features.calibrated``. Otherwise they are ``pixel_*``. Nothing here convertsdigital numbers to brightness temperature.The simplified DAV terms are the circular variance of the angle between theimage gradient and the radial direction, at fixed fractions of the crophalf-width. That is not operational deviation-angle variance: there is noradius search, no flight-level wind, and no agency radius product.Radial, eye, and DAV features assume the storm is already near the imagecenter. This module does not recenter with a best-track fix.Temporal deltas use the previous frame of the same storm after cross-splitlinks have been removed. Wind, R34, RMW, and class labels are not features.Crop height and width are the array shape. ``data.image_size`` may be``native`` or a square resize for the deep model. It is not applied here.Feature selection calls``storm_ids_by_split`` and fits only the training storms."""from __future__ import annotationsimport jsonimport loggingfrom dataclasses import dataclassfrom pathlib import Pathimport numpy as npimport pandas as pdfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.feature_selection import RFEfrom sklearn.impute import SimpleImputerfrom src.data_loader import load_image, resolve_imagefrom src.preprocessing import MAX_MISSING_FRACTION, as_channel_first, missing_fractionfrom src.schema import FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5from src.splits import (LeakageError,add_previous_frame_id,assert_no_forbidden_inputs,null_cross_split_links,storm_ids_by_split,)logger = logging.getLogger(__name__)GLCM_NAMES = ("glcm_contrast","glcm_dissimilarity","glcm_homogeneity","glcm_energy","glcm_correlation","glcm_asm",)HAAR_NAMES = ("haar_energy_ll","haar_energy_lh","haar_energy_hl","haar_energy_hh",)EYE_NAMES = ("eye_center_mean","cdo_annulus_mean","eye_cdo_contrast","eye_present",)@dataclass(frozen=True)class FeatureSpec:"""Geometry of one feature vector. Thresholds are in image units."""calibrated: bool = Falsecold_thresholds: tuple[float, ...] = (200.0, 210.0, 220.0, 230.0, 240.0)radial_bins: int = 8eye_radius_fraction: float = 0.12cdo_outer_fraction: float = 0.35eye_contrast_min: float = 2.0dav_radii_fractions: tuple[float, ...] = (0.15, 0.30, 0.45, 0.60)dav_annulus_width_fraction: float = 0.08glcm_levels: int = 16glcm_distance: int = 1def __post_init__(self) -> None:if not self.cold_thresholds:raise ValueError("cold_thresholds must not be empty")if self.radial_bins < 2:raise ValueError("radial_bins must be at least 2")if not 0 < self.eye_radius_fraction < self.cdo_outer_fraction <= 1:raise ValueError("eye radius must sit inside the CDO annulus")if self.eye_contrast_min < 0:raise ValueError("eye_contrast_min must be >= 0")if any(not 0 < radius < 1 for radius in self.dav_radii_fractions):raise ValueError("DAV radii must be fractions of the half-width")if not 0 < self.dav_annulus_width_fraction < 0.5:raise ValueError("DAV annulus width fraction is out of range")if not 8 <= self.glcm_levels <= 32:raise ValueError("glcm_levels must be between 8 and 32")if self.glcm_distance < 1:raise ValueError("glcm_distance must be >= 1")@propertydef prefix(self) -> str:return "tb" if self.calibrated else "pixel"@classmethoddef from_config(cls, config: dict) -> FeatureSpec:raw = config.get("features")if not isinstance(raw, dict):raise KeyError("config features is required")required = ("calibrated","cold_thresholds","radial_bins","eye_radius_fraction","cdo_outer_fraction","eye_contrast_min","dav_radii_fractions","dav_annulus_width_fraction","glcm_levels","glcm_distance",)missing = [key for key in required if key not in raw]if missing:raise KeyError(f"config features missing {missing}")return cls(calibrated=bool(raw["calibrated"]),cold_thresholds=tuple(float(value) for value in raw["cold_thresholds"]),radial_bins=int(raw["radial_bins"]),eye_radius_fraction=float(raw["eye_radius_fraction"]),cdo_outer_fraction=float(raw["cdo_outer_fraction"]),eye_contrast_min=float(raw["eye_contrast_min"]),dav_radii_fractions=tuple(float(value) for value in raw["dav_radii_fractions"]),dav_annulus_width_fraction=float(raw["dav_annulus_width_fraction"]),glcm_levels=int(raw["glcm_levels"]),glcm_distance=int(raw["glcm_distance"]),)def feature_groups(self) -> dict[str, tuple[str, ...]]:"""Feature names by group.``pixel_stats`` are order statistics of the stored image values.They are not brightness temperature unless ``calibrated`` is set,in which case the same slots use the ``tb_`` prefix.``dav_simplified`` is gradient-angle variance, not operational DAV."""prefix = self.prefixreturn {"pixel_stats": (f"{prefix}_min",f"{prefix}_max",f"{prefix}_mean",f"{prefix}_std",f"{prefix}_p10",f"{prefix}_p25",f"{prefix}_p50",f"{prefix}_p75",f"{prefix}_p90",f"{prefix}_iqr",),"cold_cloud": tuple(f"cold_frac_{_token(threshold)}" for threshold in self.cold_thresholds),"radial": tuple(f"radial_mean_{index:02d}" for index in range(self.radial_bins)),"eye_cdo": EYE_NAMES,"dav_simplified": tuple(f"dav_simplified_r{index:02d}" for index in range(len(self.dav_radii_fractions))),"glcm": GLCM_NAMES,"haar": HAAR_NAMES,"temporal": ("has_prev",f"delta_{prefix}_mean",f"delta_{prefix}_min","delta_cold_primary","delta_eye_cdo_contrast","delta_radial_mean_00",),}def image_feature_names(self) -> tuple[str, ...]:groups = self.feature_groups()names: list[str] = []for key in ("pixel_stats","cold_cloud","radial","eye_cdo","dav_simplified","glcm","haar",):names.extend(groups[key])return tuple(names)def feature_names(self) -> tuple[str, ...]:return self.image_feature_names() + self.feature_groups()["temporal"]@dataclass(frozen=True)class FeatureSelection:names: tuple[str, ...]source_split: strimportances: dict[str, float]dropped_variance: tuple[str, ...]dropped_correlation: tuple[str, ...]train_storms: frozenset[str] = frozenset()def _token(value: float) -> str:number = float(value)if number.is_integer():return str(int(number))return str(number).replace("-", "m").replace(".", "p")def _single_channel(image: np.ndarray) -> np.ndarray:return as_channel_first(image)[0]def _finite_fill(image: np.ndarray) -> np.ndarray:filled = np.array(image, dtype=np.float64, copy=True)finite = np.isfinite(filled)fill = float(np.median(filled[finite])) if finite.any() else 0.0filled[~finite] = fillreturn filleddef _distribution(image: np.ndarray, prefix: str) -> dict[str, float]:finite = image[np.isfinite(image)]if finite.size == 0:keys = ("min","max","mean","std","p10","p25","p50","p75","p90","iqr",)return {f"{prefix}_{key}": float("nan") for key in keys}percentiles = np.percentile(finite, [10, 25, 50, 75, 90])return {f"{prefix}_min": float(finite.min()),f"{prefix}_max": float(finite.max()),f"{prefix}_mean": float(finite.mean()),f"{prefix}_std": float(finite.std()),f"{prefix}_p10": float(percentiles[0]),f"{prefix}_p25": float(percentiles[1]),f"{prefix}_p50": float(percentiles[2]),f"{prefix}_p75": float(percentiles[3]),f"{prefix}_p90": float(percentiles[4]),f"{prefix}_iqr": float(percentiles[3] - percentiles[1]),}def _cold_coverage(image: np.ndarray, thresholds: tuple[float, ...]) -> dict[str, float]:finite = image[np.isfinite(image)]out: dict[str, float] = {}for threshold in thresholds:key = f"cold_frac_{_token(threshold)}"if finite.size == 0:out[key] = float("nan")else:out[key] = float(np.mean(finite < threshold))return outdef _radial_and_eye(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:height, width = image.shapeyy, xx = np.mgrid[0:height, 0:width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0radius = np.hypot(yy - center_y, xx - center_x)max_radius = max(float(radius.max()), 1e-6)edges = np.linspace(0.0, max_radius + 1e-6, spec.radial_bins + 1)out: dict[str, float] = {}for index in range(spec.radial_bins):mask = (radius >= edges[index]) & (radius < edges[index + 1]) & np.isfinite(image)out[f"radial_mean_{index:02d}"] = (float(image[mask].mean()) if mask.any() else float("nan"))half = min(height, width) / 2.0eye = radius <= spec.eye_radius_fraction * halfannulus = (radius > spec.eye_radius_fraction * half) & (radius <= spec.cdo_outer_fraction * half)eye_values = image[eye & np.isfinite(image)]annulus_values = image[annulus & np.isfinite(image)]eye_mean = float(eye_values.mean()) if eye_values.size else float("nan")annulus_mean = float(annulus_values.mean()) if annulus_values.size else float("nan")contrast = eye_mean - annulus_meaneye_present = (0.0if not np.isfinite(contrast)else float(contrast >= spec.eye_contrast_min))out["eye_center_mean"] = eye_meanout["cdo_annulus_mean"] = annulus_meanout["eye_cdo_contrast"] = float(contrast)out["eye_present"] = eye_presentreturn outdef _deviation_angle_variance(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:"""Circular variance of gradient angle minus radial angle. Not operational DAV."""height, width = image.shapeyy, xx = np.mgrid[0:height, 0:width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0dy = yy - center_ydx = xx - center_xradius = np.hypot(dy, dx)half = min(height, width) / 2.0gradient_y, gradient_x = np.gradient(image)magnitude = np.hypot(gradient_y, gradient_x)radial_angle = np.arctan2(dy, dx)gradient_angle = np.arctan2(gradient_y, gradient_x)deviation = np.arctan2(np.sin(gradient_angle - radial_angle),np.cos(gradient_angle - radial_angle),)# Keep the ring at least two pixels thick. On a small crop the fractional# width can otherwise fall between grid points and the statistic is empty.width_px = max(spec.dav_annulus_width_fraction * half, 2.0)out: dict[str, float] = {}for index, fraction in enumerate(spec.dav_radii_fractions):radius_px = fraction * halfannulus = (radius >= radius_px - width_px / 2.0) & (radius <= radius_px + width_px / 2.0)# A zero gradient has no direction. arctan2(0, 0) is 0 and would# look like a full circle of disagreement.selected = deviation[annulus & (magnitude > 1e-6)]if selected.size < 8:out[f"dav_simplified_r{index:02d}"] = float("nan")continuemean_vector = np.exp(1j * selected).mean()out[f"dav_simplified_r{index:02d}"] = float(1.0 - np.abs(mean_vector))return outdef _pair_counts(bins: np.ndarray, valid: np.ndarray, dy: int, dx: int, levels: int) -> np.ndarray | None:height, width = bins.shapeif abs(dy) >= height or abs(dx) >= width:return Noneif dy >= 0:src_y, dst_y = slice(0, height - dy), slice(dy, height)else:src_y, dst_y = slice(-dy, height), slice(0, height + dy)if dx >= 0:src_x, dst_x = slice(0, width - dx), slice(dx, width)else:src_x, dst_x = slice(-dx, width), slice(0, width + dx)mask = valid[src_y, src_x] & valid[dst_y, dst_x]if not mask.any():return Nonesource = bins[src_y, src_x][mask].ravel()dest = bins[dst_y, dst_x][mask].ravel()flat = source.astype(np.int64) * levels + dest.astype(np.int64)counts = np.bincount(flat, minlength=levels * levels).reshape(levels, levels)total = float(counts.sum())if total <= 0:return Nonereturn counts.astype(np.float64) / totaldef _haralick(probs: np.ndarray) -> dict[str, float]:levels = probs.shape[0]rows, cols = np.indices((levels, levels))contrast = float(((rows - cols) ** 2 * probs).sum())dissimilarity = float((np.abs(rows - cols) * probs).sum())homogeneity = float((probs / (1.0 + (rows - cols) ** 2)).sum())asm = float((probs**2).sum())energy = float(np.sqrt(asm))mean_i = float((rows * probs).sum())mean_j = float((cols * probs).sum())std_i = float(np.sqrt(((rows - mean_i) ** 2 * probs).sum()))std_j = float(np.sqrt(((cols - mean_j) ** 2 * probs).sum()))if std_i < 1e-12 or std_j < 1e-12:correlation = 0.0else:correlation = float(((rows - mean_i) * (cols - mean_j) * probs).sum() / (std_i * std_j))return {"glcm_contrast": contrast,"glcm_dissimilarity": dissimilarity,"glcm_homogeneity": homogeneity,"glcm_energy": energy,"glcm_correlation": correlation,"glcm_asm": asm,}def _glcm_features(image: np.ndarray, levels: int, distance: int) -> dict[str, float]:height, width = image.shapeempty = {name: float("nan") for name in GLCM_NAMES}if height <= distance or width <= distance:return emptyfinite = image[np.isfinite(image)]if finite.size == 0:return emptylow = float(finite.min())high = float(finite.max())if high - low < 1e-6:bins = np.zeros(image.shape, dtype=np.int32)else:scaled = np.clip((image - low) / (high - low), 0.0, 1.0)bins = np.minimum((scaled * levels).astype(np.int32), levels - 1)valid = np.isfinite(image)offsets = ((0, distance),(-distance, distance),(-distance, 0),(-distance, -distance),)collected = []for dy, dx in offsets:probs = _pair_counts(bins, valid, dy, dx, levels)if probs is not None:collected.append(_haralick(probs))if not collected:return emptyreturn {name: float(np.mean([item[name] for item in collected])) for name in GLCM_NAMES}def _haar_energies(image: np.ndarray) -> dict[str, float]:band = imageif band.shape[0] % 2:band = band[:-1, :]if band.shape[1] % 2:band = band[:, :-1]if min(band.shape) < 2:return {name: float("nan") for name in HAAR_NAMES}even_even = band[0::2, 0::2]even_odd = band[0::2, 1::2]odd_even = band[1::2, 0::2]odd_odd = band[1::2, 1::2]low_low = (even_even + even_odd + odd_even + odd_odd) / 4.0low_high = (even_even + odd_even - even_odd - odd_odd) / 4.0high_low = (even_even - odd_even + even_odd - odd_odd) / 4.0high_high = (even_even - odd_even - even_odd + odd_odd) / 4.0energies = {"haar_energy_ll": float(np.mean(low_low**2)),"haar_energy_lh": float(np.mean(low_high**2)),"haar_energy_hl": float(np.mean(high_low**2)),"haar_energy_hh": float(np.mean(high_high**2)),}total = sum(energies.values())if total <= 1e-12:return {name: 0.0 for name in HAAR_NAMES}return {name: value / total for name, value in energies.items()}def native_shape(image: np.ndarray) -> tuple[int, int]:"""Height and width of one crop. This is not ``data.image_size``."""channel = _single_channel(image)return int(channel.shape[0]), int(channel.shape[1])def extract_image_features(image: np.ndarray,spec: FeatureSpec,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> dict[str, float]:"""Features of one centered IR crop. The label is not an input.The crop is not resized. Callers that need the crop size use``native_shape``, which reads the array. ``data.image_size`` is not applied."""channel = _single_channel(image)fraction = missing_fraction(channel)if fraction > max_missing_fraction:raise ValueError(f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}")if not np.isfinite(channel).any():raise ValueError("image has no finite pixels")dense = _finite_fill(channel)features: dict[str, float] = {}features.update(_distribution(channel, spec.prefix))features.update(_cold_coverage(channel, spec.cold_thresholds))features.update(_radial_and_eye(channel, spec))features.update(_deviation_angle_variance(dense, spec))features.update(_glcm_features(dense, spec.glcm_levels, spec.glcm_distance))features.update(_haar_energies(dense))expected = spec.image_feature_names()missing = [name for name in expected if name not in features]if missing:raise RuntimeError(f"feature extractor omitted {missing}")return {name: float(features[name]) for name in expected}def _temporal_defaults(spec: FeatureSpec) -> dict[str, float]:prefix = spec.prefixreturn {"has_prev": 0.0,f"delta_{prefix}_mean": float("nan"),f"delta_{prefix}_min": float("nan"),"delta_cold_primary": float("nan"),"delta_eye_cdo_contrast": float("nan"),"delta_radial_mean_00": float("nan"),}# Optional frame labels. Copied when the manifest has them. Not model features._CARRIED_COLUMNS = ("timestamp","relative_time_s","source_split","wind_averaging","wind_averaging_s","on_fix","near_land","distance_to_land_km","cv_group",)def _extract_path(task: tuple[str, FeatureSpec, float]) -> dict[str, float]:"""Load one image and return its feature dict. Used by the worker pool."""path, spec, max_missing_fraction = taskreturn extract_image_features(load_image(path), spec, max_missing_fraction)def _spec_fingerprint(spec: FeatureSpec, max_missing_fraction: float) -> str:"""Identity of the extractor settings stored next to an image checkpoint."""payload = {"calibrated": bool(spec.calibrated),"cold_thresholds": [float(value) for value in spec.cold_thresholds],"radial_bins": int(spec.radial_bins),"eye_radius_fraction": float(spec.eye_radius_fraction),"cdo_outer_fraction": float(spec.cdo_outer_fraction),"eye_contrast_min": float(spec.eye_contrast_min),"dav_radii_fractions": [float(value) for value in spec.dav_radii_fractions],"dav_annulus_width_fraction": float(spec.dav_annulus_width_fraction),"glcm_levels": int(spec.glcm_levels),"glcm_distance": int(spec.glcm_distance),"max_missing_fraction": float(max_missing_fraction),}return json.dumps(payload, sort_keys=True)def _checkpoint_spec_path(path: Path) -> Path:return path.with_suffix(path.suffix + ".spec.json")def _image_checkpoint_rows(path: Path, spec: FeatureSpec, max_missing_fraction: float) -> dict[str, dict[str, float]]:if not path.is_file():return {}spec_path = _checkpoint_spec_path(path)if not spec_path.is_file():return {}saved_spec = json.loads(spec_path.read_text(encoding="utf-8"))if saved_spec.get("fingerprint") != _spec_fingerprint(spec, max_missing_fraction):return {}saved = pd.read_csv(path)if "sample_id" not in saved.columns:return {}rows: dict[str, dict[str, float]] = {}for record in saved.to_dict(orient="records"):sample_id = str(record.pop("sample_id"))rows[sample_id] = recordreturn rowsdef _write_image_checkpoint(path: Path,rows: dict[str, dict[str, float]],spec: FeatureSpec,max_missing_fraction: float,) -> None:records = [{"sample_id": sample_id, **features} for sample_id, features in rows.items()]path.parent.mkdir(parents=True, exist_ok=True)pd.DataFrame(records).to_csv(path, index=False)_checkpoint_spec_path(path).write_text(json.dumps({"fingerprint": _spec_fingerprint(spec, max_missing_fraction)},indent=2,sort_keys=True,)+ "\n",encoding="utf-8",)def extract_feature_table(frame: pd.DataFrame,manifest_path: str,spec: FeatureSpec,max_missing_fraction: float = MAX_MISSING_FRACTION,workers: int = 1,image_checkpoint: str | Path | None = None,) -> tuple[pd.DataFrame, int]:"""Extract features and same-split temporal deltas.Previous-frame ids are recomputed from ``storm_id`` and the observationclock (``timestamp``, else NASA ``relative_time_s``), then any link thatcrosses ``split`` is dropped before the delta is taken. ``workers`` above1 only parallelizes the per-image extract. It does not change the values.``image_checkpoint``, when set, stores per-image features so a restartedrun does not re-read frames that already finished. Temporal deltas arestill computed after every frame in this call has image features."""if "split" not in frame.columns:raise LeakageError("feature extraction requires a split column")if workers < 1:raise ValueError("workers must be at least 1")linked = add_previous_frame_id(frame)linked, dropped = null_cross_split_links(linked)rows_in = linked.to_dict(orient="records")tasks = [(str(resolve_image(manifest_path, str(row["image_path"]))), spec, max_missing_fraction)for row in rows_in]expected = spec.image_feature_names()checkpoint = Path(image_checkpoint) if image_checkpoint else Nonestored = (_image_checkpoint_rows(checkpoint, spec, max_missing_fraction) if checkpoint else {})extracted: list[dict[str, float] | None] = [None] * len(rows_in)pending: list[int] = []for index, row in enumerate(rows_in):sample_id = str(row["sample_id"])cached = stored.get(sample_id)if cached is not None and all(name in cached for name in expected):extracted[index] = {name: float(cached[name]) for name in expected}else:pending.append(index)if pending:logger.info("Extracting %s images (%s already cached)", len(pending), len(rows_in) - len(pending))def _finish(index: int) -> tuple[int, dict[str, float]]:return index, _extract_path(tasks[index])batch = 200if workers == 1:for start in range(0, len(pending), batch):chunk = pending[start : start + batch]for index in chunk:_index, features = _finish(index)extracted[_index] = featuresstored[str(rows_in[_index]["sample_id"])] = featuresif checkpoint:_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))else:from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(max_workers=workers) as pool:for start in range(0, len(pending), batch):chunk = pending[start : start + batch]for index, features in pool.map(_finish, chunk):extracted[index] = featuresstored[str(rows_in[index]["sample_id"])] = featuresif checkpoint:_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))if any(item is None for item in extracted):raise RuntimeError("image feature extraction left a row empty")cache: dict[str, tuple[str, dict[str, float]]] = {}packed: list[tuple[dict[str, object], dict[str, float]]] = []for row, image_features in zip(rows_in, extracted, strict=True):sample_id = str(row["sample_id"])cache[sample_id] = (str(row["split"]), image_features)packed.append((row, image_features))prefix = spec.prefixcold_key = f"cold_frac_{_token(spec.cold_thresholds[0])}"rows: list[dict[str, object]] = []for row, image_features in packed:temporal = _temporal_defaults(spec)prev = row.get("prev_sample_id")if not pd.isna(prev) and str(prev) in cache:prev_split, previous = cache[str(prev)]if prev_split != str(row["split"]):raise LeakageError(f"temporal feature for {row['sample_id']} crossed a split")temporal["has_prev"] = 1.0temporal[f"delta_{prefix}_mean"] = (image_features[f"{prefix}_mean"] - previous[f"{prefix}_mean"])temporal[f"delta_{prefix}_min"] = (image_features[f"{prefix}_min"] - previous[f"{prefix}_min"])temporal["delta_cold_primary"] = image_features[cold_key] - previous[cold_key]temporal["delta_eye_cdo_contrast"] = (image_features["eye_cdo_contrast"] - previous["eye_cdo_contrast"])temporal["delta_radial_mean_00"] = (image_features["radial_mean_00"] - previous["radial_mean_00"])klass = row.get("imd5_class")if pd.isna(klass):klass = wind_to_imd5(float(row["wind_speed_kt"]))built: dict[str, object] = {"sample_id": str(row["sample_id"]),"storm_id": str(row["storm_id"]),"split": str(row["split"]),"wind_speed_kt": float(row["wind_speed_kt"]),"imd5_class": klass,}if "is_synthetic" in row:built["is_synthetic"] = parse_is_synthetic(row["is_synthetic"])for column in _CARRIED_COLUMNS:if column in row:built[column] = row[column]built.update(image_features)built.update(temporal)rows.append(built)table = pd.DataFrame(rows)assert_no_forbidden_inputs(spec.feature_names(), "feature names include labels")return table, droppeddef model_matrix(frame: pd.DataFrame, names: tuple[str, ...] | list[str]) -> np.ndarray:"""Numeric feature matrix. Raises if a label column is requested."""assert_no_forbidden_inputs(names, "forbidden features in model matrix")missing = [name for name in names if name not in frame.columns]if missing:raise KeyError(f"missing feature columns: {missing}")return frame.loc[:, list(names)].to_numpy(dtype=np.float64)def _impute_matrix(values: np.ndarray) -> np.ndarray:imputer = SimpleImputer(strategy="median", keep_empty_features=True)filled = imputer.fit_transform(values)return np.where(np.isfinite(filled), filled, 0.0)def _training_view(frame: pd.DataFrame, target: np.ndarray) -> tuple[pd.DataFrame, np.ndarray, frozenset[str]]:"""Rows whose storm is in the train side of ``storm_ids_by_split``.Val and test rows stay in ``frame`` so a caller can pass a full manifest,and they are dropped before any selection statistic is computed. A stormthat sits in two splits raises ``LeakageError``."""if "storm_id" not in frame.columns or "split" not in frame.columns:raise LeakageError("feature selection requires storm_id and split")y = np.asarray(target, dtype=np.float64).ravel()if len(y) != len(frame):raise ValueError("target must align with the selection frame")groups = storm_ids_by_split(frame)train_ids = groups["train"]if not train_ids:raise LeakageError("feature selection needs at least one training storm")mask = frame["storm_id"].astype(str).isin(train_ids).to_numpy()mask = mask & (frame["split"].astype(str) == "train").to_numpy()train = frame.loc[mask].reset_index(drop=True)if train.empty:raise LeakageError("feature selection needs at least one training storm")return train, y[mask], train_idsdef select_features(frame: pd.DataFrame,feature_names: tuple[str, ...] | list[str],target: np.ndarray,*,source_split: str,correlation_threshold: float = 0.95,max_features: int = 25,method: str = "correlation_rf",n_estimators: int = 40,seed: int = 42,) -> FeatureSelection:"""Fit a correlation filter and RF importance or RFE on train storms.Correlation filtering does not look at the label. Forest importance andRFE do. Both see only the storms ``storm_ids_by_split`` assigns to train.Changing val or test rows does not change the returned names."""if source_split != "train":raise LeakageError("feature selection is allowed on the train split only")names = tuple(feature_names)assert_no_forbidden_inputs(names, "forbidden features in selection")train, y, train_storms = _training_view(frame, target)if len(train) < 5:raise ValueError("feature selection needs at least 5 training rows")method = method.lower().strip()if method not in {"correlation_rf", "rfe", "none"}:raise ValueError(f"unknown selection method: {method}")values = _impute_matrix(model_matrix(train, names))variance = values.var(axis=0)kept_mask = variance > 1e-8dropped_variance = tuple(name for name, keep in zip(names, kept_mask, strict=True) if not keep)kept_names = [name for name, keep in zip(names, kept_mask, strict=True) if keep]kept_values = values[:, kept_mask]if not kept_names:raise ValueError("every candidate feature was constant on the train split")dropped_correlation: list[str] = []if method in {"correlation_rf", "rfe", "none"} and len(kept_names) > 1:corr = np.corrcoef(kept_values, rowvar=False)corr = np.where(np.isfinite(corr), corr, 0.0)drop_flags = np.zeros(len(kept_names), dtype=bool)for left in range(len(kept_names)):if drop_flags[left]:continuefor right in range(left + 1, len(kept_names)):if drop_flags[right]:continueif abs(corr[left, right]) > correlation_threshold:drop_flags[right] = Truedropped_correlation.append(kept_names[right])kept_names = [name for name, drop in zip(kept_names, drop_flags, strict=True) if not drop]kept_values = kept_values[:, ~drop_flags]cap = max(1, int(max_features))if method == "none":chosen = kept_names[:cap]importances: dict[str, float] = {}elif method == "correlation_rf":rank_cap = cap if len(kept_names) > cap else len(kept_names)ranked, importances = _rank_by_forest(kept_values, y, kept_names, rank_cap, n_estimators, seed)chosen = ranked if len(kept_names) > cap else kept_nameselse:chosen, importances = _rank_by_rfe(kept_values, y, kept_names, min(cap, len(kept_names)), n_estimators, seed)return FeatureSelection(names=tuple(chosen),source_split=source_split,importances=importances,dropped_variance=dropped_variance,dropped_correlation=tuple(dropped_correlation),train_storms=train_storms,)def _rank_by_forest(values: np.ndarray,target: np.ndarray,names: list[str],cap: int,n_estimators: int,seed: int,) -> tuple[list[str], dict[str, float]]:forest = RandomForestRegressor(n_estimators=max(10, int(n_estimators)),max_depth=4,random_state=seed,n_jobs=1,)forest.fit(values, target)importance = np.asarray(forest.feature_importances_, dtype=np.float64)order = sorted(range(len(names)),key=lambda index: (-importance[index], names[index]),)chosen = [names[index] for index in order[:cap]]return chosen, {names[index]: float(importance[index]) for index in order}def _rank_by_rfe(values: np.ndarray,target: np.ndarray,names: list[str],cap: int,n_estimators: int,seed: int,) -> tuple[list[str], dict[str, float]]:forest = RandomForestRegressor(n_estimators=max(10, int(n_estimators)),max_depth=4,random_state=seed,n_jobs=1,)step = max(1, len(names) // 10)selector = RFE(forest,n_features_to_select=max(1, min(cap, len(names))),step=step,)selector.fit(values, target)ranking = np.asarray(selector.ranking_)chosen = [name for name, keep in zip(names, selector.support_, strict=True) if keep]importance = {name: float(1.0 / rank) for name, rank in zip(names, ranking, strict=True)}return chosen, importance
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778"""INCYDE loader for the cropped INSAT-3D North Indian Ocean set.Images come from the Zenodo 8015544 file ``Cropped_cyclone_data.zip``(MD5 ``ed5dac254c689e5a327dee7580324347``). This module never downloadsthat zip. Point ``paths.incyde_root`` at an extracted copy.Filename times are IST (UTC+05:30). ``Sequence`` in the labels CSV is thestorm key. The trailing ``obj`` index is not a storm id. The default splitand the exclusion list are ``incyde/audit/storm_split.csv`` and``incyde/audit/exclusions.csv``.``on_fix``, ``distance_to_land_km``, and ``near_land`` are joined from``incyde/audit/frame_flags.csv`` on the source filename. A ``rot_180``copy inherits that source row. A filename the table does not list staysunknown: ``on_fix`` is ``unknown``, the distance is null, and``near_land`` is ``unknown``. Those gaps are not filled with false orzero. The labels are already 3-minute winds, so the join does notrescale them. ``basin`` value ``LAND`` is the IMD basin of a landdepression, not a frame landfall.Only original frames and ``rot_180`` copies are kept. ``rot_180`` issynthetic, stays with its source storm, and is train-only. Flips reversecyclone spin. ``rot_90`` and ``rot_270`` add black bars. Both are dropped."""from __future__ import annotationsimport argparseimport hashlibimport refrom datetime import datetime, timedelta, timezonefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validfrom src.splits import LeakageErrorZIP_MD5 = "ed5dac254c689e5a327dee7580324347"WIND_AVERAGING = "3min"WIND_AVERAGING_S = 180CV_SEED = 42YEAR_HOLDOUT_NOTE = ("indicative only: different training years and images from ""Agrawal et al. 2024, arXiv:2410.08218. Landfall frames are kept; ""the audit outputs have no landfall flag.")KEPT_AUG = frozenset({"", "rot_180"})DROPPED_AUG = frozenset({"flip_h", "flip_v", "rot_90", "rot_270"})_IST = timezone(timedelta(hours=5, minutes=30))_MONTHS = {name: indexfor index, name in enumerate(("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),start=1,)}_FILENAME = re.compile(r"^(?P<day>\d{2})(?P<mon>[A-Za-z]{3})(?P<year>\d{4})_"r"(?P<hour>\d{2})(?P<minute>\d{2})_(?P<obj>\d+)"r"(?:_(?P<aug>flip_h|flip_v|rot_90|rot_180|rot_270))?\.jpe?g$",re.IGNORECASE,)_AUG_SUFFIX = re.compile(r"_(?:flip_h|flip_v|rot_90|rot_180|rot_270)(?=\.jpe?g$)",re.IGNORECASE,)_STORM_ID = re.compile(r"^INCYDE-S\d+_IMD-(?P<year>\d{4})-\d+$")_AUDIT_DIR = Path(__file__).resolve().parents[1] / "incyde" / "audit"DEFAULT_STORM_SPLIT = _AUDIT_DIR / "storm_split.csv"DEFAULT_EXCLUSIONS = _AUDIT_DIR / "exclusions.csv"DEFAULT_FRAME_FLAGS = _AUDIT_DIR / "frame_flags.csv"_FRAME_FLAG_COLUMNS = ("filename", "on_fix", "distance_to_land_km", "near_land")def imd_class_of(wind_kt: float) -> str:"""IMD class on a 3-minute wind, in knots.D ≤27, DD ≤33, CS ≤47, SCS ≤63, VSCS ≤89, ESCS ≤119, SuCS ≥120.Below 17 kt is ``<17``. These are not the project's 17/34/48/64/91 bins."""wind = float(wind_kt)if wind < 17:return "<17"if wind <= 27:return "D"if wind <= 33:return "DD"if wind <= 47:return "CS"if wind <= 63:return "SCS"if wind <= 89:return "VSCS"if wind <= 119:return "ESCS"return "SuCS"def storm_year(storm_id: object) -> int:"""Year from ``INCYDE-Sxx_IMD-yyyy-nnn``. Filename dates are not used."""match = _STORM_ID.match(str(storm_id).strip())if match is None:raise ValueError(f"storm_id {storm_id!r} is not INCYDE-Sxx_IMD-yyyy-nnn")return int(match.group("year"))def assert_one_storm_year(frame: pd.DataFrame) -> pd.Series:"""Each storm id maps to one IMD year. A filename that crosses 1 January does not add a second year."""years = frame["storm_id"].map(storm_year)counts = pd.DataFrame({"storm_id": frame["storm_id"].astype(str), "year": years}).groupby("storm_id")["year"].nunique()if bool((counts > 1).any()):raise LeakageError("a storm_id maps to more than one year")return yearsdef archive_md5(path: str | Path) -> str:"""MD5 of a local file. Does not download."""digest = hashlib.md5(usedforsecurity=False)with Path(path).open("rb") as handle:for chunk in iter(lambda: handle.read(1 << 20), b""):digest.update(chunk)return digest.hexdigest()def assert_archive_md5(path: str | Path) -> None:"""Refuse a cropped-zip copy whose MD5 is not the Zenodo value."""found = archive_md5(path)if found != ZIP_MD5:raise ValueError(f"INCYDE archive md5 is {found}, expected {ZIP_MD5}")def _optional_path(value: object, default: Path) -> Path:if value is None:return defaulttext = str(value).strip()if text.lower() in {"", "none", "null"}:return defaultreturn Path(text)def read_storm_split(path: str | Path | None = None) -> pd.DataFrame:"""One row per Sequence. ``proposed_split`` is Bean's grouped split."""table = pd.read_csv(_optional_path(path, DEFAULT_STORM_SPLIT))table.columns = [str(column).strip() for column in table.columns]required = {"Sequence", "storm_id", "proposed_split", "cooccurrence_group"}missing = sorted(required - set(table.columns))if missing:raise ValueError(f"storm_split.csv missing {missing}")out = table.copy()out["Sequence"] = pd.to_numeric(out["Sequence"], errors="raise").astype(int)out["storm_id"] = out["storm_id"].astype(str).str.strip()out["proposed_split"] = out["proposed_split"].astype(str).str.strip()out["cooccurrence_group"] = pd.to_numeric(out["cooccurrence_group"], errors="raise").astype(int)if out["storm_id"].duplicated().any() or out["Sequence"].duplicated().any():raise ValueError("storm_split.csv repeats a storm")bad = sorted(set(out["proposed_split"]) - {"train", "val", "test"})if bad:raise ValueError(f"storm_split.csv has unknown splits {bad}")assert_one_storm_year(out)return outdef read_exclusions(path: str | Path | None = None) -> pd.DataFrame:table = pd.read_csv(_optional_path(path, DEFAULT_EXCLUSIONS))table.columns = [str(column).strip() for column in table.columns]required = {"filename", "qc_flag", "default_exclude"}missing = sorted(required - set(table.columns))if missing:raise ValueError(f"exclusions.csv missing {missing}")out = table.copy()out["filename"] = out["filename"].astype(str).map(lambda name: Path(name).name)out["qc_flag"] = out["qc_flag"].fillna("").astype(str)out["default_exclude"] = [_is_true(value) for value in out["default_exclude"].tolist()]if out["filename"].duplicated().any():raise ValueError("exclusions.csv repeats a filename")return outdef _is_true(value: object) -> bool:if isinstance(value, (bool, np.bool_)):return bool(value)return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}def _blank_flag(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _on_fix_value(value: object) -> bool | str:"""Explicit bool, or ``unknown`` when the audit did not decide.``unknown`` is not stored as false. A later on-fix metric uses onlythe true rows."""if isinstance(value, (bool, np.bool_)):return bool(value)if _blank_flag(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return Trueif text in {"0", "false", "no", "n", "f"}:return Falseif text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"on_fix value {value!r} is not true, false, or unknown")def _near_land_token(value: object) -> str:"""``true``, ``false``, or ``unknown``. Blank stays unknown."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank_flag(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"near_land value {value!r} is not true, false, or unknown")def _distance_km(value: object) -> float:"""Kilometres, or NaN when the audit left the cell blank."""if _blank_flag(value):return float("nan")try:number = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from excif not np.isfinite(number):return float("nan")return numberdef read_frame_flags(path: str | Path | None = None) -> pd.DataFrame:"""Original-frame flags. Augmented filenames are not required in the file."""table = pd.read_csv(_optional_path(path, DEFAULT_FRAME_FLAGS))table.columns = [str(column).strip() for column in table.columns]missing = [column for column in _FRAME_FLAG_COLUMNS if column not in table.columns]if missing:raise ValueError(f"frame_flags.csv missing {missing}")on_fix = [_on_fix_value(value) for value in table["on_fix"].tolist()]out = pd.DataFrame({"filename": table["filename"].astype(str).map(lambda name: Path(name).name),"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],})# Object dtype so a homogeneous true/false column stays a Python bool# and an unknown cell is not coerced to false.out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)if out["filename"].duplicated().any():raise ValueError("frame_flags.csv repeats a filename")return outdef _flag_key(frame: pd.DataFrame) -> pd.Series:"""Source filename. Augmented copies inherit; they are not their own key."""if "source_frame_id" in frame.columns:return frame["source_frame_id"].astype(str).map(lambda name: Path(name).name)if "filename" in frame.columns:return frame["filename"].astype(str).map(lambda name: Path(_AUG_SUFFIX.sub("", name)).name)raise ValueError("frame flags need source_frame_id or filename")def attach_frame_flags(frame: pd.DataFrame, flags: pd.DataFrame) -> pd.DataFrame:"""Add ``on_fix``, ``distance_to_land_km``, and ``near_land``.The lookup key is the source filename, so a ``rot_180`` copy receivesthe original frame's row. A miss stays unknown. Distance is not filledwith 0, and ``on_fix`` is not filled with false."""lookup = flags.drop_duplicates("filename").set_index("filename")on_fix: list[object] = []distance: list[float] = []near: list[str] = []for key in _flag_key(frame).tolist():if key not in lookup.index:on_fix.append("unknown")distance.append(float("nan"))near.append("unknown")continuerow = lookup.loc[key]if isinstance(row, pd.DataFrame):raise ValueError(f"frame_flags.csv repeats {key}")on_fix.append(_on_fix_value(row["on_fix"]))distance.append(_distance_km(row["distance_to_land_km"]))near.append(_near_land_token(row["near_land"]))out = frame.copy()out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)out["distance_to_land_km"] = np.asarray(distance, dtype=float)out["near_land"] = nearreturn outdef parse_filename(filename: str) -> dict[str, object]:"""Parse ``DDMONYYYY_HHMM_<obj>[_aug].jpg``. ``obj`` is not a storm id."""name = Path(str(filename)).namematch = _FILENAME.match(name)if match is None:raise ValueError(f"INCYDE filename {name} does not match DDMONYYYY_HHMM_<obj>[_aug].jpg")parts = match.groupdict()month = _MONTHS.get(parts["mon"].upper())if month is None:raise ValueError(f"INCYDE filename {name} has an unknown month")ist = datetime(int(parts["year"]),month,int(parts["day"]),int(parts["hour"]),int(parts["minute"]),tzinfo=_IST,)utc = ist.astimezone(timezone.utc)aug = "" if not parts["aug"] else parts["aug"].lower()return {"filename": name,"time_ist": ist.isoformat(),"time_utc": utc.strftime("%Y-%m-%dT%H:%M:%SZ"),"object_index": int(parts["obj"]),"aug_type": aug,"source_frame_id": _AUG_SUFFIX.sub("", name),}def _source_table(frame: pd.DataFrame) -> pd.DataFrame:"""Labels CSV or the audit manifest, reduced to one column set."""columns = {str(column).strip(): column for column in frame.columns}renamed = frame.rename(columns={raw: clean for clean, raw in columns.items()})if "Sequence" in renamed.columns and ("MSWS kts" in renamed.columns or "label_kt" in renamed.columns):wind_column = "MSWS kts" if "MSWS kts" in renamed.columns else "label_kt"filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]out = pd.DataFrame({"sequence": pd.to_numeric(renamed["Sequence"], errors="raise").astype(int),"filename": filename.astype(str),"wind_kt": pd.to_numeric(renamed[wind_column], errors="coerce"),"source_category": renamed["Category"].astype(str) if "Category" in renamed.columns else "","incyde_set": renamed["Set"].astype(str) if "Set" in renamed.columns else "","given_storm_id": renamed["storm_id"].astype(str) if "storm_id" in renamed.columns else pd.NA,})return outif "storm_id" in renamed.columns and "label_kt" in renamed.columns:filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]sequence = renamed["incyde_sequence"] if "incyde_sequence" in renamed.columns else pd.Series(pd.NA, index=renamed.index)category = renamed["label_class_imd"] if "label_class_imd" in renamed.columns else ""return pd.DataFrame({"sequence": pd.to_numeric(sequence, errors="coerce"),"filename": filename.astype(str),"wind_kt": pd.to_numeric(renamed["label_kt"], errors="coerce"),"source_category": category.astype(str) if not isinstance(category, str) else category,"incyde_set": renamed["incyde_set"].astype(str) if "incyde_set" in renamed.columns else "","given_storm_id": renamed["storm_id"].astype(str),})raise ValueError("INCYDE manifest needs the labels columns (Sequence, MSWS kts, filename) ""or the audit columns (storm_id, label_kt, file)")def _locate_labels(root: Path) -> Path:candidates = [root / "Cropped_cyclone_labels.csv",root / "Cropped_cyclone_data" / "Cropped_cyclone_labels.csv",root / "labels.csv",]for path in candidates:if path.is_file():return pathraise FileNotFoundError(f"No INCYDE labels CSV under {root}. This loader does not download imagery.")def locate_image(root: Path, filename: str) -> Path:name = Path(filename).namecandidates = [root / name,root / "Cropped_cyclone_images" / name,root / "Cropped_cyclone_data" / "Cropped_cyclone_images" / name,root / "Cropped_cyclone_data" / name,]for path in candidates:if path.is_file():return pathraise FileNotFoundError(f"INCYDE image {name} is missing under {root}. This loader does not download imagery.")def _qc_tokens(flag: object) -> set[str]:text = "" if flag is None or (isinstance(flag, float) and np.isnan(flag)) else str(flag)return {part.strip() for part in text.split(";") if part.strip()}def _drop_reason(aug: str, exclude: bool, qc_flag: str, drop_qc_flags: set[str]) -> str | None:if exclude:return "default_exclude"if aug in DROPPED_AUG:return f"dropped aug {aug}"if aug not in KEPT_AUG:return f"unknown aug {aug or 'blank'}"if drop_qc_flags and _qc_tokens(qc_flag) & drop_qc_flags:return "drop_qc_flags"return Nonedef read_rows(root: str | Path,*,manifest_csv: str | Path | None = None,storm_split_csv: str | Path | None = None,exclusions_csv: str | Path | None = None,frame_flags_csv: str | Path | None = None,drop_qc_flags: list[str] | tuple[str, ...] | None = None,check_images: bool = True,) -> tuple[pd.DataFrame, int]:"""Frame rows before the final split. ``rot_180`` is still present.Flips, ``rot_90``, ``rot_270``, and ``default_exclude`` rows are gone.The returned count is how many source rows were dropped here."""root = Path(root)if not root.is_dir():raise FileNotFoundError(f"INCYDE root {root} is missing. Set paths.incyde_root to the extracted ""Cropped_cyclone_data directory. This entrypoint does not download imagery.")label_path = Path(manifest_csv) if manifest_csv not in (None, "", "null") else _locate_labels(root)if not label_path.is_file():raise FileNotFoundError(f"INCYDE manifest {label_path} is missing. Nothing is downloaded.")storms = read_storm_split(storm_split_csv)exclusions = read_exclusions(exclusions_csv)source = _source_table(pd.read_csv(label_path, encoding="utf-8-sig"))parsed = [parse_filename(name) for name in source["filename"].tolist()]parsed_frame = pd.DataFrame(parsed).drop(columns=["filename"])work = pd.concat([source.reset_index(drop=True), parsed_frame], axis=1)work["filename"] = work["filename"].map(lambda name: Path(str(name)).name)by_sequence = storms.set_index("Sequence")by_storm = storms.drop_duplicates("storm_id").set_index("storm_id")storm_ids: list[str] = []sequences: list[int] = []proposed: list[str] = []groups: list[int] = []names: list[str] = []basins: list[str] = []for sequence, given in zip(work["sequence"].tolist(), work["given_storm_id"].tolist(), strict=True):row = Noneif pd.notna(sequence) and int(sequence) in by_sequence.index:row = by_sequence.loc[int(sequence)]elif isinstance(given, str) and given in by_storm.index:row = by_storm.loc[given]if row is None:raise ValueError(f"no storm_split row for sequence {sequence!r} storm {given!r}")if isinstance(row, pd.DataFrame):raise ValueError(f"storm_split matched more than one row for sequence {sequence}")storm_id = str(row["storm_id"]) if "storm_id" in row.index else str(row.name)sequence_id = int(row["Sequence"]) if "Sequence" in row.index else int(row.name)if isinstance(given, str) and given not in {"", "nan", "<NA>"} and given != storm_id:raise ValueError(f"manifest storm_id {given} does not match storm_split.csv ({storm_id})")storm_ids.append(storm_id)sequences.append(sequence_id)proposed.append(str(row["proposed_split"]))groups.append(int(row["cooccurrence_group"]))names.append("" if "name" not in row.index or pd.isna(row["name"]) else str(row["name"]))basins.append("" if "basin" not in row.index or pd.isna(row["basin"]) else str(row["basin"]))work["storm_id"] = storm_idswork["sequence"] = sequenceswork["proposed_split"] = proposedwork["cooccurrence_group"] = groupswork["name"] = nameswork["basin"] = basinsqc = exclusions.set_index("filename")flags = []exclude = []for filename in work["filename"].tolist():if filename in qc.index:flags.append(str(qc.at[filename, "qc_flag"]))exclude.append(bool(qc.at[filename, "default_exclude"]))else:flags.append("")exclude.append(False)work["qc_flag"] = flagsdrop_flags = {str(flag).strip() for flag in (drop_qc_flags or []) if str(flag).strip()}reasons = [_drop_reason(aug, dropped, flag, drop_flags)for aug, dropped, flag in zip(work["aug_type"], exclude, work["qc_flag"], strict=True)]dropped_count = sum(reason is not None for reason in reasons)kept = work.loc[[reason is None for reason in reasons]].reset_index(drop=True)if kept.empty:raise ValueError("INCYDE filters removed every row")if kept["filename"].duplicated().any():raise ValueError("INCYDE labels repeat a filename")years = assert_one_storm_year(kept)image_paths: list[str] = []heights: list[int] = []widths: list[int] = []if check_images:from PIL import Imagefor filename in kept["filename"].tolist():path = locate_image(root, filename)image_paths.append(path.resolve().as_posix())with Image.open(path) as image:widths.append(int(image.width))heights.append(int(image.height))else:image_paths = kept["filename"].tolist()heights = [0] * len(kept)widths = [0] * len(kept)frame = pd.DataFrame({"sample_id": [Path(name).stem for name in kept["filename"].tolist()],"image_path": image_paths,"storm_id": kept["storm_id"].astype(str),"wind_speed_kt": kept["wind_kt"].to_numpy(dtype=float),"wind_kt": kept["wind_kt"].to_numpy(dtype=float),"wind_averaging": WIND_AVERAGING,"wind_averaging_s": WIND_AVERAGING_S,"is_synthetic": [aug == "rot_180" for aug in kept["aug_type"].tolist()],"imd_class": [imd_class_of(wind) for wind in kept["wind_kt"].tolist()],"split": kept["proposed_split"].astype(str),"proposed_split": kept["proposed_split"].astype(str),"cooccurrence_group": kept["cooccurrence_group"].astype(int),"time_utc": kept["time_utc"].astype(str),"time_ist": kept["time_ist"].astype(str),"storm_year": years.to_numpy(dtype=int),"aug_type": kept["aug_type"].astype(str),"source_frame_id": kept["source_frame_id"].astype(str),"object_index": kept["object_index"].astype(int),"qc_flag": kept["qc_flag"].astype(str),"incyde_sequence": kept["sequence"].astype(int),"incyde_set": kept["incyde_set"].astype(str),"source_category": kept["source_category"].astype(str),"name": kept["name"].astype(str),"basin": kept["basin"].astype(str),"native_height": heights,"native_width": widths,"orig_size": [height if height == width else -1 for height, width in zip(heights, widths, strict=True)],"sensor": "INSAT-3D","channel": "IR","pixel_units": "jpeg_uncalibrated","label_source": "incyde_imd_3min","center_source": "dataset_precentered",})# Join after the row filter so dropped augs are not looked up. The# source filename is the key; unknown audit cells stay unknown.flagged = attach_frame_flags(frame, read_frame_flags(frame_flags_csv))return require_valid(flagged), int(dropped_count)def build_cv_folds(storms: pd.DataFrame, n_folds: int, seed: int) -> pd.DataFrame:"""Storm-grouped folds over train+val only. Test storms are absent.Groups are shuffled with ``seed`` and dealt round-robin, so every stormin one ``cooccurrence_group`` shares a fold. The training path passes``incyde.cv_seed`` (42 in the YAML)."""folds = int(n_folds)if folds < 2:raise ValueError("incyde.n_folds must be at least 2")pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")if pool.empty:raise ValueError("storm_cv needs train and val storms")groups = sorted({int(group) for group in pool["cooccurrence_group"].tolist()})order = np.random.default_rng(int(seed)).permutation(len(groups))shuffled = [groups[int(index)] for index in order]group_fold = {group: index % folds for index, group in enumerate(shuffled)}out = pd.DataFrame({"storm_id": pool["storm_id"].astype(str).tolist(),"fold": [int(group_fold[int(group)]) for group in pool["cooccurrence_group"].tolist()],})return out.sort_values(["fold", "storm_id"]).reset_index(drop=True)def read_cv_folds(path: str | Path) -> pd.DataFrame:"""Use a folds file verbatim. Columns are ``storm_id`` and ``fold``."""table = pd.read_csv(path)table.columns = [str(column).strip() for column in table.columns]if "storm_id" not in table.columns or "fold" not in table.columns:raise ValueError("cv folds csv needs columns storm_id and fold")out = pd.DataFrame({"storm_id": table["storm_id"].astype(str).str.strip(),"fold": pd.to_numeric(table["fold"], errors="raise").astype(int),})if out["storm_id"].duplicated().any():raise ValueError("cv folds csv repeats a storm_id")return out.reset_index(drop=True)def validate_cv_folds(folds: pd.DataFrame, storms: pd.DataFrame) -> None:"""No test storm, and no cooccurrence group spread across folds."""test_ids = set(storms.loc[storms["proposed_split"].astype(str) == "test", "storm_id"].astype(str))listed = set(folds["storm_id"].astype(str))leaked = sorted(listed & test_ids)if leaked:raise LeakageError(f"cv folds include test storms {leaked[:8]}")pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")pool_ids = set(pool["storm_id"].astype(str))missing = sorted(pool_ids - listed)extra = sorted(listed - pool_ids)if missing:raise ValueError(f"cv folds omit train/val storms {missing[:8]}")if extra:raise ValueError(f"cv folds name storms that are not train/val {extra[:8]}")merged = pool.assign(storm_id=pool["storm_id"].astype(str)).merge(folds, on="storm_id", how="left")spread = merged.groupby("cooccurrence_group")["fold"].nunique()if bool((spread > 1).any()):groups = [int(group) for group in spread.index[spread > 1].tolist()]raise LeakageError(f"cooccurrence_group spans folds {groups[:8]}")def _folds_for(storms: pd.DataFrame, n_folds: int, seed: int, cv_folds_csv: str | Path | None) -> pd.DataFrame:if cv_folds_csv not in (None, "", "null"):folds = read_cv_folds(cv_folds_csv)else:folds = build_cv_folds(storms, n_folds, seed)validate_cv_folds(folds, storms)return foldsdef _assert_storms(frame: pd.DataFrame) -> None:per_storm = frame.groupby(frame["storm_id"].astype(str))["split"].nunique()if bool((per_storm > 1).any()):raise LeakageError("a storm is in more than one split")synthetic = frame["is_synthetic"].astype(bool) & frame["split"].astype(str).ne("train")if bool(synthetic.any()):raise LeakageError("synthetic INCYDE rows are train-only")bad_aug = sorted(set(frame["aug_type"].astype(str)) - KEPT_AUG)if bad_aug:raise LeakageError(f"INCYDE kept dropped augmentations {bad_aug}")def _assert_groups(frame: pd.DataFrame) -> None:spread = frame.groupby("cooccurrence_group")["split"].nunique()if bool((spread > 1).any()):raise LeakageError("a cooccurrence_group is in more than one split")def assign_incyde_split(frame: pd.DataFrame,strategy: str,*,n_folds: int = 5,cv_val_fold: int = 0,cv_seed: int = CV_SEED,cv_folds_csv: str | Path | None = None,) -> tuple[pd.DataFrame, int]:"""Write ``split`` and drop synthetic rows that are not in train.``storm_wise`` uses ``proposed_split`` (60/14/17 on the audit file).``storm_cv`` keeps test storms out of the folds. ``year_holdout_2019``puts 2019 in test and 2021 in val. The year comes from ``storm_id``."""name = str(strategy).strip().lower()work = frame.copy()if "proposed_split" not in work.columns:raise ValueError("INCYDE rows need proposed_split from storm_split.csv")storms = work.groupby("storm_id", as_index=False).agg(proposed_split=("proposed_split", "first"),cooccurrence_group=("cooccurrence_group", "first"),)assert_one_storm_year(work)if name in {"storm_wise", "proposed", "bean"}:work["split"] = work["proposed_split"].astype(str)_assert_groups(work)elif name == "storm_cv":using_file = cv_folds_csv not in (None, "", "null")folds = _folds_for(storms, n_folds, cv_seed, cv_folds_csv)chosen = int(cv_val_fold)if not using_file and (chosen < 0 or chosen >= int(n_folds)):raise ValueError("incyde.cv_val_fold is outside 0 .. n_folds-1")fold_of = dict(zip(folds["storm_id"].astype(str), folds["fold"].astype(int), strict=True))splits = []for storm_id, proposed in zip(work["storm_id"].astype(str), work["proposed_split"].astype(str), strict=True):if proposed == "test":splits.append("test")else:splits.append("val" if fold_of[storm_id] == chosen else "train")work["split"] = splitswork["cv_fold"] = work["storm_id"].astype(str).map(lambda storm_id: fold_of.get(storm_id, pd.NA))_assert_groups(work)elif name == "year_holdout_2019":years = work["storm_id"].map(storm_year)work["split"] = np.where(years.eq(2019), "test", np.where(years.eq(2021), "val", "train"))else:raise LeakageError(f"unknown INCYDE split strategy {strategy}")synthetic_eval = work["is_synthetic"].astype(bool) & work["split"].astype(str).ne("train")dropped = int(synthetic_eval.sum())work = work.loc[~synthetic_eval].reset_index(drop=True)_assert_storms(work)for split_name in ("train", "val", "test"):if split_name not in set(work["split"].astype(str)):raise LeakageError(f"INCYDE split {name} produced no {split_name} rows")return work, droppeddef load_frame(config: dict) -> tuple[pd.DataFrame, int]:"""Rows for ``python -m src.train --dataset incyde``. Nothing is downloaded."""paths = config["paths"]block = config["incyde"]archive = block["archive"]if archive not in (None, "", "null"):assert_archive_md5(archive)frame, dropped = read_rows(paths["incyde_root"],manifest_csv=block["manifest_csv"],storm_split_csv=block["storm_split_csv"],exclusions_csv=block["exclusions_csv"],frame_flags_csv=block.get("frame_flags_csv"),drop_qc_flags=list(block["drop_qc_flags"] or []),check_images=True,)assigned, synthetic_dropped = assign_incyde_split(frame,str(config["split"]["strategy"]),n_folds=int(block["n_folds"]),cv_val_fold=int(block["cv_val_fold"]),cv_seed=int(block["cv_seed"]),cv_folds_csv=block["cv_folds_csv"],)return assigned, int(dropped) + int(synthetic_dropped)def main(argv: list[str] | None = None) -> Path:"""Write a manifest from a local extracted tree. Does not download."""parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--root", type=Path, required=True)parser.add_argument("--manifest-csv", type=Path, default=None)parser.add_argument("--storm-split", type=Path, default=None)parser.add_argument("--exclusions", type=Path, default=None)parser.add_argument("--frame-flags", type=Path, default=None)parser.add_argument("--out", type=Path, required=True)parser.add_argument("--strategy", default="storm_wise")parser.add_argument("--archive", type=Path, default=None)args = parser.parse_args(argv)if args.archive is not None:assert_archive_md5(args.archive)frame, dropped = read_rows(args.root,manifest_csv=args.manifest_csv,storm_split_csv=args.storm_split,exclusions_csv=args.exclusions,frame_flags_csv=args.frame_flags,)assigned, synthetic_dropped = assign_incyde_split(frame, args.strategy)args.out.parent.mkdir(parents=True, exist_ok=True)assigned.to_csv(args.out, index=False)print(f"Wrote {args.out} ({len(assigned)} rows, dropped {dropped + synthetic_dropped}). Not a forecast.")return args.outif __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778"""INCYDE loader for the cropped INSAT-3D North Indian Ocean set.Images come from the Zenodo 8015544 file ``Cropped_cyclone_data.zip``(MD5 ``ed5dac254c689e5a327dee7580324347``). This module never downloadsthat zip. Point ``paths.incyde_root`` at an extracted copy.Filename times are IST (UTC+05:30). ``Sequence`` in the labels CSV is thestorm key. The trailing ``obj`` index is not a storm id. The default splitand the exclusion list are ``incyde/audit/storm_split.csv`` and``incyde/audit/exclusions.csv``.``on_fix``, ``distance_to_land_km``, and ``near_land`` are joined from``incyde/audit/frame_flags.csv`` on the source filename. A ``rot_180``copy inherits that source row. A filename the table does not list staysunknown: ``on_fix`` is ``unknown``, the distance is null, and``near_land`` is ``unknown``. Those gaps are not filled with false orzero. The labels are already 3-minute winds, so the join does notrescale them. ``basin`` value ``LAND`` is the IMD basin of a landdepression, not a frame landfall.Only original frames and ``rot_180`` copies are kept. ``rot_180`` issynthetic, stays with its source storm, and is train-only. Flips reversecyclone spin. ``rot_90`` and ``rot_270`` add black bars. Both are dropped."""from __future__ import annotationsimport argparseimport hashlibimport refrom datetime import datetime, timedelta, timezonefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validfrom src.splits import LeakageErrorZIP_MD5 = "ed5dac254c689e5a327dee7580324347"WIND_AVERAGING = "3min"WIND_AVERAGING_S = 180CV_SEED = 42YEAR_HOLDOUT_NOTE = ("indicative only: different training years and images from ""Agrawal et al. 2024, arXiv:2410.08218. Landfall frames are kept; ""the audit outputs have no landfall flag.")KEPT_AUG = frozenset({"", "rot_180"})DROPPED_AUG = frozenset({"flip_h", "flip_v", "rot_90", "rot_270"})_IST = timezone(timedelta(hours=5, minutes=30))_MONTHS = {name: indexfor index, name in enumerate(("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),start=1,)}_FILENAME = re.compile(r"^(?P<day>\d{2})(?P<mon>[A-Za-z]{3})(?P<year>\d{4})_"r"(?P<hour>\d{2})(?P<minute>\d{2})_(?P<obj>\d+)"r"(?:_(?P<aug>flip_h|flip_v|rot_90|rot_180|rot_270))?\.jpe?g$",re.IGNORECASE,)_AUG_SUFFIX = re.compile(r"_(?:flip_h|flip_v|rot_90|rot_180|rot_270)(?=\.jpe?g$)",re.IGNORECASE,)_STORM_ID = re.compile(r"^INCYDE-S\d+_IMD-(?P<year>\d{4})-\d+$")_AUDIT_DIR = Path(__file__).resolve().parents[1] / "incyde" / "audit"DEFAULT_STORM_SPLIT = _AUDIT_DIR / "storm_split.csv"DEFAULT_EXCLUSIONS = _AUDIT_DIR / "exclusions.csv"DEFAULT_FRAME_FLAGS = _AUDIT_DIR / "frame_flags.csv"_FRAME_FLAG_COLUMNS = ("filename", "on_fix", "distance_to_land_km", "near_land")def imd_class_of(wind_kt: float) -> str:"""IMD class on a 3-minute wind, in knots.D ≤27, DD ≤33, CS ≤47, SCS ≤63, VSCS ≤89, ESCS ≤119, SuCS ≥120.Below 17 kt is ``<17``. These are not the project's 17/34/48/64/91 bins."""wind = float(wind_kt)if wind < 17:return "<17"if wind <= 27:return "D"if wind <= 33:return "DD"if wind <= 47:return "CS"if wind <= 63:return "SCS"if wind <= 89:return "VSCS"if wind <= 119:return "ESCS"return "SuCS"def storm_year(storm_id: object) -> int:"""Year from ``INCYDE-Sxx_IMD-yyyy-nnn``. Filename dates are not used."""match = _STORM_ID.match(str(storm_id).strip())if match is None:raise ValueError(f"storm_id {storm_id!r} is not INCYDE-Sxx_IMD-yyyy-nnn")return int(match.group("year"))def assert_one_storm_year(frame: pd.DataFrame) -> pd.Series:"""Each storm id maps to one IMD year. A filename that crosses 1 January does not add a second year."""years = frame["storm_id"].map(storm_year)counts = pd.DataFrame({"storm_id": frame["storm_id"].astype(str), "year": years}).groupby("storm_id")["year"].nunique()if bool((counts > 1).any()):raise LeakageError("a storm_id maps to more than one year")return yearsdef archive_md5(path: str | Path) -> str:"""MD5 of a local file. Does not download."""digest = hashlib.md5(usedforsecurity=False)with Path(path).open("rb") as handle:for chunk in iter(lambda: handle.read(1 << 20), b""):digest.update(chunk)return digest.hexdigest()def assert_archive_md5(path: str | Path) -> None:"""Refuse a cropped-zip copy whose MD5 is not the Zenodo value."""found = archive_md5(path)if found != ZIP_MD5:raise ValueError(f"INCYDE archive md5 is {found}, expected {ZIP_MD5}")def _optional_path(value: object, default: Path) -> Path:if value is None:return defaulttext = str(value).strip()if text.lower() in {"", "none", "null"}:return defaultreturn Path(text)def read_storm_split(path: str | Path | None = None) -> pd.DataFrame:"""One row per Sequence. ``proposed_split`` is Bean's grouped split."""table = pd.read_csv(_optional_path(path, DEFAULT_STORM_SPLIT))table.columns = [str(column).strip() for column in table.columns]required = {"Sequence", "storm_id", "proposed_split", "cooccurrence_group"}missing = sorted(required - set(table.columns))if missing:raise ValueError(f"storm_split.csv missing {missing}")out = table.copy()out["Sequence"] = pd.to_numeric(out["Sequence"], errors="raise").astype(int)out["storm_id"] = out["storm_id"].astype(str).str.strip()out["proposed_split"] = out["proposed_split"].astype(str).str.strip()out["cooccurrence_group"] = pd.to_numeric(out["cooccurrence_group"], errors="raise").astype(int)if out["storm_id"].duplicated().any() or out["Sequence"].duplicated().any():raise ValueError("storm_split.csv repeats a storm")bad = sorted(set(out["proposed_split"]) - {"train", "val", "test"})if bad:raise ValueError(f"storm_split.csv has unknown splits {bad}")assert_one_storm_year(out)return outdef read_exclusions(path: str | Path | None = None) -> pd.DataFrame:table = pd.read_csv(_optional_path(path, DEFAULT_EXCLUSIONS))table.columns = [str(column).strip() for column in table.columns]required = {"filename", "qc_flag", "default_exclude"}missing = sorted(required - set(table.columns))if missing:raise ValueError(f"exclusions.csv missing {missing}")out = table.copy()out["filename"] = out["filename"].astype(str).map(lambda name: Path(name).name)out["qc_flag"] = out["qc_flag"].fillna("").astype(str)out["default_exclude"] = [_is_true(value) for value in out["default_exclude"].tolist()]if out["filename"].duplicated().any():raise ValueError("exclusions.csv repeats a filename")return outdef _is_true(value: object) -> bool:if isinstance(value, (bool, np.bool_)):return bool(value)return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}def _blank_flag(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _on_fix_value(value: object) -> bool | str:"""Explicit bool, or ``unknown`` when the audit did not decide.``unknown`` is not stored as false. A later on-fix metric uses onlythe true rows."""if isinstance(value, (bool, np.bool_)):return bool(value)if _blank_flag(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return Trueif text in {"0", "false", "no", "n", "f"}:return Falseif text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"on_fix value {value!r} is not true, false, or unknown")def _near_land_token(value: object) -> str:"""``true``, ``false``, or ``unknown``. Blank stays unknown."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank_flag(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"near_land value {value!r} is not true, false, or unknown")def _distance_km(value: object) -> float:"""Kilometres, or NaN when the audit left the cell blank."""if _blank_flag(value):return float("nan")try:number = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from excif not np.isfinite(number):return float("nan")return numberdef read_frame_flags(path: str | Path | None = None) -> pd.DataFrame:"""Original-frame flags. Augmented filenames are not required in the file."""table = pd.read_csv(_optional_path(path, DEFAULT_FRAME_FLAGS))table.columns = [str(column).strip() for column in table.columns]missing = [column for column in _FRAME_FLAG_COLUMNS if column not in table.columns]if missing:raise ValueError(f"frame_flags.csv missing {missing}")on_fix = [_on_fix_value(value) for value in table["on_fix"].tolist()]out = pd.DataFrame({"filename": table["filename"].astype(str).map(lambda name: Path(name).name),"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],})# Object dtype so a homogeneous true/false column stays a Python bool# and an unknown cell is not coerced to false.out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)if out["filename"].duplicated().any():raise ValueError("frame_flags.csv repeats a filename")return outdef _flag_key(frame: pd.DataFrame) -> pd.Series:"""Source filename. Augmented copies inherit; they are not their own key."""if "source_frame_id" in frame.columns:return frame["source_frame_id"].astype(str).map(lambda name: Path(name).name)if "filename" in frame.columns:return frame["filename"].astype(str).map(lambda name: Path(_AUG_SUFFIX.sub("", name)).name)raise ValueError("frame flags need source_frame_id or filename")def attach_frame_flags(frame: pd.DataFrame, flags: pd.DataFrame) -> pd.DataFrame:"""Add ``on_fix``, ``distance_to_land_km``, and ``near_land``.The lookup key is the source filename, so a ``rot_180`` copy receivesthe original frame's row. A miss stays unknown. Distance is not filledwith 0, and ``on_fix`` is not filled with false."""lookup = flags.drop_duplicates("filename").set_index("filename")on_fix: list[object] = []distance: list[float] = []near: list[str] = []for key in _flag_key(frame).tolist():if key not in lookup.index:on_fix.append("unknown")distance.append(float("nan"))near.append("unknown")continuerow = lookup.loc[key]if isinstance(row, pd.DataFrame):raise ValueError(f"frame_flags.csv repeats {key}")on_fix.append(_on_fix_value(row["on_fix"]))distance.append(_distance_km(row["distance_to_land_km"]))near.append(_near_land_token(row["near_land"]))out = frame.copy()out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)out["distance_to_land_km"] = np.asarray(distance, dtype=float)out["near_land"] = nearreturn outdef parse_filename(filename: str) -> dict[str, object]:"""Parse ``DDMONYYYY_HHMM_<obj>[_aug].jpg``. ``obj`` is not a storm id."""name = Path(str(filename)).namematch = _FILENAME.match(name)if match is None:raise ValueError(f"INCYDE filename {name} does not match DDMONYYYY_HHMM_<obj>[_aug].jpg")parts = match.groupdict()month = _MONTHS.get(parts["mon"].upper())if month is None:raise ValueError(f"INCYDE filename {name} has an unknown month")ist = datetime(int(parts["year"]),month,int(parts["day"]),int(parts["hour"]),int(parts["minute"]),tzinfo=_IST,)utc = ist.astimezone(timezone.utc)aug = "" if not parts["aug"] else parts["aug"].lower()return {"filename": name,"time_ist": ist.isoformat(),"time_utc": utc.strftime("%Y-%m-%dT%H:%M:%SZ"),"object_index": int(parts["obj"]),"aug_type": aug,"source_frame_id": _AUG_SUFFIX.sub("", name),}def _source_table(frame: pd.DataFrame) -> pd.DataFrame:"""Labels CSV or the audit manifest, reduced to one column set."""columns = {str(column).strip(): column for column in frame.columns}renamed = frame.rename(columns={raw: clean for clean, raw in columns.items()})if "Sequence" in renamed.columns and ("MSWS kts" in renamed.columns or "label_kt" in renamed.columns):wind_column = "MSWS kts" if "MSWS kts" in renamed.columns else "label_kt"filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]out = pd.DataFrame({"sequence": pd.to_numeric(renamed["Sequence"], errors="raise").astype(int),"filename": filename.astype(str),"wind_kt": pd.to_numeric(renamed[wind_column], errors="coerce"),"source_category": renamed["Category"].astype(str) if "Category" in renamed.columns else "","incyde_set": renamed["Set"].astype(str) if "Set" in renamed.columns else "","given_storm_id": renamed["storm_id"].astype(str) if "storm_id" in renamed.columns else pd.NA,})return outif "storm_id" in renamed.columns and "label_kt" in renamed.columns:filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]sequence = renamed["incyde_sequence"] if "incyde_sequence" in renamed.columns else pd.Series(pd.NA, index=renamed.index)category = renamed["label_class_imd"] if "label_class_imd" in renamed.columns else ""return pd.DataFrame({"sequence": pd.to_numeric(sequence, errors="coerce"),"filename": filename.astype(str),"wind_kt": pd.to_numeric(renamed["label_kt"], errors="coerce"),"source_category": category.astype(str) if not isinstance(category, str) else category,"incyde_set": renamed["incyde_set"].astype(str) if "incyde_set" in renamed.columns else "","given_storm_id": renamed["storm_id"].astype(str),})raise ValueError("INCYDE manifest needs the labels columns (Sequence, MSWS kts, filename) ""or the audit columns (storm_id, label_kt, file)")def _locate_labels(root: Path) -> Path:candidates = [root / "Cropped_cyclone_labels.csv",root / "Cropped_cyclone_data" / "Cropped_cyclone_labels.csv",root / "labels.csv",]for path in candidates:if path.is_file():return pathraise FileNotFoundError(f"No INCYDE labels CSV under {root}. This loader does not download imagery.")def locate_image(root: Path, filename: str) -> Path:name = Path(filename).namecandidates = [root / name,root / "Cropped_cyclone_images" / name,root / "Cropped_cyclone_data" / "Cropped_cyclone_images" / name,root / "Cropped_cyclone_data" / name,]for path in candidates:if path.is_file():return pathraise FileNotFoundError(f"INCYDE image {name} is missing under {root}. This loader does not download imagery.")def _qc_tokens(flag: object) -> set[str]:text = "" if flag is None or (isinstance(flag, float) and np.isnan(flag)) else str(flag)return {part.strip() for part in text.split(";") if part.strip()}def _drop_reason(aug: str, exclude: bool, qc_flag: str, drop_qc_flags: set[str]) -> str | None:if exclude:return "default_exclude"if aug in DROPPED_AUG:return f"dropped aug {aug}"if aug not in KEPT_AUG:return f"unknown aug {aug or 'blank'}"if drop_qc_flags and _qc_tokens(qc_flag) & drop_qc_flags:return "drop_qc_flags"return Nonedef read_rows(root: str | Path,*,manifest_csv: str | Path | None = None,storm_split_csv: str | Path | None = None,exclusions_csv: str | Path | None = None,frame_flags_csv: str | Path | None = None,drop_qc_flags: list[str] | tuple[str, ...] | None = None,check_images: bool = True,) -> tuple[pd.DataFrame, int]:"""Frame rows before the final split. ``rot_180`` is still present.Flips, ``rot_90``, ``rot_270``, and ``default_exclude`` rows are gone.The returned count is how many source rows were dropped here."""root = Path(root)if not root.is_dir():raise FileNotFoundError(f"INCYDE root {root} is missing. Set paths.incyde_root to the extracted ""Cropped_cyclone_data directory. This entrypoint does not download imagery.")label_path = Path(manifest_csv) if manifest_csv not in (None, "", "null") else _locate_labels(root)if not label_path.is_file():raise FileNotFoundError(f"INCYDE manifest {label_path} is missing. Nothing is downloaded.")storms = read_storm_split(storm_split_csv)exclusions = read_exclusions(exclusions_csv)source = _source_table(pd.read_csv(label_path, encoding="utf-8-sig"))parsed = [parse_filename(name) for name in source["filename"].tolist()]parsed_frame = pd.DataFrame(parsed).drop(columns=["filename"])work = pd.concat([source.reset_index(drop=True), parsed_frame], axis=1)work["filename"] = work["filename"].map(lambda name: Path(str(name)).name)by_sequence = storms.set_index("Sequence")by_storm = storms.drop_duplicates("storm_id").set_index("storm_id")storm_ids: list[str] = []sequences: list[int] = []proposed: list[str] = []groups: list[int] = []names: list[str] = []basins: list[str] = []for sequence, given in zip(work["sequence"].tolist(), work["given_storm_id"].tolist(), strict=True):row = Noneif pd.notna(sequence) and int(sequence) in by_sequence.index:row = by_sequence.loc[int(sequence)]elif isinstance(given, str) and given in by_storm.index:row = by_storm.loc[given]if row is None:raise ValueError(f"no storm_split row for sequence {sequence!r} storm {given!r}")if isinstance(row, pd.DataFrame):raise ValueError(f"storm_split matched more than one row for sequence {sequence}")storm_id = str(row["storm_id"]) if "storm_id" in row.index else str(row.name)sequence_id = int(row["Sequence"]) if "Sequence" in row.index else int(row.name)if isinstance(given, str) and given not in {"", "nan", "<NA>"} and given != storm_id:raise ValueError(f"manifest storm_id {given} does not match storm_split.csv ({storm_id})")storm_ids.append(storm_id)sequences.append(sequence_id)proposed.append(str(row["proposed_split"]))groups.append(int(row["cooccurrence_group"]))names.append("" if "name" not in row.index or pd.isna(row["name"]) else str(row["name"]))basins.append("" if "basin" not in row.index or pd.isna(row["basin"]) else str(row["basin"]))work["storm_id"] = storm_idswork["sequence"] = sequenceswork["proposed_split"] = proposedwork["cooccurrence_group"] = groupswork["name"] = nameswork["basin"] = basinsqc = exclusions.set_index("filename")flags = []exclude = []for filename in work["filename"].tolist():if filename in qc.index:flags.append(str(qc.at[filename, "qc_flag"]))exclude.append(bool(qc.at[filename, "default_exclude"]))else:flags.append("")exclude.append(False)work["qc_flag"] = flagsdrop_flags = {str(flag).strip() for flag in (drop_qc_flags or []) if str(flag).strip()}reasons = [_drop_reason(aug, dropped, flag, drop_flags)for aug, dropped, flag in zip(work["aug_type"], exclude, work["qc_flag"], strict=True)]dropped_count = sum(reason is not None for reason in reasons)kept = work.loc[[reason is None for reason in reasons]].reset_index(drop=True)if kept.empty:raise ValueError("INCYDE filters removed every row")if kept["filename"].duplicated().any():raise ValueError("INCYDE labels repeat a filename")years = assert_one_storm_year(kept)image_paths: list[str] = []heights: list[int] = []widths: list[int] = []if check_images:from PIL import Imagefor filename in kept["filename"].tolist():path = locate_image(root, filename)image_paths.append(path.resolve().as_posix())with Image.open(path) as image:widths.append(int(image.width))heights.append(int(image.height))else:image_paths = kept["filename"].tolist()heights = [0] * len(kept)widths = [0] * len(kept)frame = pd.DataFrame({"sample_id": [Path(name).stem for name in kept["filename"].tolist()],"image_path": image_paths,"storm_id": kept["storm_id"].astype(str),"wind_speed_kt": kept["wind_kt"].to_numpy(dtype=float),"wind_kt": kept["wind_kt"].to_numpy(dtype=float),"wind_averaging": WIND_AVERAGING,"wind_averaging_s": WIND_AVERAGING_S,"is_synthetic": [aug == "rot_180" for aug in kept["aug_type"].tolist()],"imd_class": [imd_class_of(wind) for wind in kept["wind_kt"].tolist()],"split": kept["proposed_split"].astype(str),"proposed_split": kept["proposed_split"].astype(str),"cooccurrence_group": kept["cooccurrence_group"].astype(int),"time_utc": kept["time_utc"].astype(str),"time_ist": kept["time_ist"].astype(str),"storm_year": years.to_numpy(dtype=int),"aug_type": kept["aug_type"].astype(str),"source_frame_id": kept["source_frame_id"].astype(str),"object_index": kept["object_index"].astype(int),"qc_flag": kept["qc_flag"].astype(str),"incyde_sequence": kept["sequence"].astype(int),"incyde_set": kept["incyde_set"].astype(str),"source_category": kept["source_category"].astype(str),"name": kept["name"].astype(str),"basin": kept["basin"].astype(str),"native_height": heights,"native_width": widths,"orig_size": [height if height == width else -1 for height, width in zip(heights, widths, strict=True)],"sensor": "INSAT-3D","channel": "IR","pixel_units": "jpeg_uncalibrated","label_source": "incyde_imd_3min","center_source": "dataset_precentered",})# Join after the row filter so dropped augs are not looked up. The# source filename is the key; unknown audit cells stay unknown.flagged = attach_frame_flags(frame, read_frame_flags(frame_flags_csv))return require_valid(flagged), int(dropped_count)def build_cv_folds(storms: pd.DataFrame, n_folds: int, seed: int) -> pd.DataFrame:"""Storm-grouped folds over train+val only. Test storms are absent.Groups are shuffled with ``seed`` and dealt round-robin, so every stormin one ``cooccurrence_group`` shares a fold. The training path passes``incyde.cv_seed`` (42 in the YAML)."""folds = int(n_folds)if folds < 2:raise ValueError("incyde.n_folds must be at least 2")pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")if pool.empty:raise ValueError("storm_cv needs train and val storms")groups = sorted({int(group) for group in pool["cooccurrence_group"].tolist()})order = np.random.default_rng(int(seed)).permutation(len(groups))shuffled = [groups[int(index)] for index in order]group_fold = {group: index % folds for index, group in enumerate(shuffled)}out = pd.DataFrame({"storm_id": pool["storm_id"].astype(str).tolist(),"fold": [int(group_fold[int(group)]) for group in pool["cooccurrence_group"].tolist()],})return out.sort_values(["fold", "storm_id"]).reset_index(drop=True)def read_cv_folds(path: str | Path) -> pd.DataFrame:"""Use a folds file verbatim. Columns are ``storm_id`` and ``fold``."""table = pd.read_csv(path)table.columns = [str(column).strip() for column in table.columns]if "storm_id" not in table.columns or "fold" not in table.columns:raise ValueError("cv folds csv needs columns storm_id and fold")out = pd.DataFrame({"storm_id": table["storm_id"].astype(str).str.strip(),"fold": pd.to_numeric(table["fold"], errors="raise").astype(int),})if out["storm_id"].duplicated().any():raise ValueError("cv folds csv repeats a storm_id")return out.reset_index(drop=True)def validate_cv_folds(folds: pd.DataFrame, storms: pd.DataFrame) -> None:"""No test storm, and no cooccurrence group spread across folds."""test_ids = set(storms.loc[storms["proposed_split"].astype(str) == "test", "storm_id"].astype(str))listed = set(folds["storm_id"].astype(str))leaked = sorted(listed & test_ids)if leaked:raise LeakageError(f"cv folds include test storms {leaked[:8]}")pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")pool_ids = set(pool["storm_id"].astype(str))missing = sorted(pool_ids - listed)extra = sorted(listed - pool_ids)if missing:raise ValueError(f"cv folds omit train/val storms {missing[:8]}")if extra:raise ValueError(f"cv folds name storms that are not train/val {extra[:8]}")merged = pool.assign(storm_id=pool["storm_id"].astype(str)).merge(folds, on="storm_id", how="left")spread = merged.groupby("cooccurrence_group")["fold"].nunique()if bool((spread > 1).any()):groups = [int(group) for group in spread.index[spread > 1].tolist()]raise LeakageError(f"cooccurrence_group spans folds {groups[:8]}")def _folds_for(storms: pd.DataFrame, n_folds: int, seed: int, cv_folds_csv: str | Path | None) -> pd.DataFrame:if cv_folds_csv not in (None, "", "null"):folds = read_cv_folds(cv_folds_csv)else:folds = build_cv_folds(storms, n_folds, seed)validate_cv_folds(folds, storms)return foldsdef _assert_storms(frame: pd.DataFrame) -> None:per_storm = frame.groupby(frame["storm_id"].astype(str))["split"].nunique()if bool((per_storm > 1).any()):raise LeakageError("a storm is in more than one split")synthetic = frame["is_synthetic"].astype(bool) & frame["split"].astype(str).ne("train")if bool(synthetic.any()):raise LeakageError("synthetic INCYDE rows are train-only")bad_aug = sorted(set(frame["aug_type"].astype(str)) - KEPT_AUG)if bad_aug:raise LeakageError(f"INCYDE kept dropped augmentations {bad_aug}")def _assert_groups(frame: pd.DataFrame) -> None:spread = frame.groupby("cooccurrence_group")["split"].nunique()if bool((spread > 1).any()):raise LeakageError("a cooccurrence_group is in more than one split")def assign_incyde_split(frame: pd.DataFrame,strategy: str,*,n_folds: int = 5,cv_val_fold: int = 0,cv_seed: int = CV_SEED,cv_folds_csv: str | Path | None = None,) -> tuple[pd.DataFrame, int]:"""Write ``split`` and drop synthetic rows that are not in train.``storm_wise`` uses ``proposed_split`` (60/14/17 on the audit file).``storm_cv`` keeps test storms out of the folds. ``year_holdout_2019``puts 2019 in test and 2021 in val. The year comes from ``storm_id``."""name = str(strategy).strip().lower()work = frame.copy()if "proposed_split" not in work.columns:raise ValueError("INCYDE rows need proposed_split from storm_split.csv")storms = work.groupby("storm_id", as_index=False).agg(proposed_split=("proposed_split", "first"),cooccurrence_group=("cooccurrence_group", "first"),)assert_one_storm_year(work)if name in {"storm_wise", "proposed", "bean"}:work["split"] = work["proposed_split"].astype(str)_assert_groups(work)elif name == "storm_cv":using_file = cv_folds_csv not in (None, "", "null")folds = _folds_for(storms, n_folds, cv_seed, cv_folds_csv)chosen = int(cv_val_fold)if not using_file and (chosen < 0 or chosen >= int(n_folds)):raise ValueError("incyde.cv_val_fold is outside 0 .. n_folds-1")fold_of = dict(zip(folds["storm_id"].astype(str), folds["fold"].astype(int), strict=True))splits = []for storm_id, proposed in zip(work["storm_id"].astype(str), work["proposed_split"].astype(str), strict=True):if proposed == "test":splits.append("test")else:splits.append("val" if fold_of[storm_id] == chosen else "train")work["split"] = splitswork["cv_fold"] = work["storm_id"].astype(str).map(lambda storm_id: fold_of.get(storm_id, pd.NA))_assert_groups(work)elif name == "year_holdout_2019":years = work["storm_id"].map(storm_year)work["split"] = np.where(years.eq(2019), "test", np.where(years.eq(2021), "val", "train"))else:raise LeakageError(f"unknown INCYDE split strategy {strategy}")synthetic_eval = work["is_synthetic"].astype(bool) & work["split"].astype(str).ne("train")dropped = int(synthetic_eval.sum())work = work.loc[~synthetic_eval].reset_index(drop=True)_assert_storms(work)for split_name in ("train", "val", "test"):if split_name not in set(work["split"].astype(str)):raise LeakageError(f"INCYDE split {name} produced no {split_name} rows")return work, droppeddef load_frame(config: dict) -> tuple[pd.DataFrame, int]:"""Rows for ``python -m src.train --dataset incyde``. Nothing is downloaded."""paths = config["paths"]block = config["incyde"]archive = block["archive"]if archive not in (None, "", "null"):assert_archive_md5(archive)frame, dropped = read_rows(paths["incyde_root"],manifest_csv=block["manifest_csv"],storm_split_csv=block["storm_split_csv"],exclusions_csv=block["exclusions_csv"],frame_flags_csv=block.get("frame_flags_csv"),drop_qc_flags=list(block["drop_qc_flags"] or []),check_images=True,)assigned, synthetic_dropped = assign_incyde_split(frame,str(config["split"]["strategy"]),n_folds=int(block["n_folds"]),cv_val_fold=int(block["cv_val_fold"]),cv_seed=int(block["cv_seed"]),cv_folds_csv=block["cv_folds_csv"],)return assigned, int(dropped) + int(synthetic_dropped)def main(argv: list[str] | None = None) -> Path:"""Write a manifest from a local extracted tree. Does not download."""parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--root", type=Path, required=True)parser.add_argument("--manifest-csv", type=Path, default=None)parser.add_argument("--storm-split", type=Path, default=None)parser.add_argument("--exclusions", type=Path, default=None)parser.add_argument("--frame-flags", type=Path, default=None)parser.add_argument("--out", type=Path, required=True)parser.add_argument("--strategy", default="storm_wise")parser.add_argument("--archive", type=Path, default=None)args = parser.parse_args(argv)if args.archive is not None:assert_archive_md5(args.archive)frame, dropped = read_rows(args.root,manifest_csv=args.manifest_csv,storm_split_csv=args.storm_split,exclusions_csv=args.exclusions,frame_flags_csv=args.frame_flags,)assigned, synthetic_dropped = assign_incyde_split(frame, args.strategy)args.out.parent.mkdir(parents=True, exist_ok=True)assigned.to_csv(args.out, index=False)print(f"Wrote {args.out} ({len(assigned)} rows, dropped {dropped + synthetic_dropped}). Not a forecast.")return args.outif __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""IMD 3-minute wind target.NASA and TCIR labels are 1-minute sustained winds. INCYDE labels are alreadyIMD 3-minute winds. The training target is ``wind_kt_3min``. Raw knots stayon ``wind_speed_kt`` and ``wind_kt``.The 1-minute to 3-minute factor is ``labels.wind_1min_to_3min`` (0.93 in theYAML). It is a derived at-sea gust factor from WMO/TD-1555 Tables 1.1 and1.2 (Harper, Kepert and Ginger 2010), not a WMO constant, and it is meantfor open water more than 20 km offshore. This module does not download acoastline. A dataset with no land indicator is marked unknown."""from __future__ import annotationsimport mathimport numpy as npimport pandas as pdfrom src.schema import wind_averaging_seconds# Citation for the default factor. The numeric factor itself lives in the YAML.WIND_CONVERSION_NOTE = ("0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, ""at-sea exposure (not a WMO constant)")HELD_RAW_NOTE = "held raw: near land, at-sea factor not applied"NEAR_LAND_POLICIES = ("flag", "raw")def conversion_note(factor: float) -> str:"""Provenance string for a row whose 1-minute wind was multiplied.The default factor of 0.93 uses the citation verbatim. Any otherconfigured factor keeps the same source and names that factor."""if not math.isfinite(factor) or factor <= 0:raise ValueError("wind factor must be a positive finite number")if f"{float(factor):.2f}" == "0.93":return WIND_CONVERSION_NOTEreturn (f"{float(factor):.2f}, derived from WMO/TD-1555 Tables 1.1 and 1.2, ""at-sea exposure (not a WMO constant)")def _blank(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _flag(value: object) -> str:"""``true``, ``false``, or ``unknown``."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"land indicator {value!r} is not true, false, or unknown")def near_land_status(frame: pd.DataFrame, open_water_km: float) -> pd.Series:"""Per-row near-land status: ``true``, ``false``, or ``unknown``.``distance_to_land_km`` is the quantitative indicator. Open water isstrictly farther than ``open_water_km`` (20 km in the YAML). A``near_land`` or ``landfall`` column is used when there is no distance.Latitude and longitude are not a land indicator. With none of thosecolumns the whole frame is unknown."""if open_water_km < 0 or not math.isfinite(open_water_km):raise ValueError("open_water_km must be a non-negative finite distance")if "distance_to_land_km" in frame.columns:distance = pd.to_numeric(frame["distance_to_land_km"], errors="coerce")status = np.where(distance.isna(),"unknown",np.where(distance > float(open_water_km), "false", "true"),)return pd.Series(status, index=frame.index, dtype=object)if "near_land" in frame.columns:return pd.Series([_flag(value) for value in frame["near_land"].tolist()],index=frame.index,dtype=object,)if "landfall" in frame.columns:return pd.Series([_flag(value) for value in frame["landfall"].tolist()],index=frame.index,dtype=object,)return pd.Series("unknown", index=frame.index, dtype=object)def _raw_knots(frame: pd.DataFrame) -> pd.Series:if "wind_speed_kt" not in frame.columns and "wind_kt" not in frame.columns:raise ValueError("a wind row needs wind_speed_kt or wind_kt")if "wind_speed_kt" in frame.columns and "wind_kt" in frame.columns:left = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")right = pd.to_numeric(frame["wind_kt"], errors="coerce")if not np.allclose(left.to_numpy(dtype=float), right.to_numpy(dtype=float), equal_nan=True):raise ValueError("wind_kt and wind_speed_kt disagree; refusing to convert either")return leftcolumn = "wind_speed_kt" if "wind_speed_kt" in frame.columns else "wind_kt"return pd.to_numeric(frame[column], errors="coerce")def apply_wind_standard(frame: pd.DataFrame,*,factor: float,policy: str,open_water_km: float,) -> pd.DataFrame:"""Add ``wind_kt_3min`` without overwriting the raw label.3-minute rows, including INCYDE, pass through (``wind_kt_3min == wind_kt``).1-minute rows are multiplied by ``factor`` unless ``policy`` is ``raw``and the row is near land. ``flag`` (the default) still multiplies thoserows and sets ``conversion_exposure_flag`` true. Unknown exposure isconverted and the flag stays ``unknown``, so the at-sea factor is notrecorded as an open-water measurement."""choice = str(policy).strip().lower()if choice not in NEAR_LAND_POLICIES:raise ValueError("labels.near_land_policy must be flag or raw")note = conversion_note(factor)if "wind_averaging" not in frame.columns:raise ValueError("wind_averaging is required before the 3-minute target is added")raw = _raw_knots(frame).to_numpy(dtype=float)status = near_land_status(frame, open_water_km).tolist()periods = [str(value).strip() for value in frame["wind_averaging"].tolist()]target = np.empty(len(frame), dtype=float)scale = np.empty(len(frame), dtype=float)notes: list[str] = []flags: list[str] = []seconds: list[int | None] = []for index, (period, land) in enumerate(zip(periods, status, strict=True)):duration = wind_averaging_seconds(period)seconds.append(duration)if duration == 60:hold = land == "true" and choice == "raw"if hold:target[index] = raw[index]scale[index] = 1.0notes.append(HELD_RAW_NOTE)flags.append("true")else:target[index] = raw[index] * float(factor)scale[index] = float(factor)notes.append(note)flags.append(land)else:target[index] = raw[index]scale[index] = 1.0notes.append("")flags.append("")out = frame.copy()out["wind_speed_kt"] = rawout["wind_kt"] = rawout["wind_kt_3min"] = targetout["wind_kt_scale"] = scaleout["wind_conversion"] = notesout["conversion_exposure_flag"] = flagsout["near_land"] = statusout["wind_averaging_s"] = pd.array(seconds, dtype="Int64")return outdef run_conversion_note(frame: pd.DataFrame) -> str | None:"""The single conversion note on this frame, or null when nothing was scaled."""if "wind_conversion" not in frame.columns or frame.empty:return Nonenotes = []for value in frame["wind_conversion"].tolist():if _blank(value):continuetext = str(value).strip()if text.lower() in {"nan", "none", "null"}:continuenotes.append(text)notes = sorted(set(notes))if not notes:return Noneif len(notes) == 1:return notes[0]return " | ".join(notes)def back_converted_prediction(prediction: np.ndarray, scale: np.ndarray) -> np.ndarray:"""Map a 3-minute prediction back to the raw label.Converted 1-minute rows use ``prediction / factor``. Pass-through rowshave scale 1. Near-land rows held at the raw label also have scale 1."""pred = np.asarray(prediction, dtype=np.float64).reshape(-1)weights = np.asarray(scale, dtype=np.float64).reshape(-1)if pred.shape != weights.shape:raise ValueError("prediction and wind_kt_scale must have the same length")if weights.size and (not np.isfinite(weights).all() or np.any(weights <= 0)):raise ValueError("wind_kt_scale must be a positive finite multiplier")return pred / weights123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""IMD 3-minute wind target.NASA and TCIR labels are 1-minute sustained winds. INCYDE labels are alreadyIMD 3-minute winds. The training target is ``wind_kt_3min``. Raw knots stayon ``wind_speed_kt`` and ``wind_kt``.The 1-minute to 3-minute factor is ``labels.wind_1min_to_3min`` (0.93 in theYAML). It is a derived at-sea gust factor from WMO/TD-1555 Tables 1.1 and1.2 (Harper, Kepert and Ginger 2010), not a WMO constant, and it is meantfor open water more than 20 km offshore. This module does not download acoastline. A dataset with no land indicator is marked unknown."""from __future__ import annotationsimport mathimport numpy as npimport pandas as pdfrom src.schema import wind_averaging_seconds# Citation for the default factor. The numeric factor itself lives in the YAML.WIND_CONVERSION_NOTE = ("0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, ""at-sea exposure (not a WMO constant)")HELD_RAW_NOTE = "held raw: near land, at-sea factor not applied"NEAR_LAND_POLICIES = ("flag", "raw")def conversion_note(factor: float) -> str:"""Provenance string for a row whose 1-minute wind was multiplied.The default factor of 0.93 uses the citation verbatim. Any otherconfigured factor keeps the same source and names that factor."""if not math.isfinite(factor) or factor <= 0:raise ValueError("wind factor must be a positive finite number")if f"{float(factor):.2f}" == "0.93":return WIND_CONVERSION_NOTEreturn (f"{float(factor):.2f}, derived from WMO/TD-1555 Tables 1.1 and 1.2, ""at-sea exposure (not a WMO constant)")def _blank(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _flag(value: object) -> str:"""``true``, ``false``, or ``unknown``."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"land indicator {value!r} is not true, false, or unknown")def near_land_status(frame: pd.DataFrame, open_water_km: float) -> pd.Series:"""Per-row near-land status: ``true``, ``false``, or ``unknown``.``distance_to_land_km`` is the quantitative indicator. Open water isstrictly farther than ``open_water_km`` (20 km in the YAML). A``near_land`` or ``landfall`` column is used when there is no distance.Latitude and longitude are not a land indicator. With none of thosecolumns the whole frame is unknown."""if open_water_km < 0 or not math.isfinite(open_water_km):raise ValueError("open_water_km must be a non-negative finite distance")if "distance_to_land_km" in frame.columns:distance = pd.to_numeric(frame["distance_to_land_km"], errors="coerce")status = np.where(distance.isna(),"unknown",np.where(distance > float(open_water_km), "false", "true"),)return pd.Series(status, index=frame.index, dtype=object)if "near_land" in frame.columns:return pd.Series([_flag(value) for value in frame["near_land"].tolist()],index=frame.index,dtype=object,)if "landfall" in frame.columns:return pd.Series([_flag(value) for value in frame["landfall"].tolist()],index=frame.index,dtype=object,)return pd.Series("unknown", index=frame.index, dtype=object)def _raw_knots(frame: pd.DataFrame) -> pd.Series:if "wind_speed_kt" not in frame.columns and "wind_kt" not in frame.columns:raise ValueError("a wind row needs wind_speed_kt or wind_kt")if "wind_speed_kt" in frame.columns and "wind_kt" in frame.columns:left = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")right = pd.to_numeric(frame["wind_kt"], errors="coerce")if not np.allclose(left.to_numpy(dtype=float), right.to_numpy(dtype=float), equal_nan=True):raise ValueError("wind_kt and wind_speed_kt disagree; refusing to convert either")return leftcolumn = "wind_speed_kt" if "wind_speed_kt" in frame.columns else "wind_kt"return pd.to_numeric(frame[column], errors="coerce")def apply_wind_standard(frame: pd.DataFrame,*,factor: float,policy: str,open_water_km: float,) -> pd.DataFrame:"""Add ``wind_kt_3min`` without overwriting the raw label.3-minute rows, including INCYDE, pass through (``wind_kt_3min == wind_kt``).1-minute rows are multiplied by ``factor`` unless ``policy`` is ``raw``and the row is near land. ``flag`` (the default) still multiplies thoserows and sets ``conversion_exposure_flag`` true. Unknown exposure isconverted and the flag stays ``unknown``, so the at-sea factor is notrecorded as an open-water measurement."""choice = str(policy).strip().lower()if choice not in NEAR_LAND_POLICIES:raise ValueError("labels.near_land_policy must be flag or raw")note = conversion_note(factor)if "wind_averaging" not in frame.columns:raise ValueError("wind_averaging is required before the 3-minute target is added")raw = _raw_knots(frame).to_numpy(dtype=float)status = near_land_status(frame, open_water_km).tolist()periods = [str(value).strip() for value in frame["wind_averaging"].tolist()]target = np.empty(len(frame), dtype=float)scale = np.empty(len(frame), dtype=float)notes: list[str] = []flags: list[str] = []seconds: list[int | None] = []for index, (period, land) in enumerate(zip(periods, status, strict=True)):duration = wind_averaging_seconds(period)seconds.append(duration)if duration == 60:hold = land == "true" and choice == "raw"if hold:target[index] = raw[index]scale[index] = 1.0notes.append(HELD_RAW_NOTE)flags.append("true")else:target[index] = raw[index] * float(factor)scale[index] = float(factor)notes.append(note)flags.append(land)else:target[index] = raw[index]scale[index] = 1.0notes.append("")flags.append("")out = frame.copy()out["wind_speed_kt"] = rawout["wind_kt"] = rawout["wind_kt_3min"] = targetout["wind_kt_scale"] = scaleout["wind_conversion"] = notesout["conversion_exposure_flag"] = flagsout["near_land"] = statusout["wind_averaging_s"] = pd.array(seconds, dtype="Int64")return outdef run_conversion_note(frame: pd.DataFrame) -> str | None:"""The single conversion note on this frame, or null when nothing was scaled."""if "wind_conversion" not in frame.columns or frame.empty:return Nonenotes = []for value in frame["wind_conversion"].tolist():if _blank(value):continuetext = str(value).strip()if text.lower() in {"nan", "none", "null"}:continuenotes.append(text)notes = sorted(set(notes))if not notes:return Noneif len(notes) == 1:return notes[0]return " | ".join(notes)def back_converted_prediction(prediction: np.ndarray, scale: np.ndarray) -> np.ndarray:"""Map a 3-minute prediction back to the raw label.Converted 1-minute rows use ``prediction / factor``. Pass-through rowshave scale 1. Near-land rows held at the raw label also have scale 1."""pred = np.asarray(prediction, dtype=np.float64).reshape(-1)weights = np.asarray(scale, dtype=np.float64).reshape(-1)if pred.shape != weights.shape:raise ValueError("prediction and wind_kt_scale must have the same length")if weights.size and (not np.isfinite(weights).all() or np.any(weights <= 0)):raise ValueError("wind_kt_scale must be a positive finite multiplier")return pred / weights
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Synthetic images for software tests. These are not cyclones."""from __future__ import annotationsimport argparsefrom pathlib import Pathimport numpy as npimport pandas as pd# Project-class winds that stay inside the bin when a few knots are added.CLASS_WINDS = (("D_DD", 26.0),("CS", 40.0),("SCS", 55.0),("VSCS", 75.0),("ESCS_SUCS", 105.0),)def _synthetic_ir(size: int, wind_kt: float, rng: np.random.Generator) -> np.ndarray:yy, xx = np.mgrid[0:size, 0:size]radius = np.hypot(yy - size / 2, xx - size / 2)cold_core = 220.0 - (wind_kt - 20.0) * 0.7 * np.exp(-(radius**2) / (2 * 8.0**2))noise = rng.normal(0.0, 1.5, size=(size, size))return (cold_core + noise).astype(np.float32)def _write_rows(root: Path, rows: list[dict[str, object]]) -> Path:manifest = root / "manifest.csv"pd.DataFrame(rows).to_csv(manifest, index=False)return manifestdef write_smoke(root: Path,n_storms: int = 8,frames_per_storm: int = 4,size: int = 64,seed: int = 7,) -> Path:"""Write a manifest and ``.npy`` images.Storm ``S06`` has frames in 2020 and 2021 so the year-holdout test canprove that a boundary storm is not cut."""rng = np.random.default_rng(seed)root.mkdir(parents=True, exist_ok=True)image_dir = root / "images"image_dir.mkdir(exist_ok=True)rows: list[dict[str, object]] = []for index in range(n_storms):storm_id = f"S{index:02d}"basin = "NIO" if index % 2 else "NA"year = 2018 + (index % 4)for time_index in range(frames_per_storm):year_t = 2021 if index == 6 and time_index >= 2 else yearwind = float(np.clip(25 + index * 12 + time_index * 2, 20, 140))relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"np.save(root / relative, _synthetic_ir(size, wind, rng))rows.append({"sample_id": f"{storm_id}_{time_index:02d}","image_path": relative.as_posix(),"storm_id": storm_id,"timestamp": f"{year_t}-06-01T{time_index:02d}:00:00Z","year": year_t,"basin": basin,"sensor": "synthetic","channel": "IR","wind_speed_kt": wind,"wind_averaging": "synthetic","label_source": "smoke","is_synthetic": True,})return _write_rows(root, rows)def write_balanced_smoke(root: Path,storms_per_class: int = 5,frames_per_storm: int = 4,size: int = 48,seed: int = 7,) -> Path:"""One wind bin per storm, several storms per project class.Used to exercise grouped classification splits. Still synthetic."""if storms_per_class < 3:raise ValueError("storms_per_class must be at least 3 for grouped folds")rng = np.random.default_rng(seed)root.mkdir(parents=True, exist_ok=True)image_dir = root / "images"image_dir.mkdir(exist_ok=True)rows: list[dict[str, object]] = []for class_index, (_name, base_wind) in enumerate(CLASS_WINDS):for storm_index in range(storms_per_class):storm_id = f"C{class_index}{storm_index}"basin = "NIO" if (class_index + storm_index) % 2 else "NA"year = 2016 + ((class_index + storm_index) % 6)for time_index in range(frames_per_storm):wind = float(base_wind + time_index)relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"np.save(root / relative, _synthetic_ir(size, wind, rng))rows.append({"sample_id": f"{storm_id}_{time_index:02d}","image_path": relative.as_posix(),"storm_id": storm_id,"timestamp": f"{year}-08-01T{time_index:02d}:00:00Z","year": year,"basin": basin,"sensor": "synthetic","channel": "IR","wind_speed_kt": wind,"wind_averaging": "synthetic","label_source": "smoke","is_synthetic": True,})return _write_rows(root, rows)def _default_out() -> Path:"""Directory that holds ``paths.manifest`` in the smoke config."""from src.config import load_configroot = Path(__file__).resolve().parents[1]manifest = Path(load_config(root / "config" / "config_smoke.yaml")["paths"]["manifest"])return manifest.parentdef main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--out", type=Path, default=_default_out())parser.add_argument("--profile",choices=("span", "balanced"),default="span",help="span: year-boundary storm. balanced: several storms per class.",)args = parser.parse_args()if args.profile == "balanced":path = write_balanced_smoke(args.out)else:path = write_smoke(args.out)print(f"Wrote synthetic manifest {path}. Not real cyclones. Do not report scores from it.")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Synthetic images for software tests. These are not cyclones."""from __future__ import annotationsimport argparsefrom pathlib import Pathimport numpy as npimport pandas as pd# Project-class winds that stay inside the bin when a few knots are added.CLASS_WINDS = (("D_DD", 26.0),("CS", 40.0),("SCS", 55.0),("VSCS", 75.0),("ESCS_SUCS", 105.0),)def _synthetic_ir(size: int, wind_kt: float, rng: np.random.Generator) -> np.ndarray:yy, xx = np.mgrid[0:size, 0:size]radius = np.hypot(yy - size / 2, xx - size / 2)cold_core = 220.0 - (wind_kt - 20.0) * 0.7 * np.exp(-(radius**2) / (2 * 8.0**2))noise = rng.normal(0.0, 1.5, size=(size, size))return (cold_core + noise).astype(np.float32)def _write_rows(root: Path, rows: list[dict[str, object]]) -> Path:manifest = root / "manifest.csv"pd.DataFrame(rows).to_csv(manifest, index=False)return manifestdef write_smoke(root: Path,n_storms: int = 8,frames_per_storm: int = 4,size: int = 64,seed: int = 7,) -> Path:"""Write a manifest and ``.npy`` images.Storm ``S06`` has frames in 2020 and 2021 so the year-holdout test canprove that a boundary storm is not cut."""rng = np.random.default_rng(seed)root.mkdir(parents=True, exist_ok=True)image_dir = root / "images"image_dir.mkdir(exist_ok=True)rows: list[dict[str, object]] = []for index in range(n_storms):storm_id = f"S{index:02d}"basin = "NIO" if index % 2 else "NA"year = 2018 + (index % 4)for time_index in range(frames_per_storm):year_t = 2021 if index == 6 and time_index >= 2 else yearwind = float(np.clip(25 + index * 12 + time_index * 2, 20, 140))relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"np.save(root / relative, _synthetic_ir(size, wind, rng))rows.append({"sample_id": f"{storm_id}_{time_index:02d}","image_path": relative.as_posix(),"storm_id": storm_id,"timestamp": f"{year_t}-06-01T{time_index:02d}:00:00Z","year": year_t,"basin": basin,"sensor": "synthetic","channel": "IR","wind_speed_kt": wind,"wind_averaging": "synthetic","label_source": "smoke","is_synthetic": True,})return _write_rows(root, rows)def write_balanced_smoke(root: Path,storms_per_class: int = 5,frames_per_storm: int = 4,size: int = 48,seed: int = 7,) -> Path:"""One wind bin per storm, several storms per project class.Used to exercise grouped classification splits. Still synthetic."""if storms_per_class < 3:raise ValueError("storms_per_class must be at least 3 for grouped folds")rng = np.random.default_rng(seed)root.mkdir(parents=True, exist_ok=True)image_dir = root / "images"image_dir.mkdir(exist_ok=True)rows: list[dict[str, object]] = []for class_index, (_name, base_wind) in enumerate(CLASS_WINDS):for storm_index in range(storms_per_class):storm_id = f"C{class_index}{storm_index}"basin = "NIO" if (class_index + storm_index) % 2 else "NA"year = 2016 + ((class_index + storm_index) % 6)for time_index in range(frames_per_storm):wind = float(base_wind + time_index)relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"np.save(root / relative, _synthetic_ir(size, wind, rng))rows.append({"sample_id": f"{storm_id}_{time_index:02d}","image_path": relative.as_posix(),"storm_id": storm_id,"timestamp": f"{year}-08-01T{time_index:02d}:00:00Z","year": year,"basin": basin,"sensor": "synthetic","channel": "IR","wind_speed_kt": wind,"wind_averaging": "synthetic","label_source": "smoke","is_synthetic": True,})return _write_rows(root, rows)def _default_out() -> Path:"""Directory that holds ``paths.manifest`` in the smoke config."""from src.config import load_configroot = Path(__file__).resolve().parents[1]manifest = Path(load_config(root / "config" / "config_smoke.yaml")["paths"]["manifest"])return manifest.parentdef main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--out", type=Path, default=_default_out())parser.add_argument("--profile",choices=("span", "balanced"),default="span",help="span: year-boundary storm. balanced: several storms per class.",)args = parser.parse_args()if args.profile == "balanced":path = write_balanced_smoke(args.out)else:path = write_smoke(args.out)print(f"Wrote synthetic manifest {path}. Not real cyclones. Do not report scores from it.")if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Regression and classification metrics. No operational baseline is implied."""from __future__ import annotationsimport numpy as npimport pandas as pdfrom sklearn.metrics import f1_score, recall_scoredef regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")error = pred - truthreturn {"n": float(truth.size),"mae_kt": float(np.mean(np.abs(error))),"rmse_kt": float(np.sqrt(np.mean(error**2))),"bias_kt": float(np.mean(error)),}def _as_seed(value: int, name: str) -> int:if isinstance(value, bool) or not isinstance(value, (int, np.integer)):raise ValueError(f"{name} must be an integer")return int(value)def _storm_index(storm_ids: np.ndarray) -> list[np.ndarray]:"""Row positions of each storm, in order of first appearance."""order: list[str] = []buckets: dict[str, list[int]] = {}for index, storm in enumerate(np.asarray(storm_ids, dtype=object).ravel().tolist()):if storm is None or pd.isna(storm):raise ValueError("storm_ids must be present on every row")key = str(storm)if key not in buckets:buckets[key] = []order.append(key)buckets[key].append(index)return [np.asarray(buckets[key], dtype=np.int64) for key in order]def storm_bootstrap_metrics(y_true: np.ndarray,y_pred: np.ndarray,storm_ids: np.ndarray,*,n_resamples: int = 1000,seed: int = 0,ci_level: float = 0.95,) -> dict[str, float | int | str]:"""RMSE, MAE, and bias with a percentile interval that resamples storms.Bias is prediction minus true wind. Each resample draws as many stormIDs as there are storms, with replacement, and keeps every row of adrawn storm. A storm drawn twice contributes its rows twice. Rows arenot drawn on their own. The point values are the full sample, not themean of the resamples. Storms are ordered by first appearance. Thegenerator is ``numpy.random.default_rng(seed)``."""truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")if not np.isfinite(truth).all() or not np.isfinite(pred).all():raise ValueError("y_true and y_pred must be finite")ids = np.asarray(storm_ids, dtype=object).ravel()if ids.size != truth.size:raise ValueError("storm_ids must align with y_true")groups = _storm_index(ids)if not groups:raise ValueError("storm_ids must align with y_true")resamples = _as_seed(n_resamples, "n_resamples")if resamples < 1:raise ValueError("n_resamples must be at least 1")seed_value = _as_seed(seed, "seed")level = float(ci_level)if not 0.0 < level < 1.0:raise ValueError(f"ci_level must be between 0 and 1, got {level}")point = regression_metrics(truth, pred)error = pred - truthn_per = np.asarray([group.size for group in groups], dtype=np.float64)sum_abs = np.asarray([np.abs(error[group]).sum() for group in groups], dtype=np.float64)sum_sq = np.asarray([(error[group] ** 2).sum() for group in groups], dtype=np.float64)sum_err = np.asarray([error[group].sum() for group in groups], dtype=np.float64)drawn = np.random.default_rng(seed_value).integers(0, len(groups), size=(resamples, len(groups)))mae_s = np.empty(resamples, dtype=np.float64)rmse_s = np.empty(resamples, dtype=np.float64)bias_s = np.empty(resamples, dtype=np.float64)for index, draw in enumerate(drawn):counts = np.bincount(draw, minlength=len(groups)).astype(np.float64)total = float(counts @ n_per)mae_s[index] = float(counts @ sum_abs) / totalrmse_s[index] = float(np.sqrt((counts @ sum_sq) / total))bias_s[index] = float(counts @ sum_err) / totalalpha = (1.0 - level) / 2.0out: dict[str, float | int | str] = {"n_rows": int(truth.size),"n_storms": int(len(groups)),"mae_kt": float(point["mae_kt"]),"rmse_kt": float(point["rmse_kt"]),"bias_kt": float(point["bias_kt"]),"n_resamples": resamples,"seed": seed_value,"ci_level": level,"resample": "storm_id",}for name, samples in (("mae_kt", mae_s),("rmse_kt", rmse_s),("bias_kt", bias_s),):out[f"{name}_ci_low"] = float(np.quantile(samples, alpha, method="linear"))out[f"{name}_ci_high"] = float(np.quantile(samples, 1.0 - alpha, method="linear"))return outdef metrics_by_class(y_true: np.ndarray, y_pred: np.ndarray, classes: np.ndarray) -> dict[str, dict[str, float]]:truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()labels = np.asarray(classes)if len(labels) != truth.size:raise ValueError("classes must align with y_true")out: dict[str, dict[str, float]] = {}for name in pd.unique(labels):if pd.isna(name):continuemask = labels == nameif np.asarray(mask).sum() == 0:continueout[str(name)] = regression_metrics(truth[mask], pred[mask])return outdef mean_baseline(y_train: np.ndarray, n_rows: int) -> np.ndarray:"""Predict the training mean. Fit this on train storms only."""return np.full(n_rows, float(np.mean(np.asarray(y_train, dtype=np.float64))))def classification_metrics(y_true: np.ndarray,y_pred: np.ndarray,labels: tuple[str, ...],) -> dict[str, float]:"""Macro-F1 over classes present in ``y_true``, plus per-class recall.Recall is NaN when the validation side has no samples of that class.Accuracy is omitted on purpose: a single headline rate hides the rareintense classes."""truth = np.asarray(y_true).ravel()pred = np.asarray(y_pred).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")present = [label for label in labels if np.any(truth == label)]if not present:present = [str(value) for value in pd.unique(truth)]macro = float(f1_score(truth, pred, labels=present, average="macro", zero_division=0))recalls = recall_score(truth, pred, labels=list(labels), average=None, zero_division=0)out: dict[str, float] = {"n": float(truth.size), "macro_f1": macro}for label, recall in zip(labels, recalls, strict=True):if not np.any(truth == label):out[f"recall_{label}"] = float("nan")else:out[f"recall_{label}"] = float(recall)return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Regression and classification metrics. No operational baseline is implied."""from __future__ import annotationsimport numpy as npimport pandas as pdfrom sklearn.metrics import f1_score, recall_scoredef regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")error = pred - truthreturn {"n": float(truth.size),"mae_kt": float(np.mean(np.abs(error))),"rmse_kt": float(np.sqrt(np.mean(error**2))),"bias_kt": float(np.mean(error)),}def _as_seed(value: int, name: str) -> int:if isinstance(value, bool) or not isinstance(value, (int, np.integer)):raise ValueError(f"{name} must be an integer")return int(value)def _storm_index(storm_ids: np.ndarray) -> list[np.ndarray]:"""Row positions of each storm, in order of first appearance."""order: list[str] = []buckets: dict[str, list[int]] = {}for index, storm in enumerate(np.asarray(storm_ids, dtype=object).ravel().tolist()):if storm is None or pd.isna(storm):raise ValueError("storm_ids must be present on every row")key = str(storm)if key not in buckets:buckets[key] = []order.append(key)buckets[key].append(index)return [np.asarray(buckets[key], dtype=np.int64) for key in order]def storm_bootstrap_metrics(y_true: np.ndarray,y_pred: np.ndarray,storm_ids: np.ndarray,*,n_resamples: int = 1000,seed: int = 0,ci_level: float = 0.95,) -> dict[str, float | int | str]:"""RMSE, MAE, and bias with a percentile interval that resamples storms.Bias is prediction minus true wind. Each resample draws as many stormIDs as there are storms, with replacement, and keeps every row of adrawn storm. A storm drawn twice contributes its rows twice. Rows arenot drawn on their own. The point values are the full sample, not themean of the resamples. Storms are ordered by first appearance. Thegenerator is ``numpy.random.default_rng(seed)``."""truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")if not np.isfinite(truth).all() or not np.isfinite(pred).all():raise ValueError("y_true and y_pred must be finite")ids = np.asarray(storm_ids, dtype=object).ravel()if ids.size != truth.size:raise ValueError("storm_ids must align with y_true")groups = _storm_index(ids)if not groups:raise ValueError("storm_ids must align with y_true")resamples = _as_seed(n_resamples, "n_resamples")if resamples < 1:raise ValueError("n_resamples must be at least 1")seed_value = _as_seed(seed, "seed")level = float(ci_level)if not 0.0 < level < 1.0:raise ValueError(f"ci_level must be between 0 and 1, got {level}")point = regression_metrics(truth, pred)error = pred - truthn_per = np.asarray([group.size for group in groups], dtype=np.float64)sum_abs = np.asarray([np.abs(error[group]).sum() for group in groups], dtype=np.float64)sum_sq = np.asarray([(error[group] ** 2).sum() for group in groups], dtype=np.float64)sum_err = np.asarray([error[group].sum() for group in groups], dtype=np.float64)drawn = np.random.default_rng(seed_value).integers(0, len(groups), size=(resamples, len(groups)))mae_s = np.empty(resamples, dtype=np.float64)rmse_s = np.empty(resamples, dtype=np.float64)bias_s = np.empty(resamples, dtype=np.float64)for index, draw in enumerate(drawn):counts = np.bincount(draw, minlength=len(groups)).astype(np.float64)total = float(counts @ n_per)mae_s[index] = float(counts @ sum_abs) / totalrmse_s[index] = float(np.sqrt((counts @ sum_sq) / total))bias_s[index] = float(counts @ sum_err) / totalalpha = (1.0 - level) / 2.0out: dict[str, float | int | str] = {"n_rows": int(truth.size),"n_storms": int(len(groups)),"mae_kt": float(point["mae_kt"]),"rmse_kt": float(point["rmse_kt"]),"bias_kt": float(point["bias_kt"]),"n_resamples": resamples,"seed": seed_value,"ci_level": level,"resample": "storm_id",}for name, samples in (("mae_kt", mae_s),("rmse_kt", rmse_s),("bias_kt", bias_s),):out[f"{name}_ci_low"] = float(np.quantile(samples, alpha, method="linear"))out[f"{name}_ci_high"] = float(np.quantile(samples, 1.0 - alpha, method="linear"))return outdef metrics_by_class(y_true: np.ndarray, y_pred: np.ndarray, classes: np.ndarray) -> dict[str, dict[str, float]]:truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()labels = np.asarray(classes)if len(labels) != truth.size:raise ValueError("classes must align with y_true")out: dict[str, dict[str, float]] = {}for name in pd.unique(labels):if pd.isna(name):continuemask = labels == nameif np.asarray(mask).sum() == 0:continueout[str(name)] = regression_metrics(truth[mask], pred[mask])return outdef mean_baseline(y_train: np.ndarray, n_rows: int) -> np.ndarray:"""Predict the training mean. Fit this on train storms only."""return np.full(n_rows, float(np.mean(np.asarray(y_train, dtype=np.float64))))def classification_metrics(y_true: np.ndarray,y_pred: np.ndarray,labels: tuple[str, ...],) -> dict[str, float]:"""Macro-F1 over classes present in ``y_true``, plus per-class recall.Recall is NaN when the validation side has no samples of that class.Accuracy is omitted on purpose: a single headline rate hides the rareintense classes."""truth = np.asarray(y_true).ravel()pred = np.asarray(y_pred).ravel()if truth.shape != pred.shape or truth.size == 0:raise ValueError("y_true and y_pred must be non-empty and the same shape")present = [label for label in labels if np.any(truth == label)]if not present:present = [str(value) for value in pd.unique(truth)]macro = float(f1_score(truth, pred, labels=present, average="macro", zero_division=0))recalls = recall_score(truth, pred, labels=list(labels), average=None, zero_division=0)out: dict[str, float] = {"n": float(truth.size), "macro_f1": macro}for label, recall in zip(labels, recalls, strict=True):if not np.any(truth == label):out[f"recall_{label}"] = float("nan")else:out[f"recall_{label}"] = float(recall)return out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Model interfaces. Importing this module requires torch.Spatial size is not fixed. The caller supplies the frame size (``data.image_size``or a native infrared frame). Both regressors pool with ``AdaptiveAvgPool2d``before the heads. ``pretrained=True`` downloads ImageNet weights and is refusedunless ``CLOUDIE_ALLOW_PRETRAINED=1``."""from __future__ import annotationsimport osimport torchfrom torch import nnclass OptionalClassHead:"""Project-class logits. Absent when the caller does not ask for them."""@staticmethoddef build(feature_dim: int, n_classes: int | None) -> nn.Linear | None:if n_classes is None:return Nonecount = int(n_classes)if count < 1:raise ValueError("n_classes must be at least 1")return nn.Linear(feature_dim, count)class SimpleCNN(nn.Module):"""Small regressor for smoke tests and a first real baseline.The regression head predicts wind speed in knots. ``n_classes`` adds aclass head on the same pooled features. Dropout stays on the wind head."""def __init__(self,in_channels: int = 1,dropout: float = 0.3,n_classes: int | None = None,) -> None:super().__init__()self.feature_dim = 64self.features = nn.Sequential(nn.Conv2d(in_channels, 16, 3, padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(16, 32, 3, padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(32, 64, 3, padding=1),nn.ReLU(),nn.AdaptiveAvgPool2d(1),)self.head = nn.Sequential(nn.Flatten(), nn.Dropout(dropout), nn.Linear(64, 1))self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)def encode(self, inputs: torch.Tensor) -> torch.Tensor:return self.features(inputs).flatten(1)def forward(self, inputs: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:features = self.encode(inputs)wind = self.head(features)if self.class_head is None:return windreturn wind, self.class_head(features)class ResNetRegressor(nn.Module):"""ResNet-18 regressor. One-channel IR is repeated to three channels.Repeating keeps the pretrained first convolution. Replacing it woulddiscard those weights. ImageNet pretraining is not a physical prior.``pretrained=True`` downloads weights and must not run in CI unless``CLOUDIE_ALLOW_PRETRAINED=1``. The regression head predicts wind speedin knots. ``n_classes`` adds a class head on the same pooled features."""def __init__(self,in_channels: int = 1,pretrained: bool = False,dropout: float = 0.2,n_classes: int | None = None,) -> None:super().__init__()if in_channels not in (1, 3):raise ValueError("ResNet-18 keeps the 3-channel conv1. ""Pass 1 channel to repeat it, or 3 channels.")weights = self.imagenet_weights(pretrained)from torchvision.models import resnet18backbone = resnet18(weights=weights)if int(backbone.conv1.in_channels) != 3:raise RuntimeError("pretrained conv1 must stay 3-channel")# Adaptive pool, so a native frame and a resized frame share the head.backbone.avgpool = nn.AdaptiveAvgPool2d(1)in_features = backbone.fc.in_featuresbackbone.fc = nn.Identity()self.backbone = backboneself.feature_dim = in_featuresself.repeat_to_rgb = in_channels == 1self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(in_features, 1))self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)@staticmethoddef imagenet_weights(pretrained: bool):"""ImageNet weights, or None.``weights=None`` builds the architecture without a download.``pretrained=True`` asks for ``ResNet18_Weights.DEFAULT`` and isrefused unless ``CLOUDIE_ALLOW_PRETRAINED=1``."""if not pretrained:return Noneif os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":raise RuntimeError("pretrained: true downloads ImageNet weights and must not run in CI. ""Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download.")from torchvision.models import ResNet18_Weightsreturn ResNet18_Weights.DEFAULTdef encode(self, inputs: torch.Tensor) -> torch.Tensor:if self.repeat_to_rgb and inputs.shape[1] == 1:inputs = inputs.repeat(1, 3, 1, 1)return self.backbone(inputs)def forward(self, inputs: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:features = self.encode(inputs)wind = self.head(features)if self.class_head is None:return windreturn wind, self.class_head(features)class ConvLSTMCell(nn.Module):"""One convolutional LSTM step. Hidden state stays on the image grid."""def __init__(self, in_channels: int, hidden: int) -> None:super().__init__()self.hidden = hiddenself.gates = nn.Conv2d(in_channels + hidden, 4 * hidden, kernel_size=3, padding=1)def forward(self, inputs: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:hidden, cell = stateinput_gate, forget_gate, candidate, output_gate = self.gates(torch.cat([inputs, hidden], dim=1)).chunk(4, dim=1)cell = torch.sigmoid(forget_gate) * cell + torch.sigmoid(input_gate) * torch.tanh(candidate)hidden = torch.sigmoid(output_gate) * torch.tanh(cell)return hidden, cellclass ConvLSTMRegressor(nn.Module):"""Four-frame ConvLSTM. The tensor is infrared imagery.Best-track wind, R34, and radius of maximum wind are not inputs. Thetraining net attaches a size head to ``encode`` only after those labelsexist. This module does not flip Southern Hemisphere frames."""def __init__(self,in_channels: int = 1,hidden: int = 16,n_frames: int = 4,dropout: float = 0.3,) -> None:super().__init__()if n_frames != 4:raise ValueError("ConvLSTM uses 4 frames")if hidden < 1:raise ValueError("hidden must be at least 1")self.n_frames = n_framesself.hidden = hiddenself.feature_dim = hiddenself.cell = ConvLSTMCell(in_channels, hidden)self.pool = nn.AdaptiveAvgPool2d(1)self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden, 1))def encode(self, inputs: torch.Tensor) -> torch.Tensor:if inputs.ndim != 5:raise ValueError("ConvLSTM expects (batch, 4, channels, height, width) infrared frames")if int(inputs.shape[1]) != self.n_frames:raise ValueError(f"ConvLSTM expects {self.n_frames} frames, got {int(inputs.shape[1])}")batch, _steps, _channels, height, width = inputs.shapehidden = inputs.new_zeros(batch, self.hidden, height, width)cell = inputs.new_zeros(batch, self.hidden, height, width)for step in range(self.n_frames):hidden, cell = self.cell(inputs[:, step], (hidden, cell))return self.pool(hidden).flatten(1)def forward(self, inputs: torch.Tensor) -> torch.Tensor:return self.head(self.encode(inputs))class MCDropout:"""Stochastic passes with BatchNorm frozen and Dropout left active.The returned standard deviation is dropout noise. It is not a calibratedprediction interval."""@staticmethoddef enable(module: nn.Module) -> None:"""Eval mode for the module, then train mode for Dropout only."""module.eval()for layer in module.modules():if isinstance(layer, nn.Dropout):layer.train()@staticmethod@torch.no_grad()def predict(module: nn.Module, inputs: torch.Tensor, n_samples: int) -> tuple[torch.Tensor, torch.Tensor]:"""Mean and std over ``n_samples`` stochastic forwards.``n_samples`` is ``model.mc_samples`` from config. A class-head tuplecontributes the wind-speed tensor only."""if n_samples < 2:raise ValueError("n_samples must be at least 2")MCDropout.enable(module)draws = []for _ in range(n_samples):output = module(inputs)if isinstance(output, tuple):output = output[0]draws.append(output)stacked = torch.stack(draws, dim=0)return stacked.mean(dim=0), stacked.std(dim=0, unbiased=True)def enable_mc_dropout(module: nn.Module) -> None:"""Eval mode for BatchNorm, train mode for Dropout."""MCDropout.enable(module)@torch.no_grad()def mc_dropout_predict(module: nn.Module, inputs: torch.Tensor, n_samples: int = 20) -> tuple[torch.Tensor, torch.Tensor]:"""Return mean and std. This is not a calibrated prediction interval."""return MCDropout.predict(module, inputs, n_samples)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""Model interfaces. Importing this module requires torch.Spatial size is not fixed. The caller supplies the frame size (``data.image_size``or a native infrared frame). Both regressors pool with ``AdaptiveAvgPool2d``before the heads. ``pretrained=True`` downloads ImageNet weights and is refusedunless ``CLOUDIE_ALLOW_PRETRAINED=1``."""from __future__ import annotationsimport osimport torchfrom torch import nnclass OptionalClassHead:"""Project-class logits. Absent when the caller does not ask for them."""@staticmethoddef build(feature_dim: int, n_classes: int | None) -> nn.Linear | None:if n_classes is None:return Nonecount = int(n_classes)if count < 1:raise ValueError("n_classes must be at least 1")return nn.Linear(feature_dim, count)class SimpleCNN(nn.Module):"""Small regressor for smoke tests and a first real baseline.The regression head predicts wind speed in knots. ``n_classes`` adds aclass head on the same pooled features. Dropout stays on the wind head."""def __init__(self,in_channels: int = 1,dropout: float = 0.3,n_classes: int | None = None,) -> None:super().__init__()self.feature_dim = 64self.features = nn.Sequential(nn.Conv2d(in_channels, 16, 3, padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(16, 32, 3, padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(32, 64, 3, padding=1),nn.ReLU(),nn.AdaptiveAvgPool2d(1),)self.head = nn.Sequential(nn.Flatten(), nn.Dropout(dropout), nn.Linear(64, 1))self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)def encode(self, inputs: torch.Tensor) -> torch.Tensor:return self.features(inputs).flatten(1)def forward(self, inputs: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:features = self.encode(inputs)wind = self.head(features)if self.class_head is None:return windreturn wind, self.class_head(features)class ResNetRegressor(nn.Module):"""ResNet-18 regressor. One-channel IR is repeated to three channels.Repeating keeps the pretrained first convolution. Replacing it woulddiscard those weights. ImageNet pretraining is not a physical prior.``pretrained=True`` downloads weights and must not run in CI unless``CLOUDIE_ALLOW_PRETRAINED=1``. The regression head predicts wind speedin knots. ``n_classes`` adds a class head on the same pooled features."""def __init__(self,in_channels: int = 1,pretrained: bool = False,dropout: float = 0.2,n_classes: int | None = None,) -> None:super().__init__()if in_channels not in (1, 3):raise ValueError("ResNet-18 keeps the 3-channel conv1. ""Pass 1 channel to repeat it, or 3 channels.")weights = self.imagenet_weights(pretrained)from torchvision.models import resnet18backbone = resnet18(weights=weights)if int(backbone.conv1.in_channels) != 3:raise RuntimeError("pretrained conv1 must stay 3-channel")# Adaptive pool, so a native frame and a resized frame share the head.backbone.avgpool = nn.AdaptiveAvgPool2d(1)in_features = backbone.fc.in_featuresbackbone.fc = nn.Identity()self.backbone = backboneself.feature_dim = in_featuresself.repeat_to_rgb = in_channels == 1self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(in_features, 1))self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)@staticmethoddef imagenet_weights(pretrained: bool):"""ImageNet weights, or None.``weights=None`` builds the architecture without a download.``pretrained=True`` asks for ``ResNet18_Weights.DEFAULT`` and isrefused unless ``CLOUDIE_ALLOW_PRETRAINED=1``."""if not pretrained:return Noneif os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":raise RuntimeError("pretrained: true downloads ImageNet weights and must not run in CI. ""Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download.")from torchvision.models import ResNet18_Weightsreturn ResNet18_Weights.DEFAULTdef encode(self, inputs: torch.Tensor) -> torch.Tensor:if self.repeat_to_rgb and inputs.shape[1] == 1:inputs = inputs.repeat(1, 3, 1, 1)return self.backbone(inputs)def forward(self, inputs: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:features = self.encode(inputs)wind = self.head(features)if self.class_head is None:return windreturn wind, self.class_head(features)class ConvLSTMCell(nn.Module):"""One convolutional LSTM step. Hidden state stays on the image grid."""def __init__(self, in_channels: int, hidden: int) -> None:super().__init__()self.hidden = hiddenself.gates = nn.Conv2d(in_channels + hidden, 4 * hidden, kernel_size=3, padding=1)def forward(self, inputs: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:hidden, cell = stateinput_gate, forget_gate, candidate, output_gate = self.gates(torch.cat([inputs, hidden], dim=1)).chunk(4, dim=1)cell = torch.sigmoid(forget_gate) * cell + torch.sigmoid(input_gate) * torch.tanh(candidate)hidden = torch.sigmoid(output_gate) * torch.tanh(cell)return hidden, cellclass ConvLSTMRegressor(nn.Module):"""Four-frame ConvLSTM. The tensor is infrared imagery.Best-track wind, R34, and radius of maximum wind are not inputs. Thetraining net attaches a size head to ``encode`` only after those labelsexist. This module does not flip Southern Hemisphere frames."""def __init__(self,in_channels: int = 1,hidden: int = 16,n_frames: int = 4,dropout: float = 0.3,) -> None:super().__init__()if n_frames != 4:raise ValueError("ConvLSTM uses 4 frames")if hidden < 1:raise ValueError("hidden must be at least 1")self.n_frames = n_framesself.hidden = hiddenself.feature_dim = hiddenself.cell = ConvLSTMCell(in_channels, hidden)self.pool = nn.AdaptiveAvgPool2d(1)self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden, 1))def encode(self, inputs: torch.Tensor) -> torch.Tensor:if inputs.ndim != 5:raise ValueError("ConvLSTM expects (batch, 4, channels, height, width) infrared frames")if int(inputs.shape[1]) != self.n_frames:raise ValueError(f"ConvLSTM expects {self.n_frames} frames, got {int(inputs.shape[1])}")batch, _steps, _channels, height, width = inputs.shapehidden = inputs.new_zeros(batch, self.hidden, height, width)cell = inputs.new_zeros(batch, self.hidden, height, width)for step in range(self.n_frames):hidden, cell = self.cell(inputs[:, step], (hidden, cell))return self.pool(hidden).flatten(1)def forward(self, inputs: torch.Tensor) -> torch.Tensor:return self.head(self.encode(inputs))class MCDropout:"""Stochastic passes with BatchNorm frozen and Dropout left active.The returned standard deviation is dropout noise. It is not a calibratedprediction interval."""@staticmethoddef enable(module: nn.Module) -> None:"""Eval mode for the module, then train mode for Dropout only."""module.eval()for layer in module.modules():if isinstance(layer, nn.Dropout):layer.train()@staticmethod@torch.no_grad()def predict(module: nn.Module, inputs: torch.Tensor, n_samples: int) -> tuple[torch.Tensor, torch.Tensor]:"""Mean and std over ``n_samples`` stochastic forwards.``n_samples`` is ``model.mc_samples`` from config. A class-head tuplecontributes the wind-speed tensor only."""if n_samples < 2:raise ValueError("n_samples must be at least 2")MCDropout.enable(module)draws = []for _ in range(n_samples):output = module(inputs)if isinstance(output, tuple):output = output[0]draws.append(output)stacked = torch.stack(draws, dim=0)return stacked.mean(dim=0), stacked.std(dim=0, unbiased=True)def enable_mc_dropout(module: nn.Module) -> None:"""Eval mode for BatchNorm, train mode for Dropout."""MCDropout.enable(module)@torch.no_grad()def mc_dropout_predict(module: nn.Module, inputs: torch.Tensor, n_samples: int = 20) -> tuple[torch.Tensor, torch.Tensor]:"""Return mean and std. This is not a calibrated prediction interval."""return MCDropout.predict(module, inputs, n_samples)
1234567891011121314151617181920212223242526"""The only import point for the network and for MC-dropout.``src.model.MCDropout`` is the class from the merged regressor work.``src.train.build_net`` wraps that module and ``cloudie.train`` re-exportsit. This file does not copy either implementation."""from __future__ import annotationsclass ModelAccess:"""Lazy imports so a gate check does not load torch."""@staticmethoddef mc_dropout():"""Return ``src.model.MCDropout``."""from src.model import MCDropoutreturn MCDropout@staticmethoddef build_net(config: dict, size_head: bool = False):"""Return the training wrapper around the configured regressor."""from src.train import build_netreturn build_net(config, size_head=size_head)1234567891011121314151617181920212223242526"""The only import point for the network and for MC-dropout.``src.model.MCDropout`` is the class from the merged regressor work.``src.train.build_net`` wraps that module and ``cloudie.train`` re-exportsit. This file does not copy either implementation."""from __future__ import annotationsclass ModelAccess:"""Lazy imports so a gate check does not load torch."""@staticmethoddef mc_dropout():"""Return ``src.model.MCDropout``."""from src.model import MCDropoutreturn MCDropout@staticmethoddef build_net(config: dict, size_head: bool = False):"""Return the training wrapper around the configured regressor."""from src.train import build_netreturn build_net(config, size_head=size_head)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""Build a Cloudie manifest from the NASA Tropical Storm Wind Speed dataset.The main path is TorchGeo ``TropicalCyclone`` (Maskey et al. 2020,https://doi.org/10.1109/JSTARS.2020.3011907). TorchGeo checks the files andreads ``{training,test}_set_{features,labels}.csv``; images sit at``<root>/<split>/<Image ID>.jpg``. A one-time download is``TropicalCyclone(root, split, download=True)`` from the public SourceCooperative blob. The copy tool and the mirror are named in``docs/DATA_SOURCES.md``. The Hugging Face repo``torchgeo/tropical_cyclone`` is only a mirror. CI never downloads either.Images keep their native size. Nothing in this module resizes. Most framesare 366 x 366, but the real train side also has 1093 x 1093 frames (storedas grey in an RGB JPEG), which TorchGeo's own ``__getitem__`` bilinearlyresizes to 366. ``native_height``, ``native_width`` and ``orig_size`` arerecorded per row. An empirical check (scripted in the PR notes) found that a1093 frame covers the same footprint as a 366 frame at about 3x the pixeldensity: its spatial autocorrelation length is about 3.2x longer in pixels,and after a 3x area average its texture and cold-cloud fraction match the366 frames, while a 366 centre crop does not. ``to_working_grid`` thereforearea-averages to the 366 working grid, and ``working_resample`` marks whichrows need it. The manifest itself is never resampled.Colour-enhanced frames (``npf_000``, ``npf_001``) are not grey IR. They aredropped from the manifest and listed with a reason in an exclusions CSV nextto it.The manifest never has a ``split`` column. The official side goes only to``source_split``. ``src.splits.assign_storms`` writes ``split`` by storm.Pixel values are an 8-bit rendering of IR brightness, not calibrated Kelvin.Call them pixel stats until a calibration table exists.Labels are HURDAT2 best-track maximum sustained winds in knots. HURDAT2 uses1-minute sustained winds, so ``wind_averaging`` is ``1min``.There is no distance-to-land join. ``storm_id`` is a 3-letter competitionidentifier and the only time field is ``relative_time_s``, so an IBTrACSmatch would be a guess. ``near_land`` stays unknown. See``nasa_tc/audit/README.md``. Do not invent a mapping.The competition's own train/test sides split frames, not storms: many teststorms also appear in train. ``source_split`` keeps that side for referenceonly. Do not train on one side and score on the other. Use the storm-wisesplitter in ``src.splits`` on the union instead."""from __future__ import annotationsimport argparseimport jsonfrom collections.abc import Callablefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validWIND_AVERAGING = "1min"LABEL_SOURCE = "nasa_tropical_storm_competition_hurdat2"SPLITS = ("train", "test")WORKING_SIZE = 366 # TorchGeo's grid and config data.image_size: native (PR #16)# Known non-IR frames in this release. Frames detected as colour are excluded too.KNOWN_EXCLUSIONS = {"npf_000": "colour-enhanced render, not grey IR","npf_001": "colour-enhanced render, not grey IR",}EXCLUSION_COLUMNS = ["sample_id", "storm_id", "source_split", "reason"]_FILE_STEM = {"train": "training_set", "test": "test_set"}def torchgeo_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:"""Return TorchGeo's features and labels frames for one competition side.Imports TorchGeo lazily so tests and the web app do not need it.``download`` stays false: this reader never fetches imagery."""import importlibtropical = importlib.import_module("torchgeo.datasets")dataset = tropical.TropicalCyclone(root=str(root), split=split, download=False)return dataset.features, dataset.labelsdef csv_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:"""Read the same CSVs TorchGeo reads, without importing TorchGeo."""stem = _FILE_STEM[split]root = Path(root)return (pd.read_csv(root / f"{stem}_features.csv"),pd.read_csv(root / f"{stem}_labels.csv"),)def build_manifest(root: str | Path,manifest_dir: str | Path,splits: tuple[str, ...] = SPLITS,tables: Callable[[str | Path, str], tuple[pd.DataFrame, pd.DataFrame]] = torchgeo_tables,check_images: bool = True,keep_excluded: bool = False,) -> pd.DataFrame:"""Return a validated manifest. ``image_path`` is relative to ``manifest_dir``."""root = Path(root).resolve()manifest_dir = Path(manifest_dir).resolve()frames = []for split in splits:if split not in _FILE_STEM:raise ValueError(f"unknown split {split}")features, labels = tables(root, split)merged = features.merge(labels, on="Image ID", how="inner", validate="1:1")if len(merged) != len(labels) or len(merged) != len(features):raise ValueError(f"{split}: features and labels do not line up")image_dir = root / splitpaths = [image_dir / f"{image_id}.jpg" for image_id in merged["Image ID"]]frames.append(pd.DataFrame({"sample_id": merged["Image ID"].astype(str),"image_path": [_relative(path, manifest_dir) for path in paths],"storm_id": merged["Storm ID"].astype(str),"wind_speed_kt": pd.to_numeric(merged["Wind Speed"]),"relative_time_s": pd.to_numeric(merged["Relative Time"]),"ocean": merged["Ocean"].astype(int),"basin": merged["Ocean"].map({1: "ATL", 2: "EPAC"}).fillna("unknown"),"sensor": "GOES","channel": "IR","pixel_units": "8bit_uncalibrated","wind_averaging": WIND_AVERAGING,"label_source": LABEL_SOURCE,"center_source": "dataset_precentered","source_split": split,"is_synthetic": False,}))frame = pd.concat(frames, ignore_index=True)if check_images:frame = add_native_size(frame, manifest_dir)if keep_excluded:return frameframe, _ = split_exclusions(frame)return require_valid(frame)def split_exclusions(frame: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:"""Return (kept, excluded). Excluded rows carry a ``reason``."""reasons = frame["sample_id"].map(KNOWN_EXCLUSIONS)if "grey_ir" in frame:detected = ~frame["grey_ir"].astype(bool) & reasons.isna()reasons = reasons.mask(detected, "channels differ, not grey IR")drop = reasons.notna()excluded = frame.loc[drop, ["sample_id", "storm_id", "source_split"]].assign(reason=reasons[drop])return frame.loc[~drop].reset_index(drop=True), excluded.reset_index(drop=True)def exclusions_for(frame: pd.DataFrame) -> pd.DataFrame:"""Exclusions for a raw (pre-filter) frame, in the CSV column order."""return split_exclusions(frame)[1][EXCLUSION_COLUMNS]def _relative(path: Path, base: Path) -> str:try:return path.relative_to(base).as_posix()except ValueError:return path.as_posix()def add_native_size(frame: pd.DataFrame, manifest_dir: str | Path) -> pd.DataFrame:"""Record native size and JPEG mode. Fails if any image is missing."""from PIL import Imagemanifest_dir = Path(manifest_dir)heights, widths, modes, grey, missing = [], [], [], [], []for image_path in frame["image_path"]:path = Path(image_path)path = path if path.is_absolute() else manifest_dir / pathif not path.is_file():missing.append(str(path))heights.append(-1)widths.append(-1)modes.append("")grey.append(False)continuewith Image.open(path) as image:widths.append(image.width)heights.append(image.height)modes.append(image.mode)grey.append(image.mode == "L" or _channels_identical(np.asarray(image)))if missing:raise FileNotFoundError(f"{len(missing)} images missing, first: {missing[:3]}")out = frame.copy()out["native_height"] = heightsout["native_width"] = widthsout["source_mode"] = modes# False for colour-enhanced frames (npf_000/001 in this release). load_ir# refuses them, so filter on this column before training.out["grey_ir"] = greyout["orig_size"] = [h if h == w else -1 for h, w in zip(heights, widths)]if (out["orig_size"] < 0).any():raise ValueError("non-square frame found; orig_size assumes square chips")out["working_resample"] = np.where(out["orig_size"] == WORKING_SIZE, "none", "area_average")return outdef _channels_identical(array: np.ndarray) -> bool:if array.ndim != 3:return Truereturn bool(np.array_equal(array[..., 0], array[..., 1]) and np.array_equal(array[..., 0], array[..., 2]))def load_ir(path: str | Path) -> np.ndarray:"""Read one frame as float32 at native size, single channel.Three-channel JPEGs are accepted only when all channels match, so acolour enhancement is never mistaken for IR."""from PIL import Imagewith Image.open(path) as image:array = np.asarray(image)if array.ndim == 3:if not _channels_identical(array):raise ValueError(f"{path}: channels differ, not a grey IR render")array = array[..., 0]return array.astype(np.float32)def to_working_grid(array: np.ndarray, size: int = WORKING_SIZE) -> tuple[np.ndarray, bool]:"""Area-average a frame onto the ``size`` grid. Returns (array, resampled).Use only for frames that cover the same footprint (the 1093 frames do).A frame already at ``size`` is returned unchanged."""from PIL import Imageif array.shape == (size, size):return array.astype(np.float32), Falseif array.ndim != 2 or array.shape[0] != array.shape[1] or array.shape[0] < size:raise ValueError(f"expected a square frame of at least {size}px, got {array.shape}")image = Image.fromarray(array.astype(np.float32), mode="F")return np.asarray(image.resize((size, size), resample=Image.BOX), dtype=np.float32), Truedef summarize(frame: pd.DataFrame) -> dict[str, object]:by_side = {side: {"rows": int((frame["source_split"] == side).sum()),"storms": int(frame.loc[frame["source_split"] == side, "storm_id"].nunique()),}for side in sorted(frame["source_split"].unique())}sides = [set(frame.loc[frame["source_split"] == side, "storm_id"]) for side in by_side]shared = len(set.intersection(*sides)) if len(sides) > 1 else 0return {"rows": int(len(frame)),"unique_storms": int(frame["storm_id"].nunique()),"by_source_split": by_side,"storms_on_both_source_sides": shared,"wind_kt_min": float(frame["wind_speed_kt"].min()),"wind_kt_max": float(frame["wind_speed_kt"].max()),"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),"native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])})if "native_height" in frameelse [],"source_modes": frame["source_mode"].value_counts().to_dict()if "source_mode" in frameelse {},"frames_not_grey_ir": sorted(frame.loc[~frame["grey_ir"], "sample_id"]) if "grey_ir" in frame else [],"native_size_counts": {f"{h}x{w}": int(n)for (h, w), n in frame.groupby(["native_height", "native_width"]).size().items()}if "native_height" in frameelse {},"orig_size_counts": {int(k): int(v) for k, v in frame["orig_size"].value_counts().items()}if "orig_size" in frameelse {},"frames_to_area_average_to_366": int((frame["working_resample"] == "area_average").sum())if "working_resample" in frameelse 0,"has_split_column": "split" in frame.columns,"wind_averaging": sorted(frame["wind_averaging"].unique()),"is_synthetic": bool(frame["is_synthetic"].any()),}def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path, index: int = 0) -> dict[str, object]:import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltrow = frame.iloc[index]path = Path(row["image_path"])path = path if path.is_absolute() else Path(manifest_dir) / pathimage = load_ir(path)fig, ax = plt.subplots(figsize=(4, 4))ax.imshow(image, cmap="gray")ax.set_title(f"{row['sample_id']} | {row['wind_speed_kt']:.0f} kt (1min) | NASA TC, real")ax.axis("off")Path(out).parent.mkdir(parents=True, exist_ok=True)fig.savefig(out, dpi=100, bbox_inches="tight")plt.close(fig)return {"sample_id": row["sample_id"], "wind_speed_kt": float(row["wind_speed_kt"]), "shape": list(image.shape), "png": str(out)}def storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:"""Run the project splitter on the combined manifest and assert no storm leaks."""from src.splits import assert_no_group_leakage, assign_stormsif "split" in frame.columns:raise ValueError("manifest must not carry split; use source_split for the official side")assigned = assign_storms(frame, strategy, seed=seed)parts = [assigned.loc[assigned["split"] == name] for name in ("train", "val", "test")]assert_no_group_leakage(*parts)return {"strategy": strategy,"rows": {name: int(len(part)) for name, part in zip(("train", "val", "test"), parts)},"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(("train", "val", "test"), parts)},"leakage": "none",}def main() -> None:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--root", required=True, help="TorchGeo TropicalCyclone root")parser.add_argument("--out", default="data/nasa_tc/manifest.csv")parser.add_argument("--splits", nargs="+", default=list(SPLITS))parser.add_argument("--reader", choices=["torchgeo", "csv"], default="torchgeo")parser.add_argument("--summary", default="reports/nasa_tc_summary.json")parser.add_argument("--sample-png", default="reports/nasa_tc_sample.png")parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/nasa_tc_exclusions.csv")args = parser.parse_args()out = Path(args.out)out.parent.mkdir(parents=True, exist_ok=True)tables = torchgeo_tables if args.reader == "torchgeo" else csv_tablesraw = build_manifest(args.root, out.parent, tuple(args.splits), tables, keep_excluded=True)excluded = exclusions_for(raw)frame = require_valid(split_exclusions(raw)[0])exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "nasa_tc_exclusions.csv"excluded.to_csv(exclusions_path, index=False)frame.drop(columns=["imd5_class"]).to_csv(out, index=False)summary = summarize(frame)summary["excluded"] = {"count": int(len(excluded)), "sample_ids": excluded["sample_id"].tolist(), "file": str(exclusions_path)}summary["storm_split_check"] = storm_split_check(frame)summary["reader"] = args.readersummary["manifest"] = str(out)summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)Path(args.summary).parent.mkdir(parents=True, exist_ok=True)Path(args.summary).write_text(json.dumps(summary, indent=2))print(json.dumps(summary, indent=2))if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""Build a Cloudie manifest from the NASA Tropical Storm Wind Speed dataset.The main path is TorchGeo ``TropicalCyclone`` (Maskey et al. 2020,https://doi.org/10.1109/JSTARS.2020.3011907). TorchGeo checks the files andreads ``{training,test}_set_{features,labels}.csv``; images sit at``<root>/<split>/<Image ID>.jpg``. A one-time download is``TropicalCyclone(root, split, download=True)`` from the public SourceCooperative blob. The copy tool and the mirror are named in``docs/DATA_SOURCES.md``. The Hugging Face repo``torchgeo/tropical_cyclone`` is only a mirror. CI never downloads either.Images keep their native size. Nothing in this module resizes. Most framesare 366 x 366, but the real train side also has 1093 x 1093 frames (storedas grey in an RGB JPEG), which TorchGeo's own ``__getitem__`` bilinearlyresizes to 366. ``native_height``, ``native_width`` and ``orig_size`` arerecorded per row. An empirical check (scripted in the PR notes) found that a1093 frame covers the same footprint as a 366 frame at about 3x the pixeldensity: its spatial autocorrelation length is about 3.2x longer in pixels,and after a 3x area average its texture and cold-cloud fraction match the366 frames, while a 366 centre crop does not. ``to_working_grid`` thereforearea-averages to the 366 working grid, and ``working_resample`` marks whichrows need it. The manifest itself is never resampled.Colour-enhanced frames (``npf_000``, ``npf_001``) are not grey IR. They aredropped from the manifest and listed with a reason in an exclusions CSV nextto it.The manifest never has a ``split`` column. The official side goes only to``source_split``. ``src.splits.assign_storms`` writes ``split`` by storm.Pixel values are an 8-bit rendering of IR brightness, not calibrated Kelvin.Call them pixel stats until a calibration table exists.Labels are HURDAT2 best-track maximum sustained winds in knots. HURDAT2 uses1-minute sustained winds, so ``wind_averaging`` is ``1min``.There is no distance-to-land join. ``storm_id`` is a 3-letter competitionidentifier and the only time field is ``relative_time_s``, so an IBTrACSmatch would be a guess. ``near_land`` stays unknown. See``nasa_tc/audit/README.md``. Do not invent a mapping.The competition's own train/test sides split frames, not storms: many teststorms also appear in train. ``source_split`` keeps that side for referenceonly. Do not train on one side and score on the other. Use the storm-wisesplitter in ``src.splits`` on the union instead."""from __future__ import annotationsimport argparseimport jsonfrom collections.abc import Callablefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validWIND_AVERAGING = "1min"LABEL_SOURCE = "nasa_tropical_storm_competition_hurdat2"SPLITS = ("train", "test")WORKING_SIZE = 366 # TorchGeo's grid and config data.image_size: native (PR #16)# Known non-IR frames in this release. Frames detected as colour are excluded too.KNOWN_EXCLUSIONS = {"npf_000": "colour-enhanced render, not grey IR","npf_001": "colour-enhanced render, not grey IR",}EXCLUSION_COLUMNS = ["sample_id", "storm_id", "source_split", "reason"]_FILE_STEM = {"train": "training_set", "test": "test_set"}def torchgeo_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:"""Return TorchGeo's features and labels frames for one competition side.Imports TorchGeo lazily so tests and the web app do not need it.``download`` stays false: this reader never fetches imagery."""import importlibtropical = importlib.import_module("torchgeo.datasets")dataset = tropical.TropicalCyclone(root=str(root), split=split, download=False)return dataset.features, dataset.labelsdef csv_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:"""Read the same CSVs TorchGeo reads, without importing TorchGeo."""stem = _FILE_STEM[split]root = Path(root)return (pd.read_csv(root / f"{stem}_features.csv"),pd.read_csv(root / f"{stem}_labels.csv"),)def build_manifest(root: str | Path,manifest_dir: str | Path,splits: tuple[str, ...] = SPLITS,tables: Callable[[str | Path, str], tuple[pd.DataFrame, pd.DataFrame]] = torchgeo_tables,check_images: bool = True,keep_excluded: bool = False,) -> pd.DataFrame:"""Return a validated manifest. ``image_path`` is relative to ``manifest_dir``."""root = Path(root).resolve()manifest_dir = Path(manifest_dir).resolve()frames = []for split in splits:if split not in _FILE_STEM:raise ValueError(f"unknown split {split}")features, labels = tables(root, split)merged = features.merge(labels, on="Image ID", how="inner", validate="1:1")if len(merged) != len(labels) or len(merged) != len(features):raise ValueError(f"{split}: features and labels do not line up")image_dir = root / splitpaths = [image_dir / f"{image_id}.jpg" for image_id in merged["Image ID"]]frames.append(pd.DataFrame({"sample_id": merged["Image ID"].astype(str),"image_path": [_relative(path, manifest_dir) for path in paths],"storm_id": merged["Storm ID"].astype(str),"wind_speed_kt": pd.to_numeric(merged["Wind Speed"]),"relative_time_s": pd.to_numeric(merged["Relative Time"]),"ocean": merged["Ocean"].astype(int),"basin": merged["Ocean"].map({1: "ATL", 2: "EPAC"}).fillna("unknown"),"sensor": "GOES","channel": "IR","pixel_units": "8bit_uncalibrated","wind_averaging": WIND_AVERAGING,"label_source": LABEL_SOURCE,"center_source": "dataset_precentered","source_split": split,"is_synthetic": False,}))frame = pd.concat(frames, ignore_index=True)if check_images:frame = add_native_size(frame, manifest_dir)if keep_excluded:return frameframe, _ = split_exclusions(frame)return require_valid(frame)def split_exclusions(frame: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:"""Return (kept, excluded). Excluded rows carry a ``reason``."""reasons = frame["sample_id"].map(KNOWN_EXCLUSIONS)if "grey_ir" in frame:detected = ~frame["grey_ir"].astype(bool) & reasons.isna()reasons = reasons.mask(detected, "channels differ, not grey IR")drop = reasons.notna()excluded = frame.loc[drop, ["sample_id", "storm_id", "source_split"]].assign(reason=reasons[drop])return frame.loc[~drop].reset_index(drop=True), excluded.reset_index(drop=True)def exclusions_for(frame: pd.DataFrame) -> pd.DataFrame:"""Exclusions for a raw (pre-filter) frame, in the CSV column order."""return split_exclusions(frame)[1][EXCLUSION_COLUMNS]def _relative(path: Path, base: Path) -> str:try:return path.relative_to(base).as_posix()except ValueError:return path.as_posix()def add_native_size(frame: pd.DataFrame, manifest_dir: str | Path) -> pd.DataFrame:"""Record native size and JPEG mode. Fails if any image is missing."""from PIL import Imagemanifest_dir = Path(manifest_dir)heights, widths, modes, grey, missing = [], [], [], [], []for image_path in frame["image_path"]:path = Path(image_path)path = path if path.is_absolute() else manifest_dir / pathif not path.is_file():missing.append(str(path))heights.append(-1)widths.append(-1)modes.append("")grey.append(False)continuewith Image.open(path) as image:widths.append(image.width)heights.append(image.height)modes.append(image.mode)grey.append(image.mode == "L" or _channels_identical(np.asarray(image)))if missing:raise FileNotFoundError(f"{len(missing)} images missing, first: {missing[:3]}")out = frame.copy()out["native_height"] = heightsout["native_width"] = widthsout["source_mode"] = modes# False for colour-enhanced frames (npf_000/001 in this release). load_ir# refuses them, so filter on this column before training.out["grey_ir"] = greyout["orig_size"] = [h if h == w else -1 for h, w in zip(heights, widths)]if (out["orig_size"] < 0).any():raise ValueError("non-square frame found; orig_size assumes square chips")out["working_resample"] = np.where(out["orig_size"] == WORKING_SIZE, "none", "area_average")return outdef _channels_identical(array: np.ndarray) -> bool:if array.ndim != 3:return Truereturn bool(np.array_equal(array[..., 0], array[..., 1]) and np.array_equal(array[..., 0], array[..., 2]))def load_ir(path: str | Path) -> np.ndarray:"""Read one frame as float32 at native size, single channel.Three-channel JPEGs are accepted only when all channels match, so acolour enhancement is never mistaken for IR."""from PIL import Imagewith Image.open(path) as image:array = np.asarray(image)if array.ndim == 3:if not _channels_identical(array):raise ValueError(f"{path}: channels differ, not a grey IR render")array = array[..., 0]return array.astype(np.float32)def to_working_grid(array: np.ndarray, size: int = WORKING_SIZE) -> tuple[np.ndarray, bool]:"""Area-average a frame onto the ``size`` grid. Returns (array, resampled).Use only for frames that cover the same footprint (the 1093 frames do).A frame already at ``size`` is returned unchanged."""from PIL import Imageif array.shape == (size, size):return array.astype(np.float32), Falseif array.ndim != 2 or array.shape[0] != array.shape[1] or array.shape[0] < size:raise ValueError(f"expected a square frame of at least {size}px, got {array.shape}")image = Image.fromarray(array.astype(np.float32), mode="F")return np.asarray(image.resize((size, size), resample=Image.BOX), dtype=np.float32), Truedef summarize(frame: pd.DataFrame) -> dict[str, object]:by_side = {side: {"rows": int((frame["source_split"] == side).sum()),"storms": int(frame.loc[frame["source_split"] == side, "storm_id"].nunique()),}for side in sorted(frame["source_split"].unique())}sides = [set(frame.loc[frame["source_split"] == side, "storm_id"]) for side in by_side]shared = len(set.intersection(*sides)) if len(sides) > 1 else 0return {"rows": int(len(frame)),"unique_storms": int(frame["storm_id"].nunique()),"by_source_split": by_side,"storms_on_both_source_sides": shared,"wind_kt_min": float(frame["wind_speed_kt"].min()),"wind_kt_max": float(frame["wind_speed_kt"].max()),"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),"native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])})if "native_height" in frameelse [],"source_modes": frame["source_mode"].value_counts().to_dict()if "source_mode" in frameelse {},"frames_not_grey_ir": sorted(frame.loc[~frame["grey_ir"], "sample_id"]) if "grey_ir" in frame else [],"native_size_counts": {f"{h}x{w}": int(n)for (h, w), n in frame.groupby(["native_height", "native_width"]).size().items()}if "native_height" in frameelse {},"orig_size_counts": {int(k): int(v) for k, v in frame["orig_size"].value_counts().items()}if "orig_size" in frameelse {},"frames_to_area_average_to_366": int((frame["working_resample"] == "area_average").sum())if "working_resample" in frameelse 0,"has_split_column": "split" in frame.columns,"wind_averaging": sorted(frame["wind_averaging"].unique()),"is_synthetic": bool(frame["is_synthetic"].any()),}def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path, index: int = 0) -> dict[str, object]:import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltrow = frame.iloc[index]path = Path(row["image_path"])path = path if path.is_absolute() else Path(manifest_dir) / pathimage = load_ir(path)fig, ax = plt.subplots(figsize=(4, 4))ax.imshow(image, cmap="gray")ax.set_title(f"{row['sample_id']} | {row['wind_speed_kt']:.0f} kt (1min) | NASA TC, real")ax.axis("off")Path(out).parent.mkdir(parents=True, exist_ok=True)fig.savefig(out, dpi=100, bbox_inches="tight")plt.close(fig)return {"sample_id": row["sample_id"], "wind_speed_kt": float(row["wind_speed_kt"]), "shape": list(image.shape), "png": str(out)}def storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:"""Run the project splitter on the combined manifest and assert no storm leaks."""from src.splits import assert_no_group_leakage, assign_stormsif "split" in frame.columns:raise ValueError("manifest must not carry split; use source_split for the official side")assigned = assign_storms(frame, strategy, seed=seed)parts = [assigned.loc[assigned["split"] == name] for name in ("train", "val", "test")]assert_no_group_leakage(*parts)return {"strategy": strategy,"rows": {name: int(len(part)) for name, part in zip(("train", "val", "test"), parts)},"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(("train", "val", "test"), parts)},"leakage": "none",}def main() -> None:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--root", required=True, help="TorchGeo TropicalCyclone root")parser.add_argument("--out", default="data/nasa_tc/manifest.csv")parser.add_argument("--splits", nargs="+", default=list(SPLITS))parser.add_argument("--reader", choices=["torchgeo", "csv"], default="torchgeo")parser.add_argument("--summary", default="reports/nasa_tc_summary.json")parser.add_argument("--sample-png", default="reports/nasa_tc_sample.png")parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/nasa_tc_exclusions.csv")args = parser.parse_args()out = Path(args.out)out.parent.mkdir(parents=True, exist_ok=True)tables = torchgeo_tables if args.reader == "torchgeo" else csv_tablesraw = build_manifest(args.root, out.parent, tuple(args.splits), tables, keep_excluded=True)excluded = exclusions_for(raw)frame = require_valid(split_exclusions(raw)[0])exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "nasa_tc_exclusions.csv"excluded.to_csv(exclusions_path, index=False)frame.drop(columns=["imd5_class"]).to_csv(out, index=False)summary = summarize(frame)summary["excluded"] = {"count": int(len(excluded)), "sample_ids": excluded["sample_id"].tolist(), "file": str(exclusions_path)}summary["storm_split_check"] = storm_split_check(frame)summary["reader"] = args.readersummary["manifest"] = str(out)summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)Path(args.summary).parent.mkdir(parents=True, exist_ok=True)Path(args.summary).write_text(json.dumps(summary, indent=2))print(json.dumps(summary, indent=2))if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Comparison figures for classical baselines.Figures are software artifacts. A title that includes a number is not aresult to quote, and these plots are not warnings."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npfrom src.schema import DEFAULT_NAMESdef _pyplot():import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltreturn pltdef save_confusion_matrix(y_true: np.ndarray,y_pred: np.ndarray,path: str | Path,title: str,labels: tuple[str, ...] = DEFAULT_NAMES,) -> Path:"""Write a count matrix. Classes absent from both sides stay in the grid."""plt = _pyplot()truth = np.asarray(y_true).ravel()pred = np.asarray(y_pred).ravel()index = {label: position for position, label in enumerate(labels)}counts = np.zeros((len(labels), len(labels)), dtype=int)for actual, guess in zip(truth, pred, strict=True):if actual not in index or guess not in index:continuecounts[index[actual], index[guess]] += 1figure, axis = plt.subplots(figsize=(6.2, 5.2))image = axis.imshow(counts, cmap="Blues")axis.set_xticks(range(len(labels)), labels, rotation=45, ha="right")axis.set_yticks(range(len(labels)), labels)axis.set_xlabel("Predicted class")axis.set_ylabel("Best-track class (noisy label)")axis.set_title(title)for row in range(counts.shape[0]):for col in range(counts.shape[1]):axis.text(col, row, str(counts[row, col]), ha="center", va="center", fontsize=8)figure.colorbar(image, ax=axis, fraction=0.046)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destinationdef save_feature_importance(importances: dict[str, float],path: str | Path,title: str,limit: int = 15,) -> Path | None:"""Horizontal bars for a train-only selection score. Empty input writes nothing."""if not importances:return Noneplt = _pyplot()ordered = sorted(importances.items(), key=lambda item: (item[1], item[0]))ordered = ordered[-limit:]labels = [name for name, _score in ordered]scores = [score for _name, score in ordered]figure, axis = plt.subplots(figsize=(7.0, 5.0))axis.barh(labels, scores, color="#3d5a40")axis.set_xlabel("Train-split selection score")axis.set_title(title)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destinationdef save_regression_scatter(y_true: np.ndarray,y_pred: np.ndarray,path: str | Path,title: str,) -> Path:plt = _pyplot()truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()figure, axis = plt.subplots(figsize=(5.2, 5.0))axis.scatter(truth, pred, s=18, alpha=0.8, color="#1d3557")low = float(min(truth.min(), pred.min()))high = float(max(truth.max(), pred.max()))axis.plot([low, high], [low, high], color="#9b2226", linewidth=1)axis.set_xlabel("Label wind (kt)")axis.set_ylabel("Predicted wind (kt)")axis.set_title(title)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destination123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Comparison figures for classical baselines.Figures are software artifacts. A title that includes a number is not aresult to quote, and these plots are not warnings."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npfrom src.schema import DEFAULT_NAMESdef _pyplot():import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltreturn pltdef save_confusion_matrix(y_true: np.ndarray,y_pred: np.ndarray,path: str | Path,title: str,labels: tuple[str, ...] = DEFAULT_NAMES,) -> Path:"""Write a count matrix. Classes absent from both sides stay in the grid."""plt = _pyplot()truth = np.asarray(y_true).ravel()pred = np.asarray(y_pred).ravel()index = {label: position for position, label in enumerate(labels)}counts = np.zeros((len(labels), len(labels)), dtype=int)for actual, guess in zip(truth, pred, strict=True):if actual not in index or guess not in index:continuecounts[index[actual], index[guess]] += 1figure, axis = plt.subplots(figsize=(6.2, 5.2))image = axis.imshow(counts, cmap="Blues")axis.set_xticks(range(len(labels)), labels, rotation=45, ha="right")axis.set_yticks(range(len(labels)), labels)axis.set_xlabel("Predicted class")axis.set_ylabel("Best-track class (noisy label)")axis.set_title(title)for row in range(counts.shape[0]):for col in range(counts.shape[1]):axis.text(col, row, str(counts[row, col]), ha="center", va="center", fontsize=8)figure.colorbar(image, ax=axis, fraction=0.046)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destinationdef save_feature_importance(importances: dict[str, float],path: str | Path,title: str,limit: int = 15,) -> Path | None:"""Horizontal bars for a train-only selection score. Empty input writes nothing."""if not importances:return Noneplt = _pyplot()ordered = sorted(importances.items(), key=lambda item: (item[1], item[0]))ordered = ordered[-limit:]labels = [name for name, _score in ordered]scores = [score for _name, score in ordered]figure, axis = plt.subplots(figsize=(7.0, 5.0))axis.barh(labels, scores, color="#3d5a40")axis.set_xlabel("Train-split selection score")axis.set_title(title)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destinationdef save_regression_scatter(y_true: np.ndarray,y_pred: np.ndarray,path: str | Path,title: str,) -> Path:plt = _pyplot()truth = np.asarray(y_true, dtype=np.float64).ravel()pred = np.asarray(y_pred, dtype=np.float64).ravel()figure, axis = plt.subplots(figsize=(5.2, 5.0))axis.scatter(truth, pred, s=18, alpha=0.8, color="#1d3557")low = float(min(truth.min(), pred.min()))high = float(max(truth.max(), pred.max()))axis.plot([low, high], [low, high], color="#9b2226", linewidth=1)axis.set_xlabel("Label wind (kt)")axis.set_ylabel("Predicted wind (kt)")axis.set_title(title)figure.tight_layout()destination = Path(path)destination.parent.mkdir(parents=True, exist_ok=True)figure.savefig(destination, dpi=100)plt.close(figure)return destination
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Image checks, resize, train-only normalization, and train-only augmentation.Southern Hemisphere frames stay as stored. ``leave_unflipped`` records ahemisphere label and does not mirror the array."""from __future__ import annotationsfrom dataclasses import dataclassimport numpy as npfrom PIL import Imagefrom src.config import parse_image_sizefrom src.splits import LeakageError# A missing-pixel fraction above this value fails closed. It does not warn.MAX_MISSING_FRACTION = 0.30@dataclass(frozen=True)class NormStats:mean: floatstd: floatsource_split: str# Pixel units stay on the dataset that produced them. NASA chips are 8-bit# counts. TCIR IR1 is brightness temperature in kelvin. They are never# pooled into one mean and std. A later dataset gets its own entry.PIXEL_KIND = {"nasa": "uint8","tcir": "brightness_temperature_k","incyde": "jpeg_uncalibrated","smoke": "synthetic",}def pixel_kind(dataset: str) -> str:"""Unit label for one dataset. Unknown datasets stay unspecified."""return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")def norm_by_dataset(dataset: str, stats: NormStats) -> dict:"""One dataset's train-split stats. The map has that key only."""if stats.source_split != "train":raise LeakageError("normalization stats may be fit on the train split only")name = str(dataset).strip().lower()if not name:raise ValueError("dataset name is required for normalization stats")return {name: {"mean": float(stats.mean),"std": float(stats.std),"source_split": "train","pixel_kind": pixel_kind(name),}}def norm_stats_from_checkpoint(payload: dict) -> NormStats:"""Stats for the checkpoint's own dataset. Mixed maps are refused.A checkpoint written before per-dataset stats still uses ``norm_mean``and ``norm_std``. A map with two datasets, or a key that is not thecheckpoint dataset, is not applied."""grouped = payload.get("norm_by_dataset")dataset = payload.get("dataset")if isinstance(grouped, dict) and grouped:if len(grouped) != 1:raise ValueError("checkpoint mixes normalization stats across datasets; refusing to apply them")name = None if dataset is None else str(dataset)if name not in grouped:raise ValueError("checkpoint norm_by_dataset does not match the checkpoint dataset; ""refusing to mix normalization stats")entry = grouped[name]if str(entry.get("source_split")) != "train":raise ValueError("checkpoint normalization was not fit on train")return NormStats(mean=float(entry["mean"]),std=float(entry["std"]),source_split="train",)if "norm_mean" not in payload or "norm_std" not in payload:raise ValueError("checkpoint is missing normalization stats")source = payload.get("norm_source_split")if source is not None and str(source) != "train":raise ValueError("checkpoint normalization was not fit on train")return NormStats(mean=float(payload["norm_mean"]),std=float(payload["norm_std"]),source_split="train",)def as_channel_first(image: np.ndarray) -> np.ndarray:array = np.asarray(image, dtype=np.float32)if array.ndim == 2:return array[None, ...]if array.ndim != 3:raise ValueError(f"expected a 2D or 3D image, got {array.shape}")if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:return arrayif array.shape[-1] <= 4:return np.moveaxis(array, -1, 0)raise ValueError(f"cannot infer the channel axis for shape {array.shape}")def missing_fraction(image: np.ndarray) -> float:return float((~np.isfinite(image)).mean())def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:"""Fit mean and std. Refuses anything other than the train split."""if source_split != "train":raise LeakageError("normalization stats may be fit on the train split only")if not images:raise ValueError("need at least one train image")values = [np.asarray(image, dtype=np.float32) for image in images]finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])if finite.size == 0:raise ValueError("train images have no finite pixels")std = float(finite.std())if std < 1e-6:std = 1.0return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)def stack_prepared(images: list[np.ndarray]) -> np.ndarray:"""Stack chips that have already been prepared.A native ``image_size`` does not resize, so every chip in the stackmust already share a height and width."""if not images:raise ValueError("no images to stack")try:return np.stack(images)except ValueError as exc:shapes = sorted({tuple(np.shape(image)) for image in images})raise ValueError("prepared chips do not share a height and width "f"{shapes}. A native image_size does not resize them onto one grid.") from excdef _resize(image: np.ndarray, size: int) -> np.ndarray:channels = []for channel in image:picture = Image.fromarray(channel.astype(np.float32), mode="F")picture = picture.resize((size, size), Image.Resampling.BILINEAR)channels.append(np.asarray(picture, dtype=np.float32))return np.stack(channels, axis=0)def prepare_image(image: np.ndarray,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> np.ndarray:"""Return ``(C, H, W)`` float32. Does not invent brightness temperature.``image_size`` ``None`` or ``native`` keeps the chip's height and width.An integer resizes to that square. ``max_missing_fraction`` is``data.max_missing_fraction`` when the caller has a config.A missing-pixel fraction above ``max_missing_fraction`` raises. Rawdigital numbers stay pixel values; this function does not name them Tb."""array = as_channel_first(image)fraction = missing_fraction(array)if fraction > max_missing_fraction:raise ValueError(f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}")filled = array.copy()for index in range(filled.shape[0]):finite = np.isfinite(filled[index])fill = float(np.median(filled[index][finite])) if finite.any() else 0.0filled[index][~finite] = fillside = parse_image_size(image_size)output = filled if side is None else _resize(filled, side)if stats is not None:output = (output - stats.mean) / stats.stdreturn outputdef dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:"""Apply a caller-supplied calibration. This does not look up a sensor table."""return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:"""Use the frame as stored.Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` recordsthe caller's label and does not change the array."""del hemispherereturn np.asarray(image)def as_grey_plane(image: np.ndarray) -> np.ndarray:"""One plane. Identical RGB channels collapse. Differing channels raise.PIL JPEGs are often ``(H, W, C)`` even when every channel is the samegrey IR value. A leading singleton channel is accepted too."""array = np.asarray(image, dtype=np.float32)if array.ndim == 2:return arrayif array.ndim != 3:raise ValueError(f"expected one grey plane, got {array.shape}")channel_last = (array.shape[-1] <= 4and array.shape[0] > array.shape[-1]and array.shape[1] > array.shape[-1])channel_first = (array.shape[0] <= 4and array.shape[1] > array.shape[0]and array.shape[2] > array.shape[0])if channel_last:count = int(array.shape[-1])if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):return array[..., 0]raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")if channel_first:count = int(array.shape[0])if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):return array[0]raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")raise ValueError(f"expected grey IR, got {array.shape}")def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:"""Rotate about the centre and drop pixels outside the inscribed circle.There is no flip. A square rotation otherwise paints the corners fromempty space, and those bars must not enter training. The disk ofdiameter equal to the short side stays inside the original chip forany angle, so the kept pixels are source pixels. Outside the disk thevalues are NaN. Callers that already normalized fill those NaNs with 0.Channel-last grey JPEGs are accepted and returned as one plane."""plane = as_grey_plane(image)finite = np.isfinite(plane)filled = plane.copy()filled[~finite] = 0.0picture = Image.fromarray(filled, mode="F")rotated = np.asarray(picture.rotate(float(angle_deg),resample=Image.Resampling.BILINEAR,fillcolor=0.0,),dtype=np.float32,)height, width = rotated.shapeyy, xx = np.ogrid[:height, :width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0radius = min(height, width) / 2.0disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2out = rotated.copy()out[~disk] = np.nanreturn outdef prepare_training_chip(image: np.ndarray,image_size: int | str | None,angle: float | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> np.ndarray:"""Prepare one training chip, then optionally rotate on that grid.The missing-pixel gate sees the source image, before the circular mask.A configured square resize happens first, so the mask is the inscribedcircle of the training grid (about a fifth of the square) and not thecorners of a wide native crop. Masked pixels are 0 after normalization,which is the training mean, not a black bar."""prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)if angle is None:return preparedmasked = rotate_with_circular_mask(prepared, float(angle))if masked.ndim == 2:masked = masked[None, ...]return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:"""Flip or rotate a train image. Refuses every other split.Classical features do not call this. A later training loop may, and onlyon rows whose split is ``train``."""if split != "train":raise LeakageError("augmentation is allowed on the train split only")array = as_channel_first(image)choice = int(rng.integers(0, 3))if choice == 0:return np.flip(array, axis=-1).copy()if choice == 1:return np.rot90(array, k=1, axes=(-2, -1)).copy()return array.copy()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Image checks, resize, train-only normalization, and train-only augmentation.Southern Hemisphere frames stay as stored. ``leave_unflipped`` records ahemisphere label and does not mirror the array."""from __future__ import annotationsfrom dataclasses import dataclassimport numpy as npfrom PIL import Imagefrom src.config import parse_image_sizefrom src.splits import LeakageError# A missing-pixel fraction above this value fails closed. It does not warn.MAX_MISSING_FRACTION = 0.30@dataclass(frozen=True)class NormStats:mean: floatstd: floatsource_split: str# Pixel units stay on the dataset that produced them. NASA chips are 8-bit# counts. TCIR IR1 is brightness temperature in kelvin. They are never# pooled into one mean and std. A later dataset gets its own entry.PIXEL_KIND = {"nasa": "uint8","tcir": "brightness_temperature_k","incyde": "jpeg_uncalibrated","smoke": "synthetic",}def pixel_kind(dataset: str) -> str:"""Unit label for one dataset. Unknown datasets stay unspecified."""return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")def norm_by_dataset(dataset: str, stats: NormStats) -> dict:"""One dataset's train-split stats. The map has that key only."""if stats.source_split != "train":raise LeakageError("normalization stats may be fit on the train split only")name = str(dataset).strip().lower()if not name:raise ValueError("dataset name is required for normalization stats")return {name: {"mean": float(stats.mean),"std": float(stats.std),"source_split": "train","pixel_kind": pixel_kind(name),}}def norm_stats_from_checkpoint(payload: dict) -> NormStats:"""Stats for the checkpoint's own dataset. Mixed maps are refused.A checkpoint written before per-dataset stats still uses ``norm_mean``and ``norm_std``. A map with two datasets, or a key that is not thecheckpoint dataset, is not applied."""grouped = payload.get("norm_by_dataset")dataset = payload.get("dataset")if isinstance(grouped, dict) and grouped:if len(grouped) != 1:raise ValueError("checkpoint mixes normalization stats across datasets; refusing to apply them")name = None if dataset is None else str(dataset)if name not in grouped:raise ValueError("checkpoint norm_by_dataset does not match the checkpoint dataset; ""refusing to mix normalization stats")entry = grouped[name]if str(entry.get("source_split")) != "train":raise ValueError("checkpoint normalization was not fit on train")return NormStats(mean=float(entry["mean"]),std=float(entry["std"]),source_split="train",)if "norm_mean" not in payload or "norm_std" not in payload:raise ValueError("checkpoint is missing normalization stats")source = payload.get("norm_source_split")if source is not None and str(source) != "train":raise ValueError("checkpoint normalization was not fit on train")return NormStats(mean=float(payload["norm_mean"]),std=float(payload["norm_std"]),source_split="train",)def as_channel_first(image: np.ndarray) -> np.ndarray:array = np.asarray(image, dtype=np.float32)if array.ndim == 2:return array[None, ...]if array.ndim != 3:raise ValueError(f"expected a 2D or 3D image, got {array.shape}")if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:return arrayif array.shape[-1] <= 4:return np.moveaxis(array, -1, 0)raise ValueError(f"cannot infer the channel axis for shape {array.shape}")def missing_fraction(image: np.ndarray) -> float:return float((~np.isfinite(image)).mean())def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:"""Fit mean and std. Refuses anything other than the train split."""if source_split != "train":raise LeakageError("normalization stats may be fit on the train split only")if not images:raise ValueError("need at least one train image")values = [np.asarray(image, dtype=np.float32) for image in images]finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])if finite.size == 0:raise ValueError("train images have no finite pixels")std = float(finite.std())if std < 1e-6:std = 1.0return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)def stack_prepared(images: list[np.ndarray]) -> np.ndarray:"""Stack chips that have already been prepared.A native ``image_size`` does not resize, so every chip in the stackmust already share a height and width."""if not images:raise ValueError("no images to stack")try:return np.stack(images)except ValueError as exc:shapes = sorted({tuple(np.shape(image)) for image in images})raise ValueError("prepared chips do not share a height and width "f"{shapes}. A native image_size does not resize them onto one grid.") from excdef _resize(image: np.ndarray, size: int) -> np.ndarray:channels = []for channel in image:picture = Image.fromarray(channel.astype(np.float32), mode="F")picture = picture.resize((size, size), Image.Resampling.BILINEAR)channels.append(np.asarray(picture, dtype=np.float32))return np.stack(channels, axis=0)def prepare_image(image: np.ndarray,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> np.ndarray:"""Return ``(C, H, W)`` float32. Does not invent brightness temperature.``image_size`` ``None`` or ``native`` keeps the chip's height and width.An integer resizes to that square. ``max_missing_fraction`` is``data.max_missing_fraction`` when the caller has a config.A missing-pixel fraction above ``max_missing_fraction`` raises. Rawdigital numbers stay pixel values; this function does not name them Tb."""array = as_channel_first(image)fraction = missing_fraction(array)if fraction > max_missing_fraction:raise ValueError(f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}")filled = array.copy()for index in range(filled.shape[0]):finite = np.isfinite(filled[index])fill = float(np.median(filled[index][finite])) if finite.any() else 0.0filled[index][~finite] = fillside = parse_image_size(image_size)output = filled if side is None else _resize(filled, side)if stats is not None:output = (output - stats.mean) / stats.stdreturn outputdef dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:"""Apply a caller-supplied calibration. This does not look up a sensor table."""return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:"""Use the frame as stored.Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` recordsthe caller's label and does not change the array."""del hemispherereturn np.asarray(image)def as_grey_plane(image: np.ndarray) -> np.ndarray:"""One plane. Identical RGB channels collapse. Differing channels raise.PIL JPEGs are often ``(H, W, C)`` even when every channel is the samegrey IR value. A leading singleton channel is accepted too."""array = np.asarray(image, dtype=np.float32)if array.ndim == 2:return arrayif array.ndim != 3:raise ValueError(f"expected one grey plane, got {array.shape}")channel_last = (array.shape[-1] <= 4and array.shape[0] > array.shape[-1]and array.shape[1] > array.shape[-1])channel_first = (array.shape[0] <= 4and array.shape[1] > array.shape[0]and array.shape[2] > array.shape[0])if channel_last:count = int(array.shape[-1])if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):return array[..., 0]raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")if channel_first:count = int(array.shape[0])if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):return array[0]raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")raise ValueError(f"expected grey IR, got {array.shape}")def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:"""Rotate about the centre and drop pixels outside the inscribed circle.There is no flip. A square rotation otherwise paints the corners fromempty space, and those bars must not enter training. The disk ofdiameter equal to the short side stays inside the original chip forany angle, so the kept pixels are source pixels. Outside the disk thevalues are NaN. Callers that already normalized fill those NaNs with 0.Channel-last grey JPEGs are accepted and returned as one plane."""plane = as_grey_plane(image)finite = np.isfinite(plane)filled = plane.copy()filled[~finite] = 0.0picture = Image.fromarray(filled, mode="F")rotated = np.asarray(picture.rotate(float(angle_deg),resample=Image.Resampling.BILINEAR,fillcolor=0.0,),dtype=np.float32,)height, width = rotated.shapeyy, xx = np.ogrid[:height, :width]center_y = (height - 1) / 2.0center_x = (width - 1) / 2.0radius = min(height, width) / 2.0disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2out = rotated.copy()out[~disk] = np.nanreturn outdef prepare_training_chip(image: np.ndarray,image_size: int | str | None,angle: float | None,stats: NormStats | None,max_missing_fraction: float = MAX_MISSING_FRACTION,) -> np.ndarray:"""Prepare one training chip, then optionally rotate on that grid.The missing-pixel gate sees the source image, before the circular mask.A configured square resize happens first, so the mask is the inscribedcircle of the training grid (about a fifth of the square) and not thecorners of a wide native crop. Masked pixels are 0 after normalization,which is the training mean, not a black bar."""prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)if angle is None:return preparedmasked = rotate_with_circular_mask(prepared, float(angle))if masked.ndim == 2:masked = masked[None, ...]return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:"""Flip or rotate a train image. Refuses every other split.Classical features do not call this. A later training loop may, and onlyon rows whose split is ``train``."""if split != "train":raise LeakageError("augmentation is allowed on the train split only")array = as_channel_first(image)choice = int(rng.integers(0, 3))if choice == 0:return np.flip(array, axis=-1).copy()if choice == 1:return np.rot90(array, k=1, axes=(-2, -1)).copy()return array.copy()
12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Centralized seed helper for reproducible runs.Sets Python, NumPy, and (when available) PyTorch random seeds in one call.Training, baselines, and splits should call ``seed_everything`` before anystochastic operation. This module does not import torch at module level sothat CPU-only installs still work."""from __future__ import annotationsimport osimport randomimport numpy as npdef seed_everything(seed: int = 42) -> int:"""Set Python, NumPy, and optional PyTorch seeds.Returns the seed so callers can log it.Parameters----------seed : intNon-negative integer seed. The same value is forwarded to everygenerator so a single config entry controls all randomness."""if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:raise ValueError(f"seed must be a non-negative integer, got {seed!r}")random.seed(seed)np.random.seed(seed)os.environ["PYTHONHASHSEED"] = str(seed)try:import torchexcept ImportError:passelse:torch.manual_seed(seed)if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)if hasattr(torch, "xpu") and torch.xpu.is_available():torch.xpu.manual_seed(seed)return seed12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Centralized seed helper for reproducible runs.Sets Python, NumPy, and (when available) PyTorch random seeds in one call.Training, baselines, and splits should call ``seed_everything`` before anystochastic operation. This module does not import torch at module level sothat CPU-only installs still work."""from __future__ import annotationsimport osimport randomimport numpy as npdef seed_everything(seed: int = 42) -> int:"""Set Python, NumPy, and optional PyTorch seeds.Returns the seed so callers can log it.Parameters----------seed : intNon-negative integer seed. The same value is forwarded to everygenerator so a single config entry controls all randomness."""if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:raise ValueError(f"seed must be a non-negative integer, got {seed!r}")random.seed(seed)np.random.seed(seed)os.environ["PYTHONHASHSEED"] = str(seed)try:import torchexcept ImportError:passelse:torch.manual_seed(seed)if torch.cuda.is_available():torch.cuda.manual_seed_all(seed)if hasattr(torch, "xpu") and torch.xpu.is_available():torch.xpu.manual_seed(seed)return seed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Manifest schema and row-level quality gates.Required columns are ``sample_id``, ``image_path``, ``storm_id``, and``wind_speed_kt``. ``require_valid`` raises ``SchemaError`` on a failedgate. It does not warn and continue.``wind_averaging`` must record one period for the whole manifest, such as``1-min``, ``3-min``, or ``10-min``. Mixed or blank periods are rejected.``is_synthetic`` must be an explicit true or false on every row so asynthetic sample cannot be read as real.Image statistics are pixel stats. This schema has no brightness-temperaturecolumns. Raw digital numbers are not named ``tb``. Those names are usedonly after a brightness-temperature calibration table exists.The 17/34/48/64/91 kt bins are this project's grouping, not official IMDclasses, and they are not a warning product. ``imd5_class`` stores thatproject group."""from __future__ import annotationsfrom dataclasses import dataclassimport pandas as pdREQUIRED_COLUMNS = ("sample_id", "image_path", "storm_id", "wind_speed_kt")FORBIDDEN_FEATURES = frozenset({"wind_speed_kt", "r34_nmi", "rmw_nmi", "imd5_class", "intensity_bin"})# Project metric labels, not an IMD warning. Five names group D+DD and# ESCS+SuCS. The edges 17/34/48/64/91 kt are this project's own grouping.# IMD operational winds are 3-minute averages and are not these bins.# NASA HURDAT2 labels are 1-minute winds; config data.wind_averaging is# 1min for that dataset. Keep these tuples equal to data.imd5_edges_kt# and data.imd5_names. The July 2024 IMD 3-minute sheet starts Extremely# Severe at 90 kt, so 90 kt is VSCS here.DEFAULT_EDGES_KT = (17.0, 34.0, 48.0, 64.0, 91.0)DEFAULT_NAMES = ("D_DD", "CS", "SCS", "VSCS", "ESCS_SUCS")DEFAULT_WIND_MIN_KT = 0.0DEFAULT_WIND_MAX_KT = 200.0_TRUE_TEXT = frozenset({"1", "true", "yes", "y", "t"})_FALSE_TEXT = frozenset({"0", "false", "no", "n", "f"})_MISSING_TEXT = frozenset({"", "nan", "none", "<na>", "nat", "null"})class SchemaError(ValueError):"""A manifest failed a quality gate."""@dataclass(frozen=True)class QualityReport:n_rows: intn_storms: interrors: tuple[str, ...]@propertydef ok(self) -> bool:return not self.errorsdef wind_to_imd5(wind_kt: float,edges: tuple[float, ...] = DEFAULT_EDGES_KT,names: tuple[str, ...] = DEFAULT_NAMES,) -> str | None:"""Return this project's intensity group, or None below the lowest edge.The names and edges are this project's grouping. They are not official IMD classes, IMD 3-minute categories, or a warning product."""if len(edges) != len(names):raise ValueError("edges and names must have the same length")if pd.isna(wind_kt) or float(wind_kt) < edges[0]:return Nonevalue = float(wind_kt)for lower, upper, name in zip(edges, edges[1:], names):if lower <= value < upper:return namereturn names[-1]def _unpack_scalar(value: object) -> object:"""Return a Python scalar when ``value`` is a numpy scalar."""if isinstance(value, (str, bytes, bytearray, bool)):return valueitem = getattr(value, "item", None)if not callable(item):return valuetry:unpacked = item()except (TypeError, ValueError):return valueif type(unpacked) is type(value):return valuereturn unpackeddef _is_missing(value: object) -> bool:if value is None:return Truetry:missing = pd.isna(value)except (TypeError, ValueError):return Falseif missing is True:return Truereturn Falsedef _sample_key(value: object) -> str:if isinstance(value, bool):return "True" if value else "False"if _is_missing(value):return ""if isinstance(value, str):return value.strip()value = _unpack_scalar(value)if isinstance(value, bool):return "True" if value else "False"if _is_missing(value):return ""if isinstance(value, str):return value.strip()if isinstance(value, int) and not isinstance(value, bool):return str(value)if isinstance(value, float):if value != value:return ""if value.is_integer():return str(int(value))return str(value).strip()def parse_is_synthetic(value: object) -> bool:"""Return an explicit synthetic flag. Ambiguous values raise.Null, blank, and unrecognized values are not treated as real data."""if isinstance(value, bool):return valueif isinstance(value, str):text = value.strip().lower()if text in _TRUE_TEXT:return Trueif text in _FALSE_TEXT:return Falseif text in _MISSING_TEXT:raise SchemaError("is_synthetic is null; synthetic rows must be explicit")try:number = float(text)except ValueError:raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false") from Nonereturn parse_is_synthetic(number)value = _unpack_scalar(value)if isinstance(value, bool):return valueif _is_missing(value):raise SchemaError("is_synthetic is null; synthetic rows must be explicit")if isinstance(value, str):return parse_is_synthetic(value)if isinstance(value, int) and not isinstance(value, bool):if value in (0, 1):return bool(value)raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")if isinstance(value, float):if value != value or value in (float("inf"), float("-inf")):raise SchemaError("is_synthetic is null; synthetic rows must be explicit")if value == 1.0:return Trueif value == 0.0:return Falseraise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")def recorded_wind_averaging(frame: pd.DataFrame) -> str:"""Return the single averaging period recorded on this manifest.The column is required. A blank row or two different periods raises."""if "wind_averaging" not in frame.columns:raise SchemaError("wind_averaging is required; record one period for the manifest ""(for example 1-min, 3-min, or 10-min)")if len(frame) == 0:raise SchemaError("wind_averaging is required; record one period for the manifest")periods: list[str] = []for value in frame["wind_averaging"].tolist():if isinstance(value, str):text = value.strip()elif _is_missing(value):text = ""else:unpacked = _unpack_scalar(value)if _is_missing(unpacked):text = ""else:text = str(unpacked).strip()if text.lower() in _MISSING_TEXT:raise SchemaError("wind_averaging has nulls; record one period for every row")periods.append(text)unique = sorted(set(periods))if len(unique) != 1:raise SchemaError(f"mixed wind_averaging periods {unique}; split or convert explicitly")return unique[0]# The label's duration in seconds. This is not a wind conversion factor._AVERAGING_SECONDS = {"1min": 60,"1-min": 60,"1minute": 60,"1-minute": 60,"3min": 180,"3-min": 180,"3minute": 180,"3-minute": 180,"10min": 600,"10-min": 600,"10minute": 600,"10-minute": 600,}def wind_averaging_seconds(period: object) -> int | None:"""Seconds for a 1, 3, or 10 minute label. Other labels have no duration.``1min`` is 60, ``3-min`` is 180, and ``10min`` is 600. Synthetic andunknown text stay null. This does not rescale a wind speed."""if period is None:return Nonetext = str(period).strip().lower().replace(" ", "").replace("_", "-")if not text:return Nonereturn _AVERAGING_SECONDS.get(text)def split_wind_averaging(frame: pd.DataFrame) -> dict[str, dict[str, list]]:"""``wind_averaging`` and ``wind_averaging_s`` for train, val, and test.Each split lists the set of labels on its rows. Seconds follow thelabel. A label with no known duration stores null and is not converted."""if "split" not in frame.columns:raise SchemaError("split is required to record wind_averaging by split")if "wind_averaging" not in frame.columns:raise SchemaError("wind_averaging is required")report: dict[str, dict[str, list]] = {}for name in ("train", "val", "test"):rows = frame.loc[frame["split"].astype(str) == name, "wind_averaging"]labels = sorted({str(value).strip() for value in rows.tolist() if str(value).strip()})report[name] = {"wind_averaging": labels,"wind_averaging_s": [wind_averaging_seconds(label) for label in labels],}return reportdef _synthetic_flags(frame: pd.DataFrame) -> list[bool]:if "is_synthetic" not in frame.columns:raise SchemaError("is_synthetic is required so a synthetic row cannot be read as real")return [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]def validate_manifest(frame: pd.DataFrame,wind_min_kt: float = DEFAULT_WIND_MIN_KT,wind_max_kt: float = DEFAULT_WIND_MAX_KT,) -> QualityReport:"""Collect quality-gate failures. Callers that load data use ``require_valid``."""errors: list[str] = []missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns]if missing:return QualityReport(len(frame), 0, (f"missing required columns: {missing}",))keys = frame["sample_id"].map(_sample_key)null_id = frame["sample_id"].isna() | keys.eq("") | keys.str.lower().isin(_MISSING_TEXT)if bool(null_id.any()):errors.append("sample_id has nulls")if bool(keys.duplicated().any()):examples = keys.loc[keys.duplicated()].head(5).tolist()errors.append(f"duplicate sample_id, examples: {examples}")blank_storm = frame["storm_id"].astype(str).str.strip().str.len() == 0if frame["storm_id"].isna().any() or blank_storm.any():errors.append("storm_id has nulls")if frame["image_path"].isna().any() or (frame["image_path"].astype(str).str.strip().str.len() == 0).any():errors.append("image_path has nulls")winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")if winds.isna().any():errors.append("wind_speed_kt has non-numeric values")else:bad = (winds < wind_min_kt) | (winds > wind_max_kt)if bad.any():errors.append(f"{int(bad.sum())} wind values outside [{wind_min_kt}, {wind_max_kt}] kt")try:recorded_wind_averaging(frame)except SchemaError as exc:errors.append(str(exc))try:_synthetic_flags(frame)except SchemaError as exc:errors.append(str(exc))n_storms = int(frame["storm_id"].nunique(dropna=True))return QualityReport(len(frame), n_storms, tuple(errors))def require_valid(frame: pd.DataFrame, **kwargs: float) -> pd.DataFrame:"""Return a copy that passed every manifest gate. Raises on failure."""report = validate_manifest(frame, **kwargs)if not report.ok:raise SchemaError("; ".join(report.errors))out = frame.copy()out["storm_id"] = out["storm_id"].astype(str).str.strip()out["sample_id"] = out["sample_id"].map(_sample_key).astype(str)out["image_path"] = out["image_path"].astype(str).str.strip()out["wind_speed_kt"] = pd.to_numeric(out["wind_speed_kt"])out["wind_averaging"] = recorded_wind_averaging(out)out["is_synthetic"] = _synthetic_flags(out)# Project grouping stored on imd5_class. Not an official IMD class code.out["imd5_class"] = out["wind_speed_kt"].map(wind_to_imd5)return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Manifest schema and row-level quality gates.Required columns are ``sample_id``, ``image_path``, ``storm_id``, and``wind_speed_kt``. ``require_valid`` raises ``SchemaError`` on a failedgate. It does not warn and continue.``wind_averaging`` must record one period for the whole manifest, such as``1-min``, ``3-min``, or ``10-min``. Mixed or blank periods are rejected.``is_synthetic`` must be an explicit true or false on every row so asynthetic sample cannot be read as real.Image statistics are pixel stats. This schema has no brightness-temperaturecolumns. Raw digital numbers are not named ``tb``. Those names are usedonly after a brightness-temperature calibration table exists.The 17/34/48/64/91 kt bins are this project's grouping, not official IMDclasses, and they are not a warning product. ``imd5_class`` stores thatproject group."""from __future__ import annotationsfrom dataclasses import dataclassimport pandas as pdREQUIRED_COLUMNS = ("sample_id", "image_path", "storm_id", "wind_speed_kt")FORBIDDEN_FEATURES = frozenset({"wind_speed_kt", "r34_nmi", "rmw_nmi", "imd5_class", "intensity_bin"})# Project metric labels, not an IMD warning. Five names group D+DD and# ESCS+SuCS. The edges 17/34/48/64/91 kt are this project's own grouping.# IMD operational winds are 3-minute averages and are not these bins.# NASA HURDAT2 labels are 1-minute winds; config data.wind_averaging is# 1min for that dataset. Keep these tuples equal to data.imd5_edges_kt# and data.imd5_names. The July 2024 IMD 3-minute sheet starts Extremely# Severe at 90 kt, so 90 kt is VSCS here.DEFAULT_EDGES_KT = (17.0, 34.0, 48.0, 64.0, 91.0)DEFAULT_NAMES = ("D_DD", "CS", "SCS", "VSCS", "ESCS_SUCS")DEFAULT_WIND_MIN_KT = 0.0DEFAULT_WIND_MAX_KT = 200.0_TRUE_TEXT = frozenset({"1", "true", "yes", "y", "t"})_FALSE_TEXT = frozenset({"0", "false", "no", "n", "f"})_MISSING_TEXT = frozenset({"", "nan", "none", "<na>", "nat", "null"})class SchemaError(ValueError):"""A manifest failed a quality gate."""@dataclass(frozen=True)class QualityReport:n_rows: intn_storms: interrors: tuple[str, ...]@propertydef ok(self) -> bool:return not self.errorsdef wind_to_imd5(wind_kt: float,edges: tuple[float, ...] = DEFAULT_EDGES_KT,names: tuple[str, ...] = DEFAULT_NAMES,) -> str | None:"""Return this project's intensity group, or None below the lowest edge.The names and edges are this project's grouping. They are not official IMD classes, IMD 3-minute categories, or a warning product."""if len(edges) != len(names):raise ValueError("edges and names must have the same length")if pd.isna(wind_kt) or float(wind_kt) < edges[0]:return Nonevalue = float(wind_kt)for lower, upper, name in zip(edges, edges[1:], names):if lower <= value < upper:return namereturn names[-1]def _unpack_scalar(value: object) -> object:"""Return a Python scalar when ``value`` is a numpy scalar."""if isinstance(value, (str, bytes, bytearray, bool)):return valueitem = getattr(value, "item", None)if not callable(item):return valuetry:unpacked = item()except (TypeError, ValueError):return valueif type(unpacked) is type(value):return valuereturn unpackeddef _is_missing(value: object) -> bool:if value is None:return Truetry:missing = pd.isna(value)except (TypeError, ValueError):return Falseif missing is True:return Truereturn Falsedef _sample_key(value: object) -> str:if isinstance(value, bool):return "True" if value else "False"if _is_missing(value):return ""if isinstance(value, str):return value.strip()value = _unpack_scalar(value)if isinstance(value, bool):return "True" if value else "False"if _is_missing(value):return ""if isinstance(value, str):return value.strip()if isinstance(value, int) and not isinstance(value, bool):return str(value)if isinstance(value, float):if value != value:return ""if value.is_integer():return str(int(value))return str(value).strip()def parse_is_synthetic(value: object) -> bool:"""Return an explicit synthetic flag. Ambiguous values raise.Null, blank, and unrecognized values are not treated as real data."""if isinstance(value, bool):return valueif isinstance(value, str):text = value.strip().lower()if text in _TRUE_TEXT:return Trueif text in _FALSE_TEXT:return Falseif text in _MISSING_TEXT:raise SchemaError("is_synthetic is null; synthetic rows must be explicit")try:number = float(text)except ValueError:raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false") from Nonereturn parse_is_synthetic(number)value = _unpack_scalar(value)if isinstance(value, bool):return valueif _is_missing(value):raise SchemaError("is_synthetic is null; synthetic rows must be explicit")if isinstance(value, str):return parse_is_synthetic(value)if isinstance(value, int) and not isinstance(value, bool):if value in (0, 1):return bool(value)raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")if isinstance(value, float):if value != value or value in (float("inf"), float("-inf")):raise SchemaError("is_synthetic is null; synthetic rows must be explicit")if value == 1.0:return Trueif value == 0.0:return Falseraise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")def recorded_wind_averaging(frame: pd.DataFrame) -> str:"""Return the single averaging period recorded on this manifest.The column is required. A blank row or two different periods raises."""if "wind_averaging" not in frame.columns:raise SchemaError("wind_averaging is required; record one period for the manifest ""(for example 1-min, 3-min, or 10-min)")if len(frame) == 0:raise SchemaError("wind_averaging is required; record one period for the manifest")periods: list[str] = []for value in frame["wind_averaging"].tolist():if isinstance(value, str):text = value.strip()elif _is_missing(value):text = ""else:unpacked = _unpack_scalar(value)if _is_missing(unpacked):text = ""else:text = str(unpacked).strip()if text.lower() in _MISSING_TEXT:raise SchemaError("wind_averaging has nulls; record one period for every row")periods.append(text)unique = sorted(set(periods))if len(unique) != 1:raise SchemaError(f"mixed wind_averaging periods {unique}; split or convert explicitly")return unique[0]# The label's duration in seconds. This is not a wind conversion factor._AVERAGING_SECONDS = {"1min": 60,"1-min": 60,"1minute": 60,"1-minute": 60,"3min": 180,"3-min": 180,"3minute": 180,"3-minute": 180,"10min": 600,"10-min": 600,"10minute": 600,"10-minute": 600,}def wind_averaging_seconds(period: object) -> int | None:"""Seconds for a 1, 3, or 10 minute label. Other labels have no duration.``1min`` is 60, ``3-min`` is 180, and ``10min`` is 600. Synthetic andunknown text stay null. This does not rescale a wind speed."""if period is None:return Nonetext = str(period).strip().lower().replace(" ", "").replace("_", "-")if not text:return Nonereturn _AVERAGING_SECONDS.get(text)def split_wind_averaging(frame: pd.DataFrame) -> dict[str, dict[str, list]]:"""``wind_averaging`` and ``wind_averaging_s`` for train, val, and test.Each split lists the set of labels on its rows. Seconds follow thelabel. A label with no known duration stores null and is not converted."""if "split" not in frame.columns:raise SchemaError("split is required to record wind_averaging by split")if "wind_averaging" not in frame.columns:raise SchemaError("wind_averaging is required")report: dict[str, dict[str, list]] = {}for name in ("train", "val", "test"):rows = frame.loc[frame["split"].astype(str) == name, "wind_averaging"]labels = sorted({str(value).strip() for value in rows.tolist() if str(value).strip()})report[name] = {"wind_averaging": labels,"wind_averaging_s": [wind_averaging_seconds(label) for label in labels],}return reportdef _synthetic_flags(frame: pd.DataFrame) -> list[bool]:if "is_synthetic" not in frame.columns:raise SchemaError("is_synthetic is required so a synthetic row cannot be read as real")return [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]def validate_manifest(frame: pd.DataFrame,wind_min_kt: float = DEFAULT_WIND_MIN_KT,wind_max_kt: float = DEFAULT_WIND_MAX_KT,) -> QualityReport:"""Collect quality-gate failures. Callers that load data use ``require_valid``."""errors: list[str] = []missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns]if missing:return QualityReport(len(frame), 0, (f"missing required columns: {missing}",))keys = frame["sample_id"].map(_sample_key)null_id = frame["sample_id"].isna() | keys.eq("") | keys.str.lower().isin(_MISSING_TEXT)if bool(null_id.any()):errors.append("sample_id has nulls")if bool(keys.duplicated().any()):examples = keys.loc[keys.duplicated()].head(5).tolist()errors.append(f"duplicate sample_id, examples: {examples}")blank_storm = frame["storm_id"].astype(str).str.strip().str.len() == 0if frame["storm_id"].isna().any() or blank_storm.any():errors.append("storm_id has nulls")if frame["image_path"].isna().any() or (frame["image_path"].astype(str).str.strip().str.len() == 0).any():errors.append("image_path has nulls")winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")if winds.isna().any():errors.append("wind_speed_kt has non-numeric values")else:bad = (winds < wind_min_kt) | (winds > wind_max_kt)if bad.any():errors.append(f"{int(bad.sum())} wind values outside [{wind_min_kt}, {wind_max_kt}] kt")try:recorded_wind_averaging(frame)except SchemaError as exc:errors.append(str(exc))try:_synthetic_flags(frame)except SchemaError as exc:errors.append(str(exc))n_storms = int(frame["storm_id"].nunique(dropna=True))return QualityReport(len(frame), n_storms, tuple(errors))def require_valid(frame: pd.DataFrame, **kwargs: float) -> pd.DataFrame:"""Return a copy that passed every manifest gate. Raises on failure."""report = validate_manifest(frame, **kwargs)if not report.ok:raise SchemaError("; ".join(report.errors))out = frame.copy()out["storm_id"] = out["storm_id"].astype(str).str.strip()out["sample_id"] = out["sample_id"].map(_sample_key).astype(str)out["image_path"] = out["image_path"].astype(str).str.strip()out["wind_speed_kt"] = pd.to_numeric(out["wind_speed_kt"])out["wind_averaging"] = recorded_wind_averaging(out)out["is_synthetic"] = _synthetic_flags(out)# Project grouping stored on imd5_class. Not an official IMD class code.out["imd5_class"] = out["wind_speed_kt"].map(wind_to_imd5)return out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Four-frame windows inside one split.The image tensor is infrared only. Wind, R34, and radius of maximum windmay be read as targets for the last frame. They are not channels.A previous-frame link that leaves the split cannot bring that frame in.Southern Hemisphere frames are not flipped."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.data_loader import load_image, resolve_imagefrom src.preprocessing import NormStats, leave_unflipped, prepare_image, stack_preparedN_FRAMES = 4SIZE_LABELS = ("r34_nmi", "rmw_nmi")def size_targets_present(frame: pd.DataFrame) -> bool:"""True when both size columns exist and one row has a finite pair.All-null columns are not labels. The size head stays off until then."""if any(column not in frame.columns for column in SIZE_LABELS):return Falsevalues = frame.loc[:, list(SIZE_LABELS)].apply(pd.to_numeric, errors="coerce")finite_pair = np.isfinite(values.to_numpy(dtype=np.float64)).all(axis=1)return bool(finite_pair.any())def _prev_id(value: object) -> str | None:if value is None:return Nonetry:if pd.isna(value):return Noneexcept (TypeError, ValueError):return Nonetext = str(value).strip()if text == "" or text.lower() in {"nan", "none", "<na>", "nat"}:return Nonereturn textdef _window_stays_in_split(sample_ids: list[str], prev_ids: list[str | None], in_split: set[str]) -> bool:"""Reject a window whose previous-frame link leaves the split.A link that was cleared is ignored. A link that is still set must namethe previous frame in this window, except at the first frame, where asame-split predecessor may sit just outside a sliding window."""for offset, _sample_id in enumerate(sample_ids):prev = prev_ids[offset]if prev is None:continueif prev not in in_split:return Falseif offset > 0 and prev != sample_ids[offset - 1]:return Falsereturn Truedef frame_windows(frame: pd.DataFrame, split: str, n_frames: int = N_FRAMES) -> list[list[str]]:"""Sample ids of consecutive frames, one storm, one split.``n_frames`` is 4. A link that points outside this split rejects thewindow. A link that was cleared stays cleared and is not followed."""if n_frames != N_FRAMES:raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")if "split" not in frame.columns:raise ValueError("frame is missing split")rows = frame[frame["split"] == split]if rows.empty:return []order = ["timestamp", "sample_id"] if "timestamp" in rows.columns else ["sample_id"]in_split = set(rows["sample_id"].astype(str))windows: list[list[str]] = []for _storm_id, group in rows.groupby("storm_id", sort=False):ordered = group.sort_values(order, kind="mergesort")sample_ids = [str(value) for value in ordered["sample_id"].tolist()]if "prev_sample_id" in ordered.columns:prev_ids = [_prev_id(value) for value in ordered["prev_sample_id"].tolist()]else:prev_ids = [None] * len(sample_ids)for start in range(0, len(sample_ids) - n_frames + 1):chosen = sample_ids[start : start + n_frames]prev = prev_ids[start : start + n_frames]if _window_stays_in_split(chosen, prev, in_split):windows.append(chosen)return windowsdef _row(indexed: pd.DataFrame, sample_id: str) -> pd.Series:row = indexed.loc[sample_id]if isinstance(row, pd.DataFrame):return row.iloc[0]return rowdef _pair(row: pd.Series, column: str) -> float:number = pd.to_numeric(pd.Series([row[column]]), errors="coerce").iloc[0]if pd.isna(number):return float("nan")return float(number)def stack_windows(frame: pd.DataFrame,manifest_path: str | Path,split_name: str,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float,n_frames: int = N_FRAMES,wind_column: str = "wind_speed_kt",) -> tuple[np.ndarray, np.ndarray, list[str | None], np.ndarray | None]:"""Return ``(N, 4, C, H, W)`` images and last-frame targets.Size targets are returned only when :func:`size_targets_present` is true."""windows = frame_windows(frame, split_name, n_frames)if not windows:raise ValueError(f"split {split_name} has no {n_frames}-frame windows")indexed = frame.set_index(frame["sample_id"].astype(str), drop=False)use_size = size_targets_present(frame)images: list[np.ndarray] = []winds: list[float] = []labels: list[str | None] = []sizes: list[list[float]] = []for sample_ids in windows:frames: list[np.ndarray] = []for sample_id in sample_ids:row = _row(indexed, sample_id)array = load_image(resolve_image(manifest_path, str(row["image_path"])))hemisphere = Noneif "hemisphere" in frame.columns and not pd.isna(row["hemisphere"]):hemisphere = str(row["hemisphere"])frames.append(prepare_image(leave_unflipped(array, hemisphere),image_size,stats,max_missing_fraction,))images.append(stack_prepared(frames))last = _row(indexed, sample_ids[-1])target_col = wind_column if wind_column in last and not pd.isna(last[wind_column]) else "wind_speed_kt"winds.append(float(last[target_col]))if "_class" in frame.columns and not pd.isna(last["_class"]):labels.append(str(last["_class"]))else:labels.append(None)if use_size:sizes.append([_pair(last, "r34_nmi"), _pair(last, "rmw_nmi")])size_array = np.asarray(sizes, dtype=np.float32) if use_size else Nonereturn (stack_prepared(images),np.asarray(winds, dtype=np.float32),labels,size_array,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Four-frame windows inside one split.The image tensor is infrared only. Wind, R34, and radius of maximum windmay be read as targets for the last frame. They are not channels.A previous-frame link that leaves the split cannot bring that frame in.Southern Hemisphere frames are not flipped."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.data_loader import load_image, resolve_imagefrom src.preprocessing import NormStats, leave_unflipped, prepare_image, stack_preparedN_FRAMES = 4SIZE_LABELS = ("r34_nmi", "rmw_nmi")def size_targets_present(frame: pd.DataFrame) -> bool:"""True when both size columns exist and one row has a finite pair.All-null columns are not labels. The size head stays off until then."""if any(column not in frame.columns for column in SIZE_LABELS):return Falsevalues = frame.loc[:, list(SIZE_LABELS)].apply(pd.to_numeric, errors="coerce")finite_pair = np.isfinite(values.to_numpy(dtype=np.float64)).all(axis=1)return bool(finite_pair.any())def _prev_id(value: object) -> str | None:if value is None:return Nonetry:if pd.isna(value):return Noneexcept (TypeError, ValueError):return Nonetext = str(value).strip()if text == "" or text.lower() in {"nan", "none", "<na>", "nat"}:return Nonereturn textdef _window_stays_in_split(sample_ids: list[str], prev_ids: list[str | None], in_split: set[str]) -> bool:"""Reject a window whose previous-frame link leaves the split.A link that was cleared is ignored. A link that is still set must namethe previous frame in this window, except at the first frame, where asame-split predecessor may sit just outside a sliding window."""for offset, _sample_id in enumerate(sample_ids):prev = prev_ids[offset]if prev is None:continueif prev not in in_split:return Falseif offset > 0 and prev != sample_ids[offset - 1]:return Falsereturn Truedef frame_windows(frame: pd.DataFrame, split: str, n_frames: int = N_FRAMES) -> list[list[str]]:"""Sample ids of consecutive frames, one storm, one split.``n_frames`` is 4. A link that points outside this split rejects thewindow. A link that was cleared stays cleared and is not followed."""if n_frames != N_FRAMES:raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")if "split" not in frame.columns:raise ValueError("frame is missing split")rows = frame[frame["split"] == split]if rows.empty:return []order = ["timestamp", "sample_id"] if "timestamp" in rows.columns else ["sample_id"]in_split = set(rows["sample_id"].astype(str))windows: list[list[str]] = []for _storm_id, group in rows.groupby("storm_id", sort=False):ordered = group.sort_values(order, kind="mergesort")sample_ids = [str(value) for value in ordered["sample_id"].tolist()]if "prev_sample_id" in ordered.columns:prev_ids = [_prev_id(value) for value in ordered["prev_sample_id"].tolist()]else:prev_ids = [None] * len(sample_ids)for start in range(0, len(sample_ids) - n_frames + 1):chosen = sample_ids[start : start + n_frames]prev = prev_ids[start : start + n_frames]if _window_stays_in_split(chosen, prev, in_split):windows.append(chosen)return windowsdef _row(indexed: pd.DataFrame, sample_id: str) -> pd.Series:row = indexed.loc[sample_id]if isinstance(row, pd.DataFrame):return row.iloc[0]return rowdef _pair(row: pd.Series, column: str) -> float:number = pd.to_numeric(pd.Series([row[column]]), errors="coerce").iloc[0]if pd.isna(number):return float("nan")return float(number)def stack_windows(frame: pd.DataFrame,manifest_path: str | Path,split_name: str,image_size: int | str | None,stats: NormStats | None,max_missing_fraction: float,n_frames: int = N_FRAMES,wind_column: str = "wind_speed_kt",) -> tuple[np.ndarray, np.ndarray, list[str | None], np.ndarray | None]:"""Return ``(N, 4, C, H, W)`` images and last-frame targets.Size targets are returned only when :func:`size_targets_present` is true."""windows = frame_windows(frame, split_name, n_frames)if not windows:raise ValueError(f"split {split_name} has no {n_frames}-frame windows")indexed = frame.set_index(frame["sample_id"].astype(str), drop=False)use_size = size_targets_present(frame)images: list[np.ndarray] = []winds: list[float] = []labels: list[str | None] = []sizes: list[list[float]] = []for sample_ids in windows:frames: list[np.ndarray] = []for sample_id in sample_ids:row = _row(indexed, sample_id)array = load_image(resolve_image(manifest_path, str(row["image_path"])))hemisphere = Noneif "hemisphere" in frame.columns and not pd.isna(row["hemisphere"]):hemisphere = str(row["hemisphere"])frames.append(prepare_image(leave_unflipped(array, hemisphere),image_size,stats,max_missing_fraction,))images.append(stack_prepared(frames))last = _row(indexed, sample_ids[-1])target_col = wind_column if wind_column in last and not pd.isna(last[wind_column]) else "wind_speed_kt"winds.append(float(last[target_col]))if "_class" in frame.columns and not pd.isna(last["_class"]):labels.append(str(last["_class"]))else:labels.append(None)if use_size:sizes.append([_pair(last, "r34_nmi"), _pair(last, "rmw_nmi")])size_array = np.asarray(sizes, dtype=np.float32) if use_size else Nonereturn (stack_prepared(images),np.asarray(winds, dtype=np.float32),labels,size_array,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318"""Storm-safe splits. Random frame splits are rejected.``storm_ids_by_split`` returns the disjoint train, val, and test storm ids.A later residual-quantile coverage check can reuse that map from an assignedframe without assigning rows again."""from __future__ import annotationsimport refrom collections.abc import Iterableimport numpy as npimport pandas as pdfrom src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, wind_to_imd5_CLASS_SEQUENCES = tuple(tuple(part for part in re.split(r"[^a-z0-9]+", name.lower()) if part)for name in DEFAULT_NAMES)_COMPACT_MARKERS = ("windspeed", "windkt", "r34", "rmw", "imd5", "intensity")_LABEL_TOKENS = frozenset({"wind", "windspeed", "windkt", "r34", "rmw", "imd5", "intensity", "class"})class LeakageError(RuntimeError):"""A split shares a storm across sides, or is a random frame split."""def _name_tokens(name: str) -> list[str]:return [part for part in re.split(r"[^a-z0-9]+", str(name).lower()) if part]def _contains_sequence(tokens: list[str], sequence: tuple[str, ...]) -> bool:width = len(sequence)if width == 0 or len(tokens) < width:return Falsereturn any(tuple(tokens[index : index + width]) == sequencefor index in range(len(tokens) - width + 1))def is_forbidden_input(name: str) -> bool:"""True for a label column or a name derived from wind, size, or class.Image features such as ``pixel_mean`` and ``delta_pixel_mean`` stay allowed."""text = str(name).strip().lower()if text in {item.lower() for item in FORBIDDEN_FEATURES}:return Trueif text in {item.lower() for item in DEFAULT_NAMES}:return Truetokens = _name_tokens(text)if any(token in _LABEL_TOKENS or token.startswith(("windspeed", "windkt", "r34", "rmw", "imd5"))for token in tokens):return Trueif any(_contains_sequence(tokens, sequence) for sequence in _CLASS_SEQUENCES):return Truecompact = "".join(tokens)return any(marker in compact for marker in _COMPACT_MARKERS)def forbidden_input_names(names: Iterable[str]) -> list[str]:return sorted({str(name) for name in names if is_forbidden_input(str(name))})def assert_no_forbidden_inputs(names: Iterable[str], detail: str) -> None:banned = forbidden_input_names(names)if banned:raise LeakageError(f"{detail}: {banned}")def assert_no_group_leakage(*frames: pd.DataFrame, group_col: str = "storm_id") -> None:seen: dict[str, int] = {}for index, frame in enumerate(frames):if frame.empty:continuefor storm_id in frame[group_col].astype(str).unique():if storm_id in seen:raise LeakageError(f"{group_col}={storm_id} is in split index {seen[storm_id]} and {index}")seen[storm_id] = indexsample_ids: list[str] = []for frame in frames:if "sample_id" in frame.columns:sample_ids.extend(frame["sample_id"].astype(str).tolist())if len(sample_ids) != len(set(sample_ids)):raise LeakageError("sample_id repeated across splits")def storm_ids_by_split(frame: pd.DataFrame) -> dict[str, frozenset[str]]:"""Return disjoint storm ids for ``train``, ``val``, and ``test``.A later residual-quantile coverage check can take ``result["test"]``from an assigned frame and score those storms without assigning rows again."""if "storm_id" not in frame.columns or "split" not in frame.columns:raise LeakageError("storm_id and split are required")known = ("train", "val", "test")labels = set(frame["split"].astype(str).unique())unknown = labels - set(known)if unknown:raise LeakageError(f"unknown splits: {sorted(unknown)}")parts = [frame.loc[frame["split"].astype(str) == name] for name in known]assert_no_group_leakage(*parts)return {name: frozenset(part["storm_id"].astype(str))for name, part in zip(known, parts, strict=True)}def _storm_table(frame: pd.DataFrame) -> pd.DataFrame:rows: list[dict[str, object]] = []for storm_id, group in frame.groupby("storm_id", sort=False):if "year" in group.columns:years = pd.to_numeric(group["year"], errors="coerce").dropna().astype(int)else:years = pd.Series(dtype=int)basins = (sorted(set(group["basin"].dropna().astype(str)))if "basin" in group.columnselse [])median_wind = float(pd.to_numeric(group["wind_speed_kt"]).median())rows.append({"storm_id": str(storm_id),"year_min": int(years.min()) if len(years) else pd.NA,"year_max": int(years.max()) if len(years) else pd.NA,"basins": basins,"stratify": wind_to_imd5(median_wind) or "below",})return pd.DataFrame(rows)def _counts(n: int, test_fraction: float, val_fraction: float) -> tuple[int, int]:if n < 3:raise LeakageError("need at least 3 storms for train/val/test")n_test = max(1, int(round(n * test_fraction)))n_val = max(1, int(round((n - n_test) * val_fraction)))if n - n_test - n_val < 1:raise LeakageError("split fractions left no training storms")return n_test, n_valdef _ordered_storms(table: pd.DataFrame, seed: int) -> list[str]:"""Interleave intensity bins so a slice is approximately stratified."""rng = np.random.default_rng(seed)groups = [list(rng.permutation(ids.to_numpy()))for _, ids in table.groupby("stratify")["storm_id"]]ordered: list[str] = []while any(groups):for group in groups:if group:ordered.append(str(group.pop()))return ordereddef _assignment_from_ids(table: pd.DataFrame, test_ids: set[str], val_ids: set[str]) -> dict[str, str]:return {sid: ("test" if sid in test_ids else "val" if sid in val_ids else "train")for sid in table["storm_id"].astype(str)}def assign_storms(frame: pd.DataFrame,strategy: str,test_fraction: float = 0.2,val_fraction: float = 0.2,seed: int = 42,holdout_years: list[int] | None = None,holdout_basin: str | None = None,) -> pd.DataFrame:"""Return a copy with ``split`` in {train, val, test}. Storms are never cut."""strategy = strategy.lower().strip()if strategy in {"random", "frame", "shuffle", "random_frame"}:raise LeakageError("random frame splits are forbidden; use storm_wise, chronological, or holdout_basin")work = frame.copy()work["storm_id"] = work["storm_id"].astype(str)table = _storm_table(work)holdout_years = list(holdout_years or [])if strategy == "chronological":if table["year_min"].isna().any():missing = table.loc[table["year_min"].isna(), "storm_id"].tolist()raise LeakageError(f"chronological split needs a year for every storm: {missing}")if not holdout_years:years = sorted(int(year) for year in table["year_min"].astype(int).unique())n_hold = max(1, int(round(len(years) * test_fraction)))holdout_years = years[-n_hold:]held = {int(year) for year in holdout_years}def touches_year(row: pd.Series) -> bool:span = set(range(int(row.year_min), int(row.year_max) + 1))return bool(span & held)test_ids = set(table.loc[table.apply(touches_year, axis=1), "storm_id"].astype(str))pool = table[~table["storm_id"].isin(test_ids)]if pool.empty or not test_ids:raise LeakageError("chronological split produced an empty side")n_val = max(1, int(round(len(pool) * val_fraction)))if n_val >= len(pool):raise LeakageError("not enough non-holdout storms for train and val")val_ids = set(_ordered_storms(pool, seed)[:n_val])assignment = _assignment_from_ids(table, test_ids, val_ids)elif strategy == "holdout_basin":if not holdout_basin:raise LeakageError("holdout_basin strategy requires holdout_basin")test_ids = set(table.loc[table["basins"].map(lambda basins: holdout_basin in basins), "storm_id"].astype(str))pool = table[~table["storm_id"].isin(test_ids)]if pool.empty or not test_ids:raise LeakageError("holdout basin split produced an empty side")n_val = max(1, int(round(len(pool) * val_fraction)))if n_val >= len(pool):raise LeakageError("not enough storms outside the holdout basin for train and val")val_ids = set(_ordered_storms(pool, seed)[:n_val])assignment = _assignment_from_ids(table, test_ids, val_ids)elif strategy == "storm_wise":ordered = _ordered_storms(table, seed)n_test, n_val = _counts(len(ordered), test_fraction, val_fraction)assignment = _assignment_from_ids(table, set(ordered[:n_test]), set(ordered[n_test : n_test + n_val]))else:raise LeakageError(f"unknown split strategy: {strategy}")work["split"] = work["storm_id"].map(assignment)if work["split"].isna().any():raise LeakageError("some rows were not assigned a split")parts = [work[work["split"] == name] for name in ("train", "val", "test")]assert_no_group_leakage(*parts)return workdef observation_order(frame: pd.DataFrame) -> pd.Series:"""Within-storm clock. Timestamp, else NASA ``relative_time_s``, else row order.A missing value in the chosen clock falls back to row order so a partialcolumn cannot reorder the other rows. This is not a split."""if "timestamp" in frame.columns:parsed = pd.to_datetime(frame["timestamp"], errors="coerce", utc=True)if not bool(parsed.isna().any()):return pd.Series(parsed.to_numpy(), index=frame.index)return frame["timestamp"].astype(str)if "relative_time_s" in frame.columns:values = pd.to_numeric(frame["relative_time_s"], errors="coerce")if not bool(values.isna().any()):return valuesreturn pd.Series(np.arange(len(frame)), index=frame.index)def add_previous_frame_id(frame: pd.DataFrame) -> pd.DataFrame:"""Attach the previous sample inside the same storm, ordered by time.The link is not yet split-safe. Call ``null_cross_split_links`` beforeusing it as a feature. NASA frames use ``relative_time_s`` when theyhave no ``timestamp``."""if "storm_id" not in frame.columns or "sample_id" not in frame.columns:raise LeakageError("storm_id and sample_id are required")out = frame.copy()out["storm_id"] = out["storm_id"].astype(str)out["sample_id"] = out["sample_id"].astype(str)out = out.assign(_order=observation_order(out))out = out.sort_values(["storm_id", "_order"], kind="mergesort")out["prev_sample_id"] = out.groupby("storm_id", sort=False)["sample_id"].shift(1)out = out.drop(columns=["_order"], errors="ignore")return out.sort_index()def _sample_split_lookup(frame: pd.DataFrame) -> pd.Series:"""Map sample id strings to the split of the first row with that id."""temporary = frame.assign(_sid=frame["sample_id"].map(str))temporary = temporary.drop_duplicates("_sid")return temporary.set_index("_sid")["split"].astype(str)def null_cross_split_links(frame: pd.DataFrame) -> tuple[pd.DataFrame, int]:"""Drop previous-frame ids that point outside the row's split.Returns the frame and the number of links removed. Unknown previous idsare removed as well; they can hide a filtered-out frame."""if "split" not in frame.columns or "prev_sample_id" not in frame.columns:raise LeakageError("split and prev_sample_id are required")lookup = _sample_split_lookup(frame)out = frame.copy()dropped = 0kept: list[object] = []for prev, split in zip(out["prev_sample_id"], out["split"].astype(str), strict=True):if pd.isna(prev):kept.append(pd.NA)continuekey = str(prev)if key not in lookup.index or lookup.loc[key] != split:kept.append(pd.NA)dropped += 1else:kept.append(key)out["prev_sample_id"] = keptreturn out, dropped123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318"""Storm-safe splits. Random frame splits are rejected.``storm_ids_by_split`` returns the disjoint train, val, and test storm ids.A later residual-quantile coverage check can reuse that map from an assignedframe without assigning rows again."""from __future__ import annotationsimport refrom collections.abc import Iterableimport numpy as npimport pandas as pdfrom src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, wind_to_imd5_CLASS_SEQUENCES = tuple(tuple(part for part in re.split(r"[^a-z0-9]+", name.lower()) if part)for name in DEFAULT_NAMES)_COMPACT_MARKERS = ("windspeed", "windkt", "r34", "rmw", "imd5", "intensity")_LABEL_TOKENS = frozenset({"wind", "windspeed", "windkt", "r34", "rmw", "imd5", "intensity", "class"})class LeakageError(RuntimeError):"""A split shares a storm across sides, or is a random frame split."""def _name_tokens(name: str) -> list[str]:return [part for part in re.split(r"[^a-z0-9]+", str(name).lower()) if part]def _contains_sequence(tokens: list[str], sequence: tuple[str, ...]) -> bool:width = len(sequence)if width == 0 or len(tokens) < width:return Falsereturn any(tuple(tokens[index : index + width]) == sequencefor index in range(len(tokens) - width + 1))def is_forbidden_input(name: str) -> bool:"""True for a label column or a name derived from wind, size, or class.Image features such as ``pixel_mean`` and ``delta_pixel_mean`` stay allowed."""text = str(name).strip().lower()if text in {item.lower() for item in FORBIDDEN_FEATURES}:return Trueif text in {item.lower() for item in DEFAULT_NAMES}:return Truetokens = _name_tokens(text)if any(token in _LABEL_TOKENS or token.startswith(("windspeed", "windkt", "r34", "rmw", "imd5"))for token in tokens):return Trueif any(_contains_sequence(tokens, sequence) for sequence in _CLASS_SEQUENCES):return Truecompact = "".join(tokens)return any(marker in compact for marker in _COMPACT_MARKERS)def forbidden_input_names(names: Iterable[str]) -> list[str]:return sorted({str(name) for name in names if is_forbidden_input(str(name))})def assert_no_forbidden_inputs(names: Iterable[str], detail: str) -> None:banned = forbidden_input_names(names)if banned:raise LeakageError(f"{detail}: {banned}")def assert_no_group_leakage(*frames: pd.DataFrame, group_col: str = "storm_id") -> None:seen: dict[str, int] = {}for index, frame in enumerate(frames):if frame.empty:continuefor storm_id in frame[group_col].astype(str).unique():if storm_id in seen:raise LeakageError(f"{group_col}={storm_id} is in split index {seen[storm_id]} and {index}")seen[storm_id] = indexsample_ids: list[str] = []for frame in frames:if "sample_id" in frame.columns:sample_ids.extend(frame["sample_id"].astype(str).tolist())if len(sample_ids) != len(set(sample_ids)):raise LeakageError("sample_id repeated across splits")def storm_ids_by_split(frame: pd.DataFrame) -> dict[str, frozenset[str]]:"""Return disjoint storm ids for ``train``, ``val``, and ``test``.A later residual-quantile coverage check can take ``result["test"]``from an assigned frame and score those storms without assigning rows again."""if "storm_id" not in frame.columns or "split" not in frame.columns:raise LeakageError("storm_id and split are required")known = ("train", "val", "test")labels = set(frame["split"].astype(str).unique())unknown = labels - set(known)if unknown:raise LeakageError(f"unknown splits: {sorted(unknown)}")parts = [frame.loc[frame["split"].astype(str) == name] for name in known]assert_no_group_leakage(*parts)return {name: frozenset(part["storm_id"].astype(str))for name, part in zip(known, parts, strict=True)}def _storm_table(frame: pd.DataFrame) -> pd.DataFrame:rows: list[dict[str, object]] = []for storm_id, group in frame.groupby("storm_id", sort=False):if "year" in group.columns:years = pd.to_numeric(group["year"], errors="coerce").dropna().astype(int)else:years = pd.Series(dtype=int)basins = (sorted(set(group["basin"].dropna().astype(str)))if "basin" in group.columnselse [])median_wind = float(pd.to_numeric(group["wind_speed_kt"]).median())rows.append({"storm_id": str(storm_id),"year_min": int(years.min()) if len(years) else pd.NA,"year_max": int(years.max()) if len(years) else pd.NA,"basins": basins,"stratify": wind_to_imd5(median_wind) or "below",})return pd.DataFrame(rows)def _counts(n: int, test_fraction: float, val_fraction: float) -> tuple[int, int]:if n < 3:raise LeakageError("need at least 3 storms for train/val/test")n_test = max(1, int(round(n * test_fraction)))n_val = max(1, int(round((n - n_test) * val_fraction)))if n - n_test - n_val < 1:raise LeakageError("split fractions left no training storms")return n_test, n_valdef _ordered_storms(table: pd.DataFrame, seed: int) -> list[str]:"""Interleave intensity bins so a slice is approximately stratified."""rng = np.random.default_rng(seed)groups = [list(rng.permutation(ids.to_numpy()))for _, ids in table.groupby("stratify")["storm_id"]]ordered: list[str] = []while any(groups):for group in groups:if group:ordered.append(str(group.pop()))return ordereddef _assignment_from_ids(table: pd.DataFrame, test_ids: set[str], val_ids: set[str]) -> dict[str, str]:return {sid: ("test" if sid in test_ids else "val" if sid in val_ids else "train")for sid in table["storm_id"].astype(str)}def assign_storms(frame: pd.DataFrame,strategy: str,test_fraction: float = 0.2,val_fraction: float = 0.2,seed: int = 42,holdout_years: list[int] | None = None,holdout_basin: str | None = None,) -> pd.DataFrame:"""Return a copy with ``split`` in {train, val, test}. Storms are never cut."""strategy = strategy.lower().strip()if strategy in {"random", "frame", "shuffle", "random_frame"}:raise LeakageError("random frame splits are forbidden; use storm_wise, chronological, or holdout_basin")work = frame.copy()work["storm_id"] = work["storm_id"].astype(str)table = _storm_table(work)holdout_years = list(holdout_years or [])if strategy == "chronological":if table["year_min"].isna().any():missing = table.loc[table["year_min"].isna(), "storm_id"].tolist()raise LeakageError(f"chronological split needs a year for every storm: {missing}")if not holdout_years:years = sorted(int(year) for year in table["year_min"].astype(int).unique())n_hold = max(1, int(round(len(years) * test_fraction)))holdout_years = years[-n_hold:]held = {int(year) for year in holdout_years}def touches_year(row: pd.Series) -> bool:span = set(range(int(row.year_min), int(row.year_max) + 1))return bool(span & held)test_ids = set(table.loc[table.apply(touches_year, axis=1), "storm_id"].astype(str))pool = table[~table["storm_id"].isin(test_ids)]if pool.empty or not test_ids:raise LeakageError("chronological split produced an empty side")n_val = max(1, int(round(len(pool) * val_fraction)))if n_val >= len(pool):raise LeakageError("not enough non-holdout storms for train and val")val_ids = set(_ordered_storms(pool, seed)[:n_val])assignment = _assignment_from_ids(table, test_ids, val_ids)elif strategy == "holdout_basin":if not holdout_basin:raise LeakageError("holdout_basin strategy requires holdout_basin")test_ids = set(table.loc[table["basins"].map(lambda basins: holdout_basin in basins), "storm_id"].astype(str))pool = table[~table["storm_id"].isin(test_ids)]if pool.empty or not test_ids:raise LeakageError("holdout basin split produced an empty side")n_val = max(1, int(round(len(pool) * val_fraction)))if n_val >= len(pool):raise LeakageError("not enough storms outside the holdout basin for train and val")val_ids = set(_ordered_storms(pool, seed)[:n_val])assignment = _assignment_from_ids(table, test_ids, val_ids)elif strategy == "storm_wise":ordered = _ordered_storms(table, seed)n_test, n_val = _counts(len(ordered), test_fraction, val_fraction)assignment = _assignment_from_ids(table, set(ordered[:n_test]), set(ordered[n_test : n_test + n_val]))else:raise LeakageError(f"unknown split strategy: {strategy}")work["split"] = work["storm_id"].map(assignment)if work["split"].isna().any():raise LeakageError("some rows were not assigned a split")parts = [work[work["split"] == name] for name in ("train", "val", "test")]assert_no_group_leakage(*parts)return workdef observation_order(frame: pd.DataFrame) -> pd.Series:"""Within-storm clock. Timestamp, else NASA ``relative_time_s``, else row order.A missing value in the chosen clock falls back to row order so a partialcolumn cannot reorder the other rows. This is not a split."""if "timestamp" in frame.columns:parsed = pd.to_datetime(frame["timestamp"], errors="coerce", utc=True)if not bool(parsed.isna().any()):return pd.Series(parsed.to_numpy(), index=frame.index)return frame["timestamp"].astype(str)if "relative_time_s" in frame.columns:values = pd.to_numeric(frame["relative_time_s"], errors="coerce")if not bool(values.isna().any()):return valuesreturn pd.Series(np.arange(len(frame)), index=frame.index)def add_previous_frame_id(frame: pd.DataFrame) -> pd.DataFrame:"""Attach the previous sample inside the same storm, ordered by time.The link is not yet split-safe. Call ``null_cross_split_links`` beforeusing it as a feature. NASA frames use ``relative_time_s`` when theyhave no ``timestamp``."""if "storm_id" not in frame.columns or "sample_id" not in frame.columns:raise LeakageError("storm_id and sample_id are required")out = frame.copy()out["storm_id"] = out["storm_id"].astype(str)out["sample_id"] = out["sample_id"].astype(str)out = out.assign(_order=observation_order(out))out = out.sort_values(["storm_id", "_order"], kind="mergesort")out["prev_sample_id"] = out.groupby("storm_id", sort=False)["sample_id"].shift(1)out = out.drop(columns=["_order"], errors="ignore")return out.sort_index()def _sample_split_lookup(frame: pd.DataFrame) -> pd.Series:"""Map sample id strings to the split of the first row with that id."""temporary = frame.assign(_sid=frame["sample_id"].map(str))temporary = temporary.drop_duplicates("_sid")return temporary.set_index("_sid")["split"].astype(str)def null_cross_split_links(frame: pd.DataFrame) -> tuple[pd.DataFrame, int]:"""Drop previous-frame ids that point outside the row's split.Returns the frame and the number of links removed. Unknown previous idsare removed as well; they can hide a filtered-out frame."""if "split" not in frame.columns or "prev_sample_id" not in frame.columns:raise LeakageError("split and prev_sample_id are required")lookup = _sample_split_lookup(frame)out = frame.copy()dropped = 0kept: list[object] = []for prev, split in zip(out["prev_sample_id"], out["split"].astype(str), strict=True):if pd.isna(prev):kept.append(pd.NA)continuekey = str(prev)if key not in lookup.index or lookup.loc[key] != split:kept.append(pd.NA)dropped += 1else:kept.append(key)out["prev_sample_id"] = keptreturn out, dropped
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591"""Build a Cloudie manifest from TCIR HDF5 files, IR1 channel only.TCIR (Chen, Chen and Lin, KDD 2018, https://doi.org/10.1145/3219819.3219926;data https://github.com/BoyoChen/TCIR) ships two HDF5 files:``TCIR-ATLN_EPAC_WPAC.h5`` and ``TCIR-CPAC_IO_SH.h5``. Each has- ``matrix``: N x 201 x 201 x 4 float32. The README lists the channels inthe order IR1, WV, VIS, PMW, so IR1 is index 0 (``IR1_INDEX``). The filehas no channel attributes. On 512 random real frames per file, channel 0has a median near 275 and is warmer than channel 1 (WV, median near 238)in over 98% of frames, channel 2 is a 0 to 2.2 reflectance with many NaNs(VIS at night) and channel 3 is a rain rate. That fits the README order.IR1 comes from GridSat-B1, which stores brightness temperature in kelvin.Reports still call these "pixel stats".- ``info``: a pandas 0.15 "fixed" frame (data_set, ID, time, lon, lat, Vmax,R35_4qAVG, MSLP). Current pandas cannot read it, so ``read_info`` decodesit with h5py and a restricted unpickler that only rebuilds numpy arrays.Only channel 0 is read (an h5py hyperslab, ``matrix[a:b, :, :, 0]``). Frameskeep their native 201 x 201 grid, centred on the best-track position, about7/100 degree per pixel.Labels. TCIR documents JTWC best tracks for WPAC and HURDAT2 for ATLN andEPAC. Both are 1-minute sustained winds, so ``wind_averaging`` is ``1min``.TCIR does not document the label source for CPAC, IO or SH. Those rows carry``label_source_documented = False`` and an ``_inferred`` label source. Across-check against IBTrACS v04r01 (matched on time and a 0.6 degreeposition window) found TCIR ``Vmax`` equal to ``USA_WIND`` on 99.8% of IOand SH rows (JTWC, 1-minute) and on 92% of CPAC rows (99.5% within 5 kt;HURDAT2/CPHC, 1-minute), while the 10-minute (BoM, RSMC La Reunion, Nadi)and 3-minute (New Delhi) agency winds match 14-21% of the time. So``wind_averaging`` is ``1min`` on every row.Southern Hemisphere storms rotate clockwise. Nothing here flips an image bydefault. ``hemisphere`` (N or S, from the row's latitude) is recorded perrow. ``flip_southern=True`` is an explicit opt-in that mirrors S framesnorth-south when exporting and sets ``flipped = True`` on those rows.Frames whose IR1 is all NaN, has a NaN fraction above``max_missing_fraction`` (0.30, the preprocessing gate), or has any finitevalue outside ``IR1_VALID_RANGE`` (150 to 340 K; the real files hold a fewframes with pixels down to 76 K or up to 348 K) are dropped and listed with a reason in anexclusions CSV. Kept frames may still hold a few NaNs; ``ir1_nan_fraction``records how many, and ``src.preprocessing`` fills them later.TCIR has no official split inside these files, so the manifest has no``source_split`` and never has ``split``. ``src.splits.assign_storms`` writes``split`` by storm. MSLP and R35 are label-derived, so they stay out of themanifest.Distance to land is joined from ``tcir/audit/distance_to_land.csv`` on``sample_id`` (``distance_to_land_km`` and ``near_land``). The trainingpath then applies ``labels.near_land_policy`` with ``labels.open_water_km``.A sample the CSV does not list, and a listed row whose distance is blank,stay unknown. The distance is not filled with 0. NASA is not in this file;that loader has no join key (``nasa_tc/audit/README.md``)."""from __future__ import annotationsimport argparseimport ioimport jsonimport picklefrom collections.abc import Iterator, Sequencefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validCHANNELS = ("IR1", "WV", "VIS", "PMW") # order in the TCIR READMEIR1_INDEX = 0IMAGE_SIZE = 201WIND_AVERAGING = "1min"IR1_VALID_RANGE = (150.0, 340.0) # kelvin; colder or warmer than any plausible IR window valueMAX_MISSING_FRACTION = 0.30 # same gate as src.preprocessingBLOCK = 256_DISTANCE_COLUMNS = ("sample_id", "distance_to_land_km", "near_land")DEFAULT_DISTANCE_CSV = Path(__file__).resolve().parents[1] / "tcir" / "audit" / "distance_to_land.csv"# data_set -> (label source, documented by TCIR)LABEL_SOURCES = {"WPAC": ("jtwc_best_track", True),"ATLN": ("hurdat2", True),"EPAC": ("hurdat2", True),# Not documented by TCIR; inferred from an IBTrACS v04r01 match (PR notes)."CPAC": ("hurdat2_inferred", False),"IO": ("jtwc_best_track_inferred", False),"SH": ("jtwc_best_track_inferred", False),}EXCLUSION_COLUMNS = ["sample_id","storm_id","basin","source_file","h5_index","ir1_nan_fraction","reason",]_ALLOWED_GLOBALS = {("numpy.core.multiarray", "_reconstruct"),("numpy._core.multiarray", "_reconstruct"),("numpy.core.multiarray", "scalar"),("numpy._core.multiarray", "scalar"),("numpy", "ndarray"),("numpy", "dtype"),("_codecs", "encode"), # Python 3 protocol-2 pickles of byte strings}class _NumpyOnlyUnpickler(pickle.Unpickler):def find_class(self, module: str, name: str): # noqa: ANN201if (module, name) not in _ALLOWED_GLOBALS:raise pickle.UnpicklingError(f"refusing to load {module}.{name} from TCIR info")target = "numpy._core.multiarray" if module.endswith(".multiarray") else moduleimport importlibreturn getattr(importlib.import_module(target), name)def _text(value: object) -> str:return value.decode() if isinstance(value, bytes) else str(value)def _block_values(dataset) -> np.ndarray: # noqa: ANN001if dataset.dtype.kind in "fiub":return dataset[()]raw = dataset[0]data = bytes(np.asarray(raw, dtype=np.uint8)) if not isinstance(raw, bytes) else rawreturn _NumpyOnlyUnpickler(io.BytesIO(data), encoding="latin1").load()def read_info(path: str | Path) -> pd.DataFrame:"""Decode the ``info`` frame with h5py. Adds ``h5_index`` (row in ``matrix``)."""import h5pywith h5py.File(path, "r") as handle:group = handle["info"]order = [_text(name) for name in group["axis0"][()]]n_rows = int(group["axis1"].shape[0])columns: dict[str, np.ndarray] = {}for block in range(int(group.attrs["nblocks"])):items = [_text(name) for name in group[f"block{block}_items"][()]]values = np.asarray(_block_values(group[f"block{block}_values"]))if values.shape != (n_rows, len(items)):raise ValueError(f"{path}: info block{block} has shape {values.shape}")for position, item in enumerate(items):columns[item] = values[:, position]n_matrix = int(handle["matrix"].shape[0])if n_matrix != n_rows:raise ValueError(f"{path}: info has {n_rows} rows but matrix has {n_matrix}")frame = pd.DataFrame({name: columns[name] for name in order})for name in frame.columns:if frame[name].dtype == object:frame[name] = frame[name].map(_text)frame["h5_index"] = np.arange(n_rows)return framedef iter_ir1(path: str | Path, block: int = BLOCK) -> Iterator[tuple[int, np.ndarray]]:"""Yield ``(start, frames)`` with frames shaped (k, 201, 201), IR1 only."""import h5pywith h5py.File(path, "r") as handle:matrix = handle["matrix"]if matrix.ndim != 4 or matrix.shape[1:] != (IMAGE_SIZE, IMAGE_SIZE, len(CHANNELS)):raise ValueError(f"{path}: matrix shape {matrix.shape}, expected N x 201 x 201 x 4")for start in range(0, matrix.shape[0], block):stop = min(start + block, matrix.shape[0])yield start, np.asarray(matrix[start:stop, :, :, IR1_INDEX], dtype=np.float32)def exclusion_reason(frame: np.ndarray,max_missing_fraction: float = MAX_MISSING_FRACTION,valid_range: tuple[float, float] = IR1_VALID_RANGE,) -> tuple[str | None, float]:"""Return (reason or None, NaN fraction) for one IR1 frame."""finite = np.isfinite(frame)nan_fraction = float(1.0 - finite.mean())if not finite.any():return "ir1 all NaN", nan_fractionif nan_fraction > max_missing_fraction:return f"ir1 NaN fraction {nan_fraction:.3f} > {max_missing_fraction:.2f}", nan_fractionvalues = frame[finite]low, high = valid_rangeif float(values.min()) < low or float(values.max()) > high:return (f"ir1 value outside [{low:g}, {high:g}] K "f"(min {float(values.min()):.2f}, max {float(values.max()):.2f})",nan_fraction,)return None, nan_fractiondef hemisphere_of(lat: pd.Series) -> pd.Series:return pd.Series(np.where(pd.to_numeric(lat) < 0, "S", "N"), index=lat.index)def _blank_distance(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _near_land_token(value: object) -> str:"""``true``, ``false``, or ``unknown``. A blank cell stays unknown."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank_distance(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"near_land value {value!r} is not true, false, or unknown")def _distance_km(value: object) -> float:if _blank_distance(value):return float("nan")try:number = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from excif not np.isfinite(number):return float("nan")return numberdef read_distance_to_land(path: str | Path | None = None) -> pd.DataFrame:"""``sample_id``, ``distance_to_land_km``, and ``near_land`` from the audit CSV.``path`` defaults to ``tcir/audit/distance_to_land.csv``. Blank distancesstay NaN. ``near_land`` stays ``unknown`` when the audit says so."""csv_path = DEFAULT_DISTANCE_CSV if path in (None, "", "null") else Path(path)if not csv_path.is_file():raise FileNotFoundError(f"TCIR distance table {csv_path} is missing. Nothing is downloaded.")table = pd.read_csv(csv_path)table.columns = [str(column).strip() for column in table.columns]missing = [column for column in _DISTANCE_COLUMNS if column not in table.columns]if missing:raise ValueError(f"distance_to_land.csv missing {missing}")out = pd.DataFrame({"sample_id": table["sample_id"].astype(str).str.strip(),"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],})if out["sample_id"].duplicated().any():raise ValueError("distance_to_land.csv repeats a sample_id")return outdef attach_distance_to_land(frame: pd.DataFrame, path: str | Path | None = None) -> pd.DataFrame:"""Left-join the audit distances onto ``sample_id``.A sample that is not in the CSV, or a row whose distance is blank,keeps a null distance and ``near_land`` ``unknown``. The null is notreplaced with 0 km or with ``false``."""if "sample_id" not in frame.columns:raise ValueError("TCIR distance join needs sample_id")flags = read_distance_to_land(path)lookup = flags.set_index("sample_id")distance: list[float] = []near: list[str] = []for sample_id in frame["sample_id"].astype(str).tolist():if sample_id not in lookup.index:distance.append(float("nan"))near.append("unknown")continuerow = lookup.loc[sample_id]if isinstance(row, pd.DataFrame):raise ValueError(f"distance_to_land.csv repeats {sample_id}")distance.append(_distance_km(row["distance_to_land_km"]))near.append(_near_land_token(row["near_land"]))out = frame.copy()out["distance_to_land_km"] = np.asarray(distance, dtype=float)out["near_land"] = nearreturn outdef orient(frame: np.ndarray, hemisphere: str, flip_southern: bool = False) -> tuple[np.ndarray, bool]:"""Return (frame, flipped). Only flips when ``flip_southern`` is set and the row is S."""if flip_southern and hemisphere == "S":return np.ascontiguousarray(frame[::-1, :]), Truereturn frame, Falsedef _rows(info: pd.DataFrame, source_file: str) -> pd.DataFrame:unknown = sorted(set(info["data_set"]) - set(LABEL_SOURCES))if unknown:raise ValueError(f"unknown TCIR data_set values {unknown}")stamp = pd.to_datetime(info["time"].astype(str), format="%Y%m%d%H", utc=True)lon = pd.to_numeric(info["lon"]).astype(float)rows = pd.DataFrame({"sample_id": "tcir_" + info["ID"].astype(str) + "_" + info["time"].astype(str),"storm_id": info["ID"].astype(str),"timestamp": stamp.dt.strftime("%Y-%m-%dT%H:%M:%SZ"),"year": stamp.dt.year.astype(int),"wind_speed_kt": pd.to_numeric(info["Vmax"]).astype(float),"basin": info["data_set"].astype(str),"lat": pd.to_numeric(info["lat"]).astype(float),"lon": ((lon + 180.0) % 360.0) - 180.0,"hemisphere": hemisphere_of(info["lat"]),"source": "tcir","source_file": source_file,"h5_index": info["h5_index"].astype(int),"sensor": "GridSat-B1","channel": "IR1","channel_index": IR1_INDEX,"native_height": IMAGE_SIZE,"native_width": IMAGE_SIZE,"orig_size": IMAGE_SIZE,"pixel_units": "kelvin_brightness_temperature","wind_averaging": WIND_AVERAGING,"label_source": info["data_set"].map(lambda b: LABEL_SOURCES[b][0]),"label_source_documented": info["data_set"].map(lambda b: LABEL_SOURCES[b][1]),"center_source": "dataset_precentered","is_synthetic": False,})return rowsclass _PixelStats:def __init__(self) -> None:self.count = 0self.total = 0.0self.total_sq = 0.0self.low = np.infself.high = -np.infdef add(self, frame: np.ndarray) -> None:values = frame[np.isfinite(frame)].astype(np.float64)if values.size:self.count += int(values.size)self.total += float(values.sum())self.total_sq += float(np.square(values).sum())self.low = min(self.low, float(values.min()))self.high = max(self.high, float(values.max()))def as_dict(self) -> dict[str, float | int]:if not self.count:return {"finite_pixels": 0}mean = self.total / self.countreturn {"finite_pixels": self.count,"min": round(self.low, 3),"max": round(self.high, 3),"mean": round(mean, 3),"std": round(float(np.sqrt(max(self.total_sq / self.count - mean**2, 0.0))), 3),}def build_manifest(h5_paths: Sequence[str | Path],manifest_dir: str | Path,export: bool = True,flip_southern: bool = False,max_missing_fraction: float = MAX_MISSING_FRACTION,block: int = BLOCK,distance_csv: str | Path | None = None,) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, object]]:"""Return (manifest, exclusions, pixel stats).With ``export`` each kept IR1 frame is saved as ``ir1/<sample_id>.npy``under ``manifest_dir`` and ``image_path`` points there (relative), so``src.data_loader`` can read it. Without ``export`` ``image_path`` is``<file>#<h5_index>`` for reference only. ``distance_csv`` defaults tothe committed audit table and is joined on ``sample_id``."""manifest_dir = Path(manifest_dir).resolve()image_dir = manifest_dir / "ir1"if export:image_dir.mkdir(parents=True, exist_ok=True)kept_parts, excluded_parts = [], []stats = _PixelStats()frames_with_nan = 0for h5_path in h5_paths:h5_path = Path(h5_path)rows = _rows(read_info(h5_path), h5_path.name)reasons: list[str | None] = [None] * len(rows)nan_fractions = np.zeros(len(rows))flipped = np.zeros(len(rows), dtype=bool)winds = rows["wind_speed_kt"].to_numpy()bad_wind = ~np.isfinite(winds) | (winds < 0)for start, frames in iter_ir1(h5_path, block):for offset, frame in enumerate(frames):index = start + offsetreason, nan_fractions[index] = exclusion_reason(frame, max_missing_fraction)if reason is None and bad_wind[index]:reason = "wind missing or negative"reasons[index] = reasonif reason is not None:continuestats.add(frame)frames_with_nan += int(nan_fractions[index] > 0)if export:out, flipped[index] = orient(frame, rows.at[index, "hemisphere"], flip_southern)np.save(image_dir / f"{rows.at[index, 'sample_id']}.npy", out.astype(np.float32))rows["ir1_nan_fraction"] = np.round(nan_fractions, 5)rows["flipped"] = flippedrows["image_path"] = ("ir1/" + rows["sample_id"] + ".npy"if exportelse rows["source_file"] + "#" + rows["h5_index"].astype(str))drop = pd.Series([reason is not None for reason in reasons], index=rows.index)excluded = rows.loc[drop].assign(reason=[r for r in reasons if r is not None])kept_parts.append(rows.loc[~drop])excluded_parts.append(excluded[EXCLUSION_COLUMNS])manifest = pd.concat(kept_parts, ignore_index=True)excluded = pd.concat(excluded_parts, ignore_index=True)if "split" in manifest.columns or "source_split" in manifest.columns:raise AssertionError("TCIR manifest must not carry split or source_split")manifest = attach_distance_to_land(manifest, distance_csv)manifest = require_valid(manifest)pixel = stats.as_dict()pixel["kept_frames_with_some_nan"] = frames_with_nanreturn manifest, excluded, pixeldef storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:"""Run the project splitter on the manifest and assert no storm leaks."""from src.splits import assert_no_group_leakage, assign_stormsif "split" in frame.columns:raise ValueError("manifest must not carry split")assigned = assign_storms(frame, strategy, seed=seed)names = ("train", "val", "test")parts = [assigned.loc[assigned["split"] == name] for name in names]assert_no_group_leakage(*parts)return {"strategy": strategy,"rows": {name: int(len(part)) for name, part in zip(names, parts)},"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(names, parts)},"leakage": "none",}def _reason_kind(reason: str) -> str:"""Strip per-frame numbers so reasons can be counted."""if reason.startswith("ir1 NaN fraction"):return f"ir1 NaN fraction > {MAX_MISSING_FRACTION:.2f}"return reason.split(" (")[0]def summarize(frame: pd.DataFrame, excluded: pd.DataFrame, pixel: dict[str, object]) -> dict[str, object]:def counts(column: str) -> dict[str, dict[str, int]]:return {str(key): {"rows": int(len(group)), "storms": int(group["storm_id"].nunique())}for key, group in frame.groupby(column)}storm_hemispheres = frame.groupby("storm_id")["hemisphere"].nunique()return {"rows": int(len(frame)),"unique_storms": int(frame["storm_id"].nunique()),"by_basin": counts("basin"),"by_hemisphere": counts("hemisphere"),"by_source_file": counts("source_file"),"storms_crossing_equator": sorted(storm_hemispheres[storm_hemispheres > 1].index.tolist()),"basin_vs_hemisphere": {f"{basin}/{hemi}": int(n)for (basin, hemi), n in frame.groupby(["basin", "hemisphere"]).size().items()},"years": [int(frame["year"].min()), int(frame["year"].max())],"wind_kt_min": float(frame["wind_speed_kt"].min()),"wind_kt_max": float(frame["wind_speed_kt"].max()),"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),"pixel_stats_ir1": pixel,"flipped_rows": int(frame["flipped"].sum()),"label_source_counts": frame["label_source"].value_counts().to_dict(),"label_source_undocumented_rows": int((~frame["label_source_documented"].astype(bool)).sum()),"wind_averaging": sorted(frame["wind_averaging"].unique()),"native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}),"has_split_column": "split" in frame.columns,"has_source_split_column": "source_split" in frame.columns,"is_synthetic": bool(frame["is_synthetic"].any()),"excluded": {"count": int(len(excluded)),"by_reason": excluded["reason"].map(_reason_kind).value_counts().to_dict(),"by_basin": excluded["basin"].value_counts().to_dict() if len(excluded) else {},},}def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path) -> list[dict[str, object]]:"""One N and one S frame side by side, as stored (no flip unless opted in)."""import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltpicks = []for hemi in ("N", "S"):subset = frame[frame["hemisphere"] == hemi]if len(subset):picks.append(subset.loc[subset["wind_speed_kt"].idxmax()])fig, axes = plt.subplots(1, len(picks), figsize=(4.2 * len(picks), 4.4), squeeze=False)info = []for ax, row in zip(axes[0], picks):image = np.load(Path(manifest_dir) / row["image_path"])shown = ax.imshow(image, cmap="gray_r")fig.colorbar(shown, ax=ax, fraction=0.046, label="IR1 pixel value")ax.set_title(f"{row['storm_id']} {row['timestamp'][:13]}Z {row['basin']}/{row['hemisphere']}\n"f"{row['wind_speed_kt']:.0f} kt (1min) | flipped={bool(row['flipped'])} | TCIR real",fontsize=8,)ax.axis("off")info.append({"sample_id": row["sample_id"],"hemisphere": row["hemisphere"],"wind_speed_kt": float(row["wind_speed_kt"]),"shape": list(image.shape),"flipped": bool(row["flipped"]),})Path(out).parent.mkdir(parents=True, exist_ok=True)fig.savefig(out, dpi=100, bbox_inches="tight")plt.close(fig)return infodef main() -> None:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--h5", nargs="+", required=True, help="TCIR .h5 files")parser.add_argument("--out", default="data/tcir/manifest.csv")parser.add_argument("--summary", default="reports/tcir_summary.json")parser.add_argument("--sample-png", default="reports/tcir_sample.png")parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/tcir_exclusions.csv")parser.add_argument("--no-export", action="store_true", help="do not write ir1/*.npy")parser.add_argument("--flip-southern",action="store_true",help="opt in: mirror Southern Hemisphere frames north-south on export (default: no flip)",)args = parser.parse_args()out = Path(args.out)out.parent.mkdir(parents=True, exist_ok=True)frame, excluded, pixel = build_manifest(args.h5, out.parent, export=not args.no_export, flip_southern=args.flip_southern)exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "tcir_exclusions.csv"excluded.to_csv(exclusions_path, index=False)frame.drop(columns=["imd5_class"], errors="ignore").to_csv(out, index=False)summary = summarize(frame, excluded, pixel)summary["exclusions_file"] = str(exclusions_path)summary["storm_split_check"] = storm_split_check(frame)summary["flip_southern"] = bool(args.flip_southern)summary["manifest"] = str(out)if not args.no_export:summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)Path(args.summary).parent.mkdir(parents=True, exist_ok=True)Path(args.summary).write_text(json.dumps(summary, indent=2, default=str))print(json.dumps(summary, indent=2, default=str))if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591"""Build a Cloudie manifest from TCIR HDF5 files, IR1 channel only.TCIR (Chen, Chen and Lin, KDD 2018, https://doi.org/10.1145/3219819.3219926;data https://github.com/BoyoChen/TCIR) ships two HDF5 files:``TCIR-ATLN_EPAC_WPAC.h5`` and ``TCIR-CPAC_IO_SH.h5``. Each has- ``matrix``: N x 201 x 201 x 4 float32. The README lists the channels inthe order IR1, WV, VIS, PMW, so IR1 is index 0 (``IR1_INDEX``). The filehas no channel attributes. On 512 random real frames per file, channel 0has a median near 275 and is warmer than channel 1 (WV, median near 238)in over 98% of frames, channel 2 is a 0 to 2.2 reflectance with many NaNs(VIS at night) and channel 3 is a rain rate. That fits the README order.IR1 comes from GridSat-B1, which stores brightness temperature in kelvin.Reports still call these "pixel stats".- ``info``: a pandas 0.15 "fixed" frame (data_set, ID, time, lon, lat, Vmax,R35_4qAVG, MSLP). Current pandas cannot read it, so ``read_info`` decodesit with h5py and a restricted unpickler that only rebuilds numpy arrays.Only channel 0 is read (an h5py hyperslab, ``matrix[a:b, :, :, 0]``). Frameskeep their native 201 x 201 grid, centred on the best-track position, about7/100 degree per pixel.Labels. TCIR documents JTWC best tracks for WPAC and HURDAT2 for ATLN andEPAC. Both are 1-minute sustained winds, so ``wind_averaging`` is ``1min``.TCIR does not document the label source for CPAC, IO or SH. Those rows carry``label_source_documented = False`` and an ``_inferred`` label source. Across-check against IBTrACS v04r01 (matched on time and a 0.6 degreeposition window) found TCIR ``Vmax`` equal to ``USA_WIND`` on 99.8% of IOand SH rows (JTWC, 1-minute) and on 92% of CPAC rows (99.5% within 5 kt;HURDAT2/CPHC, 1-minute), while the 10-minute (BoM, RSMC La Reunion, Nadi)and 3-minute (New Delhi) agency winds match 14-21% of the time. So``wind_averaging`` is ``1min`` on every row.Southern Hemisphere storms rotate clockwise. Nothing here flips an image bydefault. ``hemisphere`` (N or S, from the row's latitude) is recorded perrow. ``flip_southern=True`` is an explicit opt-in that mirrors S framesnorth-south when exporting and sets ``flipped = True`` on those rows.Frames whose IR1 is all NaN, has a NaN fraction above``max_missing_fraction`` (0.30, the preprocessing gate), or has any finitevalue outside ``IR1_VALID_RANGE`` (150 to 340 K; the real files hold a fewframes with pixels down to 76 K or up to 348 K) are dropped and listed with a reason in anexclusions CSV. Kept frames may still hold a few NaNs; ``ir1_nan_fraction``records how many, and ``src.preprocessing`` fills them later.TCIR has no official split inside these files, so the manifest has no``source_split`` and never has ``split``. ``src.splits.assign_storms`` writes``split`` by storm. MSLP and R35 are label-derived, so they stay out of themanifest.Distance to land is joined from ``tcir/audit/distance_to_land.csv`` on``sample_id`` (``distance_to_land_km`` and ``near_land``). The trainingpath then applies ``labels.near_land_policy`` with ``labels.open_water_km``.A sample the CSV does not list, and a listed row whose distance is blank,stay unknown. The distance is not filled with 0. NASA is not in this file;that loader has no join key (``nasa_tc/audit/README.md``)."""from __future__ import annotationsimport argparseimport ioimport jsonimport picklefrom collections.abc import Iterator, Sequencefrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.schema import require_validCHANNELS = ("IR1", "WV", "VIS", "PMW") # order in the TCIR READMEIR1_INDEX = 0IMAGE_SIZE = 201WIND_AVERAGING = "1min"IR1_VALID_RANGE = (150.0, 340.0) # kelvin; colder or warmer than any plausible IR window valueMAX_MISSING_FRACTION = 0.30 # same gate as src.preprocessingBLOCK = 256_DISTANCE_COLUMNS = ("sample_id", "distance_to_land_km", "near_land")DEFAULT_DISTANCE_CSV = Path(__file__).resolve().parents[1] / "tcir" / "audit" / "distance_to_land.csv"# data_set -> (label source, documented by TCIR)LABEL_SOURCES = {"WPAC": ("jtwc_best_track", True),"ATLN": ("hurdat2", True),"EPAC": ("hurdat2", True),# Not documented by TCIR; inferred from an IBTrACS v04r01 match (PR notes)."CPAC": ("hurdat2_inferred", False),"IO": ("jtwc_best_track_inferred", False),"SH": ("jtwc_best_track_inferred", False),}EXCLUSION_COLUMNS = ["sample_id","storm_id","basin","source_file","h5_index","ir1_nan_fraction","reason",]_ALLOWED_GLOBALS = {("numpy.core.multiarray", "_reconstruct"),("numpy._core.multiarray", "_reconstruct"),("numpy.core.multiarray", "scalar"),("numpy._core.multiarray", "scalar"),("numpy", "ndarray"),("numpy", "dtype"),("_codecs", "encode"), # Python 3 protocol-2 pickles of byte strings}class _NumpyOnlyUnpickler(pickle.Unpickler):def find_class(self, module: str, name: str): # noqa: ANN201if (module, name) not in _ALLOWED_GLOBALS:raise pickle.UnpicklingError(f"refusing to load {module}.{name} from TCIR info")target = "numpy._core.multiarray" if module.endswith(".multiarray") else moduleimport importlibreturn getattr(importlib.import_module(target), name)def _text(value: object) -> str:return value.decode() if isinstance(value, bytes) else str(value)def _block_values(dataset) -> np.ndarray: # noqa: ANN001if dataset.dtype.kind in "fiub":return dataset[()]raw = dataset[0]data = bytes(np.asarray(raw, dtype=np.uint8)) if not isinstance(raw, bytes) else rawreturn _NumpyOnlyUnpickler(io.BytesIO(data), encoding="latin1").load()def read_info(path: str | Path) -> pd.DataFrame:"""Decode the ``info`` frame with h5py. Adds ``h5_index`` (row in ``matrix``)."""import h5pywith h5py.File(path, "r") as handle:group = handle["info"]order = [_text(name) for name in group["axis0"][()]]n_rows = int(group["axis1"].shape[0])columns: dict[str, np.ndarray] = {}for block in range(int(group.attrs["nblocks"])):items = [_text(name) for name in group[f"block{block}_items"][()]]values = np.asarray(_block_values(group[f"block{block}_values"]))if values.shape != (n_rows, len(items)):raise ValueError(f"{path}: info block{block} has shape {values.shape}")for position, item in enumerate(items):columns[item] = values[:, position]n_matrix = int(handle["matrix"].shape[0])if n_matrix != n_rows:raise ValueError(f"{path}: info has {n_rows} rows but matrix has {n_matrix}")frame = pd.DataFrame({name: columns[name] for name in order})for name in frame.columns:if frame[name].dtype == object:frame[name] = frame[name].map(_text)frame["h5_index"] = np.arange(n_rows)return framedef iter_ir1(path: str | Path, block: int = BLOCK) -> Iterator[tuple[int, np.ndarray]]:"""Yield ``(start, frames)`` with frames shaped (k, 201, 201), IR1 only."""import h5pywith h5py.File(path, "r") as handle:matrix = handle["matrix"]if matrix.ndim != 4 or matrix.shape[1:] != (IMAGE_SIZE, IMAGE_SIZE, len(CHANNELS)):raise ValueError(f"{path}: matrix shape {matrix.shape}, expected N x 201 x 201 x 4")for start in range(0, matrix.shape[0], block):stop = min(start + block, matrix.shape[0])yield start, np.asarray(matrix[start:stop, :, :, IR1_INDEX], dtype=np.float32)def exclusion_reason(frame: np.ndarray,max_missing_fraction: float = MAX_MISSING_FRACTION,valid_range: tuple[float, float] = IR1_VALID_RANGE,) -> tuple[str | None, float]:"""Return (reason or None, NaN fraction) for one IR1 frame."""finite = np.isfinite(frame)nan_fraction = float(1.0 - finite.mean())if not finite.any():return "ir1 all NaN", nan_fractionif nan_fraction > max_missing_fraction:return f"ir1 NaN fraction {nan_fraction:.3f} > {max_missing_fraction:.2f}", nan_fractionvalues = frame[finite]low, high = valid_rangeif float(values.min()) < low or float(values.max()) > high:return (f"ir1 value outside [{low:g}, {high:g}] K "f"(min {float(values.min()):.2f}, max {float(values.max()):.2f})",nan_fraction,)return None, nan_fractiondef hemisphere_of(lat: pd.Series) -> pd.Series:return pd.Series(np.where(pd.to_numeric(lat) < 0, "S", "N"), index=lat.index)def _blank_distance(value: object) -> bool:if value is None:return Truetry:if pd.isna(value):return Trueexcept (TypeError, ValueError):return Falsereturn str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}def _near_land_token(value: object) -> str:"""``true``, ``false``, or ``unknown``. A blank cell stays unknown."""if isinstance(value, (bool, np.bool_)):return "true" if bool(value) else "false"if _blank_distance(value):return "unknown"text = str(value).strip().lower()if text in {"1", "true", "yes", "y", "t"}:return "true"if text in {"0", "false", "no", "n", "f"}:return "false"if text in {"unknown", "na", "n/a"}:return "unknown"raise ValueError(f"near_land value {value!r} is not true, false, or unknown")def _distance_km(value: object) -> float:if _blank_distance(value):return float("nan")try:number = float(value)except (TypeError, ValueError) as exc:raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from excif not np.isfinite(number):return float("nan")return numberdef read_distance_to_land(path: str | Path | None = None) -> pd.DataFrame:"""``sample_id``, ``distance_to_land_km``, and ``near_land`` from the audit CSV.``path`` defaults to ``tcir/audit/distance_to_land.csv``. Blank distancesstay NaN. ``near_land`` stays ``unknown`` when the audit says so."""csv_path = DEFAULT_DISTANCE_CSV if path in (None, "", "null") else Path(path)if not csv_path.is_file():raise FileNotFoundError(f"TCIR distance table {csv_path} is missing. Nothing is downloaded.")table = pd.read_csv(csv_path)table.columns = [str(column).strip() for column in table.columns]missing = [column for column in _DISTANCE_COLUMNS if column not in table.columns]if missing:raise ValueError(f"distance_to_land.csv missing {missing}")out = pd.DataFrame({"sample_id": table["sample_id"].astype(str).str.strip(),"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],})if out["sample_id"].duplicated().any():raise ValueError("distance_to_land.csv repeats a sample_id")return outdef attach_distance_to_land(frame: pd.DataFrame, path: str | Path | None = None) -> pd.DataFrame:"""Left-join the audit distances onto ``sample_id``.A sample that is not in the CSV, or a row whose distance is blank,keeps a null distance and ``near_land`` ``unknown``. The null is notreplaced with 0 km or with ``false``."""if "sample_id" not in frame.columns:raise ValueError("TCIR distance join needs sample_id")flags = read_distance_to_land(path)lookup = flags.set_index("sample_id")distance: list[float] = []near: list[str] = []for sample_id in frame["sample_id"].astype(str).tolist():if sample_id not in lookup.index:distance.append(float("nan"))near.append("unknown")continuerow = lookup.loc[sample_id]if isinstance(row, pd.DataFrame):raise ValueError(f"distance_to_land.csv repeats {sample_id}")distance.append(_distance_km(row["distance_to_land_km"]))near.append(_near_land_token(row["near_land"]))out = frame.copy()out["distance_to_land_km"] = np.asarray(distance, dtype=float)out["near_land"] = nearreturn outdef orient(frame: np.ndarray, hemisphere: str, flip_southern: bool = False) -> tuple[np.ndarray, bool]:"""Return (frame, flipped). Only flips when ``flip_southern`` is set and the row is S."""if flip_southern and hemisphere == "S":return np.ascontiguousarray(frame[::-1, :]), Truereturn frame, Falsedef _rows(info: pd.DataFrame, source_file: str) -> pd.DataFrame:unknown = sorted(set(info["data_set"]) - set(LABEL_SOURCES))if unknown:raise ValueError(f"unknown TCIR data_set values {unknown}")stamp = pd.to_datetime(info["time"].astype(str), format="%Y%m%d%H", utc=True)lon = pd.to_numeric(info["lon"]).astype(float)rows = pd.DataFrame({"sample_id": "tcir_" + info["ID"].astype(str) + "_" + info["time"].astype(str),"storm_id": info["ID"].astype(str),"timestamp": stamp.dt.strftime("%Y-%m-%dT%H:%M:%SZ"),"year": stamp.dt.year.astype(int),"wind_speed_kt": pd.to_numeric(info["Vmax"]).astype(float),"basin": info["data_set"].astype(str),"lat": pd.to_numeric(info["lat"]).astype(float),"lon": ((lon + 180.0) % 360.0) - 180.0,"hemisphere": hemisphere_of(info["lat"]),"source": "tcir","source_file": source_file,"h5_index": info["h5_index"].astype(int),"sensor": "GridSat-B1","channel": "IR1","channel_index": IR1_INDEX,"native_height": IMAGE_SIZE,"native_width": IMAGE_SIZE,"orig_size": IMAGE_SIZE,"pixel_units": "kelvin_brightness_temperature","wind_averaging": WIND_AVERAGING,"label_source": info["data_set"].map(lambda b: LABEL_SOURCES[b][0]),"label_source_documented": info["data_set"].map(lambda b: LABEL_SOURCES[b][1]),"center_source": "dataset_precentered","is_synthetic": False,})return rowsclass _PixelStats:def __init__(self) -> None:self.count = 0self.total = 0.0self.total_sq = 0.0self.low = np.infself.high = -np.infdef add(self, frame: np.ndarray) -> None:values = frame[np.isfinite(frame)].astype(np.float64)if values.size:self.count += int(values.size)self.total += float(values.sum())self.total_sq += float(np.square(values).sum())self.low = min(self.low, float(values.min()))self.high = max(self.high, float(values.max()))def as_dict(self) -> dict[str, float | int]:if not self.count:return {"finite_pixels": 0}mean = self.total / self.countreturn {"finite_pixels": self.count,"min": round(self.low, 3),"max": round(self.high, 3),"mean": round(mean, 3),"std": round(float(np.sqrt(max(self.total_sq / self.count - mean**2, 0.0))), 3),}def build_manifest(h5_paths: Sequence[str | Path],manifest_dir: str | Path,export: bool = True,flip_southern: bool = False,max_missing_fraction: float = MAX_MISSING_FRACTION,block: int = BLOCK,distance_csv: str | Path | None = None,) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, object]]:"""Return (manifest, exclusions, pixel stats).With ``export`` each kept IR1 frame is saved as ``ir1/<sample_id>.npy``under ``manifest_dir`` and ``image_path`` points there (relative), so``src.data_loader`` can read it. Without ``export`` ``image_path`` is``<file>#<h5_index>`` for reference only. ``distance_csv`` defaults tothe committed audit table and is joined on ``sample_id``."""manifest_dir = Path(manifest_dir).resolve()image_dir = manifest_dir / "ir1"if export:image_dir.mkdir(parents=True, exist_ok=True)kept_parts, excluded_parts = [], []stats = _PixelStats()frames_with_nan = 0for h5_path in h5_paths:h5_path = Path(h5_path)rows = _rows(read_info(h5_path), h5_path.name)reasons: list[str | None] = [None] * len(rows)nan_fractions = np.zeros(len(rows))flipped = np.zeros(len(rows), dtype=bool)winds = rows["wind_speed_kt"].to_numpy()bad_wind = ~np.isfinite(winds) | (winds < 0)for start, frames in iter_ir1(h5_path, block):for offset, frame in enumerate(frames):index = start + offsetreason, nan_fractions[index] = exclusion_reason(frame, max_missing_fraction)if reason is None and bad_wind[index]:reason = "wind missing or negative"reasons[index] = reasonif reason is not None:continuestats.add(frame)frames_with_nan += int(nan_fractions[index] > 0)if export:out, flipped[index] = orient(frame, rows.at[index, "hemisphere"], flip_southern)np.save(image_dir / f"{rows.at[index, 'sample_id']}.npy", out.astype(np.float32))rows["ir1_nan_fraction"] = np.round(nan_fractions, 5)rows["flipped"] = flippedrows["image_path"] = ("ir1/" + rows["sample_id"] + ".npy"if exportelse rows["source_file"] + "#" + rows["h5_index"].astype(str))drop = pd.Series([reason is not None for reason in reasons], index=rows.index)excluded = rows.loc[drop].assign(reason=[r for r in reasons if r is not None])kept_parts.append(rows.loc[~drop])excluded_parts.append(excluded[EXCLUSION_COLUMNS])manifest = pd.concat(kept_parts, ignore_index=True)excluded = pd.concat(excluded_parts, ignore_index=True)if "split" in manifest.columns or "source_split" in manifest.columns:raise AssertionError("TCIR manifest must not carry split or source_split")manifest = attach_distance_to_land(manifest, distance_csv)manifest = require_valid(manifest)pixel = stats.as_dict()pixel["kept_frames_with_some_nan"] = frames_with_nanreturn manifest, excluded, pixeldef storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:"""Run the project splitter on the manifest and assert no storm leaks."""from src.splits import assert_no_group_leakage, assign_stormsif "split" in frame.columns:raise ValueError("manifest must not carry split")assigned = assign_storms(frame, strategy, seed=seed)names = ("train", "val", "test")parts = [assigned.loc[assigned["split"] == name] for name in names]assert_no_group_leakage(*parts)return {"strategy": strategy,"rows": {name: int(len(part)) for name, part in zip(names, parts)},"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(names, parts)},"leakage": "none",}def _reason_kind(reason: str) -> str:"""Strip per-frame numbers so reasons can be counted."""if reason.startswith("ir1 NaN fraction"):return f"ir1 NaN fraction > {MAX_MISSING_FRACTION:.2f}"return reason.split(" (")[0]def summarize(frame: pd.DataFrame, excluded: pd.DataFrame, pixel: dict[str, object]) -> dict[str, object]:def counts(column: str) -> dict[str, dict[str, int]]:return {str(key): {"rows": int(len(group)), "storms": int(group["storm_id"].nunique())}for key, group in frame.groupby(column)}storm_hemispheres = frame.groupby("storm_id")["hemisphere"].nunique()return {"rows": int(len(frame)),"unique_storms": int(frame["storm_id"].nunique()),"by_basin": counts("basin"),"by_hemisphere": counts("hemisphere"),"by_source_file": counts("source_file"),"storms_crossing_equator": sorted(storm_hemispheres[storm_hemispheres > 1].index.tolist()),"basin_vs_hemisphere": {f"{basin}/{hemi}": int(n)for (basin, hemi), n in frame.groupby(["basin", "hemisphere"]).size().items()},"years": [int(frame["year"].min()), int(frame["year"].max())],"wind_kt_min": float(frame["wind_speed_kt"].min()),"wind_kt_max": float(frame["wind_speed_kt"].max()),"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),"pixel_stats_ir1": pixel,"flipped_rows": int(frame["flipped"].sum()),"label_source_counts": frame["label_source"].value_counts().to_dict(),"label_source_undocumented_rows": int((~frame["label_source_documented"].astype(bool)).sum()),"wind_averaging": sorted(frame["wind_averaging"].unique()),"native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}),"has_split_column": "split" in frame.columns,"has_source_split_column": "source_split" in frame.columns,"is_synthetic": bool(frame["is_synthetic"].any()),"excluded": {"count": int(len(excluded)),"by_reason": excluded["reason"].map(_reason_kind).value_counts().to_dict(),"by_basin": excluded["basin"].value_counts().to_dict() if len(excluded) else {},},}def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path) -> list[dict[str, object]]:"""One N and one S frame side by side, as stored (no flip unless opted in)."""import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltpicks = []for hemi in ("N", "S"):subset = frame[frame["hemisphere"] == hemi]if len(subset):picks.append(subset.loc[subset["wind_speed_kt"].idxmax()])fig, axes = plt.subplots(1, len(picks), figsize=(4.2 * len(picks), 4.4), squeeze=False)info = []for ax, row in zip(axes[0], picks):image = np.load(Path(manifest_dir) / row["image_path"])shown = ax.imshow(image, cmap="gray_r")fig.colorbar(shown, ax=ax, fraction=0.046, label="IR1 pixel value")ax.set_title(f"{row['storm_id']} {row['timestamp'][:13]}Z {row['basin']}/{row['hemisphere']}\n"f"{row['wind_speed_kt']:.0f} kt (1min) | flipped={bool(row['flipped'])} | TCIR real",fontsize=8,)ax.axis("off")info.append({"sample_id": row["sample_id"],"hemisphere": row["hemisphere"],"wind_speed_kt": float(row["wind_speed_kt"]),"shape": list(image.shape),"flipped": bool(row["flipped"]),})Path(out).parent.mkdir(parents=True, exist_ok=True)fig.savefig(out, dpi=100, bbox_inches="tight")plt.close(fig)return infodef main() -> None:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument("--h5", nargs="+", required=True, help="TCIR .h5 files")parser.add_argument("--out", default="data/tcir/manifest.csv")parser.add_argument("--summary", default="reports/tcir_summary.json")parser.add_argument("--sample-png", default="reports/tcir_sample.png")parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/tcir_exclusions.csv")parser.add_argument("--no-export", action="store_true", help="do not write ir1/*.npy")parser.add_argument("--flip-southern",action="store_true",help="opt in: mirror Southern Hemisphere frames north-south on export (default: no flip)",)args = parser.parse_args()out = Path(args.out)out.parent.mkdir(parents=True, exist_ok=True)frame, excluded, pixel = build_manifest(args.h5, out.parent, export=not args.no_export, flip_southern=args.flip_southern)exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "tcir_exclusions.csv"excluded.to_csv(exclusions_path, index=False)frame.drop(columns=["imd5_class"], errors="ignore").to_csv(out, index=False)summary = summarize(frame, excluded, pixel)summary["exclusions_file"] = str(exclusions_path)summary["storm_split_check"] = storm_split_check(frame)summary["flip_southern"] = bool(args.flip_southern)summary["manifest"] = str(out)if not args.no_export:summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)Path(args.summary).parent.mkdir(parents=True, exist_ok=True)Path(args.summary).write_text(json.dumps(summary, indent=2, default=str))print(json.dumps(summary, indent=2, default=str))if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""CLI that runs a 6-point data-leakage audit on the configured splits.The six checks are:1. storm_wise splits keep storms whole and disjoint.2. chronological splits keep storms whole and disjoint.3. holdout_basin splits keep storms whole and disjoint.4. Random / frame / shuffle strategies raise ``LeakageError``.5. No forbidden feature name leaks into the model matrix.6. Cross-split previous-frame links are nulled.Usage::python -m src.verify_splits --config config/config_smoke.yamlThe exit code is 0 when all six checks pass. This module does not importtorch and does not download imagery."""from __future__ import annotationsimport argparseimport sysfrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.config import load_configfrom src.make_smoke_data import write_smokefrom src.schema import require_validfrom src.splits import (LeakageError,add_previous_frame_id,assert_no_forbidden_inputs,assign_storms,null_cross_split_links,storm_ids_by_split,)def _build_smoke_frame(config: dict) -> pd.DataFrame:"""Return a validated manifest from the smoke config's data path."""manifest_path = Path(config["paths"]["manifest"])if not manifest_path.exists():# Generate smoke data on the fly so the audit is self-contained.out_dir = manifest_path.parentwrite_smoke(out_dir, seed=config.get("project", {}).get("seed", 7))frame = pd.read_csv(manifest_path)return require_valid(frame)def _assert_disjoint(assigned: pd.DataFrame) -> dict[str, frozenset[str]]:"""Verify that storm-id sets across splits are disjoint."""groups = storm_ids_by_split(assigned)assert groups["train"], "train is empty"assert groups["val"], "val is empty"assert groups["test"], "test is empty"assert groups["train"].isdisjoint(groups["val"]), "train ∩ val is non-empty"assert groups["train"].isdisjoint(groups["test"]), "train ∩ test is non-empty"assert groups["val"].isdisjoint(groups["test"]), "val ∩ test is non-empty"# Every storm is in exactly one split.counts = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()assert int(counts.max()) == 1, "a storm appears in more than one split"return groupsdef _run_strategy(frame: pd.DataFrame, strategy: str, config: dict) -> None:"""Check that a strategy assigns splits correctly."""split_cfg = dict(config.get("split", {}))kwargs: dict = {"test_fraction": float(split_cfg.get("test_fraction", 0.2)),"val_fraction": float(split_cfg.get("val_fraction", 0.2)),"seed": int(split_cfg.get("seed", 42)),}if strategy == "chronological":holdout_years = [int(y) for y in (split_cfg.get("holdout_years") or [])]if not holdout_years:# Use at least one year for the audit.if "year" in frame.columns:years = sorted(frame["year"].dropna().unique())holdout_years = [int(years[-1])] if years else [2021]else:holdout_years = [2021]kwargs["holdout_years"] = holdout_yearsif strategy == "holdout_basin":holdout_basin = split_cfg.get("holdout_basin") or Noneif not holdout_basin:if "basin" in frame.columns:basins = sorted(frame["basin"].dropna().unique())holdout_basin = basins[0] if basins else "NIO"else:holdout_basin = "NIO"kwargs["holdout_basin"] = holdout_basinassigned = assign_storms(frame, strategy, **kwargs)# Deterministic: same call same result.again = assign_storms(frame, strategy, **kwargs)assert assigned["split"].tolist() == again["split"].tolist(), (f"{strategy}: non-deterministic assignment")_assert_disjoint(assigned)def audit(config: dict) -> list[str]:"""Run the 6-point leakage audit. Returns a list of failure messages."""frame = _build_smoke_frame(config)failures: list[str] = []# --- Check 1: storm_wise ---try:_run_strategy(frame, "storm_wise", config)print(" [PASS] 1. storm_wise splits are disjoint")except Exception as exc:failures.append(f"1. storm_wise: {exc}")print(f" [FAIL] 1. storm_wise: {exc}")# --- Check 2: chronological ---try:_run_strategy(frame, "chronological", config)print(" [PASS] 2. chronological splits are disjoint")except Exception as exc:failures.append(f"2. chronological: {exc}")print(f" [FAIL] 2. chronological: {exc}")# --- Check 3: holdout_basin ---try:_run_strategy(frame, "holdout_basin", config)print(" [PASS] 3. holdout_basin splits are disjoint")except Exception as exc:failures.append(f"3. holdout_basin: {exc}")print(f" [FAIL] 3. holdout_basin: {exc}")# --- Check 4: random splits raise LeakageError ---random_ok = Truefor name in ("random", "frame", "shuffle", "random_frame"):try:assign_storms(frame, name)failures.append(f"4. {name} did not raise LeakageError")random_ok = Falseexcept LeakageError:passexcept Exception as exc:failures.append(f"4. {name} raised unexpected {type(exc).__name__}: {exc}")random_ok = Falseif random_ok:print(" [PASS] 4. Random splits raise LeakageError")else:print(" [FAIL] 4. Random splits did not all raise LeakageError")# --- Check 5: no forbidden features in model matrix ---try:from src.features import FeatureSpecfeature_names = list(FeatureSpec().feature_names())assert_no_forbidden_inputs(feature_names, "model features")print(" [PASS] 5. No forbidden features in default feature set")except LeakageError as exc:failures.append(f"5. forbidden features: {exc}")print(f" [FAIL] 5. {exc}")except Exception as exc:failures.append(f"5. feature check error: {exc}")print(f" [FAIL] 5. {exc}")# --- Check 6: cross-split links are nulled ---try:split_cfg = dict(config.get("split", {}))assigned = assign_storms(frame,"storm_wise",test_fraction=float(split_cfg.get("test_fraction", 0.2)),val_fraction=float(split_cfg.get("val_fraction", 0.2)),seed=int(split_cfg.get("seed", 42)),)linked = add_previous_frame_id(assigned)linked["split"] = assigned.loc[linked.index, "split"]# Artificially set a cross-split link.train_ids = linked.loc[linked["split"] == "train", "sample_id"].tolist()test_ids = linked.loc[linked["split"] == "test", "sample_id"].tolist()if train_ids and test_ids:dirty = linked.copy()dirty.loc[dirty["sample_id"] == train_ids[0], "prev_sample_id"] = test_ids[0]cleaned, dropped = null_cross_split_links(dirty)assert dropped >= 1, "cross-split link was not removed"assert pd.isna(cleaned.loc[cleaned["sample_id"] == train_ids[0], "prev_sample_id"]).all(), "cross-split link survived cleaning"print(" [PASS] 6. Cross-split previous-frame links are nulled")except Exception as exc:failures.append(f"6. cross-split links: {exc}")print(f" [FAIL] 6. {exc}")return failuresdef main() -> None:parser = argparse.ArgumentParser(description="Run a 6-point data-leakage audit on the split strategy.")parser.add_argument("--config",type=str,default="config/config_smoke.yaml",help="Path to YAML config file.",)args = parser.parse_args()config = load_config(args.config)print(f"Running 6-point leakage audit with {args.config}")failures = audit(config)if failures:print(f"\n{len(failures)} check(s) failed:")for msg in failures:print(f" - {msg}")sys.exit(1)else:print("\nAll 6 checks passed.")if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""CLI that runs a 6-point data-leakage audit on the configured splits.The six checks are:1. storm_wise splits keep storms whole and disjoint.2. chronological splits keep storms whole and disjoint.3. holdout_basin splits keep storms whole and disjoint.4. Random / frame / shuffle strategies raise ``LeakageError``.5. No forbidden feature name leaks into the model matrix.6. Cross-split previous-frame links are nulled.Usage::python -m src.verify_splits --config config/config_smoke.yamlThe exit code is 0 when all six checks pass. This module does not importtorch and does not download imagery."""from __future__ import annotationsimport argparseimport sysfrom pathlib import Pathimport numpy as npimport pandas as pdfrom src.config import load_configfrom src.make_smoke_data import write_smokefrom src.schema import require_validfrom src.splits import (LeakageError,add_previous_frame_id,assert_no_forbidden_inputs,assign_storms,null_cross_split_links,storm_ids_by_split,)def _build_smoke_frame(config: dict) -> pd.DataFrame:"""Return a validated manifest from the smoke config's data path."""manifest_path = Path(config["paths"]["manifest"])if not manifest_path.exists():# Generate smoke data on the fly so the audit is self-contained.out_dir = manifest_path.parentwrite_smoke(out_dir, seed=config.get("project", {}).get("seed", 7))frame = pd.read_csv(manifest_path)return require_valid(frame)def _assert_disjoint(assigned: pd.DataFrame) -> dict[str, frozenset[str]]:"""Verify that storm-id sets across splits are disjoint."""groups = storm_ids_by_split(assigned)assert groups["train"], "train is empty"assert groups["val"], "val is empty"assert groups["test"], "test is empty"assert groups["train"].isdisjoint(groups["val"]), "train ∩ val is non-empty"assert groups["train"].isdisjoint(groups["test"]), "train ∩ test is non-empty"assert groups["val"].isdisjoint(groups["test"]), "val ∩ test is non-empty"# Every storm is in exactly one split.counts = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()assert int(counts.max()) == 1, "a storm appears in more than one split"return groupsdef _run_strategy(frame: pd.DataFrame, strategy: str, config: dict) -> None:"""Check that a strategy assigns splits correctly."""split_cfg = dict(config.get("split", {}))kwargs: dict = {"test_fraction": float(split_cfg.get("test_fraction", 0.2)),"val_fraction": float(split_cfg.get("val_fraction", 0.2)),"seed": int(split_cfg.get("seed", 42)),}if strategy == "chronological":holdout_years = [int(y) for y in (split_cfg.get("holdout_years") or [])]if not holdout_years:# Use at least one year for the audit.if "year" in frame.columns:years = sorted(frame["year"].dropna().unique())holdout_years = [int(years[-1])] if years else [2021]else:holdout_years = [2021]kwargs["holdout_years"] = holdout_yearsif strategy == "holdout_basin":holdout_basin = split_cfg.get("holdout_basin") or Noneif not holdout_basin:if "basin" in frame.columns:basins = sorted(frame["basin"].dropna().unique())holdout_basin = basins[0] if basins else "NIO"else:holdout_basin = "NIO"kwargs["holdout_basin"] = holdout_basinassigned = assign_storms(frame, strategy, **kwargs)# Deterministic: same call same result.again = assign_storms(frame, strategy, **kwargs)assert assigned["split"].tolist() == again["split"].tolist(), (f"{strategy}: non-deterministic assignment")_assert_disjoint(assigned)def audit(config: dict) -> list[str]:"""Run the 6-point leakage audit. Returns a list of failure messages."""frame = _build_smoke_frame(config)failures: list[str] = []# --- Check 1: storm_wise ---try:_run_strategy(frame, "storm_wise", config)print(" [PASS] 1. storm_wise splits are disjoint")except Exception as exc:failures.append(f"1. storm_wise: {exc}")print(f" [FAIL] 1. storm_wise: {exc}")# --- Check 2: chronological ---try:_run_strategy(frame, "chronological", config)print(" [PASS] 2. chronological splits are disjoint")except Exception as exc:failures.append(f"2. chronological: {exc}")print(f" [FAIL] 2. chronological: {exc}")# --- Check 3: holdout_basin ---try:_run_strategy(frame, "holdout_basin", config)print(" [PASS] 3. holdout_basin splits are disjoint")except Exception as exc:failures.append(f"3. holdout_basin: {exc}")print(f" [FAIL] 3. holdout_basin: {exc}")# --- Check 4: random splits raise LeakageError ---random_ok = Truefor name in ("random", "frame", "shuffle", "random_frame"):try:assign_storms(frame, name)failures.append(f"4. {name} did not raise LeakageError")random_ok = Falseexcept LeakageError:passexcept Exception as exc:failures.append(f"4. {name} raised unexpected {type(exc).__name__}: {exc}")random_ok = Falseif random_ok:print(" [PASS] 4. Random splits raise LeakageError")else:print(" [FAIL] 4. Random splits did not all raise LeakageError")# --- Check 5: no forbidden features in model matrix ---try:from src.features import FeatureSpecfeature_names = list(FeatureSpec().feature_names())assert_no_forbidden_inputs(feature_names, "model features")print(" [PASS] 5. No forbidden features in default feature set")except LeakageError as exc:failures.append(f"5. forbidden features: {exc}")print(f" [FAIL] 5. {exc}")except Exception as exc:failures.append(f"5. feature check error: {exc}")print(f" [FAIL] 5. {exc}")# --- Check 6: cross-split links are nulled ---try:split_cfg = dict(config.get("split", {}))assigned = assign_storms(frame,"storm_wise",test_fraction=float(split_cfg.get("test_fraction", 0.2)),val_fraction=float(split_cfg.get("val_fraction", 0.2)),seed=int(split_cfg.get("seed", 42)),)linked = add_previous_frame_id(assigned)linked["split"] = assigned.loc[linked.index, "split"]# Artificially set a cross-split link.train_ids = linked.loc[linked["split"] == "train", "sample_id"].tolist()test_ids = linked.loc[linked["split"] == "test", "sample_id"].tolist()if train_ids and test_ids:dirty = linked.copy()dirty.loc[dirty["sample_id"] == train_ids[0], "prev_sample_id"] = test_ids[0]cleaned, dropped = null_cross_split_links(dirty)assert dropped >= 1, "cross-split link was not removed"assert pd.isna(cleaned.loc[cleaned["sample_id"] == train_ids[0], "prev_sample_id"]).all(), "cross-split link survived cleaning"print(" [PASS] 6. Cross-split previous-frame links are nulled")except Exception as exc:failures.append(f"6. cross-split links: {exc}")print(f" [FAIL] 6. {exc}")return failuresdef main() -> None:parser = argparse.ArgumentParser(description="Run a 6-point data-leakage audit on the split strategy.")parser.add_argument("--config",type=str,default="config/config_smoke.yaml",help="Path to YAML config file.",)args = parser.parse_args()config = load_config(args.config)print(f"Running 6-point leakage audit with {args.config}")failures = audit(config)if failures:print(f"\n{len(failures)} check(s) failed:")for msg in failures:print(f" - {msg}")sys.exit(1)else:print("\nAll 6 checks passed.")if __name__ == "__main__":main()
config/config.yaml+233-233
config/config_incyde.yaml+201-201
config/config_incyde_224.yamlAdded+264
config/config_incyde_safe.yamlAdded+264
config/config_nasa_safe.yamlAdded+264
config/config_smoke.yaml+196-196
config/incyde_cpu.yaml+41-41
src/__init__.py+6-6
src/baselines.py
src/cache_frames.py+72-72
src/calibration.py+345-345
src/config.py+68-68
src/data_loader.py+102-102
src/device.py+390-390
src/evaluate.py
src/features.py+899-899
src/incyde.py+778-778
src/inference.py
src/labels.py+216-216
src/make_smoke_data.py+153-153
src/metrics.py+174-174
src/model.py+262-262
src/model_access.py+26-26
src/nasa_tc.py+360-360
src/plots.py+109-109
src/preprocessing.py+314-314
src/reproducibility.py+46-46
src/schema.py+342-342
src/sequences.py+171-171
src/splits.py+318-318
src/tcir.py+591-591
src/train.py
src/verify_splits.py+220-220