File size: 7,039 Bytes
b553e52
 
 
 
 
8a3abc3
 
b553e52
 
8a3abc3
 
b553e52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21bb2fa
 
b553e52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a3abc3
 
 
 
 
 
 
 
6ca06f3
8a3abc3
 
 
b553e52
 
8a3abc3
b553e52
 
8a3abc3
b553e52
 
8a3abc3
a4bd7d7
 
 
8a3abc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ca06f3
 
8a3abc3
 
 
b553e52
 
8a3abc3
 
 
 
 
b553e52
 
 
 
8a3abc3
b553e52
 
8a3abc3
 
 
 
 
b553e52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import random
from glob import glob
import json


import pyarrow as pa
from astropy.io import fits
import datasets
from datasets import DatasetInfo, DownloadManager
from fsspec.core import url_to_fs

_DESCRIPTION = (
"GBI-16-4D is a dataset which is part of the AstroCompress project. It contains data "
"assembled from the Sloan Digital SkySurvey (SDSS). Each FITS file contains a series "
"of 800x800 pixel uint16 observations of the same portion of the Stripe82 field, "
"taken in 5 bandpass filters (u, g, r, i, z) over time. The filenames give the "
"starting run, field, camcol of the observations, the number of filtered images per "
"timestep, and the number of timesteps. For example: "
"`cube_center_run4203_camcol6_f44_35-5-800-800.fits` contains 35 frames of 800x800 "
"pixel images in 5 bandpasses starting with run 4203, field 44, and camcol 6. "
"The images are stored in the FITS standard."
)

_HOMEPAGE = "https://google.github.io/AstroCompress"

_LICENSE = "CC BY 4.0"

_URL = "https://huggingface.co/datasets/AstroCompress/GBI-16-4D/resolve/main/"

_URLS = {
    "tiny": {
        "train": "./splits/tiny_train.jsonl",
        "test": "./splits/tiny_test.jsonl",
    },
    "full": {
        "train": "./splits/full_train.jsonl",
        "test": "./splits/full_test.jsonl",
    }
}

class GBI_16_4D(datasets.GeneratorBasedBuilder):
    """GBI-16-4D Dataset"""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="tiny",
            version=VERSION,
            description="A small subset of the data, to test downsteam workflows.",
        ),
        datasets.BuilderConfig(
            name="full",
            version=VERSION,
            description="The full dataset",
        ),
    ]

    DEFAULT_CONFIG_NAME = "tiny"

    def __init__(self, **kwargs):
        super().__init__(version=self.VERSION, **kwargs)

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "image": datasets.Array4D(shape=(None, 5, 800, 800), dtype="uint16"),
                    "ra": datasets.Value("float64"),
                    "dec": datasets.Value("float64"),
                    "pixscale": datasets.Value("float64"),
                    "ntimes": datasets.Value("int64"),
                    "nbands": datasets.Value("int64"),
                    "image_id": datasets.Value("string"),
                }
            ),
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation="TBD",
        )

    def _split_generators(self, dl_manager: DownloadManager):

        ret = []
        base_path = dl_manager._base_path
        #if base_path.startswith(datasets.config.HF_ENDPOINT):
        #    base_path = base_path[len(datasets.config.HF_ENDPOINT):].replace("/resolve/", "@", 1)
        #    base_path = "hf://" + base_path.lstrip("/")
        _, path = url_to_fs(base_path)

        for split in ["train", "test"]:
            split_file_location = os.path.normpath(os.path.join(path, _URLS[self.config.name][split]))
            split_file = dl_manager.download(split_file_location)
            with open(split_file, encoding="utf-8") as f:
                data_filenames = []
                data_metadata = []
                for line in f:
                    item = json.loads(line)
                    data_filenames.append(item["image"])
                    data_metadata.append({"ra": item["ra"], 
                                          "dec": item["dec"], 
                                          "pixscale": item["pixscale"], 
                                          "ntimes": item["ntimes"], 
                                          "nbands": item["nbands"],
                                          "image_id": item["image_id"]})

                data_urls = [os.path.normpath(os.path.join(path,data_filename)) for data_filename in data_filenames]
                data_files = [dl_manager.download(data_url) for data_url in data_urls]
            ret.append(
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN if split == "train" else datasets.Split.TEST,
                    gen_kwargs={"filepaths": data_files,
                                "split_file": split_file,
                                "split": split, 
                                "data_metadata": data_metadata},
                ),
            )
        return ret

    def _generate_examples(self, filepaths, split_file, split, data_metadata):
        """Generate GBI-16-4D examples"""

        for idx, (filepath, item) in enumerate(zip(filepaths, data_metadata)):
            task_instance_key = f"{self.config.name}-{split}-{idx}"
            with fits.open(filepath, memmap=False) as hdul:
                image_data = hdul[0].data.tolist()
                yield task_instance_key, {**{"image": image_data}, **item}

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 files:
                print(file, flush=True, end="...")
                with fits.open(file, memmap=False) as hdul:
                    image_id = os.path.basename(file).split(".fits")[0]
                    ra = hdul[0].header.get('CRVAL1', 0)
                    dec = hdul[0].header.get('CRVAL2', 0)
                    pixscale = hdul[0].header.get('CD1_2', 0.396)
                    ntimes = hdul[0].data.shape[0]
                    nbands = hdul[0].data.shape[1]
                    item = {"image_id": image_id, "image": file, "ra": ra, "dec": dec, 
                            "pixscale": pixscale, "ntimes": ntimes, "nbands": nbands}
                    out_f.write(json.dumps(item) + "\n")

    create_jsonl(train_files, "train")
    create_jsonl(test_files, "test")