File size: 8,440 Bytes
9fa663b 352a93a 9fa663b 88109f2 9fa663b 4f8ca91 9fa663b 88109f2 9fa663b 352a93a 4f8ca91 9fa663b 352a93a 88109f2 4f8ca91 88109f2 4f8ca91 88109f2 ece7187 4f8ca91 ece7187 39a7e37 88109f2 352a93a 88109f2 39a7e37 88109f2 39a7e37 88109f2 39a7e37 88109f2 39a7e37 9fa663b 88109f2 9fa663b 352a93a 88109f2 39a7e37 9fa663b 352a93a 9fa663b 88109f2 9fa663b |
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
from io import BytesIO
import datasets
import pandas as pd
import numpy as np
import json
from astropy.io import fits
from utils import ParallelZipFile
_DESCRIPTION = (
"AstroM3 is a time-series astronomy dataset containing photometry, spectra, "
"and metadata features for variable stars. The dataset includes multiple "
"subsets (full, sub10, sub25, sub50) and supports different random seeds (42, 66, 0, 12, 123). "
"Each sample consists of:\n"
"- **Photometry**: Light curve data of shape `(N, 3)` (time, flux, flux_error).\n"
"- **Spectra**: Spectral observations of shape `(M, 3)` (wavelength, flux, flux_error).\n"
"- **Metadata**: Auxiliary features of shape `(25,)`.\n"
"- **Label**: The class name as a string."
)
_HOMEPAGE = "https://huggingface.co/datasets/AstroM3"
_LICENSE = "CC BY 4.0"
_URL = "https://huggingface.co/datasets/MeriDK/AstroM3Dataset/resolve/main"
_VERSION = datasets.Version("1.0.0")
_CITATION = """
@article{AstroM3,
title={AstroM3: A Multi-Modal Astronomy Dataset},
author={Your Name},
year={2025},
journal={AstroML Conference}
}
"""
class AstroM3Dataset(datasets.GeneratorBasedBuilder):
"""Hugging Face dataset for AstroM3 with configurable subsets and seeds."""
DEFAULT_CONFIG_NAME = "full_42"
BUILDER_CONFIGS = [
datasets.BuilderConfig(name=f"{sub}_{seed}", version=_VERSION, data_dir=None)
for sub in ["full", "sub10", "sub25", "sub50"]
for seed in [42, 66, 0, 12, 123]
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"photometry": datasets.Array2D(shape=(None, 3), dtype="float32"),
"spectra": datasets.Array2D(shape=(None, 3), dtype="float32"),
"metadata": datasets.Sequence(datasets.Value("float32"), length=38),
"label": datasets.Value("string"),
}
),
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _get_photometry(self, file_name):
csv = BytesIO()
file_name = file_name.replace(' ', '')
data_path = f'vardb_files/{file_name}.dat'
csv.write(self.reader_v.read(data_path))
csv.seek(0)
lc = pd.read_csv(csv, sep=r'\s+', skiprows=2, names=['HJD', 'MAG', 'MAG_ERR', 'FLUX', 'FLUX_ERR'],
dtype={'HJD': float, 'MAG': float, 'MAG_ERR': float, 'FLUX': float, 'FLUX_ERR': float})
return lc[['HJD', 'FLUX', 'FLUX_ERR']].values
@staticmethod
def _get_spectra(file_name):
hdulist = fits.open(file_name)
len_list = len(hdulist)
if len_list == 1:
head = hdulist[0].header
scidata = hdulist[0].data
coeff0 = head['COEFF0']
coeff1 = head['COEFF1']
pixel_num = head['NAXIS1']
specflux = scidata[0,]
ivar = scidata[1,]
wavelength = np.linspace(0, pixel_num - 1, pixel_num)
wavelength = np.power(10, (coeff0 + wavelength * coeff1))
hdulist.close()
elif len_list == 2:
head = hdulist[0].header
scidata = hdulist[1].data
wavelength = scidata[0][2]
ivar = scidata[0][1]
specflux = scidata[0][0]
else:
raise ValueError(f'Wrong number of fits files. {len_list} should be 1 or 2')
return np.vstack((wavelength, specflux, ivar)).T
@staticmethod
def _transform_metadata(row, info):
row_copy = row.copy(deep=True)
for transformation_type, value in info["metadata_func"].items():
if transformation_type == "abs":
for col in value:
row_copy[col] = (
row_copy[col] - 10 + 5 * np.log10(np.where(row_copy["parallax"] <= 0, 1, row_copy["parallax"]))
)
elif transformation_type == "cos":
for col in value:
row_copy[col] = np.cos(np.radians(row_copy[col]))
elif transformation_type == "sin":
for col in value:
row_copy[col] = np.sin(np.radians(row_copy[col]))
elif transformation_type == "log":
for col in value:
row_copy[col] = np.log10(row_copy[col])
row_copy = (row_copy - info["mean"]) / info["std"]
return row_copy
def _split_generators(self, dl_manager):
"""Returns SplitGenerators for train, val, and test."""
# Get subset and seed info from the name
sub, seed = self.config.name.split("_")
# Load the splits and info files
urls = {
"train": f"{_URL}/splits/{sub}/{seed}/train.csv",
"val": f"{_URL}/splits/{sub}/{seed}/val.csv",
"test": f"{_URL}/splits/{sub}/{seed}/test.csv",
"info": f"{_URL}/splits/{sub}/{seed}/info.json",
}
extracted_path = dl_manager.download(urls)
df1 = pd.read_csv(extracted_path["train"])
df2 = pd.read_csv(extracted_path["val"])
df3 = pd.read_csv(extracted_path["test"])
df_combined = pd.concat([df1, df2, df3], ignore_index=True)
# Load all spectra files
spectra_urls = {}
for _, row in df_combined.iterrows():
spectra_urls[row["spec_filename"]] = f"{_URL}/spectra/{row['target']}/{row['spec_filename']}"
spectra_files = dl_manager.download(spectra_urls)
# Load photometry and init reader
photometry_path = dl_manager.download(f"{_URL}/photometry.zip")
self.reader_v = ParallelZipFile(photometry_path)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={"csv_path": extracted_path["train"],
"info_path": extracted_path["info"],
"spectra_files": spectra_files,
"split": "train"}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION, gen_kwargs={"csv_path": extracted_path["val"],
"info_path": extracted_path["info"],
"spectra_files": spectra_files,
"split": "val"}
),
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={"csv_path": extracted_path["test"],
"info_path": extracted_path["info"],
"spectra_files": spectra_files,
"split": "test"}
),
]
def _generate_examples(self, csv_path, info_path, spectra_files, split):
"""Yields examples from a CSV file containing photometry, spectra, metadata, and labels."""
df = pd.read_csv(csv_path)
with open(info_path) as f:
info = json.loads(f.read())
for i, (idx, row) in enumerate(df.iterrows()):
photometry = self._get_photometry(row["name"])
spectra = self._get_spectra(spectra_files[row["spec_filename"]])
metadata = row[info["all_cols"]]
# metadata_norm = self._transform_metadata(metadata, info)
# yield idx, {
# "photometry": photometry,
# "spectra": spectra,
# "metadata": {
# "original": {
# "photometry": metadata[info["photo_cols"]].to_dict(),
# "metadata": metadata[info["meta_cols"]].to_dict()
# },
# "transformed": {
# "photometry": metadata_norm[info["photo_cols"]].to_dict(),
# "metadata": metadata_norm[info["meta_cols"]].to_dict()
# }
# },
# "label": row["target"],
# }
yield idx, {
"photometry": photometry,
"spectra": spectra,
"metadata": row[info["all_cols"]],
"label": row["target"],
}
|