src/core/fits.js
FITS reader for the cases photometry needs, with no dependency: primary image HDU, IMAGE extensions,
BINTABLE extensions (TESS / Kepler target pixel files, TESScut cutouts), BITPIX 8/16/32/64/-32/-64,
BSCALE/BZERO/BLANK, gzip through DecompressionStream, tile-compressed images (fpack, .fz: RICE_1, GZIP_1,
GZIP_2, PLIO_1, NOCOMPRESS, quantised floats with every dither method), headers without END, cubes, Bayer
frames. Also the time, exposure, airmass, pixel scale, WCS (TAN) and pier side keywords of a frame, and the
UTC -> BJD_TDB conversion. No DOM; runs in Node, in a page and in a worker.
The aim is to open what astropy.io.fits opens for EXOTIC (fits.open(..., ignore_missing_end=True), first HDU
with NAXIS != 0); test/fits.test.mjs compares each case with astropy (test/make_fits_variants.py).
Not read: HCOMPRESS_1 tiles (a clear error), random groups, ASCII tables, WCS projections other than TAN
and SIP distortion (its presence is reported), colour cubes stored as (H, W, 3) with the colour on NAXIS1.
Pixel convention (same as astropy / photutils): data[y * width + x], x along NAXIS1, y along NAXIS2,
both zero-based, the centre of the first pixel at (0, 0).Import: import { … } from './src/core/fits.js' — no DOM, runs in Node and the browser.
isGzip
function isGzip(buf)True when the bytes start with the gzip magic number.
gunzip
function async gunzip(buf)Decompress gzip bytes with the platform DecompressionStream (browsers, Node 18+). Returns an ArrayBuffer.
openFits
function async openFits(buf, opts = {})Parse FITS bytes (ArrayBuffer or Uint8Array), decompressing gzip first. Async because of gzip: both the
whole-file kind (.fits.gz) and the gzip tiles of a tile-compressed image, which are inflated here (unless
opts.inflate === false) so that the synchronous readImage can decode the image afterwards.parseHeader
function parseHeader(u8, offset = 0)Parse one header starting at byte `offset`. Returns { header, comments, cards, end, missingEnd } where `end`
is the byte offset of the data unit. `header` maps keyword -> value (first occurrence wins, as in astropy),
COMMENT and HISTORY are joined arrays, and CONTINUE long strings are assembled.
A header with no END card (astropy: ignore_missing_end) is taken to stop at the first 2880-byte block that is
not printable ASCII, or at the end of the bytes; `missingEnd` is then true. (astropy itself reads on to the end
of the file in that case and finds no data, so this recovers more than it does.)imageHeader
function imageHeader(H, comments = {})The header of the image inside a tile-compressed HDU (a BINTABLE with ZIMAGE = T), as astropy presents it:
ZBITPIX -> BITPIX, ZNAXISn -> NAXISn, ZSIMPLE / ZTENSION / ZEXTEND / ZPCOUNT / ZGCOUNT / ZHECKSUM / ZDATASUM
back to their names, and the table's own keywords (TFORMn, ZCMPTYPE, ZTILEn, ...) removed. Any other header is
returned unchanged. Returns { header, comments }.parseFits
function parseFits(buffer)Split FITS bytes into HDUs without decoding any data. Returns { buffer, hdus: [{ index, header, comments, cards, type, name, dataOffset, dataBytes, shape }] } where type is 'image', 'bintable', 'table', 'compressed' or 'empty', and shape is [NAXISn, ..., NAXIS1] (numpy order) for images.
firstImageHdu
function firstImageHdu(fits)Index of the first HDU holding a 2D (or higher) image, plain or tile-compressed, or -1 (EXOTIC: the first HDU with NAXIS != 0).readImage
function readImage(fits, index = -1, opts = {})Decode an image HDU, plain or tile-compressed, to physical values. Gzip tiles need openFits (or await inflateTiles(fits)) first: decompression is asynchronous in a browser.
- param fits result of parseFits / openFits
- param index HDU index (default: the first HDU with a 2D image)
- param opts { plane: index of the 2D plane for cubes (default 0), weights: [w0, w1, ...] to return the weighted sum of the planes instead (a colour cube: [0.299, 0.587, 0.114]; not normalised here), float64: force Float64Array, out: a typed array of the right length to reuse (no allocation per frame) }
- returns { data, width, height, planes, plane, bitpix, header, compression } data is Float32Array (Float64Array for BITPIX 64/-64, or 32 with scaling); plane is -1 for a weighted sum; compression is null or ZCMPTYPE.
readImageAsync
function async readImageAsync(fits, index = -1, opts = {})readImage for any file: inflates the gzip tiles of a tile-compressed HDU first if openFits has not.
inflateTiles
function async inflateTiles(fits, index = -1)Inflate the gzip parts of the tile-compressed HDUs (all, or the one at index): the tiles of GZIP_1 / GZIP_2 images, and the GZIP_COMPRESSED_DATA fallback tiles of quantised images. The bytes are kept on the HDU (hdu.inflated) for readImage. openFits calls this.
readBinTable
function readBinTable(fits, index)Describe a binary table HDU. Returns { nrows, rowBytes, columns: [{ name, type, repeat, dim, unit, offset, width, scale, zero, nulls }], column(name) } where column(name) decodes one column for all rows into a flat typed array of nrows * repeat values (Float32Array for E, Float64Array for D and K, Int32Array for J/I/B, Uint8Array for L and X, an array of strings for A). TDIM gives dim in FITS order ([nx, ny] for an image cell). Variable-length array columns (1PB, 1PI, 1PJ, 1PE, 1PD and the 64-bit 1Q forms): descriptor(name, row) gives { count, offset (absolute, in fits.u8), bytes, elem }, heap(name, row) the raw big-endian bytes and array(name, row) the values as a Float64Array. Works on a tile-compressed image HDU too (its underlying table).
calendarToJd
function calendarToJd(y, m, d, h = 0, mi = 0, s = 0)Julian date (UTC) of a calendar date; month 1-12, fractional day allowed. Gregorian calendar.
parseFitsDate
function parseFitsDate(date, timeOfDay = null)Parse an ISO-like FITS date string ('2020-01-12T03:14:15.5', '2020-01-12', '12/01/99') to JD, or NaN.
taiMinusUtc
function taiMinusUtc(jdUtc)TAI - UTC [s] at a UTC Julian date (37 s from 2017; no leap second has been announced since).
tdbMinusUtc
function tdbMinusUtc(jdUtc)TDB - UTC in days at a UTC Julian date: leap seconds + 32.184 s + the 1.7 ms periodic term.
earthBarycentric
function earthBarycentric(jdTdb, out = [0, 0, 0])Barycentric position of the Earth [au], equatorial J2000, from a low-precision solar theory (Meeus ch. 25, 0.01 deg) plus the Sun's offset from the barycentre due to Jupiter, Saturn, Uranus and Neptune. Good to about 2e-4 au, which is 0.1 s of light time. Checked against astropy in test/fits.test.mjs.
utcToBjdTdb
function utcToBjdTdb(jdUtc, raDeg, decDeg)UTC Julian date -> BJD_TDB for a target at (raDeg, decDeg) ICRS: clock correction (leap seconds, TT, TDB)
plus the Roemer delay to the solar-system barycentre for a source at infinity. The observatory's position on
the Earth (up to 21 ms), the Shapiro delay (< 0.1 ms away from the Sun) and proper motion are left out.
Accuracy about 0.2 s (test/fits.test.mjs against astropy).exposureTime
function exposureTime(H, comments = {})Exposure time in seconds, or NaN: EXPTIME, EXPOSURE, EXP (EXOTIC's list), then EXP_TIME, EXPOSED, ITIME, INTTIME, XPOSURE, TELAPSE. A value is taken as milliseconds only when the keyword's comment says ms / msec / milliseconds and does not also mention seconds; EXPOINUS (SharpCap) is in microseconds.
frameTime
function frameTime(H, comments = {}, at = 'start')Time of a frame from its header.
Order of preference: a barycentric keyword (BJD_TDB, BJD_TBD, BJD); an explicit mid-exposure keyword (JD-MID,
JD-AVG, MJD-MID, MJD-AVG, DATE-AVG, DATE-MID); a heliocentric one (HJD, JD-HELIO: scale 'HJD'); JD keywords (JD,
JD-OBS, JULIAN, JD_UTC, JD-BEG, JD-START); MJD keywords (MJD-OBS, MJD_OBS, MJD, MJD-BEG); calendar dates (DATE-OBS,
UT-OBS, DATE-BEG, with the time of day from TIME-OBS / UT / UTC / UTSTART / UTC-OBS / UT-TIME / TIME-BEG / TIME
when the date has none); end-of-exposure keywords (DATE-END, MJD-END, JD-END); and last DATE (file creation).
`at` says where in the exposure a start-type keyword sits when its comment does not: 'start' (the FITS
standard's meaning of DATE-OBS, and the default here), 'mid' (never shift), 'end', or 'exotic', which reproduces
EXOTIC exactly (its keyword order BJD_TDB, BJD_TBD, BJD, UT-OBS, JULIAN, MJD-OBS, DATE-OBS and its rule: half an
exposure is added only when the keyword's comment contains "start"). Otherwise a comment containing "mid",
"cent" or "average" means mid-exposure, "end" the end, "start" / "begin" the start.
TIMESYS = TT, TDT, ET, TDB, TAI or GPS on a JD / MJD / date keyword is converted to UTC (`clock` = the days
subtracted, `timesys` = what the header said), so scale 'UTC' always means UTC.- returns { jd, scale: 'BJD_TDB' | 'HJD' | 'UTC' | 'none', keyword, exptime [s], shifted: days added to reach mid-exposure, position: 'start' | 'mid' | 'end' as understood, timesys, clock, dateOnly }
gmstDeg
function gmstDeg(jd)Greenwich mean sidereal time [deg] at a UT Julian date (IAU 1982 polynomial; UT1 = UTC to within 0.9 s).airmassAt
function airmassAt(jdUtc, raDeg, decDeg, latDeg, lonDeg)Airmass as sec(z) (the definition EXOTIC uses) for a J2000 position seen from a site; longitude east positive. The position is precessed to the date with the first-order formula (enough for an airmass). Returns NaN below the horizon.
framePointing
function framePointing(H)Pointing and site from common header keywords: { ra, dec [deg, NaN when absent], lat, lon [deg, east positive] }.
frameAirmass
function frameAirmass(H, fallback = null)Airmass of a frame: the AIRMASS (or SECZ) keyword, else the mean of AMSTART and AMEND, else sec(z) from an altitude or zenith-distance keyword
(TELALT as in EXOTIC, ALTITUDE, ALT, OBJCTALT, CENTALT, ELEVATIO; ZD, ZENITH), else computed from the target
position, the site and the time when all are known (`fallback` = { jdUtc, ra, dec, lat, lon }), else NaN.- returns { airmass, source }
pixelScale
function pixelScale(H, opts = {})Image scale in arcsec per pixel: IM_SCALE, PIXSCALE (EXOTIC's two), SCALE, PIXSCAL, SECPIX, SECPIX1/2, PIXSCAL1/2, then the WCS (CD matrix, PC + CDELT, CDELT on celestial axes: the mean of the two axis scales, as EXOTIC does with astropy's proj_plane_pixel_scales), then pixel size and focal length (206.265 * XPIXSZ [um] / FOCALLEN [mm]). XPIXSZ is taken as the size of a binned pixel, which is what MaxIm DL, SBIG, N.I.N.A., SharpCap and ASCOM drivers write; pass { unbinnedPixelSize: true } to multiply by XBINNING for software that does not.
- returns { scale, x, y (arcsec/px, NaN when unknown), source }
readWcs
function readWcs(H)A minimal celestial WCS: the gnomonic (TAN) projection with CRVAL, CRPIX and CD, PC + CDELT or CDELT + CROTA2. Pixel coordinates are this module's: zero-based, the centre of the first pixel at (0, 0) (FITS CRPIX is one-based). SIP and other distortions are not applied (sip / distortion say they are there); a projection other than TAN, or LONPOLE other than 180, sets approximate and the result is then only the tangent-plane approximation.
- returns null without CRVAL / CRPIX / a matrix, else { projection, approximate, sip, distortion, crval, crpix, cd: [m11, m12, m21, m22] deg/px, scale [arcsec/px], rotation (position angle of the +y axis, deg east of north), flipped (true when east is to the right with north up), pixToSky(x, y) -> [ra, dec] deg, skyToPix(ra, dec) -> [x, y] (NaN on the far hemisphere) }
pierSide
function pierSide(H)Which side of the pier a German equatorial mount was on, to anticipate a meridian flip between frames:
any keyword with PIER in its name (PIERSIDE, PIER_SIDE, PIER-SID, HIERARCH ... PIER SIDE) holding EAST / WEST
(also E / W, pierEast / pierWest, or the ASCOM numbers 0 = east, 1 = west).- returns { side: 'east' | 'west' | null, keyword }
bayerPattern
function bayerPattern(H)The colour filter array of a frame from its header: BAYERPAT, COLORTYP, CFA_PAT, CFAPAT or BAYER holding four of R, G, B (first row left to right, then the second row). XBAYROFF / YBAYROFF (odd) shift the pattern. ROWORDER is passed on, not applied: with 'BOTTOM-UP' files some software means the pattern to be read from the top row of the displayed image; check on a known colour target.
- returns null for a monochrome frame, else { pattern: 'RGGB' | 'BGGR' | 'GRBG' | 'GBRG', keyword, xoff, yoff, rowOrder }
demosaicBilinear
function demosaicBilinear(data, width, height, pattern = 'RGGB')Bilinear demosaicing of a Bayer frame, the same as colour_demosaicing.demosaicing_CFA_Bayer_bilinear that EXOTIC
calls: each colour is its own samples convolved with [[1,2,1],[2,4,2],[1,2,1]]/4 (red, blue) or
[[0,1,0],[1,4,1],[0,1,0]]/4 (green), the image edge handled as scipy.ndimage's 'reflect' (the edge pixel repeated).
`pattern` gives the colours of pixels (x, y) = (0,0), (1,0), (0,1), (1,1), e.g. 'RGGB'.- returns { r, g, b (Float32Array, same size as the frame), width, height }
mixChannels
function mixChannels(rgb, weights = 'green', opts = {})One image from the R, G, B planes, as EXOTIC's demosaic_out: 'red', 'green' (the default, also for an unknown name), 'blue', 'gray' (0.299, 0.587, 0.114), 'blueblock' (0.299, 0.587, 0) or [wR, wG, wB]; the weights are divided by their sum. opts: { truncate: true to cut towards zero as EXOTIC's cast back to an integer image does, out: a typed array to fill }. Returns a Float32Array (or out).
readTargetPixelFile
function readTargetPixelFile(fits)Read a TESS or Kepler/K2 target pixel file, or a TESScut cutout (same layout): the table of cadences with an
image in each cell, and the aperture image.
Times: the TIME column is BJD_TDB - (BJDREFI + BJDREFF) at mid-cadence (BTJD for TESS, BKJD for Kepler); `time`
here is that column and `bjdRef` the reference, so BJD_TDB = time + bjdRef.- returns { mission, object, id, sector, quarter, camera, ccd, ra, dec, nx, ny, ncad, time, bjdRef, timeUnit, cadenceno, flux, fluxErr, fluxBkg, raw, quality, posCorr1, posCorr2, aperture (Int32Array ny*nx or null), exptime [s], cadence [d], col0, row0 (CCD coordinates of pixel 0,0), bkgSubtracted, header } flux etc. are Float32Array of ncad * ny * nx, cadence-major.
encodeFitsImage
function encodeFitsImage(data, width, height, cards = {}, bitpix = -32)Encode a single-image FITS file (BITPIX -32 or 16) from a typed array; cards is an object of extra keywords. Returns Uint8Array.