Release binary forecasting code and seed42 checkpoints
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- .gitignoreAdded+4
- README.mdAdded+195
- configs/settingA.jsonAdded+22
- configs/settingB.jsonAdded+31
- configs/training.jsonAdded+341
- data/align_hdf5.pyAdded+54
- data/extract_cache.pyAdded+31
- data/pack_aia_2014_2016.pyAdded+156
- data/pack_aia_3_2011_2013.pyAdded+92
- data/pack_hmi_2011_2013.pyAdded+89
- data/pack_hmi_2014_2016.pyAdded+91
- data/prepare.pyAdded+15
- data/preprocess.pyAdded+22
- manifests/A/manifest.jsonAdded+50
- manifests/A/test_frames.csvAdded
- manifests/A/train_frames.csvAdded+3
- manifests/A/validation_frames.csvAdded
- manifests/B/manifest.jsonAdded+50
- manifests/B/test_frames.csvAdded
- manifests/B/train_frames.csvAdded+3
- manifests/B/validation_frames.csvAdded
- manifests/index.jsonAdded+1
- models/A/HMI2D_seed42.jsonAdded+15
- models/A/HMI2D_seed42.pthAdded+3
- models/A/HMI3D_CTL_seed42.jsonAdded+17
- models/A/HMI3D_CTL_seed42.pthAdded+3
- models/A/MDT2D_seed42.jsonAdded+15
- models/A/MDT2D_seed42.pthAdded+3
- models/A/dual_selected_logit_KD_seed42.jsonAdded+23
- models/A/dual_selected_logit_KD_seed42.pthAdded+3
- models/B/HMI2D_seed42.jsonAdded+15
- models/B/HMI2D_seed42.pthAdded+3
- models/B/HMI3D_CTL_seed42.jsonAdded+17
- models/B/HMI3D_CTL_seed42.pthAdded+3
- models/B/MDT2D_seed42.jsonAdded+15
- models/B/MDT2D_seed42.pthAdded+3
- models/B/dual_selected_logit_KD_seed42.jsonAdded+23
- models/B/dual_selected_logit_KD_seed42.pthAdded+3
- pyproject.tomlAdded+10
- registry.jsonAdded+130
- requirements-preprocess.txtAdded+5
- requirements.txtAdded+6
- scripts/common.pyAdded+3
- scripts/predict.pyAdded+12
- scripts/run_experiment.pyAdded+27
- src/binaryforecast/__init__.pyAdded+1
- src/binaryforecast/api.pyAdded+99
- src/binaryforecast/core/__init__.pyAdded+1
- src/binaryforecast/core/loss/__init__.pyAdded+12
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmanifests/A/train_frames.csv filter=lfs diff=lfs merge=lfs -textmanifests/B/train_frames.csv filter=lfs diff=lfs merge=lfs -text
1234__pycache__/*.pycruns/*.log123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195# Binary Solar Flare Forecasting
Corrected-data binary solar flare forecasting for chronological Settings A and B. This repository contains HMI-only CNN baselines, an AIA/HMI MDT spatial teacher, an HMI3D-CTL temporal teacher, and single- or dual-teacher knowledge distillation.
The task is to predict whether at least one **M1.0+** flare starts during **(t, t + 24 h]**. The distilled HMI2D student needs only the current HMI magnetogram at inference.
## Released models
Each setting contains these four models:
| Method identifier | Inference input | Description ||---|---|---|| `HMI2D` | Current HMI magnetogram | Undistilled student baseline || `MDT2D` | Current HMI + AIA 94/193/304 Å | Spatial teacher with corrected squared orthogonality loss || `HMI3D_CTL` | Five hourly HMI magnetograms | Temporal teacher trained with supervised contrastive learning || `dual_selected_logit_KD` | Current HMI magnetogram | HMI2D student distilled from MDT2D and HMI3D-CTL |
## Layout
```textconfigs/ Shared training settings and A/B-specific settings training.json settingA.json settingB.jsondata/ FITS packing, HDF5 alignment, manifests and KD cache extractionmanifests/{A,B}/ Published train/validation/test sample manifestsmodels/{A,B}/ Eight seed42 weight files and their JSON metadatascripts/ run_experiment.py Unified training and evaluation entry predict.py Inference on preprocessed tensors common.py Shared script importssrc/binaryforecast/ api.py Configuration generation and checkpoint resolution core/ model/ Network architectures and backbones loss/ Focal, MDT, CTL and KD losses utils/ Datasets, time protocols, labels and metrics training/ baseline/ Supervised 2D/3D CNN training teacher/ MDT and CTL training kd/ Single- and dual-teacher trainingregistry.json Released checkpoint identities and checksums```
## Installation
Use Python 3.10 or newer with an environment compatible with the pinned dependencies. The supplied requirements target PyTorch 2.5.1 with CUDA 12.1:
```bashpython -m pip install --extra-index-url https://download.pytorch.org/whl/cu121 -r requirements.txtpython -m pip install -e . --no-deps```
For raw FITS preprocessing, also install:
```bashpython -m pip install -r requirements-preprocess.txt```
Training uses CUDA. Released checkpoints can be loaded for CPU inference. Exact numerical agreement across different hardware and dependency versions is not guaranteed.
## Data and labels
AIA images (94, 193 and 304 Å) and HMI magnetograms are available from [NASA SDO](https://sdo.gsfc.nasa.gov/data/dataaccess.php). GOES flare metadata are provided by [Surya-Bench](https://huggingface.co/datasets/nasa-ibm-ai4science/surya-bench-flare-forecasting).
A sample is positive if an **M1.0+ flare starts within `(t, t+24h]`**; otherwise, it is negative. Times use UTC. Invalid samples are excluded, and the final **96 hours** of training and validation intervals are removed. All models use the same five-frame-eligible samples; 2D models read only the current image.
| Setting | Training | Validation | Test | Samples: train / val / test ||---|---|---|---|---|| A | 2011-01-01–2013-07-01 | 2013-07-01–2014-01-01 | 2014-01-01–2015-01-01 | 20,192 / 4,050 / 7,672 || B | 2011-01-01–2014-01-01 | 2014-01-01–2015-01-01 | 2015-01-01–2017-01-01 | 24,342 / 7,600 / 15,884 |
Intervals exclude their right endpoints and precede eligibility filtering.
### Data preparation
To use the published manifests, provide `--data-root` with matching HDF5 filenames, or `--path-map mapping.json` for custom paths. HDF5 files contain `images` and `times`, with images shaped `(N,C,512,512)`: HMI has one channel; AIA has three channels ordered 94, 193, 304 Å.
To rebuild, convert FITS files using `data/pack_*.py`, then run:
```bashpython data/prepare.py \ --source 2011_2013 /path/to/aia_2011_2013.h5 /path/to/hmi_2011_2013.h5 \ --source 2014_2016 /path/to/aia_2014_2016.h5 /path/to/hmi_2014_2016.h5 \ --events /path/to/flare_catalog_2010-2024.csv \ --coverage-start 2010-05-01 --coverage-end 2025-01-01 \ --setting all --output runs/prepared_data \ --reference-root manifests```
Use the [event-level catalogue](https://github.com/NASA-IMPACT/SuryaBench/blob/main/flare/flare_catalog_2010-2024.csv) for `--events`; Hugging Face’s window-level `data.csv` is not a compatible input. Set coverage bounds to match the catalogue.
Alignment uses nearest HMI observations within 30 minutes, followed by input-time checks. `--reference-root` verifies agreement with published samples; omit it for a different dataset. Update the setting configurations to use newly generated manifests.
## Load a released model
After installation:
```pythonimport torchfrom binaryforecast import artifact, load_model
model = load_model(artifact('A/dual_selected_logit_KD/seed42'), device='cpu')# hmi: preprocessed float32 tensor, shape (batch, 1, 512, 512).with torch.inference_mode(): logits = model(hmi) probability_m1_plus = logits.softmax(dim=1)[:, 1]```
For the command-line interface, save a dictionary of preprocessed tensors in a PyTorch file. HMI-only input uses key `HMI`; MDT additionally uses key `AIA`. Then run:
```bashpython scripts/predict.py \ --artifact A/dual_selected_logit_KD/seed42 \ --input /path/to/preprocessed_batch.pt \ --device cpu --output predictions.npz```
This writes logits, probabilities and predictions to `runs/predictions.npz`. For HMI3D-CTL, the HMI tensor is `(batch,1,5,512,512)`, ordered from `t-4h` to `t`; 2D HMI and AIA tensors are `(batch,1,512,512)` and `(batch,3,512,512)`.
## Train and evaluate
All commands below run from the repository root. Change `--setting A` to `B` to use Setting B, including its CTL and dual-teacher parameters.
Preview a run without training:
```bashpython scripts/run_experiment.py --setting A --method HMI2D --seed 42```
Add `--execute` and a data location to train. For a fresh run of the released model chain, train these methods with the same run tag:
```bashfor method in HMI2D AIA2D HMI3D_CTL MDT2D; do python scripts/run_experiment.py \ --setting A --method "$method" --seed 42 --gpu 0 \ --data-root /path/to/hdf5 --run-tag retrain --execute || breakdone```
Extract the dual-teacher cache and train the student:
```bashCUDA_VISIBLE_DEVICES=0 python data/extract_cache.py \ --artifact A/dual_selected_logit_KD/seed42 \ --data-root /path/to/hdf5 --run-tag retrain \ --output runs/retrain/cache --device cuda
python scripts/run_experiment.py \ --setting A --method dual_selected_logit_KD --seed 42 --gpu 0 \ --data-root /path/to/hdf5 --run-tag retrain \ --cache-dir runs/retrain/cache --execute```
Caches contain training/validation teacher outputs and must match the checkpoint hashes and manifest identity. Use the same run tag and checkpoint source for extraction and KD training. Both teachers are frozen during extraction; only the student is optimized during KD.
Evaluate a newly trained run separately:
```bashpython scripts/run_experiment.py \ --setting A --method dual_selected_logit_KD --seed 42 \ --phase evaluate --gpu 0 --data-root /path/to/hdf5 \ --run-tag retrain --execute```
### Single-teacher KD
```bashCUDA_VISIBLE_DEVICES=0 python data/extract_cache.py \ --artifact A/MDT2D_to_HMI2D_logits/seed42 \ --data-root /path/to/hdf5 --run-tag retrain \ --output runs/retrain/cache --device cuda
python scripts/run_experiment.py \ --setting A --method MDT2D_to_HMI2D_logits --seed 42 --gpu 0 \ --data-root /path/to/hdf5 --run-tag retrain \ --cache-dir runs/retrain/cache --execute```
12345678910111213141516171819202122{ "manifest_dir": "manifests/A", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "sample_counts": [ 20192, 4050, 7672 ], "method_overrides": {}, "initial_state_sha256": { "HMI2D": { "42": "27017a48e5debca0d66786d5603cc92f6cb1ec421426a477ba43350341abf1ec", "2024": "6a47551b879ef11677b0567ac7db432c96120764b3ecad4f0e34782dd10447d3", "3407": "af14f6e81e8a6e2cefe8113731ee003008d37888dfa02013730cfb41d04cab1c" }, "HMI3D": { "42": "f7cab249ae1c800b31d0c887b3a283c8b0a459d5da82ba6c77aef1077425229d", "2024": "6473c879d68fac7055315d8134b548e18cac1e1b733bee25bb22481e9cd44095", "3407": "8bd1ac77b2247199f9c52b4e138629b10587bea273be6a879924fd76a65e81b0" } }}12345678910111213141516171819202122232425262728293031{ "manifest_dir": "manifests/B", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "sample_counts": [ 24342, 7600, 15884 ], "method_overrides": { "HMI3D_CTL": { "lambda_con": 0.005, "con_temperature": 0.1 }, "dual_selected_logit_KD": { "weight_ctl": 0.8, "weight_mdt": 0.2 } }, "initial_state_sha256": { "HMI2D": { "42": "27017a48e5debca0d66786d5603cc92f6cb1ec421426a477ba43350341abf1ec", "2024": "6a47551b879ef11677b0567ac7db432c96120764b3ecad4f0e34782dd10447d3", "3407": "af14f6e81e8a6e2cefe8113731ee003008d37888dfa02013730cfb41d04cab1c" }, "HMI3D": { "42": "f7cab249ae1c800b31d0c887b3a283c8b0a459d5da82ba6c77aef1077425229d", "2024": "6473c879d68fac7055315d8134b548e18cac1e1b733bee25bb22481e9cd44095", "3407": "8bd1ac77b2247199f9c52b4e138629b10587bea273be6a879924fd76a65e81b0" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341{ "seeds": [ 42, 2024, 3407 ], "defaults": { "epochs": 30, "lr": 0.0001, "weight_decay": 0.0 }, "methods": { "AIA2D": { "parameters": { "modality": "AIA", "temporal": false, "batch_size": 16, "lr": 5e-05 }, "model": { "kind": "baseline", "architecture": "cnn", "training_module": "binaryforecast.training.baseline.supervised" } }, "AIA3D": { "parameters": { "modality": "AIA", "temporal": true, "batch_size": 4, "lr": 5e-05, "weight_decay": 0.0001 }, "model": { "kind": "baseline", "architecture": "cnn", "training_module": "binaryforecast.training.baseline.supervised" } }, "HMI2D": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16 }, "model": { "kind": "baseline", "architecture": "cnn", "training_module": "binaryforecast.training.baseline.supervised" } }, "HMI3D": { "parameters": { "modality": "HMI", "temporal": true, "batch_size": 4, "weight_decay": 0.0001 }, "model": { "kind": "baseline", "architecture": "cnn", "training_module": "binaryforecast.training.baseline.supervised" } }, "HMI3D_CTL": { "parameters": { "modality": "HMI", "temporal": true, "batch_size": 4, "weight_decay": 0.0001, "lambda_con": 0.001, "con_temperature": 0.2 }, "initial_state_model": "HMI3D", "model": { "kind": "ctl", "architecture": "cnn", "training_module": "binaryforecast.training.teacher.ctl" } }, "HMI3D_to_HMI2D_feature_only": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "HMI3D", "teacher_feature_dim": 512, "feature_kd": true, "lambda_logits": 0.0, "lambda_feature": 0.5, "temperature": 4.0 }, "dependencies": [ "HMI3D" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "HMI3D_to_HMI2D_logits": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "HMI3D", "teacher_feature_dim": 512, "feature_kd": false, "lambda_logits": 0.5, "lambda_feature": 0.0, "temperature": 4.0 }, "dependencies": [ "HMI3D" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "HMICTL_to_HMI2D_feature_only": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "HMICTL", "teacher_feature_dim": 512, "feature_kd": true, "lambda_logits": 0.0, "lambda_feature": 0.5, "temperature": 4.0 }, "dependencies": [ "HMI3D_CTL" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "HMICTL_to_HMI2D_logits": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "HMICTL", "teacher_feature_dim": 512, "feature_kd": false, "lambda_logits": 0.5, "lambda_feature": 0.0, "temperature": 4.0 }, "dependencies": [ "HMI3D_CTL" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "HMICTL_to_HMI2D_logits_feature": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "HMICTL", "teacher_feature_dim": 512, "feature_kd": true, "lambda_logits": 0.5, "lambda_feature": 0.5, "temperature": 4.0 }, "dependencies": [ "HMI3D_CTL" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "MDT2D": { "parameters": { "modality": "BOTH", "temporal": false, "batch_size": 8 }, "dependencies": [ "AIA2D", "HMI2D" ], "model": { "kind": "mdt", "architecture": "mdt", "training_module": "binaryforecast.training.teacher.mdt" } }, "MDT2D_to_HMI2D_feature_only": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "MDT2D", "teacher_feature_dim": 64, "feature_kd": true, "lambda_logits": 0.0, "lambda_feature": 0.5, "temperature": 4.0 }, "dependencies": [ "MDT2D" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "MDT2D_to_HMI2D_logits": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "MDT2D", "teacher_feature_dim": 64, "feature_kd": false, "lambda_logits": 0.5, "lambda_feature": 0.0, "temperature": 4.0 }, "dependencies": [ "MDT2D" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "MDT2D_to_HMI2D_logits_feature": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "teacher": "MDT2D", "teacher_feature_dim": 64, "feature_kd": true, "lambda_logits": 0.5, "lambda_feature": 0.5, "temperature": 4.0 }, "dependencies": [ "MDT2D" ], "initial_state_model": "HMI2D", "model": { "kind": "single", "architecture": "cnn", "training_module": "binaryforecast.training.kd.single_teacher" } }, "MDT3D": { "parameters": { "modality": "BOTH", "temporal": true, "batch_size": 2, "weight_decay": 0.0001 }, "dependencies": [ "AIA3D", "HMI3D" ], "model": { "kind": "mdt", "architecture": "mdt", "training_module": "binaryforecast.training.teacher.mdt" } }, "dual_equal_logit_KD": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "temperature": 4.0, "lambda_kd": 0.5, "weight_ctl": 0.5, "weight_mdt": 0.5, "warmup": false, "warmup_start": 5, "warmup_epochs": 10, "grad_clip": 0.0 }, "dependencies": [ "MDT2D", "HMI3D_CTL" ], "initial_state_model": "HMI2D", "model": { "kind": "dual", "architecture": "cnn", "training_module": "binaryforecast.training.kd.dual_teacher" } }, "dual_selected_logit_KD": { "parameters": { "modality": "HMI", "temporal": false, "batch_size": 16, "temperature": 4.0, "lambda_kd": 0.5, "weight_ctl": 0.7, "weight_mdt": 0.3, "warmup": false, "warmup_start": 5, "warmup_epochs": 10, "grad_clip": 0.0 }, "dependencies": [ "MDT2D", "HMI3D_CTL" ], "initial_state_model": "HMI2D", "model": { "kind": "dual", "architecture": "cnn", "training_module": "binaryforecast.training.kd.dual_teacher" } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Read HDF5 timestamps and construct a label-free paired AIA/HMI index.Matching follows the original build_aligned_index_2011_2016.py:AIA reference, pandas merge_asof nearest, default tolerance 30 minutes.Actual times are retained so later temporal eligibility can reject future/misaligned input."""import argparse,pathlib,jsonimport h5py,numpy as np,pandas as pd
def read_h5_times(path,prefix,time_unit=None): with h5py.File(path,'r')as f: if 'images'not in f or 'times'not in f:raise ValueError('HDF5 requires images and times') raw=f['times'][:];shape=f['images'].shape if len(raw)!=shape[0]:raise ValueError('Image/time row counts differ: '+str(path)) if len(shape)!=4 or shape[1]!=(3 if prefix=='aia'else 1)or shape[2:]!=(512,512):raise ValueError('Expected AIA/HMI N,C,512,512: '+str(shape)) if raw.dtype.kind in 'iuf': if time_unit is None:raise ValueError('Numeric timestamps require explicit --time-unit') times=pd.to_datetime(raw,unit=time_unit,errors='raise',utc=True) else:times=pd.to_datetime([x.decode('utf-8')if isinstance(x,bytes)else str(x)for x in raw],errors='raise',utc=True) times=pd.DatetimeIndex(times).tz_convert(None) if times.isna().any()or times.duplicated().any():raise ValueError('Missing/duplicate HDF5 timestamps: '+str(path)) # Indices are allocated before sorting, retaining actual HDF5 image-row correspondence. return pd.DataFrame({'timestamp':times,prefix+'_timestamp':times,prefix+'_idx':np.arange(len(times),dtype=np.int64)}).sort_values('timestamp').reset_index(drop=True)
def align_period(period,aia_path,hmi_path,tolerance='30min',time_unit=None): aia=read_h5_times(aia_path,'aia',time_unit);hmi=read_h5_times(hmi_path,'hmi',time_unit) tol=pd.Timedelta(tolerance) if tol<pd.Timedelta(0):raise ValueError('Negative alignment tolerance') paired=pd.merge_asof(aia,hmi,on='timestamp',direction='nearest',tolerance=tol) paired=paired.dropna(subset=['hmi_idx']).copy();paired['hmi_idx']=paired.hmi_idx.astype(np.int64) paired['aia_h5']=pathlib.Path(aia_path).name;paired['hmi_h5']=pathlib.Path(hmi_path).name;paired['period']=period # This flag certifies valid metadata references only, not a fresh pixel-integrity audit. paired['aia_quality_ok']=True;paired['hmi_quality_ok']=True return paired,{'period':period,'aia_rows':len(aia),'hmi_rows':len(hmi),'paired_rows':len(paired),'unmatched_aia':len(aia)-len(paired),'future_hmi_matches':int((paired.hmi_timestamp>paired.timestamp).sum())}
def build_index(sources,tolerance='30min',time_unit=None): names={};tables=[];reports=[] for period,aia,hmi in sources: for path in [aia,hmi]: resolved=pathlib.Path(path).resolve();name=resolved.name # Store the supplied basename (symlinks can resolve to differently named data disks). name=pathlib.Path(path).name if name in names and names[name]!=resolved:raise ValueError('Distinct HDF5 files share a basename: '+name) names[name]=resolved table,report=align_period(period,aia,hmi,tolerance,time_unit);tables.append(table);reports.append(report) result=pd.concat(tables,ignore_index=True).sort_values('timestamp').reset_index(drop=True) if result.timestamp.duplicated().any():raise ValueError('Overlapping source periods produce duplicate anchors') return result,reports
def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',nargs=3,action='append',required=True,metavar=('PERIOD','AIA_H5','HMI_H5'));p.add_argument('--output',required=True);p.add_argument('--tolerance',default='30min');p.add_argument('--time-unit',choices=['s','ms','us','ns']);args=p.parse_args() frame,reports=build_index(args.source,args.tolerance,args.time_unit);out=pathlib.Path(args.output) if out.exists():raise FileExistsError(out) out.parent.mkdir(parents=True,exist_ok=True);frame.to_csv(out,index=False);print(json.dumps({'rows':len(frame),'periods':reports}))if __name__=='__main__':main()12345678910111213141516171819202122232425262728293031import pathlib,sys,argparse,json,ossys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]/'src'))from binaryforecast.api import *p=argparse.ArgumentParser();p.add_argument('--artifact',required=True);p.add_argument('--data-root');p.add_argument('--path-map');p.add_argument('--output',required=True);p.add_argument('--device',default='cuda');p.add_argument('--checkpoint-root');p.add_argument('--run-tag',default='reproduction');args=p.parse_args()if not args.data_root and not args.path_map:p.error('Specify --data-root or --path-map')if args.data_root:os.environ['BINARY_DATA_ROOT']=args.data_rootif args.path_map:os.environ['BINARY_PATH_MAP']=pathlib.Path(args.path_map).read_text()import torch,numpy as npfrom binaryforecast.core.utils.data_api import load_manifestfrom binaryforecast.core.utils.vendor.protocol import eligiblefrom binaryforecast.core.utils.datasets import SolarMultiSourceRAMDataset,SolarTemporalMultiSourceRAMDatasetfrom binaryforecast.core.utils.experiment import make_loaderstudent=artifact(args.artifact);cfg=build_plan(student['setting'],student['family'],student['seed'],args.run_tag,args.checkpoint_root);job=cfg['jobs'][0];assert student['kind']in ['single','dual'];_,frames=load_manifest(cfg['manifest_dir']);teachers={}for ident in cfg['dependencies']: a=artifact(ident);key='mdt'if a['family']=='MDT2D'else'ctl'if a['family']=='HMI3D_CTL'else'teacher';key=key if student['kind']=='dual'else'teacher';entry=resolve_checkpoint(ident,args.checkpoint_root,args.run_tag);teachers[key]=(a,load_model(a,args.device,args.checkpoint_root,args.run_tag),entry)out=pathlib.Path(args.output)/job['cache_id'];out.mkdir(parents=True,exist_ok=False);paths={}for split in ['train','validation']: ends=eligible(frames[split]);collected={};reference=None for key,(a,model,entry)in teachers.items(): mod='BOTH'if a['architecture']=='mdt'else a['modality'];ds=SolarTemporalMultiSourceRAMDataset(frames[split],5,1,mod,'target_binary')if a['temporal']else SolarMultiSourceRAMDataset(ends,mod,'target_binary');loader=make_loader(ds,4,False,0,student['seed']);zs=[];fs=[];ys=[] with torch.inference_mode(): for batch in loader: if a['architecture']=='mdt':ai,hi,y=batch;z,_,features=model(ai.to(args.device),hi.to(args.device));feature=features[0]+features[1] else:x,y=batch;z,feature=model(x.to(args.device),return_features=True) zs.append(z.cpu().numpy());fs.append(feature.cpu().numpy());ys.append(y.numpy()) labels=np.concatenate(ys);assert np.array_equal(labels,ends.target_binary.to_numpy());assert reference is None or np.array_equal(labels,reference);reference=labels if student['kind']=='dual':collected['logits_'+key]=np.concatenate(zs) else:collected.update(logits=np.concatenate(zs),features=np.concatenate(fs)) del ds,loader collected.update(sample_ids=ends.sample_id.to_numpy(dtype=str),labels=reference);file=out/(split+'.npz');np.savez(file,**collected);paths[file.name]=sha(file)meta={'manifest_id':cfg['manifest_id'],'files':paths,'teacher_frozen':True};meta.update({'teacher_shas':job['teacher_shas']}if student['kind']=='dual'else{'checkpoint_sha256':job['teacher_sha256']});(out/'complete.json').write_text(json.dumps(meta,indent=2));print(json.dumps({'cache':str(out),'splits':['train','validation']}))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import argparse
def _parse_args(): parser = argparse.ArgumentParser(description='Pack original FITS images to HDF5 using the published experiment preprocessing.') parser.add_argument('--input-dir', required=True, help='Directory containing original FITS files (nonrecursive).') parser.add_argument('--output', required=True, help='Output HDF5 path.') parser.add_argument('--log-file', default=None, help='Optional log path; otherwise log to the console only.') parser.add_argument('--resume', action='store_true', help='Append using the original 2014-2016 AIA resume logic.') parser.add_argument('--overwrite', action='store_true', help='Explicitly allow replacement for non-resumable packers.') return parser.parse_args()if __name__ == '__main__': _args = _parse_args()import osimport globimport h5pyimport numpy as npimport cv2from datetime import datetimefrom tqdm import tqdmimport loggingimport warningsimport gcimport multiprocessingfrom astropy.utils.iers import confconf.auto_download = Falsewarnings.filterwarnings('ignore')BASE_DIR = NoneOUTPUT_H5 = NoneTARGET_SIZE = (512, 512)CHANNELS = ['94', '193', '304']LOG_FILE = None
def get_time_from_filename(fname): try: time_str = os.path.basename(fname).split('.')[2] return datetime.strptime(time_str, '%Y-%m-%dT%H%M%SZ') except: return None
def read_single_fits(file_path, target_size, return_dict): try: import sunpy.map smap = sunpy.map.Map(file_path, memmap=False) img = np.nan_to_num(smap.data, nan=0.0, posinf=0.0, neginf=0.0) img_resized = cv2.resize(img, (target_size[1], target_size[0]), interpolation=cv2.INTER_AREA) return_dict['data'] = img_resized.astype(np.float32) except Exception as e: return_dict['error'] = str(e)
def pack_data(): logging.info(f'🚀 开始扫描 {BASE_DIR} 中的 FITS 文件...') all_fits = glob.glob(os.path.join(BASE_DIR, '*.fits')) data_groups = {} for f in all_fits: wave = os.path.basename(f).split('.')[3] if wave in CHANNELS: dt = get_time_from_filename(f) if dt: hour_key = dt.replace(minute=0, second=0) if hour_key not in data_groups: data_groups[hour_key] = {} data_groups[hour_key][wave] = f valid_hours = sorted([h for (h, waves) in data_groups.items() if len(waves) == len(CHANNELS)]) logging.info(f'✅ 扫描完成!共发现 {len(valid_hours)} 个完整的跨模态样本组。') with h5py.File(OUTPUT_H5, 'a') as h5f: if 'images' not in h5f: dataset = h5f.create_dataset('images', shape=(0, 3, *TARGET_SIZE), maxshape=(None, 3, *TARGET_SIZE), dtype=np.float32, chunks=(1, 3, *TARGET_SIZE), compression='gzip') times_db = h5f.create_dataset('times', shape=(0,), maxshape=(None,), dtype='S20') existing_times = set() logging.info('🆕 创建新的 HDF5 数据集结构...') else: dataset = h5f['images'] times_db = h5f['times'] existing_times = set([t.decode('ascii') for t in times_db[:]]) logging.info(f'📂 发现已有数据集,当前已包含 {len(existing_times)} 个样本。') remaining_hours = [h for h in valid_hours if h.isoformat() not in existing_times] if not remaining_hours: logging.info('🎉 所有数据此前已全部打包完成!') return logging.info(f'🔄 剩余 {len(remaining_hours)} 个样本待处理。') start_idx = dataset.shape[0] total_to_add = len(remaining_hours) logging.info('⏳ 正在预分配 HDF5 存储空间,请稍候...') dataset.resize((start_idx + total_to_add, 3, *TARGET_SIZE)) times_db.resize((start_idx + total_to_add,)) success_count = 0 pbar = tqdm(remaining_hours, desc='打包进度', dynamic_ncols=True) for (i, hour) in enumerate(pbar): if i > 0 and i % 100 == 0: logging.info(f'当前进度: {i}/{len(remaining_hours)} - 正在处理: {hour.isoformat()}') success = True temp_img_array = np.zeros((3, *TARGET_SIZE), dtype=np.float32) for (c_idx, wave) in enumerate(CHANNELS): file_path = data_groups[hour][wave] if os.path.getsize(file_path) < 102400: logging.error(f'🗑️ 文件过小疑似损坏,跳过: {file_path}') success = False break manager = multiprocessing.Manager() return_dict = manager.dict() p = multiprocessing.Process(target=read_single_fits, args=(file_path, TARGET_SIZE, return_dict)) p.start() p.join(timeout=15) if p.is_alive(): p.terminate() p.join() logging.error(f'💀 捕捉到底层死锁!已强制猎杀并跳过文件: {file_path}') success = False break if 'error' in return_dict: logging.error(f"⚠️ 读取 {wave} 失败 ({hour.isoformat()}): {return_dict['error']}") success = False break elif 'data' in return_dict: temp_img_array[c_idx, :, :] = return_dict['data'] else: logging.error(f'⚠️ 子进程未知崩溃 ({hour.isoformat()} - {wave})') success = False break if success: current_write_idx = start_idx + success_count dataset[current_write_idx, :, :, :] = temp_img_array times_db[current_write_idx] = hour.isoformat().encode('ascii') success_count += 1 if i % 50 == 0: gc.collect() final_len = start_idx + success_count if final_len < dataset.shape[0]: logging.info(f'✂️ 剔除了 {dataset.shape[0] - final_len} 个损坏或读取失败的样本空间。') dataset.resize((final_len, 3, *TARGET_SIZE)) times_db.resize((final_len,)) h5f.flush() logging.info(f'🎉 任务结束!实际新增成功样本: {success_count} 个。文件已更新至:{OUTPUT_H5}')if __name__ == '__main__': from pathlib import Path _input = Path(_args.input_dir).expanduser().resolve() _output = Path(_args.output).expanduser().resolve() if not _input.is_dir(): raise SystemExit('Input FITS directory does not exist: ' + str(_input)) if _args.resume and _args.overwrite: raise SystemExit('Use either --resume or --overwrite, not both.') if _args.overwrite: raise SystemExit('This packer appends; use a new output file or --resume.') if _output.exists() and (not _args.resume): raise SystemExit('Output exists; specify --resume to append.') BASE_DIR = str(_input) OUTPUT_H5 = str(_output) LOG_FILE = _args.log_file _output.parent.mkdir(parents=True, exist_ok=True) _handlers = [logging.StreamHandler()] if LOG_FILE: _log = Path(LOG_FILE).expanduser().resolve() _log.parent.mkdir(parents=True, exist_ok=True) _handlers.append(logging.FileHandler(_log)) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=_handlers) pack_data()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import argparse
def _parse_args(): parser = argparse.ArgumentParser(description='Pack original FITS images to HDF5 using the published experiment preprocessing.') parser.add_argument('--input-dir', required=True, help='Directory containing original FITS files (nonrecursive).') parser.add_argument('--output', required=True, help='Output HDF5 path.') parser.add_argument('--log-file', default=None, help='Optional log path; otherwise log to the console only.') parser.add_argument('--resume', action='store_true', help='Append using the original 2014-2016 AIA resume logic.') parser.add_argument('--overwrite', action='store_true', help='Explicitly allow replacement for non-resumable packers.') return parser.parse_args()if __name__ == '__main__': _args = _parse_args()import osimport globimport h5pyimport numpy as npimport sunpy.mapfrom skimage.transform import resizefrom datetime import datetimefrom tqdm import tqdmimport loggingimport warningswarnings.filterwarnings('ignore')BASE_DIR = NoneOUTPUT_H5 = NoneTARGET_SIZE = (512, 512)CHANNELS = ['94', '193', '304']LOG_FILE = None
def get_time_from_filename(fname): try: time_str = os.path.basename(fname).split('.')[2] return datetime.strptime(time_str, '%Y-%m-%dT%H%M%SZ') except: return None
def pack_data(): logging.info(f'🚀 开始扫描 {BASE_DIR} 中的 FITS 文件...') all_fits = glob.glob(os.path.join(BASE_DIR, '*.fits')) data_groups = {} for f in all_fits: wave = os.path.basename(f).split('.')[3] if wave in CHANNELS: dt = get_time_from_filename(f) if dt: hour_key = dt.replace(minute=0, second=0) if hour_key not in data_groups: data_groups[hour_key] = {} data_groups[hour_key][wave] = f valid_hours = sorted([h for (h, waves) in data_groups.items() if len(waves) == len(CHANNELS)]) logging.info(f'✅ 扫描完成!共发现 {len(valid_hours)} 个完整的跨模态样本组。即将开始打包...') with h5py.File(OUTPUT_H5, 'w') as h5f: dataset = h5f.create_dataset('images', shape=(len(valid_hours), 3, *TARGET_SIZE), dtype=np.float32, chunks=(1, 3, *TARGET_SIZE), compression='gzip') times_db = h5f.create_dataset('times', shape=(len(valid_hours),), dtype='S20') pbar = tqdm(valid_hours, desc='打包进度', dynamic_ncols=True) for (i, hour) in enumerate(pbar): if i % 50 == 0: logging.info(f'当前进度: {i}/{len(valid_hours)} ({i / len(valid_hours) * 100:.1f}%) - 正在处理: {hour.isoformat()}') for (c_idx, wave) in enumerate(CHANNELS): file_path = data_groups[hour][wave] try: smap = sunpy.map.Map(file_path) img = np.nan_to_num(smap.data, nan=0.0, posinf=0.0, neginf=0.0) img_resized = resize(img, TARGET_SIZE, anti_aliasing=True, preserve_range=True) dataset[i, c_idx, :, :] = img_resized.astype(np.float32) except Exception as e: logging.error(f'⚠️ 读取 {wave} 失败 ({hour.isoformat()}): {e}') times_db[i] = hour.isoformat().encode('ascii') logging.info(f'🎉 全部打包完成!文件已生成:{OUTPUT_H5}')if __name__ == '__main__': from pathlib import Path _input = Path(_args.input_dir).expanduser().resolve() _output = Path(_args.output).expanduser().resolve() if not _input.is_dir(): raise SystemExit('Input FITS directory does not exist: ' + str(_input)) if _args.resume and _args.overwrite: raise SystemExit('Use either --resume or --overwrite, not both.') if _args.resume: raise SystemExit('This packer does not support resume.') if _output.exists() and (not _args.overwrite): raise SystemExit('Output exists; use a new path or explicit --overwrite.') BASE_DIR = str(_input) OUTPUT_H5 = str(_output) LOG_FILE = _args.log_file _output.parent.mkdir(parents=True, exist_ok=True) _handlers = [logging.StreamHandler()] if LOG_FILE: _log = Path(LOG_FILE).expanduser().resolve() _log.parent.mkdir(parents=True, exist_ok=True) _handlers.append(logging.FileHandler(_log)) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=_handlers) pack_data()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import argparse
def _parse_args(): parser = argparse.ArgumentParser(description='Pack original FITS images to HDF5 using the published experiment preprocessing.') parser.add_argument('--input-dir', required=True, help='Directory containing original FITS files (nonrecursive).') parser.add_argument('--output', required=True, help='Output HDF5 path.') parser.add_argument('--log-file', default=None, help='Optional log path; otherwise log to the console only.') parser.add_argument('--resume', action='store_true', help='Append using the original 2014-2016 AIA resume logic.') parser.add_argument('--overwrite', action='store_true', help='Explicitly allow replacement for non-resumable packers.') return parser.parse_args()if __name__ == '__main__': _args = _parse_args()import osimport globimport h5pyimport numpy as npimport sunpy.mapimport cv2from datetime import datetimefrom tqdm import tqdmimport loggingimport warningswarnings.filterwarnings('ignore')HMI_DIR = NoneOUTPUT_H5 = NoneTARGET_SIZE = (512, 512)LOG_FILE = NoneCLIP_MIN = -3000.0CLIP_MAX = 3000.0
def get_time_from_hmi(fname): """解析 HMI 文件名: hmi.M_720s.20110101_000000_TAI.1.magnetogram.fits""" try: time_str = os.path.basename(fname).split('.')[2][:15] return datetime.strptime(time_str, '%Y%m%d_%H%M%S') except Exception as e: return None
def pack_hmi_data(): logging.info(f'🚀 开始扫描 {HMI_DIR} 中的 HMI 磁图...') all_fits = glob.glob(os.path.join(HMI_DIR, '*.fits')) valid_files = [] for f in all_fits: dt = get_time_from_hmi(f) if dt: valid_files.append((dt, f)) valid_files.sort(key=lambda x: x[0]) logging.info(f'✅ 扫描完成!共发现 {len(valid_files)} 个 HMI 样本。即将开始打包...') with h5py.File(OUTPUT_H5, 'w') as h5f: dataset = h5f.create_dataset('images', shape=(len(valid_files), 1, *TARGET_SIZE), dtype=np.float32, chunks=(1, 1, *TARGET_SIZE), compression='gzip') times_db = h5f.create_dataset('times', shape=(len(valid_files),), dtype='S20') pbar = tqdm(valid_files, desc='HMI打包进度', dynamic_ncols=True) for (i, (dt, file_path)) in enumerate(pbar): if i % 100 == 0: logging.info(f'当前进度: {i}/{len(valid_files)} - 正在处理: {dt.isoformat()}') try: smap = sunpy.map.Map(file_path) img = smap.data img = np.nan_to_num(img, nan=0.0, posinf=0.0, neginf=0.0) img = np.clip(img, CLIP_MIN, CLIP_MAX) img_resized = cv2.resize(img, (TARGET_SIZE[1], TARGET_SIZE[0]), interpolation=cv2.INTER_AREA) dataset[i, 0, :, :] = img_resized.astype(np.float32) times_db[i] = dt.isoformat().encode('ascii') except Exception as e: logging.error(f'⚠️ 读取 {file_path} 失败: {e}') logging.info(f'🎉 HMI 磁图全部打包完成!文件已生成:{OUTPUT_H5}')if __name__ == '__main__': from pathlib import Path _input = Path(_args.input_dir).expanduser().resolve() _output = Path(_args.output).expanduser().resolve() if not _input.is_dir(): raise SystemExit('Input FITS directory does not exist: ' + str(_input)) if _args.resume and _args.overwrite: raise SystemExit('Use either --resume or --overwrite, not both.') if _args.resume: raise SystemExit('This packer does not support resume.') if _output.exists() and (not _args.overwrite): raise SystemExit('Output exists; use a new path or explicit --overwrite.') HMI_DIR = str(_input) OUTPUT_H5 = str(_output) LOG_FILE = _args.log_file _output.parent.mkdir(parents=True, exist_ok=True) _handlers = [logging.StreamHandler()] if LOG_FILE: _log = Path(LOG_FILE).expanduser().resolve() _log.parent.mkdir(parents=True, exist_ok=True) _handlers.append(logging.FileHandler(_log)) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=_handlers) pack_hmi_data()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import argparse
def _parse_args(): parser = argparse.ArgumentParser(description='Pack original FITS images to HDF5 using the published experiment preprocessing.') parser.add_argument('--input-dir', required=True, help='Directory containing original FITS files (nonrecursive).') parser.add_argument('--output', required=True, help='Output HDF5 path.') parser.add_argument('--log-file', default=None, help='Optional log path; otherwise log to the console only.') parser.add_argument('--resume', action='store_true', help='Append using the original 2014-2016 AIA resume logic.') parser.add_argument('--overwrite', action='store_true', help='Explicitly allow replacement for non-resumable packers.') return parser.parse_args()if __name__ == '__main__': _args = _parse_args()import osimport globimport h5pyimport numpy as npimport cv2from datetime import datetimefrom tqdm import tqdmimport loggingimport warningsfrom astropy.utils.iers import confconf.auto_download = Falseimport sunpy.mapwarnings.filterwarnings('ignore')HMI_DIR = NoneOUTPUT_H5 = NoneTARGET_SIZE = (512, 512)LOG_FILE = NoneCLIP_MIN = -3000.0CLIP_MAX = 3000.0
def get_time_from_hmi(fname): """解析 HMI 文件名: hmi.M_720s.20110101_000000_TAI.1.magnetogram.fits""" try: time_str = os.path.basename(fname).split('.')[2][:15] return datetime.strptime(time_str, '%Y%m%d_%H%M%S') except Exception as e: return None
def pack_hmi_data(): logging.info(f'🚀 开始扫描 {HMI_DIR} 中的 HMI 磁图...') all_fits = glob.glob(os.path.join(HMI_DIR, '*.fits')) valid_files = [] for f in all_fits: dt = get_time_from_hmi(f) if dt: valid_files.append((dt, f)) valid_files.sort(key=lambda x: x[0]) logging.info(f'✅ 扫描完成!共发现 {len(valid_files)} 个 HMI 样本。即将开始打包...') with h5py.File(OUTPUT_H5, 'w') as h5f: dataset = h5f.create_dataset('images', shape=(len(valid_files), 1, *TARGET_SIZE), dtype=np.float32, chunks=(1, 1, *TARGET_SIZE), compression='gzip') times_db = h5f.create_dataset('times', shape=(len(valid_files),), dtype='S20') pbar = tqdm(valid_files, desc='HMI打包进度', dynamic_ncols=True) for (i, (dt, file_path)) in enumerate(pbar): if i % 100 == 0: logging.info(f'当前进度: {i}/{len(valid_files)} - 正在处理: {dt.isoformat()}') try: smap = sunpy.map.Map(file_path, memmap=False) img = smap.data img = np.nan_to_num(img, nan=0.0, posinf=0.0, neginf=0.0) img = np.clip(img, CLIP_MIN, CLIP_MAX) img_resized = cv2.resize(img, (TARGET_SIZE[1], TARGET_SIZE[0]), interpolation=cv2.INTER_AREA) dataset[i, 0, :, :] = img_resized.astype(np.float32) times_db[i] = dt.isoformat().encode('ascii') except Exception as e: logging.error(f'⚠️ 读取 {file_path} 失败: {e}') logging.info(f'🎉 HMI 磁图全部打包完成!文件已生成:{OUTPUT_H5}')if __name__ == '__main__': from pathlib import Path _input = Path(_args.input_dir).expanduser().resolve() _output = Path(_args.output).expanduser().resolve() if not _input.is_dir(): raise SystemExit('Input FITS directory does not exist: ' + str(_input)) if _args.resume and _args.overwrite: raise SystemExit('Use either --resume or --overwrite, not both.') if _args.resume: raise SystemExit('This packer does not support resume.') if _output.exists() and (not _args.overwrite): raise SystemExit('Output exists; use a new path or explicit --overwrite.') HMI_DIR = str(_input) OUTPUT_H5 = str(_output) LOG_FILE = _args.log_file _output.parent.mkdir(parents=True, exist_ok=True) _handlers = [logging.StreamHandler()] if LOG_FILE: _log = Path(LOG_FILE).expanduser().resolve() _log.parent.mkdir(parents=True, exist_ok=True) _handlers.append(logging.FileHandler(_log)) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', handlers=_handlers) pack_hmi_data()123456789101112131415"""One entry from existing AIA/HMI HDF5 files to corrected binary A/B manifests."""import argparse,pathlib,subprocess,sysfrom align_hdf5 import build_index
def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',nargs=3,action='append',required=True,metavar=('PERIOD','AIA_H5','HMI_H5'));p.add_argument('--events',required=True);p.add_argument('--output',required=True);p.add_argument('--setting',choices=['A','B','all'],default='all');p.add_argument('--tolerance',default='30min');p.add_argument('--time-unit',choices=['s','ms','us','ns']);p.add_argument('--coverage-start',required=True);p.add_argument('--coverage-end',required=True);p.add_argument('--reference-root',help='Optional published manifests root; require exact sample/label/sequence agreement before reusing its manifest ID');args=p.parse_args() out=pathlib.Path(args.output) if out.exists():raise FileExistsError(out) frame,reports=build_index(args.source,args.tolerance,args.time_unit);out.mkdir(parents=True);index=out/'aligned_index.csv';frame.to_csv(index,index=False) script=pathlib.Path(__file__).resolve().with_name('preprocess.py') for setting in ['A','B']if args.setting=='all'else[args.setting]: cmd=[sys.executable,'-B',str(script),'--index',str(index),'--events',args.events,'--setting',setting,'--output',str(out/setting),'--coverage-start',args.coverage_start,'--coverage-end',args.coverage_end] if args.reference_root:cmd.extend(['--reference-manifest',str(pathlib.Path(args.reference_root)/setting)]) subprocess.run(cmd,check=True)if __name__=='__main__':main()12345678910111213141516171819202122import pathlib,sys,argparse,json,hashlibsys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]/'src'))from binaryforecast.api import ROOTfrom binaryforecast.core.utils.vendor.protocol import specification,annotate,verify_frames,eligiblefrom binaryforecast.core.utils.vendor.surya_labels import event_targetsimport pandas as pdp=argparse.ArgumentParser(description='Existing aligned HDF5 index + GOES event catalogue -> binary A/B manifests; no second rolling labels.');p.add_argument('--index',required=True);p.add_argument('--events',required=True);p.add_argument('--setting',choices=['A','B'],required=True);p.add_argument('--output',required=True);p.add_argument('--reference-manifest');p.add_argument('--coverage-start',required=True);p.add_argument('--coverage-end',required=True);args=p.parse_args()f=pd.read_csv(args.index);f['timestamp']=pd.to_datetime(f.timestamp);assert f.timestamp.is_uniquelabels,_=event_targets(f.timestamp,pd.read_csv(args.events),24,args.coverage_start,args.coverage_end);f=f.drop(columns=[c for c in labels if c!='timestamp'and c in f]);f=f.merge(labels,on='timestamp',validate='one_to_one');f['target_binary']=(f.max_flare_rank>=2).astype(int)bounds=[['2011-01-01','2013-07-01'],['2013-07-01','2014-01-01'],['2014-01-01','2015-01-01']]if args.setting=='A'else[['2011-01-01','2014-01-01'],['2014-01-01','2015-01-01'],['2015-01-01','2017-01-01']];spec=specification([-4,-3,-2,-1,0],24);frames={}for i,(split,(start,end))in enumerate(zip(['train','validation','test'],bounds)): cutoff=pd.Timestamp(end)-pd.Timedelta(hours=96)if i<2 else pd.Timestamp(end);part=f[(f.timestamp>=start)&(f.timestamp<cutoff)].copy() for c in ['aia_h5','hmi_h5']:part[c]=part[c].map(lambda x:pathlib.Path(str(x)).name) frames[split]=annotate(part,spec,start,end)verify_frames(frames,spec);out=pathlib.Path(args.output);out.mkdir(parents=True,exist_ok=False);files={}for split,frame in frames.items(): path=out/(split+'_frames.csv');frame.to_csv(path,index=False);files[path.name]=hashlib.sha256(path.read_bytes()).hexdigest()if args.reference_manifest: reference=pathlib.Path(args.reference_manifest) for split,f in frames.items(): expected=pd.read_csv(reference/(split+'_frames.csv'));cols=['sample_id','target_binary','sequence_valid','sequence_indices'];assert f[cols].reset_index(drop=True).equals(expected[cols].reset_index(drop=True)),splitprotocol={'input':spec,'bounds':bounds,'tail_buffer_hours':96,'label_col':'target_binary'};ident=hashlib.sha256(json.dumps({'protocol':protocol,'files':files},sort_keys=True).encode()).hexdigest();ident=json.loads((pathlib.Path(args.reference_manifest)/'manifest.json').read_text())['manifest_id']if args.reference_manifest else ident;(out/'manifest.json').write_text(json.dumps({'schema':'portable_binary_v1','manifest_id':ident,'protocol':protocol,'files':files},indent=2));print(json.dumps({'samples':{s:len(eligible(x))for s,x in frames.items()},'manifest_id':ident}))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{ "schema": "portable_binary_v1", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "protocol": { "input": { "version": "twoclass_event_binary_v1", "offset_hours": [ -4.0, -3.0, -2.0, -1.0, 0.0 ], "seq_len": 5, "horizon_hours": 24, "tolerance_minutes": 0.0, "modalities": [ "aia", "hmi" ], "label_interval": "(t,t+P]", "split_interval": "[S,E)", "period_crossing_allowed": false, "missing_input_policy": "exclude", "utc_naive_source_assumption": true, "label_basis": "GOES event_starttime in (t,t+P]; binary iff maximum physical GOES flux >=1e-5 W/m2" }, "bounds": [ [ "2011-01-01", "2013-07-01" ], [ "2013-07-01", "2014-01-01" ], [ "2014-01-01", "2015-01-01" ] ], "tail_buffer_hours": 96, "label_col": "target_binary" }, "files": { "train_frames.csv": "87ca3673b85cf67477635eab5f1f816475f7003b08ca6b1a49629c90786f308b", "validation_frames.csv": "4d0caacf8994ce41cfb9d7cbff244255056d939e3bfa619a56d3dc91f3ec0bb3", "test_frames.csv": "67749bebbc0c019e121291367f10e2213d1e6063f2517d7f886cb5ba0f3be68a" }}123version https://git-lfs.github.com/spec/v1oid sha256:87ca3673b85cf67477635eab5f1f816475f7003b08ca6b1a49629c90786f308bsize 121999491234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950{ "schema": "portable_binary_v1", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "protocol": { "input": { "version": "twoclass_event_binary_v1", "offset_hours": [ -4.0, -3.0, -2.0, -1.0, 0.0 ], "seq_len": 5, "horizon_hours": 24, "tolerance_minutes": 0.0, "modalities": [ "aia", "hmi" ], "label_interval": "(t,t+P]", "split_interval": "[S,E)", "period_crossing_allowed": false, "missing_input_policy": "exclude", "utc_naive_source_assumption": true, "label_basis": "GOES event_starttime in (t,t+P]; binary iff maximum physical GOES flux >=1e-5 W/m2" }, "bounds": [ [ "2011-01-01", "2014-01-01" ], [ "2014-01-01", "2015-01-01" ], [ "2015-01-01", "2017-01-01" ] ], "tail_buffer_hours": 96, "label_col": "target_binary" }, "files": { "train_frames.csv": "3ea9127e8f8f1a153d0efb084a30a1e6b156514bb77c4439fe2fd2ce36e7e9ae", "validation_frames.csv": "1de13a712df76a47c890b3f5da2474018098a2112f6d635d48576482192ef096", "test_frames.csv": "823c0544d02d9041dbf7ddafff0977ea8c195e67ef8b45b80020af18875a523c" }}123version https://git-lfs.github.com/spec/v1oid sha256:3ea9127e8f8f1a153d0efb084a30a1e6b156514bb77c4439fe2fd2ce36e7e9aesize 147149381{"A": "manifests/A", "B": "manifests/B"}123456789101112131415{ "id": "A/HMI2D/seed42", "weight_sha256": "99e69453d5b402916c74dc513feb38b28cb4b92322b98b3eb0ec8be38d614880", "args": { "temporal": false, "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "lr": 0.0001, "batch_size": 16, "epochs": 30, "label_col": "target_binary", "weight_decay": 0.0, "modality": "HMI", "seed": 42 }}123version https://git-lfs.github.com/spec/v1oid sha256:99e69453d5b402916c74dc513feb38b28cb4b92322b98b3eb0ec8be38d614880size 65650281234567891011121314151617{ "id": "A/HMI3D_CTL/seed42", "weight_sha256": "e3a4e3c874279b92674e5e065309fce1a3691001f4401a97c85bc0616008cfa0", "args": { "temporal": true, "con_temperature": 0.2, "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "lr": 0.0001, "batch_size": 4, "epochs": 30, "label_col": "target_binary", "seed": 42, "weight_decay": 0.0001, "modality": "HMI", "lambda_con": 0.001 }}123version https://git-lfs.github.com/spec/v1oid sha256:e3a4e3c874279b92674e5e065309fce1a3691001f4401a97c85bc0616008cfa0size 19101092123456789101112131415{ "id": "A/MDT2D/seed42", "weight_sha256": "f10b85bb77950c6a34f10376be0628c331195b475c6afedc1c3e160bd9499f34", "args": { "temporal": false, "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "lr": 0.0001, "batch_size": 8, "epochs": 30, "label_col": "target_binary", "weight_decay": 0.0, "modality": "BOTH", "seed": 42 }}123version https://git-lfs.github.com/spec/v1oid sha256:f10b85bb77950c6a34f10376be0628c331195b475c6afedc1c3e160bd9499f34size 135489301234567891011121314151617181920212223{ "id": "A/dual_selected_logit_KD/seed42", "weight_sha256": "7bf5ab873287389cef10c45194507e9643edcec347acfda8c69b7d9e80b87269", "args": { "warmup_start": 5, "temporal": false, "temperature": 4.0, "lr": 0.0001, "warmup_epochs": 10, "seed": 42, "grad_clip": 0.0, "warmup": false, "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "batch_size": 16, "epochs": 30, "label_col": "target_binary", "weight_mdt": 0.3, "weight_decay": 0.0, "lambda_kd": 0.5, "weight_ctl": 0.7, "modality": "HMI" }}123version https://git-lfs.github.com/spec/v1oid sha256:7bf5ab873287389cef10c45194507e9643edcec347acfda8c69b7d9e80b87269size 6565028123456789101112131415{ "id": "B/HMI2D/seed42", "weight_sha256": "29e4afd333bfdf75db92c6f8df7e1ddbc968254ddc66b669c5b895030ba4943f", "args": { "temporal": false, "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "lr": 0.0001, "batch_size": 16, "epochs": 30, "label_col": "target_binary", "weight_decay": 0.0, "modality": "HMI", "seed": 42 }}123version https://git-lfs.github.com/spec/v1oid sha256:29e4afd333bfdf75db92c6f8df7e1ddbc968254ddc66b669c5b895030ba4943fsize 65650281234567891011121314151617{ "id": "B/HMI3D_CTL/seed42", "weight_sha256": "730d72516115bb0dee8f4e0e3d9c0cf187d752a5334f837143478b48c1136c17", "args": { "temporal": true, "con_temperature": 0.1, "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "lr": 0.0001, "batch_size": 4, "epochs": 30, "label_col": "target_binary", "seed": 42, "weight_decay": 0.0001, "modality": "HMI", "lambda_con": 0.005 }}123version https://git-lfs.github.com/spec/v1oid sha256:730d72516115bb0dee8f4e0e3d9c0cf187d752a5334f837143478b48c1136c17size 19101092123456789101112131415{ "id": "B/MDT2D/seed42", "weight_sha256": "19eb42d1ef36da977497de9329a792654509b99ef7b48f69a5871c8fa891ea80", "args": { "temporal": false, "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "lr": 0.0001, "batch_size": 8, "epochs": 30, "label_col": "target_binary", "weight_decay": 0.0, "modality": "BOTH", "seed": 42 }}123version https://git-lfs.github.com/spec/v1oid sha256:19eb42d1ef36da977497de9329a792654509b99ef7b48f69a5871c8fa891ea80size 135489301234567891011121314151617181920212223{ "id": "B/dual_selected_logit_KD/seed42", "weight_sha256": "bf6b4a0431d02d82f0836d8288718a74fa41878f95b093567583696d3bd5b60d", "args": { "warmup_start": 5, "temporal": false, "temperature": 4.0, "lr": 0.0001, "warmup_epochs": 10, "seed": 42, "grad_clip": 0.0, "warmup": false, "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "batch_size": 16, "epochs": 30, "label_col": "target_binary", "weight_mdt": 0.2, "weight_decay": 0.0, "lambda_kd": 0.5, "weight_ctl": 0.8, "modality": "HMI" }}123version https://git-lfs.github.com/spec/v1oid sha256:bf6b4a0431d02d82f0836d8288718a74fa41878f95b093567583696d3bd5b60dsize 656502812345678910[build-system]requires = ["setuptools>=61"]build-backend = "setuptools.build_meta"[project]name = "binary-solar-forecast"version = "0.1.0"description = "Corrected-data binary solar flare forecasting: server working release"requires-python = ">=3.10"[tool.setuptools.packages.find]where = ["src"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130[ { "id": "A/HMI2D/seed42", "setting": "A", "family": "HMI2D", "seed": 42, "kind": "baseline", "modality": "HMI", "temporal": false, "architecture": "cnn", "weight": "models/A/HMI2D_seed42.pth", "weight_sha256": "99e69453d5b402916c74dc513feb38b28cb4b92322b98b3eb0ec8be38d614880", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "training_module": "binaryforecast.training.baseline.supervised", "weight_available": true, "metadata": "models/A/HMI2D_seed42.json" }, { "id": "A/MDT2D/seed42", "setting": "A", "family": "MDT2D", "seed": 42, "kind": "mdt", "modality": "BOTH", "temporal": false, "architecture": "mdt", "weight": "models/A/MDT2D_seed42.pth", "weight_sha256": "f10b85bb77950c6a34f10376be0628c331195b475c6afedc1c3e160bd9499f34", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "training_module": "binaryforecast.training.teacher.mdt", "weight_available": true, "metadata": "models/A/MDT2D_seed42.json" }, { "id": "A/HMI3D_CTL/seed42", "setting": "A", "family": "HMI3D_CTL", "seed": 42, "kind": "ctl", "modality": "HMI", "temporal": true, "architecture": "cnn", "weight": "models/A/HMI3D_CTL_seed42.pth", "weight_sha256": "e3a4e3c874279b92674e5e065309fce1a3691001f4401a97c85bc0616008cfa0", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "training_module": "binaryforecast.training.teacher.ctl", "weight_available": true, "metadata": "models/A/HMI3D_CTL_seed42.json" }, { "id": "A/dual_selected_logit_KD/seed42", "setting": "A", "family": "dual_selected_logit_KD", "seed": 42, "kind": "dual", "modality": "HMI", "temporal": false, "architecture": "cnn", "weight": "models/A/dual_selected_logit_KD_seed42.pth", "weight_sha256": "7bf5ab873287389cef10c45194507e9643edcec347acfda8c69b7d9e80b87269", "manifest_id": "c2e455420a780a086e4f3d77b996f2c43ed21802aed9d63edf260859a7a9644e", "training_module": "binaryforecast.training.kd.dual_teacher", "weight_available": true, "metadata": "models/A/dual_selected_logit_KD_seed42.json" }, { "id": "B/HMI2D/seed42", "setting": "B", "family": "HMI2D", "seed": 42, "kind": "baseline", "modality": "HMI", "temporal": false, "architecture": "cnn", "weight": "models/B/HMI2D_seed42.pth", "weight_sha256": "29e4afd333bfdf75db92c6f8df7e1ddbc968254ddc66b669c5b895030ba4943f", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "training_module": "binaryforecast.training.baseline.supervised", "weight_available": true, "metadata": "models/B/HMI2D_seed42.json" }, { "id": "B/MDT2D/seed42", "setting": "B", "family": "MDT2D", "seed": 42, "kind": "mdt", "modality": "BOTH", "temporal": false, "architecture": "mdt", "weight": "models/B/MDT2D_seed42.pth", "weight_sha256": "19eb42d1ef36da977497de9329a792654509b99ef7b48f69a5871c8fa891ea80", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "training_module": "binaryforecast.training.teacher.mdt", "weight_available": true, "metadata": "models/B/MDT2D_seed42.json" }, { "id": "B/HMI3D_CTL/seed42", "setting": "B", "family": "HMI3D_CTL", "seed": 42, "kind": "ctl", "modality": "HMI", "temporal": true, "architecture": "cnn", "weight": "models/B/HMI3D_CTL_seed42.pth", "weight_sha256": "730d72516115bb0dee8f4e0e3d9c0cf187d752a5334f837143478b48c1136c17", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "training_module": "binaryforecast.training.teacher.ctl", "weight_available": true, "metadata": "models/B/HMI3D_CTL_seed42.json" }, { "id": "B/dual_selected_logit_KD/seed42", "setting": "B", "family": "dual_selected_logit_KD", "seed": 42, "kind": "dual", "modality": "HMI", "temporal": false, "architecture": "cnn", "weight": "models/B/dual_selected_logit_KD_seed42.pth", "weight_sha256": "bf6b4a0431d02d82f0836d8288718a74fa41878f95b093567583696d3bd5b60d", "manifest_id": "992fe89273f3a8416e55fcc8f95a1a4320674290700188235d4bf4d0d161bbb0", "training_module": "binaryforecast.training.kd.dual_teacher", "weight_available": true, "metadata": "models/B/dual_selected_logit_KD_seed42.json" }]12345-r requirements.txtastropysunpy[map]scikit-imageopencv-python-headless123456torch==2.5.1+cu121numpy==2.2.6pandas==2.3.3scikit-learn==1.7.2h5py==3.16.0tqdm==4.67.3123import pathlib,syssys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]/'src'))from binaryforecast.api import *123456789101112"""Frozen inference on preprocessed tensor inputs, not raw magnetograms."""import argparse,jsonfrom common import *p=argparse.ArgumentParser(description=__doc__);p.add_argument('--artifact',required=True);p.add_argument('--input',required=True,help='torch tensor dictionary: HMI and/or AIA');p.add_argument('--output',default='predictions.npz');p.add_argument('--device',default='cpu');p.add_argument('--checkpoint-root');p.add_argument('--run-tag');args=p.parse_args()import torch,numpy as npa=artifact(args.artifact);model=load_model(a,args.device,args.checkpoint_root,args.run_tag);batch=torch.load(args.input,map_location='cpu',weights_only=True)with torch.inference_mode(): if a['architecture']=='mdt':logits=model(batch['AIA'].to(args.device),batch['HMI'].to(args.device))[0] elif a['temporal']:logits=model(batch[a['modality']].to(args.device),return_features=False) else:logits=model(batch[a['modality']].to(args.device)) assert logits.ndim==2 and logits.shape[1]==2 and torch.isfinite(logits).all();prob=logits.softmax(-1).cpu().numpy()out=output_path(args.output);np.savez(out,logits=logits.cpu().numpy(),probabilities=prob,predictions=(prob[:,1]>=.5).astype(int));print(json.dumps({'artifact':a['id'],'output':str(out),'n':len(prob)}))123456789101112131415161718192021222324252627import argparse,os,json,pathlib,importlibfrom common import *p=argparse.ArgumentParser();p.add_argument('--artifact');p.add_argument('--setting',choices=['A','B']);p.add_argument('--method',choices=sorted({a['family']for a in experiments()}));p.add_argument('--seed',type=int,choices=[42,2024,3407],default=42);p.add_argument('--phase',choices=['train','evaluate'],default='train');p.add_argument('--gpu',default='0');p.add_argument('--data-root');p.add_argument('--path-map');p.add_argument('--cache-dir');p.add_argument('--checkpoint-root',help='Optional local checkpoint store, SETTING/METHOD_seedN.pth plus .json training record');p.add_argument('--run-tag',default='reproduction');p.add_argument('--check-dependencies',action='store_true');p.add_argument('--execute',action='store_true');args=p.parse_args()if args.artifact: if args.setting or args.method:p.error('Use either --artifact or --setting/--method') a=artifact(args.artifact)else: if not args.setting or not args.method:p.error('--setting and --method required') a=artifact(f'{args.setting}/{args.method}/seed{args.seed}')plan=build_plan(a['setting'],a['family'],a['seed'],args.run_tag,args.checkpoint_root,resolve=args.check_dependencies or args.execute and args.phase=='train');j=plan['jobs'][0];out=run_directory(a['id'],args.run_tag)print(json.dumps({'artifact':a['id'],'execute':args.execute,'output':str(out),'dependencies':plan['dependencies']}))if not args.execute:raise SystemExit(0)if not args.data_root and not args.path_map:p.error('Specify --data-root or --path-map')if args.phase=='train'and a['kind']in ['single','dual']and not args.cache_dir:p.error('Specify --cache-dir; first run data/extract_cache.py with the same --run-tag/--checkpoint-root')os.environ['CUDA_VISIBLE_DEVICES']=args.gpuif args.data_root:os.environ['BINARY_DATA_ROOT']=args.data_rootif args.path_map:os.environ['BINARY_PATH_MAP']=pathlib.Path(args.path_map).read_text()module=importlib.import_module(a['training_module']);module.ROOT=out;module.HERE=out;module.PLAN=plan;out.mkdir(exist_ok=True,parents=True)for name in ['logs','checkpoints']:(out/name).mkdir(exist_ok=True)if args.cache_dir:module.CACHE_ROOT=pathlib.Path(args.cache_dir).resolve()if args.phase=='train': module.train(plan,j) weight=export_checkpoint(a['id'],out/'checkpoints'/j['run_name']/'best_model_state.pth',out/'logs'/j['run_name']/'training_complete.json',args.run_tag);print(json.dumps({'exported_checkpoint':weight}))else: paths=[out/'logs'/j['run_name']/'training_complete.json',out/'checkpoints'/j['run_name']/'best_model_state.pth'];assert all(x.exists()for x in paths);frozen={'files':{str(x):sha(x)for x in paths}} for name in ['frozen_training_results.json',j['id']+'.frozen_training_results.json']:(out/name).write_text(json.dumps(frozen)) module.evaluate(plan,j)1from .api import artifact, registry, load_model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import pathlib,json,hashlib,shutilROOT=pathlib.Path(__file__).resolve().parents[2]
def sha(path): h=hashlib.sha256() with pathlib.Path(path).open('rb')as f: for block in iter(lambda:f.read(1024*1024),b''):h.update(block) return h.hexdigest()
def registry():return json.loads((ROOT/'registry.json').read_text())def experiments(): common=_read(ROOT/'configs/training.json');published={a['id']:a for a in registry()};items=[] for setting in ['A','B']: specific=_read(ROOT/'configs'/('setting'+setting+'.json')) for method,spec in common['methods'].items(): params={**common['defaults'],**spec['parameters'],**specific.get('method_overrides',{}).get(method,{})} for seed in common['seeds']: ident=f'{setting}/{method}/seed{seed}' a={'id':ident,'setting':setting,'family':method,'seed':seed,'manifest_id':specific['manifest_id'],'modality':params['modality'],'temporal':params['temporal'],**spec['model'],'weight':None,'weight_available':False} a.update(published.get(ident,{}));items.append(a) return itemsdef artifact(ident): for a in experiments(): if a['id']==ident:return a raise ValueError('Unknown experiment: '+ident)
def output_path(name): p=(ROOT/'runs'/name).resolve() if not p.is_relative_to((ROOT/'runs').resolve()):raise ValueError('Output must stay inside runs/') p.parent.mkdir(parents=True,exist_ok=True);return p
def run_directory(ident,run_tag='reproduction'): p=(ROOT/'runs'/run_tag/ident).resolve() if not p.is_relative_to((ROOT/'runs').resolve()):raise ValueError('Invalid run tag') return p
def _read(path):return json.loads(pathlib.Path(path).read_text())def resolve_checkpoint(ident,checkpoint_root=None,run_tag=None): """Prefer explicitly supplied/retrained models; then use published seed42 weights.""" a=artifact(ident);setting,method,seed=ident.split('/');name=method+'_'+seed;candidates=[] if checkpoint_root: folder=pathlib.Path(checkpoint_root).expanduser().resolve()/setting;candidates.append((folder/(name+'.pth'),folder/(name+'.json'),False)) if run_tag: folder=ROOT/'runs'/run_tag/'weights'/setting;candidates.append((folder/(name+'.pth'),folder/(name+'.json'),False)) if a.get('weight'):candidates.append((ROOT/a['weight'],ROOT/a['metadata'],True)) for weight,record,published in candidates: if not weight.exists():continue if not record.exists():raise FileNotFoundError('Checkpoint training record missing: '+str(record)) meta=_read(record);args=meta['args'] if args['seed']!=a['seed']or args['manifest_id']!=a['manifest_id']or args['label_col']!='target_binary' or args['modality']!=a['modality']or args['temporal']!=a['temporal']:raise ValueError('Checkpoint/configuration mismatch: '+ident) common=_read(ROOT/'configs/training.json');specific=_read(ROOT/'configs'/('setting'+setting+'.json')) expected={**common['defaults'],**common['methods'][method]['parameters'],**specific.get('method_overrides',{}).get(method,{})} for key,value in expected.items(): if args.get(key)!=value:raise ValueError('Checkpoint hyperparameter mismatch: '+ident+' / '+key) if a['kind']=='baseline' and (args.get('lambda_con',0)>0 or args.get('lambda_kd',0)>0 or args.get('lambda_logits',0)>0 or args.get('lambda_feature',0)>0):raise ValueError('A distilled/CTL checkpoint cannot be used as a supervised baseline: '+ident) digest=sha(weight) if meta.get('weight_sha256',digest)!=digest:raise ValueError('Checkpoint metadata hash differs: '+ident) if published and digest!=a['weight_sha256']:raise ValueError('Published checkpoint hash differs: '+ident) return {'id':ident,'path':str(weight),'training_record':str(record),'sha256':digest,'published':published} raise FileNotFoundError('Missing prerequisite '+ident+'. Train it first using the same --run-tag, or supply --checkpoint-root with '+setting+'/'+name+'.pth and matching .json training record.')
def load_model(a,device='cpu',checkpoint_root=None,run_tag=None): from binaryforecast.core.model import build_model from binaryforecast.core.model import build_mdt from binaryforecast.core.utils.experiment import load_state_dict_file entry=resolve_checkpoint(a['id'],checkpoint_root,run_tag) m=build_mdt(a['temporal'])if a['architecture']=='mdt'else build_model(a['modality'],a['temporal']) m.load_state_dict(load_state_dict_file(entry['path'],__import__('torch').device('cpu')),strict=True) return m.to(device).eval().requires_grad_(False)
def build_plan(setting,method,seed=42,run_tag='reproduction',checkpoint_root=None,resolve=True): common=_read(ROOT/'configs/training.json');specific=_read(ROOT/'configs'/('setting'+setting+'.json')) if seed not in common['seeds']:raise ValueError('Unsupported seed') spec=common['methods'][method];job={**common['defaults'],**spec['parameters'],**specific.get('method_overrides',{}).get(method,{})};job.update(id=f'{method}_{seed}',family=method,seed=seed,run_name=f'{method}_seed{seed}_setting{setting}') if not isinstance(job['epochs'],int)or isinstance(job['epochs'],bool)or job['epochs']<1:raise ValueError('epochs must be a positive integer') ident=f'{setting}/{method}/seed{seed}';a=artifact(ident);dep_ids=[f'{setting}/{name}/seed{seed}'for name in spec.get('dependencies',[])] plan={'setting':setting,'manifest_id':specific['manifest_id'],'manifest_dir':str(ROOT/specific['manifest_dir']),'sample_counts':specific['sample_counts'],'jobs':[job],'dependencies':dep_ids} initial=spec.get('initial_state_model') if initial:job['baseline_initial_sha256']=specific['initial_state_sha256'][initial][str(seed)] if a['kind']in ['single','dual']:job['cache_id']=f'{setting}_'+('_'.join(spec['dependencies']))+f'_{seed}' if resolve: deps={name:resolve_checkpoint(f'{setting}/{name}/seed{seed}',checkpoint_root,run_tag)for name in spec.get('dependencies',[])} if a['kind']=='mdt':job['initialization']={modality:{k:v for k,v in deps[modality+('3D'if a['temporal']else'2D')].items()if k in ['path','training_record','sha256']}for modality in ['AIA','HMI']} elif a['kind']=='single': teacher=deps[spec['dependencies'][0]];job.update(teacher_checkpoint=teacher['path'],teacher_record=teacher['training_record'],teacher_sha256=teacher['sha256']) elif a['kind']=='dual':job['teacher_shas']={'mdt':deps['MDT2D']['sha256'],'ctl':deps['HMI3D_CTL']['sha256']} return plan
def export_checkpoint(ident,checkpoint,training_record,run_tag='reproduction'): a=artifact(ident);setting,method,seed=ident.split('/');folder=ROOT/'runs'/run_tag/'weights'/setting if not folder.resolve().is_relative_to((ROOT/'runs').resolve()):raise ValueError('Invalid run tag') folder.mkdir(parents=True,exist_ok=True);weight=folder/(method+'_'+seed+'.pth');record=weight.with_suffix('.json') if weight.exists()or record.exists():raise FileExistsError('Export already exists: '+str(weight)) meta=_read(training_record);meta.update(id=ident,weight_sha256=sha(checkpoint)) shutil.copyfile(checkpoint,weight);record.write_text(json.dumps(meta,indent=2));return str(weight)
def metrics(): from binaryforecast.core.utils.binary_metrics import binary return binary1
123456789101112"""Loss API shared by baseline, teacher and KD training."""from .focal import FocalLoss, build_class_weightsfrom .mdt import SquaredMDTLoss, squared_orthogonalityfrom .ctl import SupConLoss, anchor_diagnosticsfrom .kd import LogitsKDLoss, DualTeacherKDLoss, logits_kd, feature_kd, kd_warmup_lambda
__all__ = [ 'FocalLoss', 'build_class_weights', 'SquaredMDTLoss', 'squared_orthogonality', 'SupConLoss', 'anchor_diagnostics', 'LogitsKDLoss', 'DualTeacherKDLoss', 'logits_kd', 'feature_kd', 'kd_warmup_lambda',].gitattributes+2
.gitignoreAdded+4
README.mdAdded+195
configs/settingA.jsonAdded+22
configs/settingB.jsonAdded+31
configs/training.jsonAdded+341
data/align_hdf5.pyAdded+54
data/extract_cache.pyAdded+31
data/pack_aia_2014_2016.pyAdded+156
data/pack_aia_3_2011_2013.pyAdded+92
data/pack_hmi_2011_2013.pyAdded+89
data/pack_hmi_2014_2016.pyAdded+91
data/prepare.pyAdded+15
data/preprocess.pyAdded+22
manifests/A/manifest.jsonAdded+50
manifests/A/test_frames.csvAdded
manifests/A/train_frames.csvAdded+3
manifests/A/validation_frames.csvAdded
manifests/B/manifest.jsonAdded+50
manifests/B/test_frames.csvAdded
manifests/B/train_frames.csvAdded+3
manifests/B/validation_frames.csvAdded
manifests/index.jsonAdded+1
models/A/HMI2D_seed42.jsonAdded+15
models/A/HMI2D_seed42.pthAdded+3
models/A/HMI3D_CTL_seed42.jsonAdded+17
models/A/HMI3D_CTL_seed42.pthAdded+3
models/A/MDT2D_seed42.jsonAdded+15
models/A/MDT2D_seed42.pthAdded+3
models/A/dual_selected_logit_KD_seed42.jsonAdded+23
models/A/dual_selected_logit_KD_seed42.pthAdded+3
models/B/HMI2D_seed42.jsonAdded+15
models/B/HMI2D_seed42.pthAdded+3
models/B/HMI3D_CTL_seed42.jsonAdded+17
models/B/HMI3D_CTL_seed42.pthAdded+3
models/B/MDT2D_seed42.jsonAdded+15
models/B/MDT2D_seed42.pthAdded+3
models/B/dual_selected_logit_KD_seed42.jsonAdded+23
models/B/dual_selected_logit_KD_seed42.pthAdded+3
pyproject.tomlAdded+10
registry.jsonAdded+130
requirements-preprocess.txtAdded+5
requirements.txtAdded+6
scripts/common.pyAdded+3
scripts/predict.pyAdded+12
scripts/run_experiment.pyAdded+27
src/binaryforecast/__init__.pyAdded+1
src/binaryforecast/api.pyAdded+99
src/binaryforecast/core/__init__.pyAdded+1
src/binaryforecast/core/loss/__init__.pyAdded+12