""" 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 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 split_uint16_to_uint8(arr): # Ensure the input is of the correct type assert arr.dtype == np.uint16, "Input array must be of type np.uint16" # Compute the top 8 bits and the bottom 8 bits top_bits = (arr >> 8).astype(np.uint8) bottom_bits = (arr & 0xFF).astype(np.uint8) return top_bits, bottom_bits def find_matching_files(): """ Returns list of test set file paths. """ df = pd.read_json("./splits/full_test.jsonl", lines=True) return list(df['image']) 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 dim == '2d': arr = hdul[0].data[0][2] arrs = [arr] elif dim == '2d-top': arr = hdul[0].data[0][2] arr = split_uint16_to_uint8(arr)[0] arrs = [arr] elif dim == '2d-bottom': arr = hdul[0].data[0][2] arr = split_uint16_to_uint8(arr)[1] arrs = [arr] elif dim == '3dt' and len(hdul[0].data) > 2: arr = hdul[0].data[0:3][2] arrs = [arr] elif dim == '3dw' and len(hdul[0].data[0]) > 2: arr = hdul[0].data[0][0:3] arrs = [arr] elif dim == '3dt_reshape' and len(hdul[0].data) > 2: arr = hdul[0].data[0:3][2].reshape((800, -1)) arrs = [arr] elif dim == '3dw_reshape' and len(hdul[0].data[0]) > 2: arr = hdul[0].data[0][0:3].reshape((800, -1)) arrs = [arr] elif dim == 'tw': init_arr = hdul[0].data def arrs_gen(): for i in range(init_arr.shape[-2]): for j in range(init_arr.shape[-1]): yield init_arr[:, :, i, j] arrs = arrs_gen() else: continue ct += 1 if ct % 10 == 0: print(df.mean()) df.to_csv(save_path) for arr_idx, arr in enumerate(arrs): for algo in ALL_CODECS.keys(): try: if algo == "JPEG_2K" and (dim == '3dt' or dim == '3dw'): 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"_arr_{arr_idx}", column] = value except Exception as e: print(f"Failed at {path} under exception {e}.") print(df.mean()) df.to_csv(save_path) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Process some 2D or 3D data.") parser.add_argument( "dimension", choices=['2d', '2d-top', '2d-bottom', '3dt', '3dw', 'tw', '3dt_reshape', '3dw_reshape'], help="Specify whether the data is 2d, 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 if dim == '3dw' or dim == '3dt' or dim == 'tw': 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], } else: 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)