GBI-16-4D / utils /create_splits.py
anonuser7251's picture
Add dataset
0ce5189
import os
import random
from glob import glob
import json
from huggingface_hub import hf_hub_download
from tqdm import tqdm
import numpy as np
from astropy.io import fits
from astropy.wcs import WCS
import datasets
from datasets import DownloadManager
from fsspec.core import url_to_fs
def get_fits_footprint(fits_path):
"""
Process a FITS file to extract WCS information and calculate the footprint.
Parameters:
fits_path (str): Path to the FITS file.
Returns:
tuple: A tuple containing the WCS footprint coordinates.
"""
with fits.open(fits_path) as hdul:
hdul[0].data = hdul[0].data[0, 0]
wcs = WCS(hdul[0].header)
shape = sorted(tuple(wcs.pixel_shape))[:2]
footprint = wcs.calc_footprint(axes=shape)
coords = list(footprint.flatten())
return coords
def calculate_pixel_scale(header):
"""
Calculate the pixel scale in arcseconds per pixel from a FITS header.
Parameters:
header (astropy.io.fits.header.Header): The FITS header containing WCS information.
Returns:
Mean of the pixel scales in x and y.
"""
# Extract the CD matrix elements
cd1_1 = header.get('CD1_1', np.nan)
cd1_2 = header.get('CD1_2', np.nan)
cd2_1 = header.get('CD2_1', np.nan)
cd2_2 = header.get('CD2_2', np.nan)
# Calculate the pixel scales in arcseconds per pixel
pixscale_x = np.sqrt(cd1_1**2 + cd1_2**2) * 3600
pixscale_y = np.sqrt(cd2_1**2 + cd2_2**2) * 3600
return np.mean([pixscale_x, pixscale_y])
def make_split_jsonl_files(config_type="tiny", data_dir="./data",
outdir="./splits", seed=42):
"""
Create jsonl files for the GBI-16-4D dataset.
config_type: str, default="tiny"
The type of split to create. Options are "tiny" and "full".
data_dir: str, default="./data"
The directory where the FITS files are located.
outdir: str, default="./splits"
The directory where the jsonl files will be created.
seed: int, default=42
The seed for the random split.
"""
random.seed(seed)
os.makedirs(outdir, exist_ok=True)
fits_files = glob(os.path.join(data_dir, "*.fits"))
random.shuffle(fits_files)
if config_type == "tiny":
train_files = fits_files[:2]
test_files = fits_files[2:3]
elif config_type == "full":
split_idx = int(0.8 * len(fits_files))
train_files = fits_files[:split_idx]
test_files = fits_files[split_idx:]
else:
raise ValueError("Unsupported config_type. Use 'tiny' or 'full'.")
def create_jsonl(files, split_name):
output_file = os.path.join(outdir, f"{config_type}_{split_name}.jsonl")
with open(output_file, "w") as out_f:
for file in tqdm(files):
#print(file, flush=True, end="...")
with fits.open(file, memmap=False, ignore_missing_simple=True) as hdul:
image_id = os.path.basename(file).split(".fits")[0]
ra = hdul[0].header.get('CRVAL1', np.nan)
dec = hdul[0].header.get('CRVAL2', np.nan)
pixscale = calculate_pixel_scale(hdul[0].header)
ntimes = hdul[0].data.shape[0]
nbands = hdul[0].data.shape[1]
footprint = get_fits_footprint(file)
item = {"image_id": image_id, "image": file, "ra": ra, "dec": dec,
"pixscale": pixscale, "ntimes": ntimes, "nbands": nbands, "footprint": footprint}
out_f.write(json.dumps(item) + "\n")
create_jsonl(train_files, "train")
create_jsonl(test_files, "test")
if __name__ == "__main__":
make_split_jsonl_files("tiny")
make_split_jsonl_files("full")