Download data/align_hdf5.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 4.06 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/data/align_hdf5.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/data/align_hdf5.py
-
curl -L -o align_hdf5.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/data/align_hdf5.py
4.06 kB
| """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,json | |
| import 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() | |