GBI-16-2D / utils /eval_baselines.py
rithwiks's picture
uploaded filtered keck files made splits made utils
89a696f
raw
history blame
4.33 kB
"""
Runs several baseline compression algorithms and stores results for each FITS file in a csv.
This code is written functionality-only and cleaning it up is a TODO.
"""
import os
import re
from pathlib import Path
import argparse
import os.path
from astropy.io import fits
import numpy as np
from time import time
import pandas as pd
from tqdm import tqdm
import glob
from astropy.io.fits import CompImageHDU
from imagecodecs import (
jpeg2k_encode,
jpeg2k_decode,
jpegls_encode,
jpegls_decode,
jpegxl_encode,
jpegxl_decode,
rcomp_encode,
rcomp_decode,
)
# Functions that require some preset parameters. All others default to lossless.
jpegxl_encode_max_effort_preset = lambda x: jpegxl_encode(x, lossless=True, effort=9)
jpegxl_encode_preset = lambda x: jpegxl_encode(x, lossless=True)
def find_matching_files(root_dir='./data'):
# Use glob to recursively find all .fits files
pattern = os.path.join(root_dir, '**', '*.fits')
fits_files = glob.glob(pattern, recursive=True)
return fits_files
def benchmark_imagecodecs_compression_algos(arr, compression_type):
encoder, decoder = ALL_CODECS[compression_type]
write_start_time = time()
encoded = encoder(arr)
write_time = time() - write_start_time
read_start_time = time()
if compression_type == "RICE":
decoded = decoder(encoded, shape=arr.shape, dtype=np.uint16)
else:
decoded = decoder(encoded)
read_time = time() - read_start_time
assert np.array_equal(arr, decoded)
buflength = len(encoded)
return {compression_type + "_BPD": buflength / arr.size,
compression_type + "_WRITE_RUNTIME": write_time,
compression_type + "_READ_RUNTIME": read_time,
#compression_type + "_TILE_DIVISOR": np.nan,
}
def main(dim):
save_path = f"baseline_results_{dim}.csv"
file_paths = find_matching_files()
df = pd.DataFrame(columns=columns, index=[str(p) for p in file_paths])
print(f"Number of files to be tested: {len(file_paths)}")
ct = 0
for path in tqdm(file_paths):
with fits.open(path) as hdul:
if len(hdul) == 1:
hdu_indices = [0]
else:
hdu_indices = [1, 2, 3, 4]
for hdu_idx in hdu_indices:
with fits.open(path) as hdul:
if dim == '2d':
arr = hdul[hdu_idx].data
else:
raise RuntimeError(f"{dim} not applicable.")
ct += 1
if ct % 10 == 0:
print(df.mean())
df.to_csv(save_path)
for algo in ALL_CODECS.keys():
try:
if algo == "JPEG_2K" and dim != '2d':
test_results = benchmark_imagecodecs_compression_algos(arr.transpose(1, 2, 0), algo)
else:
test_results = benchmark_imagecodecs_compression_algos(arr, algo)
for column, value in test_results.items():
if column in df.columns:
df.at[path + f"_hdu{hdu_idx}", column] = value
except Exception as e:
print(f"Failed at {path} under exception {e}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process some 2D or 3D data.")
parser.add_argument(
"dimension",
choices=['2d'],
help="Specify whether the data is 2d, or; not applicable here: 3dt (3d time dimension), or 3dw (3d wavelength dimension)."
)
args = parser.parse_args()
dim = args.dimension.lower()
# RICE REQUIRES UNIQUE INPUT OF ARR SHAPE AND DTYPE INTO DECODER
ALL_CODECS = {
"JPEG_XL_MAX_EFFORT": [jpegxl_encode_max_effort_preset, jpegxl_decode],
"JPEG_XL": [jpegxl_encode_preset, jpegxl_decode],
"JPEG_2K": [jpeg2k_encode, jpeg2k_decode],
"JPEG_LS": [jpegls_encode, jpegls_decode],
"RICE": [rcomp_encode, rcomp_decode],
}
columns = []
for algo in ALL_CODECS.keys():
columns.append(algo + "_BPD")
columns.append(algo + "_WRITE_RUNTIME")
columns.append(algo + "_READ_RUNTIME")
#columns.append(algo + "_TILE_DIVISOR")
main(dim)