import 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 os import glob import h5py import numpy as np import cv2 from datetime import datetime from tqdm import tqdm import logging import warnings from astropy.utils.iers import conf conf.auto_download = False import sunpy.map warnings.filterwarnings('ignore') HMI_DIR = None OUTPUT_H5 = None TARGET_SIZE = (512, 512) LOG_FILE = None CLIP_MIN = -3000.0 CLIP_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()