"""Walk the bytes of a real FITS file by the rules of the FITS Standard 4.0, then check with astropy. The file is a public TESS SPOC 2-minute light curve (TIC 52368076, sector 1; NASA data, public domain). The walker uses only the standard's rules: * the file is a sequence of 2880-byte records (FITS 4.0 section 3.1); * a header is 80-byte ASCII cards, ended by END, padded with spaces to a whole record (3.3.1); * the data size in bits is |BITPIX| x GCOUNT x (PCOUNT + NAXIS1 x ... x NAXISm) (Eq. 1 for the primary HDU with GCOUNT = 1 and PCOUNT = 0; Eq. 2 for extensions), padded with zeros to a whole record (3.3.2). uv run --no-project --python 3.13 --with astropy==8.0.3 --with numpy==2.5.5 \ --with matplotlib==3.11.2 python -I analysis.py """ from __future__ import annotations import csv import io import json import math import pathlib import re import struct import sys import numpy as np from astropy.io import fits from astropy.time import Time HERE = pathlib.Path(__file__).resolve().parent REPO = HERE.parents[3] sys.path.insert(0, str(REPO / ".claude" / "skills" / "blog-post" / "scripts")) import figstyle # noqa: E402 RECORD = 2880 CARD = 80 def parse_value(raw: str): v = raw.split("/", 1)[0].strip() if not raw.strip().startswith("'") else raw.strip() if v.startswith("'"): return v.split("'")[1].rstrip() if v in ("T", "F"): return v == "T" try: return int(v) except ValueError: try: return float(v) except ValueError: return v # bytes per element for each binary-table format letter (FITS 4.0 Table 18); X is bits TFORM_BYTES = {"L": 1, "B": 1, "I": 2, "J": 4, "K": 8, "A": 1, "E": 4, "D": 8, "C": 8, "M": 16, "P": 8, "Q": 16} def tform_bytes(tform: str) -> int: m = re.match(r"^\s*(\d*)([LXBIJKAEDCMPQ])", tform) repeat = int(m.group(1)) if m.group(1) else 1 if m.group(2) == "X": return -(-repeat // 8) return repeat * TFORM_BYTES[m.group(2)] def bzero_demo() -> dict: """Write three unsigned 16-bit pixels with astropy, then read the stored integers by hand.""" buf = io.BytesIO() pixels = np.array([0, 1000, 65535], dtype=np.uint16) fits.PrimaryHDU(pixels).writeto(buf) raw = buf.getvalue() hdr = fits.Header.fromstring(raw[:RECORD].decode("ascii")) d0 = walk(raw)[0]["data_offset"] stored = struct.unpack(">3h", raw[d0:d0 + 6]) shape_demo = io.BytesIO() fits.PrimaryHDU(np.zeros((2, 3), dtype=np.int16)).writeto(shape_demo) sh = fits.Header.fromstring(shape_demo.getvalue()[:RECORD].decode("ascii")) return { "numpy_shape_2x3_gives_NAXIS1_NAXIS2": [sh["NAXIS1"], sh["NAXIS2"]], "pixels_written": [int(v) for v in pixels], "BITPIX": hdr["BITPIX"], "BZERO": hdr["BZERO"], "BSCALE": hdr["BSCALE"], "stored_int16": list(stored), "physical_from_eq3": [hdr["BZERO"] + hdr["BSCALE"] * v for v in stored], } def walk(raw: bytes) -> list[dict]: hdus = [] pos = 0 while pos < len(raw): start = pos cards = {} n_cards = 0 while True: block = raw[pos:pos + RECORD] if len(block) < RECORD: raise SystemExit(f"truncated record at byte {pos}") pos += RECORD done = False for i in range(0, RECORD, CARD): card = block[i:i + CARD].decode("ascii") key = card[:8].strip() n_cards += 1 if key == "END": done = True break if card[8:10] == "= ": cards.setdefault(key, parse_value(card[10:])) if done: break header_bytes = pos - start # padding after END must be ASCII spaces pad = raw[start + n_cards * CARD:pos] assert pad == b" " * len(pad), "header padding is not ASCII spaces" naxis = cards.get("NAXIS", 0) shape = [cards[f"NAXIS{k}"] for k in range(1, naxis + 1)] bits = abs(cards["BITPIX"]) * cards.get("GCOUNT", 1) * ( cards.get("PCOUNT", 0) + (math.prod(shape) if naxis else 0)) data_bytes = bits // 8 data_records = -(-data_bytes // RECORD) dpad = raw[pos + data_bytes:pos + data_records * RECORD] assert dpad == b"\0" * len(dpad), "data padding is not zero bytes" hdus.append({ "index": len(hdus), "kind": cards.get("XTENSION", "PRIMARY"), "extname": cards.get("EXTNAME", ""), "bitpix": cards["BITPIX"], "naxis": shape, "pcount": cards.get("PCOUNT", 0), "gcount": cards.get("GCOUNT", 1), "cards_including_end": n_cards, "header_offset": start, "header_bytes": header_bytes, "header_records": header_bytes // RECORD, "data_offset": pos, "data_bytes": data_bytes, "data_records": data_records, "data_padding_bytes": data_records * RECORD - data_bytes, }) pos += data_records * RECORD return hdus def main(path: str) -> int: p = pathlib.Path(path) raw = p.read_bytes() hdus = walk(raw) total = sum(h["header_bytes"] + h["data_records"] * RECORD for h in hdus) # cross-check with astropy with fits.open(p, memmap=False) as hdul: info = [hdul.fileinfo(i) for i in range(len(hdul))] check = [] for h, fi, hdu in zip(hdus, info, hdul): ok = (fi["hdrLoc"] == h["header_offset"] and fi["datLoc"] == h["data_offset"] and fi["datSpan"] == h["data_records"] * RECORD) check.append(ok) lc = hdul[1] timecol = {"TIMESYS": lc.header["TIMESYS"], "TIMEREF": lc.header["TIMEREF"], "BJDREFI": lc.header["BJDREFI"], "BJDREFF": lc.header["BJDREFF"], "TIMEUNIT": lc.header["TIMEUNIT"], "TFIELDS": lc.header["TFIELDS"], "TFORM1": lc.header["TFORM1"], "TTYPE1": lc.header["TTYPE1"], "TUNIT1": lc.header["TUNIT1"], "TSTART": lc.header["TSTART"], "TSTOP": lc.header["TSTOP"], "TIMEDEL": lc.header["TIMEDEL"]} ref = lc.header["BJDREFI"] + lc.header["BJDREFF"] span_tdb = [Time(ref + lc.header[k], format="jd", scale="tdb").isot[:16] for k in ("TSTART", "TSTOP")] primary = {k: hdul[0].header[k] for k in ("TELESCOP", "OBJECT", "SECTOR", "ORIGIN", "DATE", "PROCVER", "DATA_REL")} ap = hdul[2].data ap_dtype = str(ap.dtype) ap_first_row_numpy = [int(v) for v in ap[0, :3]] # row width from the column formats (FITS 4.0 Table 18) must equal NAXIS1 tforms = [lc.header[f"TFORM{n}"] for n in range(1, lc.header["TFIELDS"] + 1)] ttypes = [lc.header[f"TTYPE{n}"] for n in range(1, lc.header["TFIELDS"] + 1)] row_bytes = sum(tform_bytes(t) for t in tforms) astropy_time0 = float(lc.data["TIME"][0]) astropy_cadence0 = int(lc.data["CADENCENO"][0]) # the first value of the table read by hand: TIME is column 1, format D (8-byte float) d0 = hdus[1]["data_offset"] first8 = raw[d0:d0 + 8] by_hand = { "first_8_bytes_hex": first8.hex(), "time_big_endian": struct.unpack(">d", first8)[0], "time_little_endian_wrong": struct.unpack("i", raw[d0 + 12:d0 + 16])[0], "astropy_cadenceno_row0": astropy_cadence0, } result = { "file": p.name, "file_bytes": len(raw), "records": len(raw) // RECORD, "remainder_bytes": len(raw) % RECORD, "hdus": hdus, "walker_total_bytes": total, "astropy_offsets_agree": check, "lightcurve_time_keywords": timecol, "observation_span_tdb": span_tdb, "primary_keywords": primary, "aperture_numpy_dtype": ap_dtype, "aperture_numpy_first_row_first_three": ap_first_row_numpy, "lightcurve_columns": [f"{a}:{b}" for a, b in zip(ttypes, tforms)], "lightcurve_row_bytes_from_tforms": row_bytes, "first_table_value_by_hand": by_hand, "bzero_demo": bzero_demo(), } (HERE / "data").mkdir(exist_ok=True) with open(HERE / "data" / "results.json", "w") as fh: json.dump(result, fh, indent=1, sort_keys=True) fh.write("\n") with open(HERE / "data" / "hdu_table.csv", "w", newline="") as fh: keys = ["index", "kind", "extname", "bitpix", "naxis", "cards_including_end", "header_offset", "header_records", "data_offset", "data_bytes", "data_records", "data_padding_bytes"] w = csv.DictWriter(fh, fieldnames=keys, lineterminator="\n", extrasaction="ignore") w.writeheader() for h in hdus: w.writerow({**h, "naxis": "x".join(str(n) for n in h["naxis"]) or "-"}) make_figure(hdus, len(raw)) print(json.dumps(result, indent=1, sort_keys=True)) return 0 def make_figure(hdus, size): fig_dir = HERE / "figures" segs = [] # (start, length, kind, label) for h in hdus: segs.append((h["header_offset"], h["header_bytes"], "header", f"HDU {h['index']} header")) if h["data_bytes"]: segs.append((h["data_offset"], h["data_bytes"], "data", f"HDU {h['index']} data")) segs.append((h["data_offset"] + h["data_bytes"], h["data_padding_bytes"], "pad", "padding")) views = [(0, size, "Whole file"), (0, hdus[1]["data_offset"] + 2 * RECORD, "First 9 records"), (size - 4 * RECORD, size, "Last 4 records")] h0, h1, h2 = hdus LABELS = { "First 9 records": [ (0, h0["header_bytes"], "primary header (2 records)"), (h1["header_offset"], h1["data_offset"], "LIGHTCURVE header (5 records)"), (h1["data_offset"], h1["data_offset"] + 2 * RECORD, "table rows"), ], "Last 4 records": [ (h1["data_offset"] + h1["data_bytes"], h2["header_offset"], "zero padding"), (h2["header_offset"], h2["data_offset"], "APERTURE header (2 records)"), (h2["data_offset"], size, "11 x 11 image + padding"), ], } for theme in figstyle.THEMES: with figstyle.style(theme) as c: colour = {"header": c["graphite"], "data": c["accent"], "pad": c["rule"]} hatch = {"header": "////", "data": "", "pad": "...."} fig, axes = figstyle.figure(7.2, 4.4, nrows=3) for ax, (lo, hi, title) in zip(axes, views): for start, length, kind, label in segs: a, b = max(lo, start), min(hi, start + length) if b <= a: continue ax.barh(0, b - a, left=a, height=0.6, color=colour[kind], edgecolor=c["surface"], linewidth=0.6, hatch=hatch[kind]) for k in range(math.ceil(lo / RECORD), math.floor(hi / RECORD) + 1): if hi - lo < 40 * RECORD: ax.vlines(k * RECORD, -0.3, 0.3, color=c["ink"], lw=0.4, alpha=0.5) for h in hdus: # HDU boundaries if lo < h["header_offset"] < hi: ax.vlines(h["header_offset"], -0.38, 0.38, color=c["ink"], lw=1.6) for x0, x1, text in LABELS.get(title, []): ax.text((x0 + x1) / 2, 0.42, text, ha="center", va="bottom", fontsize=7.5, color=c["ink"]) ax.set_ylim(-0.4, 1.0) ax.set_xlim(lo, hi) ax.set_yticks([]) ax.grid(False) ax.spines["left"].set_visible(False) ax.set_title(title, loc="left", fontsize=9) ax.ticklabel_format(axis="x", style="plain") ax.xaxis.set_major_formatter(lambda v, _: f"{int(v):,}") axes[-1].set_xlabel("Byte offset in the file (thin lines: 2880-byte records; thick lines: start of an HDU)") from matplotlib.patches import Patch handles = [Patch(facecolor=colour[k], hatch=hatch[k], edgecolor=c["surface"], label=l) for k, l in (("header", "Header cards"), ("data", "Data"), ("pad", "Zero padding"))] axes[0].legend(handles=handles, loc="upper right", ncols=3, bbox_to_anchor=(1, 1.75)) figstyle.save(fig, fig_dir / "fig-1-byte-map", theme) with open(fig_dir / "fig-1-byte-map.csv", "w") as fh: fh.write("start_byte,length_bytes,kind,label\n") for s in segs: fh.write(f"{s[0]},{s[1]},{s[2]},{s[3]}\n") if __name__ == "__main__": sys.exit(main(sys.argv[1]))