File size: 4,366 Bytes
0119ae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef312f6
 
 
 
 
0119ae3
 
 
 
ef312f6
 
0119ae3
 
 
ef312f6
 
 
0119ae3
 
 
 
 
 
 
 
ef312f6
0119ae3
 
 
 
 
 
 
 
 
 
 
ef312f6
0119ae3
 
 
 
ef312f6
 
0119ae3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""
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 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()
    
    if os.path.isfile(save_path):
        df = pd.read_csv(save_path)
    else:
        pass
        #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
    
    #print(df)

    for path in tqdm(file_paths):
        for hdu_idx in [1, 4]:
            df_idx = path + f"_hdu{hdu_idx}"
            if df_idx in df[df.columns[0]].values:
                continue
            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[df_idx, column] = value

                except Exception as e:
                    print(f"Failed at {path} under exception {e}.")
            
            df.to_csv(save_path)
            
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)