Commit ·
a92ca42
1
Parent(s): 57e33cc
bug fixes for windows users... make sure timestamps are formatted properly
Browse files- .gitattributes +2 -0
- .github/workflows/compatibility.yml +1 -0
- data/_timestamps.py +13 -0
- data/align_aia_sxr.py +24 -25
- data/clean_aia.py +6 -5
- data/convert_aia.py +2 -3
- download/download_sdo.py +8 -2
- download/hugging_face_data_download.py +3 -0
- forecasting/dataset.py +4 -4
- forecasting/evaluation.py +5 -4
- forecasting/inference.py +5 -3
- helio_foxes/api.py +3 -2
- tests/test_aia_calibration.py +4 -0
- tests/test_evaluation_patch_maps.py +13 -5
- tests/test_hf_download.py +5 -3
- tests/test_public_api.py +4 -3
- tests/test_sxr_combiner.py +25 -2
- tests/test_training_expansion.py +15 -6
.gitattributes
CHANGED
|
@@ -6,5 +6,7 @@ model_assets/results/evaluation/plots/*.png -filter -diff -merge -text
|
|
| 6 |
foxes_logo.png filter=lfs diff=lfs merge=lfs -text
|
| 7 |
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 8 |
tutorials/heliofoxes_demo/saved_observations/*.npz filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
| 9 |
docs/_static/foxes-logo.png filter=lfs diff=lfs merge=lfs -text
|
| 10 |
model_assets/*/evaluation/plots/*.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 6 |
foxes_logo.png filter=lfs diff=lfs merge=lfs -text
|
| 7 |
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 8 |
tutorials/heliofoxes_demo/saved_observations/*.npz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
# The packaged calibration snapshot is verified against its upstream SHA-256.
|
| 10 |
+
data/calibration/sdo_autocal_table.csv text eol=lf
|
| 11 |
docs/_static/foxes-logo.png filter=lfs diff=lfs merge=lfs -text
|
| 12 |
model_assets/*/evaluation/plots/*.png filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/compatibility.yml
CHANGED
|
@@ -67,6 +67,7 @@ jobs:
|
|
| 67 |
run: |
|
| 68 |
python -m pytest -q --import-mode=importlib \
|
| 69 |
"$GITHUB_WORKSPACE/tests/test_public_api.py::test_predict_matches_model_outputs" \
|
|
|
|
| 70 |
"$GITHUB_WORKSPACE/tests/test_aia_calibration.py" \
|
| 71 |
"$GITHUB_WORKSPACE/tests/test_harp_uncertainty.py" \
|
| 72 |
"$GITHUB_WORKSPACE/tests/test_sxr_api.py" \
|
|
|
|
| 67 |
run: |
|
| 68 |
python -m pytest -q --import-mode=importlib \
|
| 69 |
"$GITHUB_WORKSPACE/tests/test_public_api.py::test_predict_matches_model_outputs" \
|
| 70 |
+
"$GITHUB_WORKSPACE/tests/test_public_api.py::test_aia_processor_uses_temporary_files_and_returns_stack" \
|
| 71 |
"$GITHUB_WORKSPACE/tests/test_aia_calibration.py" \
|
| 72 |
"$GITHUB_WORKSPACE/tests/test_harp_uncertainty.py" \
|
| 73 |
"$GITHUB_WORKSPACE/tests/test_sxr_api.py" \
|
data/_timestamps.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Timestamp spelling at filesystem boundaries."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_WINDOWS = os.name == "nt"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def timestamp_filename(timestamp: str, suffix: str) -> str:
|
| 10 |
+
"""Keep existing filename conventions while avoiding colons on Windows."""
|
| 11 |
+
if _WINDOWS:
|
| 12 |
+
timestamp = timestamp.replace(":", "")
|
| 13 |
+
return timestamp + suffix
|
data/align_aia_sxr.py
CHANGED
|
@@ -6,18 +6,20 @@ AIA files with no matching SXR value are moved to a "missing" directory.
|
|
| 6 |
|
| 7 |
Called by build_dataset.py — not meant to be run standalone.
|
| 8 |
"""
|
| 9 |
-
import glob
|
| 10 |
import os
|
| 11 |
import re
|
| 12 |
import time
|
| 13 |
import warnings
|
| 14 |
from datetime import datetime
|
| 15 |
from multiprocessing import Pool, cpu_count
|
|
|
|
| 16 |
|
| 17 |
import numpy as np
|
| 18 |
import pandas as pd
|
| 19 |
from tqdm import tqdm
|
| 20 |
|
|
|
|
|
|
|
| 21 |
warnings.filterwarnings('ignore')
|
| 22 |
|
| 23 |
|
|
@@ -143,7 +145,8 @@ def process_batch(batch_data, output_sxr_dir):
|
|
| 143 |
try:
|
| 144 |
sxr_b = data['sxr_b']
|
| 145 |
|
| 146 |
-
|
|
|
|
| 147 |
|
| 148 |
successful_count += 1
|
| 149 |
|
|
@@ -183,18 +186,22 @@ def align_aia_sxr(goes_data_dir, aia_processed_dir, output_sxr_dir, aia_missing_
|
|
| 183 |
print(f"\nFinding target timestamps from AIA files in: {aia_processed_dir}")
|
| 184 |
# Skip macOS AppleDouble sidecar files (e.g. "._2023-08-01T00:00:00.npy")
|
| 185 |
# that external/non-native filesystems litter alongside real files.
|
| 186 |
-
aia_files = sorted(
|
| 187 |
-
if
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
]
|
| 193 |
|
| 194 |
-
print(f"Found {len(
|
| 195 |
|
| 196 |
# Create optimized lookup table
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
if not lookup_data:
|
| 200 |
print("No valid data found for any timestamps!")
|
|
@@ -260,7 +267,7 @@ def align_aia_sxr(goes_data_dir, aia_processed_dir, output_sxr_dir, aia_missing_
|
|
| 260 |
print(f"Available GOES instruments: {sorted(goes_data_dict.keys())}")
|
| 261 |
|
| 262 |
# Report on timestamps that couldn't be processed
|
| 263 |
-
missing_count = len(
|
| 264 |
if missing_count > 0:
|
| 265 |
print(f"\n{missing_count} timestamps had no valid GOES data available")
|
| 266 |
print("This may be due to:")
|
|
@@ -272,23 +279,15 @@ def align_aia_sxr(goes_data_dir, aia_processed_dir, output_sxr_dir, aia_missing_
|
|
| 272 |
print("\nChecking for AIA files with missing GOES data...")
|
| 273 |
print(f"Moving files with missing GOES data to: {aia_missing_dir}")
|
| 274 |
|
| 275 |
-
# Create a set of timestamps that have valid GOES data for faster lookup
|
| 276 |
-
valid_timestamps = {data['timestamp'] for data in lookup_data}
|
| 277 |
-
|
| 278 |
moved_count = 0
|
| 279 |
-
for
|
| 280 |
-
|
| 281 |
-
filename = file.split('/')[-1].split('.')[0]
|
| 282 |
-
timestamp = datetime.fromisoformat(filename).strftime('%Y-%m-%dT%H:%M:%S')
|
| 283 |
-
|
| 284 |
-
if timestamp not in valid_timestamps:
|
| 285 |
try:
|
| 286 |
-
|
| 287 |
-
os.rename(file, target_path)
|
| 288 |
moved_count += 1
|
| 289 |
-
print(f"Moved {
|
| 290 |
except Exception as e:
|
| 291 |
-
print(f"Failed to move {
|
| 292 |
|
| 293 |
print(f"Moved {moved_count} files to {aia_missing_dir}")
|
| 294 |
print("\nDone!")
|
|
|
|
| 6 |
|
| 7 |
Called by build_dataset.py — not meant to be run standalone.
|
| 8 |
"""
|
|
|
|
| 9 |
import os
|
| 10 |
import re
|
| 11 |
import time
|
| 12 |
import warnings
|
| 13 |
from datetime import datetime
|
| 14 |
from multiprocessing import Pool, cpu_count
|
| 15 |
+
from pathlib import Path
|
| 16 |
|
| 17 |
import numpy as np
|
| 18 |
import pandas as pd
|
| 19 |
from tqdm import tqdm
|
| 20 |
|
| 21 |
+
from data._timestamps import timestamp_filename
|
| 22 |
+
|
| 23 |
warnings.filterwarnings('ignore')
|
| 24 |
|
| 25 |
|
|
|
|
| 145 |
try:
|
| 146 |
sxr_b = data['sxr_b']
|
| 147 |
|
| 148 |
+
filename = data.get('filename') or timestamp_filename(timestamp, '.npy')
|
| 149 |
+
np.save(Path(output_sxr_dir) / filename, np.array([sxr_b], dtype=np.float32))
|
| 150 |
|
| 151 |
successful_count += 1
|
| 152 |
|
|
|
|
| 186 |
print(f"\nFinding target timestamps from AIA files in: {aia_processed_dir}")
|
| 187 |
# Skip macOS AppleDouble sidecar files (e.g. "._2023-08-01T00:00:00.npy")
|
| 188 |
# that external/non-native filesystems litter alongside real files.
|
| 189 |
+
aia_files = sorted(path for path in Path(aia_processed_dir).glob('*.npy')
|
| 190 |
+
if path.is_file() and not path.name.startswith('._'))
|
| 191 |
+
aia_timestamps = {
|
| 192 |
+
path: datetime.fromisoformat(path.stem.replace('_', ':')).strftime('%Y-%m-%dT%H:%M:%S')
|
| 193 |
+
for path in aia_files
|
| 194 |
+
}
|
|
|
|
| 195 |
|
| 196 |
+
print(f"Found {len(aia_timestamps)} target timestamps")
|
| 197 |
|
| 198 |
# Create optimized lookup table
|
| 199 |
+
lookup_by_time = {
|
| 200 |
+
row['timestamp']: row
|
| 201 |
+
for row in create_combined_lookup_table(goes_data_dict, list(dict.fromkeys(aia_timestamps.values())))
|
| 202 |
+
}
|
| 203 |
+
lookup_data = [dict(lookup_by_time[timestamp], filename=path.name)
|
| 204 |
+
for path, timestamp in aia_timestamps.items() if timestamp in lookup_by_time]
|
| 205 |
|
| 206 |
if not lookup_data:
|
| 207 |
print("No valid data found for any timestamps!")
|
|
|
|
| 267 |
print(f"Available GOES instruments: {sorted(goes_data_dict.keys())}")
|
| 268 |
|
| 269 |
# Report on timestamps that couldn't be processed
|
| 270 |
+
missing_count = len(aia_timestamps) - len(lookup_data)
|
| 271 |
if missing_count > 0:
|
| 272 |
print(f"\n{missing_count} timestamps had no valid GOES data available")
|
| 273 |
print("This may be due to:")
|
|
|
|
| 279 |
print("\nChecking for AIA files with missing GOES data...")
|
| 280 |
print(f"Moving files with missing GOES data to: {aia_missing_dir}")
|
| 281 |
|
|
|
|
|
|
|
|
|
|
| 282 |
moved_count = 0
|
| 283 |
+
for path, timestamp in aia_timestamps.items():
|
| 284 |
+
if timestamp not in lookup_by_time:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
try:
|
| 286 |
+
os.rename(path, Path(aia_missing_dir) / path.name)
|
|
|
|
| 287 |
moved_count += 1
|
| 288 |
+
print(f"Moved {path} to {aia_missing_dir}")
|
| 289 |
except Exception as e:
|
| 290 |
+
print(f"Failed to move {path}: {e}")
|
| 291 |
|
| 292 |
print(f"Moved {moved_count} files to {aia_missing_dir}")
|
| 293 |
print("\nDone!")
|
data/clean_aia.py
CHANGED
|
@@ -46,11 +46,13 @@ def process_fits_file(file_path):
|
|
| 46 |
if date_obs.tz is not None:
|
| 47 |
date_obs = date_obs.tz_localize(None)
|
| 48 |
wavelength = header['WAVELNTH']
|
| 49 |
-
|
|
|
|
| 50 |
blank = _is_blank(hdu[1].data) # type: ignore[union-attr]
|
| 51 |
quality = pd.to_numeric(pd.Series([header.get('QUALITY')]), errors='coerce').iloc[0]
|
| 52 |
bad_quality = bool(pd.notna(quality) and quality != 0)
|
| 53 |
-
return {'DATE-OBS': date_obs, 'WAVELNTH': wavelength, 'FILENAME':
|
|
|
|
| 54 |
'BLANK': blank, 'BAD_QUALITY': bad_quality}
|
| 55 |
except Exception as e:
|
| 56 |
print(f"Error processing {file_path}: {e}")
|
|
@@ -78,7 +80,7 @@ def clean_aia_data(input_folder, bad_files_dir, wavelengths):
|
|
| 78 |
|
| 79 |
# Add a column for date difference between DATE-OBS and FILENAME
|
| 80 |
aia_header['DATE_DIFF'] = (
|
| 81 |
-
pd.to_datetime(aia_header['FILENAME']) -
|
| 82 |
).dt.total_seconds()
|
| 83 |
|
| 84 |
# Remove rows where DATE_DIFF is greater than ±60 seconds, the image is
|
|
@@ -91,8 +93,7 @@ def clean_aia_data(input_folder, bad_files_dir, wavelengths):
|
|
| 91 |
|
| 92 |
for wavelength in wavelengths:
|
| 93 |
print(f"\nProcessing wavelength: {wavelength}")
|
| 94 |
-
for
|
| 95 |
-
filename = pd.to_datetime(names).strftime('%Y-%m-%dT%H:%M:%S') + ".fits"
|
| 96 |
file_path = os.path.join(input_folder, f"{wavelength}/{filename}")
|
| 97 |
destination_folder = os.path.join(bad_files_dir, str(wavelength))
|
| 98 |
os.makedirs(destination_folder, exist_ok=True)
|
|
|
|
| 46 |
if date_obs.tz is not None:
|
| 47 |
date_obs = date_obs.tz_localize(None)
|
| 48 |
wavelength = header['WAVELNTH']
|
| 49 |
+
basename = os.path.basename(file_path)
|
| 50 |
+
filename_time = pd.Timestamp(os.path.splitext(basename)[0].replace('_', ':'))
|
| 51 |
blank = _is_blank(hdu[1].data) # type: ignore[union-attr]
|
| 52 |
quality = pd.to_numeric(pd.Series([header.get('QUALITY')]), errors='coerce').iloc[0]
|
| 53 |
bad_quality = bool(pd.notna(quality) and quality != 0)
|
| 54 |
+
return {'DATE-OBS': date_obs, 'WAVELNTH': wavelength, 'FILENAME': filename_time,
|
| 55 |
+
'BASENAME': basename,
|
| 56 |
'BLANK': blank, 'BAD_QUALITY': bad_quality}
|
| 57 |
except Exception as e:
|
| 58 |
print(f"Error processing {file_path}: {e}")
|
|
|
|
| 80 |
|
| 81 |
# Add a column for date difference between DATE-OBS and FILENAME
|
| 82 |
aia_header['DATE_DIFF'] = (
|
| 83 |
+
pd.to_datetime(aia_header['FILENAME']) - aia_header['DATE-OBS']
|
| 84 |
).dt.total_seconds()
|
| 85 |
|
| 86 |
# Remove rows where DATE_DIFF is greater than ±60 seconds, the image is
|
|
|
|
| 93 |
|
| 94 |
for wavelength in wavelengths:
|
| 95 |
print(f"\nProcessing wavelength: {wavelength}")
|
| 96 |
+
for filename in files_to_remove['BASENAME']:
|
|
|
|
| 97 |
file_path = os.path.join(input_folder, f"{wavelength}/{filename}")
|
| 98 |
destination_folder = os.path.join(bad_files_dir, str(wavelength))
|
| 99 |
os.makedirs(destination_folder, exist_ok=True)
|
data/convert_aia.py
CHANGED
|
@@ -84,9 +84,8 @@ def check_existing_files(base_input_folder, wavelengths, output_folder):
|
|
| 84 |
|
| 85 |
for i in range(total_expected):
|
| 86 |
first_wl_file = files[0][i]
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
base_name = '_'.join(base_name.split('_')[:-1])
|
| 90 |
output_path = os.path.join(output_folder, base_name) + '.npy'
|
| 91 |
if os.path.exists(output_path):
|
| 92 |
existing_count += 1
|
|
|
|
| 84 |
|
| 85 |
for i in range(total_expected):
|
| 86 |
first_wl_file = files[0][i]
|
| 87 |
+
# Match ITI StackDataset.getId, which save_sample uses for the output.
|
| 88 |
+
base_name = os.path.basename(first_wl_file).split('.')[0]
|
|
|
|
| 89 |
output_path = os.path.join(output_folder, base_name) + '.npy'
|
| 90 |
if os.path.exists(output_path):
|
| 91 |
existing_count += 1
|
download/download_sdo.py
CHANGED
|
@@ -22,10 +22,16 @@ from tqdm.auto import tqdm
|
|
| 22 |
|
| 23 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 24 |
from forecasting.config import load_config
|
|
|
|
| 25 |
|
| 26 |
_JSOC_CONNECTION_LIMIT = threading.Semaphore(6)
|
| 27 |
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
class SDODownloader:
|
| 30 |
"""
|
| 31 |
Class to download SDO data from JSOC.
|
|
@@ -153,7 +159,7 @@ class SDODownloader:
|
|
| 153 |
tmp_path = None
|
| 154 |
try:
|
| 155 |
dir = os.path.join(self.ds_path, '%d' % header['WAVELNTH'])
|
| 156 |
-
map_path = os.path.join(dir,
|
| 157 |
if os.path.exists(map_path):
|
| 158 |
return map_path
|
| 159 |
if not segment or pd.isna(segment):
|
|
@@ -316,7 +322,7 @@ if __name__ == '__main__':
|
|
| 316 |
if not os.path.exists(os.path.join(
|
| 317 |
download_dir,
|
| 318 |
str(wl),
|
| 319 |
-
|
| 320 |
)):
|
| 321 |
break
|
| 322 |
else:
|
|
|
|
| 22 |
|
| 23 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 24 |
from forecasting.config import load_config
|
| 25 |
+
from data._timestamps import timestamp_filename
|
| 26 |
|
| 27 |
_JSOC_CONNECTION_LIMIT = threading.Semaphore(6)
|
| 28 |
|
| 29 |
|
| 30 |
+
def aia_fits_filename(timestamp):
|
| 31 |
+
"""Name a raw AIA FITS file for the requested timestamp."""
|
| 32 |
+
return timestamp_filename(timestamp.isoformat('T', timespec='seconds'), '.fits')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
class SDODownloader:
|
| 36 |
"""
|
| 37 |
Class to download SDO data from JSOC.
|
|
|
|
| 159 |
tmp_path = None
|
| 160 |
try:
|
| 161 |
dir = os.path.join(self.ds_path, '%d' % header['WAVELNTH'])
|
| 162 |
+
map_path = os.path.join(dir, aia_fits_filename(t))
|
| 163 |
if os.path.exists(map_path):
|
| 164 |
return map_path
|
| 165 |
if not segment or pd.isna(segment):
|
|
|
|
| 322 |
if not os.path.exists(os.path.join(
|
| 323 |
download_dir,
|
| 324 |
str(wl),
|
| 325 |
+
aia_fits_filename(d)
|
| 326 |
)):
|
| 327 |
break
|
| 328 |
else:
|
download/hugging_face_data_download.py
CHANGED
|
@@ -31,6 +31,7 @@ from huggingface_hub import login
|
|
| 31 |
|
| 32 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 33 |
from forecasting.config import load_config
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# HuggingFace uses "validation"; local pipeline directories use "val"
|
|
@@ -56,6 +57,8 @@ def _restore_aia_shape(array: np.ndarray) -> np.ndarray:
|
|
| 56 |
def _write_arrays(filename: str, aia_arr: np.ndarray, sxr_arr: np.ndarray,
|
| 57 |
aia_split_dir: str, sxr_split_dir: str) -> bool:
|
| 58 |
"""Save pre-materialized arrays to disk. Returns True if written, False if already exists."""
|
|
|
|
|
|
|
| 59 |
aia_path = os.path.join(aia_split_dir, filename)
|
| 60 |
sxr_path = os.path.join(sxr_split_dir, filename)
|
| 61 |
|
|
|
|
| 31 |
|
| 32 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 33 |
from forecasting.config import load_config
|
| 34 |
+
from data._timestamps import timestamp_filename
|
| 35 |
|
| 36 |
|
| 37 |
# HuggingFace uses "validation"; local pipeline directories use "val"
|
|
|
|
| 57 |
def _write_arrays(filename: str, aia_arr: np.ndarray, sxr_arr: np.ndarray,
|
| 58 |
aia_split_dir: str, sxr_split_dir: str) -> bool:
|
| 59 |
"""Save pre-materialized arrays to disk. Returns True if written, False if already exists."""
|
| 60 |
+
stem, suffix = os.path.splitext(filename)
|
| 61 |
+
filename = timestamp_filename(stem, suffix)
|
| 62 |
aia_path = os.path.join(aia_split_dir, filename)
|
| 63 |
sxr_path = os.path.join(sxr_split_dir, filename)
|
| 64 |
|
forecasting/dataset.py
CHANGED
|
@@ -196,12 +196,12 @@ class AIAGOESDataset(torch.utils.data.Dataset):
|
|
| 196 |
print(f"Scanning AIA filenames in {self.aia_dir}...", flush=True)
|
| 197 |
with os.scandir(self.aia_dir) as entries:
|
| 198 |
aia_files = sorted(
|
| 199 |
-
Path(entry.path)
|
| 200 |
-
for entry in tqdm(
|
| 201 |
entries, desc="Scanning AIA directory", unit="entry",
|
| 202 |
disable=not show_scan_progress,
|
| 203 |
)
|
| 204 |
-
if entry.name.endswith('.npy')
|
|
|
|
| 205 |
)
|
| 206 |
if show_scan_progress:
|
| 207 |
print(
|
|
@@ -306,7 +306,7 @@ class AIAGOESDataset(torch.utils.data.Dataset):
|
|
| 306 |
def split_dataset_by_time(dataset, fraction):
|
| 307 |
"""Return the earliest ``fraction`` of a dataset's samples and the rest.
|
| 308 |
|
| 309 |
-
Samples are kept in
|
| 310 |
parts share only the boundary between them. ``fraction=1`` leaves the
|
| 311 |
second part empty.
|
| 312 |
"""
|
|
|
|
| 196 |
print(f"Scanning AIA filenames in {self.aia_dir}...", flush=True)
|
| 197 |
with os.scandir(self.aia_dir) as entries:
|
| 198 |
aia_files = sorted(
|
| 199 |
+
(Path(entry.path) for entry in tqdm(
|
|
|
|
| 200 |
entries, desc="Scanning AIA directory", unit="entry",
|
| 201 |
disable=not show_scan_progress,
|
| 202 |
)
|
| 203 |
+
if entry.name.endswith('.npy')),
|
| 204 |
+
key=lambda path: path.stem.replace(':', '').replace('_', ''),
|
| 205 |
)
|
| 206 |
if show_scan_progress:
|
| 207 |
print(
|
|
|
|
| 306 |
def split_dataset_by_time(dataset, fraction):
|
| 307 |
"""Return the earliest ``fraction`` of a dataset's samples and the rest.
|
| 308 |
|
| 309 |
+
Samples are kept in chronological order, so the two
|
| 310 |
parts share only the boundary between them. ``fraction=1`` leaves the
|
| 311 |
second part empty.
|
| 312 |
"""
|
forecasting/evaluation.py
CHANGED
|
@@ -16,6 +16,7 @@ from tqdm import tqdm
|
|
| 16 |
|
| 17 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 18 |
from forecasting.config import load_config
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
def _as_bool(value):
|
|
@@ -566,10 +567,10 @@ class FOXESEvaluator:
|
|
| 566 |
|
| 567 |
available = []
|
| 568 |
for row in self.df.itertuples(index=False):
|
| 569 |
-
|
| 570 |
-
flux_path = self.inference_patch_dir / 'flux' /
|
| 571 |
uncertainty_path = (
|
| 572 |
-
self.inference_patch_dir / 'patch_uncertainty' /
|
| 573 |
)
|
| 574 |
if flux_path.is_file() or uncertainty_path.is_file():
|
| 575 |
available.append((row, flux_path, uncertainty_path))
|
|
@@ -658,7 +659,7 @@ class FOXESEvaluator:
|
|
| 658 |
panels = []
|
| 659 |
image_shape = None
|
| 660 |
if self.aia_dir is not None:
|
| 661 |
-
aia_path = self.aia_dir /
|
| 662 |
if aia_path.is_file():
|
| 663 |
image = np.load(aia_path, allow_pickle=False)
|
| 664 |
if image.ndim == 1 and image.size == 7 * 512 * 512:
|
|
|
|
| 16 |
|
| 17 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 18 |
from forecasting.config import load_config
|
| 19 |
+
from data._timestamps import timestamp_filename
|
| 20 |
|
| 21 |
|
| 22 |
def _as_bool(value):
|
|
|
|
| 567 |
|
| 568 |
available = []
|
| 569 |
for row in self.df.itertuples(index=False):
|
| 570 |
+
filename = timestamp_filename(str(row.timestamp), '.npy')
|
| 571 |
+
flux_path = self.inference_patch_dir / 'flux' / filename
|
| 572 |
uncertainty_path = (
|
| 573 |
+
self.inference_patch_dir / 'patch_uncertainty' / filename
|
| 574 |
)
|
| 575 |
if flux_path.is_file() or uncertainty_path.is_file():
|
| 576 |
available.append((row, flux_path, uncertainty_path))
|
|
|
|
| 659 |
panels = []
|
| 660 |
image_shape = None
|
| 661 |
if self.aia_dir is not None:
|
| 662 |
+
aia_path = self.aia_dir / timestamp_filename(stamp, '.npy')
|
| 663 |
if aia_path.is_file():
|
| 664 |
image = np.load(aia_path, allow_pickle=False)
|
| 665 |
if image.ndim == 1 and image.size == 7 * 512 * 512:
|
forecasting/inference.py
CHANGED
|
@@ -32,6 +32,7 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
|
| 32 |
from forecasting.dataset import AIAGOESDataset, AIANormTransform
|
| 33 |
from forecasting.config import load_config
|
| 34 |
from forecasting.calibration import LegacyCalibration
|
|
|
|
| 35 |
from forecasting.model import (
|
| 36 |
CoupledGaussianViTLocal,
|
| 37 |
ViTLocal,
|
|
@@ -282,6 +283,7 @@ def evaluate_model_on_dataset(model, dataset, batch_size=16, times=None, config_
|
|
| 282 |
calibration = _legacy_calibration(config_data, model)
|
| 283 |
if calibration.enabled and (times is None or len(times) != len(dataset)):
|
| 284 |
raise ValueError("legacy_model=True requires one timestamp per inference sample")
|
|
|
|
| 285 |
scale_factors = (
|
| 286 |
np.asarray([calibration.factor(stamp) for stamp in times], dtype=np.float32)
|
| 287 |
if calibration.enabled else None
|
|
@@ -490,7 +492,7 @@ def evaluate_model_on_dataset(model, dataset, batch_size=16, times=None, config_
|
|
| 490 |
weight_data = candidate
|
| 491 |
if weight_dir is not None and global_idx < len(times):
|
| 492 |
np.save(
|
| 493 |
-
weight_dir /
|
| 494 |
weight_data,
|
| 495 |
)
|
| 496 |
|
|
@@ -499,7 +501,7 @@ def evaluate_model_on_dataset(model, dataset, batch_size=16, times=None, config_
|
|
| 499 |
flux_data = flux_maps_cpu[i]
|
| 500 |
if flux_dir is not None and global_idx < len(times):
|
| 501 |
np.save(
|
| 502 |
-
flux_dir /
|
| 503 |
flux_data,
|
| 504 |
)
|
| 505 |
|
|
@@ -507,7 +509,7 @@ def evaluate_model_on_dataset(model, dataset, batch_size=16, times=None, config_
|
|
| 507 |
try:
|
| 508 |
if uncertainty_dir is not None and global_idx < len(times):
|
| 509 |
np.save(
|
| 510 |
-
uncertainty_dir /
|
| 511 |
patch_std_maps_cpu[i],
|
| 512 |
)
|
| 513 |
except Exception as exc:
|
|
|
|
| 32 |
from forecasting.dataset import AIAGOESDataset, AIANormTransform
|
| 33 |
from forecasting.config import load_config
|
| 34 |
from forecasting.calibration import LegacyCalibration
|
| 35 |
+
from data._timestamps import timestamp_filename
|
| 36 |
from forecasting.model import (
|
| 37 |
CoupledGaussianViTLocal,
|
| 38 |
ViTLocal,
|
|
|
|
| 283 |
calibration = _legacy_calibration(config_data, model)
|
| 284 |
if calibration.enabled and (times is None or len(times) != len(dataset)):
|
| 285 |
raise ValueError("legacy_model=True requires one timestamp per inference sample")
|
| 286 |
+
times = () if times is None else times
|
| 287 |
scale_factors = (
|
| 288 |
np.asarray([calibration.factor(stamp) for stamp in times], dtype=np.float32)
|
| 289 |
if calibration.enabled else None
|
|
|
|
| 492 |
weight_data = candidate
|
| 493 |
if weight_dir is not None and global_idx < len(times):
|
| 494 |
np.save(
|
| 495 |
+
weight_dir / timestamp_filename(str(times[global_idx]), '.npy'),
|
| 496 |
weight_data,
|
| 497 |
)
|
| 498 |
|
|
|
|
| 501 |
flux_data = flux_maps_cpu[i]
|
| 502 |
if flux_dir is not None and global_idx < len(times):
|
| 503 |
np.save(
|
| 504 |
+
flux_dir / timestamp_filename(str(times[global_idx]), '.npy'),
|
| 505 |
flux_data,
|
| 506 |
)
|
| 507 |
|
|
|
|
| 509 |
try:
|
| 510 |
if uncertainty_dir is not None and global_idx < len(times):
|
| 511 |
np.save(
|
| 512 |
+
uncertainty_dir / timestamp_filename(str(times[global_idx]), '.npy'),
|
| 513 |
patch_std_maps_cpu[i],
|
| 514 |
)
|
| 515 |
except Exception as exc:
|
helio_foxes/api.py
CHANGED
|
@@ -1573,7 +1573,7 @@ class AIAProcessor:
|
|
| 1573 |
ValueError
|
| 1574 |
If processing returns the wrong shape or non-finite values.
|
| 1575 |
"""
|
| 1576 |
-
from download.download_sdo import SDODownloader
|
| 1577 |
|
| 1578 |
time = _utc_datetime(time).replace(tzinfo=None)
|
| 1579 |
|
|
@@ -1586,8 +1586,9 @@ class AIAProcessor:
|
|
| 1586 |
)
|
| 1587 |
downloader.downloadDate(time)
|
| 1588 |
stamp = time.isoformat("T", timespec="seconds")
|
|
|
|
| 1589 |
paths = [
|
| 1590 |
-
Path(temporary_path) / str(w) /
|
| 1591 |
for w in self.WAVELENGTHS
|
| 1592 |
]
|
| 1593 |
missing = [w for w, path in zip(self.WAVELENGTHS, paths)
|
|
|
|
| 1573 |
ValueError
|
| 1574 |
If processing returns the wrong shape or non-finite values.
|
| 1575 |
"""
|
| 1576 |
+
from download.download_sdo import SDODownloader, aia_fits_filename
|
| 1577 |
|
| 1578 |
time = _utc_datetime(time).replace(tzinfo=None)
|
| 1579 |
|
|
|
|
| 1586 |
)
|
| 1587 |
downloader.downloadDate(time)
|
| 1588 |
stamp = time.isoformat("T", timespec="seconds")
|
| 1589 |
+
filename = aia_fits_filename(time)
|
| 1590 |
paths = [
|
| 1591 |
+
Path(temporary_path) / str(w) / filename
|
| 1592 |
for w in self.WAVELENGTHS
|
| 1593 |
]
|
| 1594 |
missing = [w for w, path in zip(self.WAVELENGTHS, paths)
|
tests/test_aia_calibration.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""Exercise the packaged calibration through ITI with no network or home cache."""
|
| 2 |
|
| 3 |
import hashlib
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
from importlib.resources import files
|
| 6 |
from io import BytesIO
|
|
@@ -53,6 +54,9 @@ def test_download_preserves_tile_compressed_fits_pixels(tmp_path, monkeypatch):
|
|
| 53 |
downloader = SDODownloader(tmp_path, wavelengths=[94])
|
| 54 |
header = {"WAVELNTH": 94, "DATE__OBS": "2023-08-01T00:00:00", "QUALITY": 0}
|
| 55 |
output = downloader.download((header, "/offline.fits", datetime(2023, 8, 1)))
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
with fits.open(output) as restored:
|
| 58 |
np.testing.assert_array_equal(restored[1].data, expected)
|
|
|
|
| 1 |
"""Exercise the packaged calibration through ITI with no network or home cache."""
|
| 2 |
|
| 3 |
import hashlib
|
| 4 |
+
import os
|
| 5 |
from datetime import datetime
|
| 6 |
from importlib.resources import files
|
| 7 |
from io import BytesIO
|
|
|
|
| 54 |
downloader = SDODownloader(tmp_path, wavelengths=[94])
|
| 55 |
header = {"WAVELNTH": 94, "DATE__OBS": "2023-08-01T00:00:00", "QUALITY": 0}
|
| 56 |
output = downloader.download((header, "/offline.fits", datetime(2023, 8, 1)))
|
| 57 |
+
expected_name = "2023-08-01T000000.fits" if os.name == "nt" else "2023-08-01T00:00:00.fits"
|
| 58 |
+
assert Path(output).name == expected_name
|
| 59 |
+
assert not Path(output + ".part").exists()
|
| 60 |
|
| 61 |
with fits.open(output) as restored:
|
| 62 |
np.testing.assert_array_equal(restored[1].data, expected)
|
tests/test_evaluation_patch_maps.py
CHANGED
|
@@ -2,13 +2,19 @@
|
|
| 2 |
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
|
|
|
| 5 |
from matplotlib.axes import Axes
|
| 6 |
from matplotlib.colors import LogNorm
|
| 7 |
|
| 8 |
from forecasting.evaluation import FOXESEvaluator
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
patches = tmp_path / 'inference_patch'
|
| 13 |
flux_dir = patches / 'flux'
|
| 14 |
uncertainty_dir = patches / 'patch_uncertainty'
|
|
@@ -18,10 +24,12 @@ def test_patch_maps_match_csv_timestamps_with_optional_aia(tmp_path, monkeypatch
|
|
| 18 |
|
| 19 |
first = '2023-08-04T15:30:00'
|
| 20 |
second = '2023-08-06T05:46:00'
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
np.save(
|
| 24 |
-
np.save(
|
|
|
|
|
|
|
| 25 |
np.save(flux_dir / 'unrelated.npy', np.ones((2, 2)))
|
| 26 |
|
| 27 |
csv_path = tmp_path / 'predictions.csv'
|
|
|
|
| 2 |
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
+
import pytest
|
| 6 |
from matplotlib.axes import Axes
|
| 7 |
from matplotlib.colors import LogNorm
|
| 8 |
|
| 9 |
from forecasting.evaluation import FOXESEvaluator
|
| 10 |
+
from data import _timestamps
|
| 11 |
|
| 12 |
|
| 13 |
+
@pytest.mark.parametrize('windows', [False, True])
|
| 14 |
+
def test_patch_maps_match_csv_timestamps_with_optional_aia(tmp_path, monkeypatch, windows):
|
| 15 |
+
if _timestamps._WINDOWS and not windows:
|
| 16 |
+
pytest.skip('Windows cannot create legacy colon-separated filenames')
|
| 17 |
+
monkeypatch.setattr(_timestamps, '_WINDOWS', windows)
|
| 18 |
patches = tmp_path / 'inference_patch'
|
| 19 |
flux_dir = patches / 'flux'
|
| 20 |
uncertainty_dir = patches / 'patch_uncertainty'
|
|
|
|
| 24 |
|
| 25 |
first = '2023-08-04T15:30:00'
|
| 26 |
second = '2023-08-06T05:46:00'
|
| 27 |
+
first_name = '2023-08-04T153000.npy' if windows else f'{first}.npy'
|
| 28 |
+
second_name = '2023-08-06T054600.npy' if windows else f'{second}.npy'
|
| 29 |
+
np.save(flux_dir / first_name, np.ones((2, 2)) * 1e-7)
|
| 30 |
+
np.save(uncertainty_dir / first_name, np.ones((2, 2)) * 1e-8)
|
| 31 |
+
np.save(aia_dir / first_name, np.zeros((7, 16, 16)))
|
| 32 |
+
np.save(flux_dir / second_name, np.ones((2, 2)) * 2e-3)
|
| 33 |
np.save(flux_dir / 'unrelated.npy', np.ones((2, 2)))
|
| 34 |
|
| 35 |
csv_path = tmp_path / 'predictions.csv'
|
tests/test_hf_download.py
CHANGED
|
@@ -6,10 +6,12 @@ import pyarrow.parquet as pq
|
|
| 6 |
import pytest
|
| 7 |
|
| 8 |
from download import hugging_face_data_download as download
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
@pytest.mark.parametrize('fail_write', [False, True])
|
| 12 |
def test_source_deleted_only_after_successful_numpy_writes(tmp_path, monkeypatch, fail_write):
|
|
|
|
| 13 |
monkeypatch.setattr(download, 'AIA_SHAPE', (7, 2, 2))
|
| 14 |
monkeypatch.setattr(download, 'AIA_SIZE', 28)
|
| 15 |
source = tmp_path / 'source'
|
|
@@ -17,7 +19,7 @@ def test_source_deleted_only_after_successful_numpy_writes(tmp_path, monkeypatch
|
|
| 17 |
parquet = source / 'part.parquet'
|
| 18 |
image = np.arange(28, dtype=np.float32)
|
| 19 |
pq.write_table(pa.table({
|
| 20 |
-
'filename': ['
|
| 21 |
'aia_stack': pa.FixedSizeListArray.from_arrays(pa.array(image), 28),
|
| 22 |
'sxr_value': [1e-6],
|
| 23 |
}), parquet)
|
|
@@ -36,6 +38,6 @@ def test_source_deleted_only_after_successful_numpy_writes(tmp_path, monkeypatch
|
|
| 36 |
download.convert_local_parquet_split(source, 'train', config)
|
| 37 |
assert not parquet.exists()
|
| 38 |
np.testing.assert_array_equal(
|
| 39 |
-
np.load(tmp_path / 'aia/train/
|
| 40 |
)
|
| 41 |
-
assert np.load(tmp_path / 'sxr/train/
|
|
|
|
| 6 |
import pytest
|
| 7 |
|
| 8 |
from download import hugging_face_data_download as download
|
| 9 |
+
from data import _timestamps
|
| 10 |
|
| 11 |
|
| 12 |
@pytest.mark.parametrize('fail_write', [False, True])
|
| 13 |
def test_source_deleted_only_after_successful_numpy_writes(tmp_path, monkeypatch, fail_write):
|
| 14 |
+
monkeypatch.setattr(_timestamps, '_WINDOWS', True)
|
| 15 |
monkeypatch.setattr(download, 'AIA_SHAPE', (7, 2, 2))
|
| 16 |
monkeypatch.setattr(download, 'AIA_SIZE', 28)
|
| 17 |
source = tmp_path / 'source'
|
|
|
|
| 19 |
parquet = source / 'part.parquet'
|
| 20 |
image = np.arange(28, dtype=np.float32)
|
| 21 |
pq.write_table(pa.table({
|
| 22 |
+
'filename': ['2020-01-01T00:00:00.npy'],
|
| 23 |
'aia_stack': pa.FixedSizeListArray.from_arrays(pa.array(image), 28),
|
| 24 |
'sxr_value': [1e-6],
|
| 25 |
}), parquet)
|
|
|
|
| 38 |
download.convert_local_parquet_split(source, 'train', config)
|
| 39 |
assert not parquet.exists()
|
| 40 |
np.testing.assert_array_equal(
|
| 41 |
+
np.load(tmp_path / 'aia/train/2020-01-01T000000.npy'), image.reshape(7, 2, 2),
|
| 42 |
)
|
| 43 |
+
assert np.load(tmp_path / 'sxr/train/2020-01-01T000000.npy').item() == pytest.approx(1e-6)
|
tests/test_public_api.py
CHANGED
|
@@ -12,6 +12,7 @@ import pytest
|
|
| 12 |
import torch
|
| 13 |
|
| 14 |
import helio_foxes
|
|
|
|
| 15 |
from forecasting.model import SXR_LOG_OFFSET, CoupledGaussianViTLocal, ViTLocal
|
| 16 |
|
| 17 |
|
|
@@ -35,7 +36,7 @@ def test_aia_processor_uses_temporary_files_and_returns_stack(monkeypatch):
|
|
| 35 |
for wavelength in self.wavelengths:
|
| 36 |
path = Path(self.base_path) / wavelength
|
| 37 |
path.mkdir()
|
| 38 |
-
(path /
|
| 39 |
|
| 40 |
class Stacker:
|
| 41 |
def __init__(self, data, wavelengths, resolution, **kwargs):
|
|
@@ -47,7 +48,7 @@ def test_aia_processor_uses_temporary_files_and_returns_stack(monkeypatch):
|
|
| 47 |
assert index == 0
|
| 48 |
return np.ones((7, self.resolution, self.resolution), dtype=np.float32)
|
| 49 |
|
| 50 |
-
monkeypatch.
|
| 51 |
monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=Stacker))
|
| 52 |
stack = helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00Z")
|
| 53 |
assert stack.shape == (7, 2, 2)
|
|
@@ -76,7 +77,7 @@ def test_aia_processor_rejects_partial_download_and_cleans_up(monkeypatch):
|
|
| 76 |
def downloadDate(self, date):
|
| 77 |
pass
|
| 78 |
|
| 79 |
-
monkeypatch.
|
| 80 |
monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=object))
|
| 81 |
with pytest.raises(FileNotFoundError, match="wavelengths"):
|
| 82 |
helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00")
|
|
|
|
| 12 |
import torch
|
| 13 |
|
| 14 |
import helio_foxes
|
| 15 |
+
from download import download_sdo
|
| 16 |
from forecasting.model import SXR_LOG_OFFSET, CoupledGaussianViTLocal, ViTLocal
|
| 17 |
|
| 18 |
|
|
|
|
| 36 |
for wavelength in self.wavelengths:
|
| 37 |
path = Path(self.base_path) / wavelength
|
| 38 |
path.mkdir()
|
| 39 |
+
(path / download_sdo.aia_fits_filename(date)).touch()
|
| 40 |
|
| 41 |
class Stacker:
|
| 42 |
def __init__(self, data, wavelengths, resolution, **kwargs):
|
|
|
|
| 48 |
assert index == 0
|
| 49 |
return np.ones((7, self.resolution, self.resolution), dtype=np.float32)
|
| 50 |
|
| 51 |
+
monkeypatch.setattr(download_sdo, "SDODownloader", Downloader)
|
| 52 |
monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=Stacker))
|
| 53 |
stack = helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00Z")
|
| 54 |
assert stack.shape == (7, 2, 2)
|
|
|
|
| 77 |
def downloadDate(self, date):
|
| 78 |
pass
|
| 79 |
|
| 80 |
+
monkeypatch.setattr(download_sdo, "SDODownloader", Downloader)
|
| 81 |
monkeypatch.setitem(sys.modules, "data.convert_aia", types.SimpleNamespace(AIAStackDataset=object))
|
| 82 |
with pytest.raises(FileNotFoundError, match="wavelengths"):
|
| 83 |
helio_foxes.AIAProcessor(resolution=2).fetch("2023-08-01T00:00:00")
|
tests/test_sxr_combiner.py
CHANGED
|
@@ -9,8 +9,10 @@ pytest.importorskip("pyarrow", reason="Requires lossless Parquet processing")
|
|
| 9 |
|
| 10 |
from data.combine_sxr import SXRDataProcessor, prepare_sxr_frame
|
| 11 |
from data.align_aia_sxr import (
|
| 12 |
-
create_combined_lookup_table, load_and_prepare_goes_data, process_batch,
|
| 13 |
)
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def test_combiner_preserves_processed_values_and_dtypes(tmp_path):
|
|
@@ -57,12 +59,33 @@ def test_binary_alignment_preserves_halfway_rounding_and_prefers_parquet(tmp_pat
|
|
| 57 |
successful, failed = process_batch(lookup, output)
|
| 58 |
|
| 59 |
expected = np.array([np.mean(np.array([first, second], dtype=np.float64))], dtype=np.float32)
|
| 60 |
-
saved = np.load(output / "2018-01-01T00:00:00.npy")
|
| 61 |
assert (successful, failed) == (1, 0)
|
| 62 |
assert saved.dtype == np.float32
|
| 63 |
assert saved.tobytes() == expected.tobytes()
|
| 64 |
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def test_historical_csv_only_directory_remains_readable(tmp_path):
|
| 67 |
frame = pd.DataFrame({
|
| 68 |
"time": ["2018-01-01 00:00:00", "2018-01-01 00:01:00"],
|
|
|
|
| 9 |
|
| 10 |
from data.combine_sxr import SXRDataProcessor, prepare_sxr_frame
|
| 11 |
from data.align_aia_sxr import (
|
| 12 |
+
align_aia_sxr, create_combined_lookup_table, load_and_prepare_goes_data, process_batch,
|
| 13 |
)
|
| 14 |
+
from data._timestamps import timestamp_filename
|
| 15 |
+
from forecasting.dataset import AIAGOESDataset
|
| 16 |
|
| 17 |
|
| 18 |
def test_combiner_preserves_processed_values_and_dtypes(tmp_path):
|
|
|
|
| 59 |
successful, failed = process_batch(lookup, output)
|
| 60 |
|
| 61 |
expected = np.array([np.mean(np.array([first, second], dtype=np.float64))], dtype=np.float32)
|
| 62 |
+
saved = np.load(output / timestamp_filename("2018-01-01T00:00:00", ".npy"))
|
| 63 |
assert (successful, failed) == (1, 0)
|
| 64 |
assert saved.dtype == np.float32
|
| 65 |
assert saved.tobytes() == expected.tobytes()
|
| 66 |
|
| 67 |
|
| 68 |
+
def test_alignment_preserves_aia_filenames_for_dataset_pairs(tmp_path):
|
| 69 |
+
goes, aia, sxr, missing = (tmp_path / name for name in ('goes', 'aia', 'sxr', 'missing'))
|
| 70 |
+
goes.mkdir()
|
| 71 |
+
aia.mkdir()
|
| 72 |
+
filenames = ('2018-01-01T00_00_00.npy', '2018-01-01T000100.npy')
|
| 73 |
+
image = np.ones((7, 2, 2), dtype=np.float32)
|
| 74 |
+
for filename in (*filenames, '2018-01-01T000200.npy'):
|
| 75 |
+
np.save(aia / filename, image)
|
| 76 |
+
pd.DataFrame({
|
| 77 |
+
'time': ['2018-01-01 00:00:00', '2018-01-01 00:01:00'],
|
| 78 |
+
'xrsb_flux': [1e-6, 2e-6], 'xrsb_flag': [0, 0],
|
| 79 |
+
}).to_csv(goes / 'combined_g16_avg1m_20180101_20180101.csv', index=False)
|
| 80 |
+
|
| 81 |
+
align_aia_sxr(goes, aia, sxr, missing, max_processes=1)
|
| 82 |
+
|
| 83 |
+
assert {path.name for path in sxr.iterdir()} == set(filenames)
|
| 84 |
+
assert (missing / '2018-01-01T000200.npy').is_file()
|
| 85 |
+
dataset = AIAGOESDataset(aia, sxr, target_size=(2, 2))
|
| 86 |
+
assert [dataset[index][1].item() for index in range(len(dataset))] == pytest.approx([1e-6, 2e-6])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
def test_historical_csv_only_directory_remains_readable(tmp_path):
|
| 90 |
frame = pd.DataFrame({
|
| 91 |
"time": ["2018-01-01 00:00:00", "2018-01-01 00:01:00"],
|
tests/test_training_expansion.py
CHANGED
|
@@ -8,6 +8,7 @@ import pytest
|
|
| 8 |
import yaml
|
| 9 |
|
| 10 |
import download.expand_training_data as expansion
|
|
|
|
| 11 |
from download.expand_training_data import WAVELENGTHS, add_goes_flux, file_times, get_catalog, make_plan
|
| 12 |
|
| 13 |
NONE = pd.DatetimeIndex([])
|
|
@@ -76,7 +77,8 @@ def test_cap_is_seeded_and_sorted(config):
|
|
| 76 |
def test_file_times_reads_timestamp_names_and_rejects_missing_folders(tmp_path):
|
| 77 |
folder = tmp_path / "aia" / "nested"
|
| 78 |
folder.mkdir(parents=True)
|
| 79 |
-
for name in ("2020-01-01T12:00:00
|
|
|
|
| 80 |
(folder / name).touch()
|
| 81 |
assert sorted(file_times([tmp_path / "aia"])) == [pd.Timestamp("2020-01-01T12:00"), pd.Timestamp("2020-01-01T13:00")]
|
| 82 |
with pytest.raises(FileNotFoundError):
|
|
@@ -112,11 +114,16 @@ def test_goes_flux_comes_from_the_training_lookup(tmp_path):
|
|
| 112 |
assert result.satellites[0] == "GOES-16,GOES-15"
|
| 113 |
|
| 114 |
|
| 115 |
-
|
|
|
|
| 116 |
import data.convert_aia
|
| 117 |
import download.download_sdo
|
| 118 |
import itipy.data.editor
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
pd.DataFrame({"timestamp": ["2020-01-01T12:00:00", "2020-01-01T13:00:00", "2020-01-01T14:00:00"],
|
| 121 |
"xrsb_flux": [1e-6, 2e-6, 3e-6]}).to_csv(tmp_path / "samples.csv", index=False)
|
| 122 |
emails, requested = [], []
|
|
@@ -131,7 +138,8 @@ def test_download_saves_pairs_removes_fits_and_resumes(tmp_path, config, monkeyp
|
|
| 131 |
if date.hour == 14:
|
| 132 |
return # JSOC had no frames within tolerance.
|
| 133 |
for wl in WAVELENGTHS:
|
| 134 |
-
|
|
|
|
| 135 |
path.parent.mkdir(exist_ok=True)
|
| 136 |
path.touch()
|
| 137 |
|
|
@@ -149,11 +157,12 @@ def test_download_saves_pairs_removes_fits_and_resumes(tmp_path, config, monkeyp
|
|
| 149 |
assert expansion.download(config, limit=1) == 0
|
| 150 |
emails.clear()
|
| 151 |
assert expansion.download(config) == 1
|
| 152 |
-
|
| 153 |
-
|
|
|
|
| 154 |
assert aia.shape == (7, 2, 2) and aia.dtype == sxr.dtype == np.float32
|
| 155 |
assert sxr.tolist() == [pytest.approx(2e-6)]
|
| 156 |
-
assert
|
| 157 |
assert "no AIA frame" in pd.read_csv(tmp_path / "failed.csv").error[0]
|
| 158 |
assert not list((tmp_path / "staging").rglob("*.fits"))
|
| 159 |
assert emails == ["a@example.com", "b@example.com"][:len(emails)]
|
|
|
|
| 8 |
import yaml
|
| 9 |
|
| 10 |
import download.expand_training_data as expansion
|
| 11 |
+
from data import _timestamps
|
| 12 |
from download.expand_training_data import WAVELENGTHS, add_goes_flux, file_times, get_catalog, make_plan
|
| 13 |
|
| 14 |
NONE = pd.DatetimeIndex([])
|
|
|
|
| 77 |
def test_file_times_reads_timestamp_names_and_rejects_missing_folders(tmp_path):
|
| 78 |
folder = tmp_path / "aia" / "nested"
|
| 79 |
folder.mkdir(parents=True)
|
| 80 |
+
for name in (_timestamps.timestamp_filename("2020-01-01T12:00:00", ".npy"),
|
| 81 |
+
"2020-01-01T13_00_00.npy", "._2020-01-01T140000.npy", "stats.npy"):
|
| 82 |
(folder / name).touch()
|
| 83 |
assert sorted(file_times([tmp_path / "aia"])) == [pd.Timestamp("2020-01-01T12:00"), pd.Timestamp("2020-01-01T13:00")]
|
| 84 |
with pytest.raises(FileNotFoundError):
|
|
|
|
| 114 |
assert result.satellites[0] == "GOES-16,GOES-15"
|
| 115 |
|
| 116 |
|
| 117 |
+
@pytest.mark.parametrize("windows", [False, True])
|
| 118 |
+
def test_download_saves_pairs_removes_fits_and_resumes(tmp_path, config, monkeypatch, windows):
|
| 119 |
import data.convert_aia
|
| 120 |
import download.download_sdo
|
| 121 |
import itipy.data.editor
|
| 122 |
|
| 123 |
+
if _timestamps._WINDOWS and not windows:
|
| 124 |
+
pytest.skip("Windows cannot create legacy colon-separated filenames")
|
| 125 |
+
monkeypatch.setattr(_timestamps, "_WINDOWS", windows)
|
| 126 |
+
|
| 127 |
pd.DataFrame({"timestamp": ["2020-01-01T12:00:00", "2020-01-01T13:00:00", "2020-01-01T14:00:00"],
|
| 128 |
"xrsb_flux": [1e-6, 2e-6, 3e-6]}).to_csv(tmp_path / "samples.csv", index=False)
|
| 129 |
emails, requested = [], []
|
|
|
|
| 138 |
if date.hour == 14:
|
| 139 |
return # JSOC had no frames within tolerance.
|
| 140 |
for wl in WAVELENGTHS:
|
| 141 |
+
stamp = date.strftime("%Y-%m-%dT%H%M%S") if windows else date.isoformat()
|
| 142 |
+
path = self.directory / str(wl) / f"{stamp}.fits"
|
| 143 |
path.parent.mkdir(exist_ok=True)
|
| 144 |
path.touch()
|
| 145 |
|
|
|
|
| 157 |
assert expansion.download(config, limit=1) == 0
|
| 158 |
emails.clear()
|
| 159 |
assert expansion.download(config) == 1
|
| 160 |
+
name = "2020-01-01T130000.npy" if windows else "2020-01-01T13:00:00.npy"
|
| 161 |
+
aia = np.load(tmp_path / "AIA_processed/train" / name)
|
| 162 |
+
sxr = np.load(tmp_path / "SXR_processed/train" / name)
|
| 163 |
assert aia.shape == (7, 2, 2) and aia.dtype == sxr.dtype == np.float32
|
| 164 |
assert sxr.tolist() == [pytest.approx(2e-6)]
|
| 165 |
+
assert len(list((tmp_path / "AIA_processed/train").glob("*.npy"))) == 2
|
| 166 |
assert "no AIA frame" in pd.read_csv(tmp_path / "failed.csv").error[0]
|
| 167 |
assert not list((tmp_path / "staging").rglob("*.fits"))
|
| 168 |
assert emails == ["a@example.com", "b@example.com"][:len(emails)]
|