Skip to content

src/core/photometry.js ​

Photometry on images: background, centroids, aperture and PSF photometry, source detection, tracking stars from frame to frame, and the choice of aperture / sky annulus / comparison star by residual scatter, the way EXOTIC does it (exotic/exotic.py: aperPhot, skybg_phot, fit_centroid and the loop over apers and annuli). No DOM. Images are typed arrays, data[y * width + x], pixel centres at integer coordinates (photutils' convention), and nothing here allocates per pixel: scratch buffers are module-level and reused.

Checked against astropy + photutils + scipy in test/photometry.test.mjs (reference made by test/make_photometry_reference.py).

Import: import { … } from './src/core/photometry.js' — no DOM, runs in Node and the browser.

circleRectOverlap ​

js
function circleRectOverlap(xmin, ymin, xmax, ymax, r)

Area of the rectangle [xmin, xmax] x [ymin, ymax] inside the circle of radius r centred on the origin.

apertureSum ​

js
function apertureSum(data, w, h, xc, yc, r, method = 'exact', subpixels = 5)
text
Sum of the image inside a circular aperture of radius r centred on (xc, yc).
method 'exact': each pixel weighted by its exact overlap area with the circle (photutils method='exact').
method 'subpixel': each pixel split into subpixels^2 and weighted by the fraction of sub-pixel centres inside
  (photutils method='subpixel'). method 'center': pixels whose centre is inside.
Non-finite pixels are skipped (and counted). Pixels outside the image contribute nothing; `clipped` says so.
  • returns the same Float64Array each call: [sum, area, max pixel value, clipped (0/1), number of NaN pixels]

sigmaClippedStats ​

js
function sigmaClippedStats(v, n, sigma = 3, maxiters = 5, presorted = false)

Sigma-clipped statistics of the first n values of v (sorted in place): clip about the median at sigma * std, repeat up to maxiters times or until nothing is rejected. This is astropy's sigma_clipped_stats(sigma, maxiters, cenfunc='median', stdfunc='std').

  • returns the shared Float64Array [median, mean, std, count]

annulusBackground ​

js
function annulusBackground(data, w, h, xc, yc, rin, rout, sigma = 3, maxiters = 5)
text
Sky background in an annulus rin <= d < rout about (xc, yc): pixels whose centres are in the annulus
(photutils CircularAnnulus mask, method='center'), sigma-clipped.
  • returns the shared Float64Array [median, mean, std, count] (count 0 and NaN values when the annulus is empty)

annulusPrepare ​

js
function annulusPrepare(data, w, h, xc, yc, rmin, rmax)

Prepare several annuli about one centre: the pixels between rmin and rmax are collected and sorted by value once; annulusFromSorted then gives the statistics of any annulus inside that range by one pass, with the same result as annulusBackground (the sort is the cost, and a grid of annuli shares it).

annulusFromSorted ​

js
function annulusFromSorted(rin, rout, sigma = 3, maxiters = 5)

No description in the source.

frameStats ​

js
function frameStats(data, w, h, nsample = 100000)

Level and noise of a whole frame from a strided sample (at most ~nsample pixels): median and 1.4826 * MAD.

  • returns { median, sigma }

centroidCom ​

js
function centroidCom(data, w, h, x0, y0, half, bkg = 0)

Flux-weighted centroid over the box of half-width half about (round(x0), round(y0)), after subtracting bkg: sum(v x) / sum(v). This is photutils.centroids.centroid_com on the same cutout. Returns [x, y] in a shared array.

centroidIter ​

js
function centroidIter(data, w, h, x0, y0, half = 7, iters = 6)

A centroid that survives a poor starting guess and a sloping sky: the level is the median of the box's border, pixels under level + 3 sigma are ignored, and the box is re-centred until the centre moves by less than 0.01 px (at most iters times); the position is then refined with a Gaussian-windowed centroid. Returns [x, y, flux above the threshold, border level, border sigma, window sigma].

fitPsf ​

js
function fitPsf(data, w, h, x0, y0, half = 7, opts = {})
text
Fit a PSF plus a constant background to the box of half-width `half` about (x0, y0) by least squares
(Levenberg-Marquardt, analytic derivatives, unweighted). The model is sampled at pixel centres as EXOTIC does,
or, with opts.oversample = n > 1, averaged over n x n points inside each pixel, which matters when the PSF is
narrower than about 1.5 px sigma (an undersampled star is not a Gaussian sampled at pixel centres).
  model 'gaussian': bg + amp * exp(-(rx^2 / 2 sx^2 + ry^2 / 2 sy^2)), optionally rotated (opts.rotate);
                    flux = 2 pi amp sx sy
  model 'moffat':   bg + amp * (1 + r^2 / gamma^2)^-beta;  flux = pi amp gamma^2 / (beta - 1);  fwhm = 2 gamma sqrt(2^(1/beta) - 1)
  • returns { x, y, amp, sx, sy, theta, gamma, beta, bg, flux, fwhm, chi2, npix, iters, ok }

detectSources ​

js
function detectSources(data, w, h, opts = {})

Find stars: 3x3 box smoothing, local maxima above nsigma (noise of the smoothed frame), then a centroid and a rough flux for each. Single hot pixels are rejected (more than sharp of the 3x3 flux in one pixel).

  • param opts { nsigma = 5, max = 60, border = 8, minSep = 6, sharp = 0.85, saturation = Infinity, half = 6 }
  • returns { sources: [{ x, y, flux, peak, saturated }] sorted by flux, brightest first; background, sigma }

estimateShift ​

js
function estimateShift(ref, cur, w, h, opts = {})

Translation (and optionally a 180 degree flip, as after a meridian flip) that maps reference source positions onto the sources of another frame, by voting on pairwise offsets among the brightest sources.

  • returns { dx, dy, flip, votes } new = ref + (dx, dy), or new = (w-1-ref.x, h-1-ref.y) + (dx, dy) when flip

trackStars ​

js
function trackStars(data, w, h, prev, out, opts = {})

Follow stars into a new frame. Each star is re-centred from its previous position; the median shift of the stars that were found is then applied to any star that was lost or that moved differently from the others (by more than tol px), so one star cannot wander off on its own.

  • param prev Float64Array [x0, y0, x1, y1, ...] positions in the previous frame
  • param out Float64Array of the same length for the new positions
  • returns { lost: number of stars placed by the median shift, dx, dy: the median shift }

linspace ​

js
const linspace

n values from a to b inclusive.

makeMeasurements ​

js
function makeMeasurements(nF, nS, apertures, annuli, gap = 2)
text
Storage for the photometry of nF frames, nS stars (star 0 is the target), on nA aperture radii and nN annulus
widths. The flux of star s in frame f for aperture a and annulus n is raw - area * bg (see fluxOf).
The sky annulus runs from r_aper + gap to r_aper + gap + width, as in EXOTIC (gap = 2 px there).

measureFrame ​

js
function measureFrame(M, f, data, w, h, pos, cfg = {})

Measure every star of one frame at every aperture and annulus and store it as frame f.

  • param pos Float64Array [x0, y0, ...] the centroids to use (from trackStars)
  • param cfg { psf: 'gaussian' | 'moffat' | 'none', psfHalf, method: 'exact' | 'subpixel', sigma, maxiters }

fluxOf ​

js
function fluxOf(M, s, a, n, out = new Float64Array(M.count)

Background-subtracted flux of star s for aperture index a and annulus index n, all frames, into out.

METHODS ​

js
const METHODS

The names of the ways a flux can be measured, in the order they are tried.

METHOD_LABEL ​

js
const METHOD_LABEL

No description in the source.

seriesOf ​

js
function seriesOf(M, kind, s, a, n, out = new Float64Array(M.count)

Flux of star s by any method ('psf', 'moffat', 'optimal', 'aperture', 'ellipse'; a, n only matter for the last two), all frames, into out.

ellipsePixelOverlap ​

js
function ellipsePixelOverlap(dx, dy, a, b, theta)

Exact area of the unit pixel centred at (dx, dy) inside the ellipse of semi-axes a, b centred on the origin with the a axis at angle theta from +x (counter-clockwise): the pixel is mapped to a parallelogram in the frame where the ellipse is the unit circle, and the polygon-circle intersection is summed edge by edge.

ellipseSum ​

js
function ellipseSum(data, w, h, xc, yc, a, b, theta = 0)
text
Sum of the image inside an elliptical aperture (semi-axes a >= or < b, a axis at angle theta from +x), every pixel
weighted by its exact overlap (photutils EllipticalAperture, method='exact').
  • returns the shared Float64Array [sum, area, max pixel value, clipped (0/1), number of NaN pixels]

optimalFlux ​

js
function optimalFlux(data, w, h, x, y, sx, sy, theta, bg, rclip, os = 1)

Optimal (variance-weighted) extraction in the sky-limited form of Naylor (1998, MNRAS 296, 339): with a profile P normalised to unit sum and a uniform variance, the minimum-variance flux is sum(P (d - bg)) / sum(P^2) over the pixels within rclip of the star. P is a Gaussian (sx, sy, theta) about (x, y), sampled at pixel centres or (os > 1) averaged over os x os points in each pixel. Used with the same profile for every star of a frame, the estimate is a fixed fraction of each star's flux even when the profile is not exactly the PSF, so ratios between stars are unbiased.

trapezoid ​

js
function trapezoid(t, tmid, dur, ing = 0.15)

Trapezoid transit shape in [0, 1]: 1 inside the flat bottom, linear ingress/egress of fraction ing of the duration each.

quickFit ​

js
function quickFit(t, f, opts = {})
text
Quick model of a light curve, for ranking candidates and for residuals, with no knowledge of the planet:
  flux = c0 + c1 * (airmass - mean)  [or c1 * time when airmass is missing or constant]  (+ c2 * time^2 when order = 2)
         - depth * trapezoid(t; tmid, duration)
linear least squares for the coefficients at each (tmid, duration) of a grid, keeping the best. The transit
term is kept only if it lowers the BIC by more than 10 and the depth is positive; otherwise the result is the
baseline alone. Points more than `clip` robust sigma from the model are dropped once and the fit repeated.
(EXOTIC fits its full transit model times a1 * exp(a2 * airmass) here, which needs the planet's parameters.)
  • param opts { airmass, order = 1, transit = true, tmid: [lo, hi] or null, durations: [d] or null, clip = 4, ntmid = 40 (steps across a given tmid range), refine = true }
  • returns { model, baseline, resid, keep (Uint8Array), scatter (std of residuals / median flux, EXOTIC's measure), robust (1.4826 MAD / median), depth (fractional), tmid, duration, hasTransit, coef, n }

optimise ​

js
function optimise(M, opts = {})

EXOTIC-style optimisation over the measurements of a stack: for every aperture radius, every annulus width and every choice of comparison (none, each comparison star alone, all comparison stars summed when there are several), and for PSF-fit fluxes with each comparison, form target / comparison, fit quickFit, and rank by the residual scatter std(residual) / median(flux). Returns the table of everything tried and the best light curve.

  • param opts { fit: options for quickFit (airmass is taken from M), comps: 'all' (default) | 'single' | 'none' , ensemble = true, psf = true, metric: 'scatter' | 'robust' }
  • returns { tried: [{ method, aperture, annulus, comp, scatter, robust, n, depth }], best: index into tried, lc: { time, flux, err, norm, normErr, model, baseline, resid, keep, target, comparison, fit } }

weightedComparison ​

js
function weightedComparison(M, kind, a, n, target)

The comparison stars of a stack combined with inverse-variance weights (ensembleWeights in detrend.js: each star's white noise from the pairwise flux ratios, the target included as one of the series). Frames where any star has no flux are left out of the noise estimate. @returns { comparison (median 1), weights, sigma, medians, series }

lightCurveFor ​

js
function lightCurveFor(M, row, fitOpts = {}, fitter = null)
text
The light curve of one row of the tried table (or any { method, ia, in, comp }).
`photErr` is the relative noise expected for each point from the CCD equation with the sky variance measured in
the annulus (which already holds the sky's photon noise, the read noise and the dark current):
  var(star) = flux / gain + npix * sigma_sky^2 * (1 + npix / nsky)      [ADU^2; gain in e-/ADU, opts.gain, default 1]
for the target and the comparison, added in quadrature. `photErrStar` is the same without the sky terms.

dilateMask ​

js
function dilateMask(mask, nx, ny, iters = 1)

Grow a mask by one pixel in the 4-connected sense (scipy.ndimage.binary_dilation's default), iters times.

pipelineMask ​

js
function pipelineMask(tpf)
text
The pipeline's optimal aperture from the APERTURE image (bit 2 = "used in the optimal aperture"), or null.

tpfMedianImage ​

js
function tpfMedianImage(tpf, step = 0, qmask = 0x7fffffff)
text
Median image over cadences (every `step`-th cadence whose QUALITY has none of the bits of `qmask` set; default any
flag), for display and for threshold masks. NaN pixels are ignored and an even count takes the mean of the two middle
values (numpy nanmedian, as lightkurve's median image when step = 1 and qmask is its quality bitmask).

thresholdMask ​

js
function thresholdMask(img, nx, ny, nsigma, x0, y0, opts = {})
text
Pixels brighter than median + nsigma × 1.4826 MAD of the median image, connected (4-neighbours) to the target
(lightkurve's 'threshold' mask). Default: the region starts from the above-threshold pixel nearest (x0, y0) if it is
within 2.5 px (else the mask is empty). opts.lightkurve: exactly create_threshold_mask(nsigma, reference_pixel), i.e.
pixels >= the cut (NaN as 0), the region whose pixel is nearest (x0, y0) however far, with x0, y0 = nx/2, ny/2 for
its 'center'.

circleMask ​

js
function circleMask(nx, ny, x0, y0, r)

Pixels whose centres lie within r of (x0, y0).

tpfLightCurve ​

js
function tpfLightCurve(tpf, mask, opts = {})
text
Simple aperture photometry of a target pixel file with a pixel mask: per cadence the sum of FLUX over the mask,
its uncertainty (FLUX_ERR in quadrature), the flux-weighted centroid over the mask (lightkurve's
estimate_centroids), and the background per pixel. Cadences with a non-zero QUALITY flag, a NaN time or a NaN
pixel in the mask have ok = 0.
When the file's fluxes are not background-subtracted (TESScut cutouts), the background per cadence is the
sigma-clipped median of the pixels outside the mask grown by two pixels, and it is subtracted.
Also the noise-pixel parameter β = (Σf)² / Σf² over the mask (the PSF-width proxy the owner's TOI extraction records).
  • param opts { quality: bitmask of flags to reject (default all; the page uses lightkurve's 'default'), subtract: 'auto' | true | false }
  • returns { time (BJD_TDB), flux, err, bkg (per pixel), x, y (pixel coordinates in the cutout), beta, ok, npix }

savgol2 ​

js
function savgol2(y, win)

Savitzky-Golay smoothing (local polynomial of order 2 in a window of win points, odd), with the ends taken from the polynomial fitted to the first / last window: scipy.signal.savgol_filter(y, win, 2, mode='interp').

runningMedian ​

js
function runningMedian(y, win)

Running median of y over a window of win points (odd; shorter at the ends).

smoothScatter ​

js
function smoothScatter(time, flux, dtHours = 0.5, relative = true, robust = false)

The scatter EXOTIC's TESS script uses to compare apertures (examples/tess/tess.py check_std): the standard deviation of flux minus a Savitzky-Golay smooth of window 1 + 2 * max(15, int(dt_hours / 24 / cadence)), order 2. EXOTIC compares that in flux units; relative divides by the median flux so that apertures of different size are comparable (a larger aperture collects more flux and more absolute noise); robust uses 1.4826 x the median absolute deviation instead of the standard deviation, so that transits and flares (a few per cent of the points) do not set the value.

optimiseTpf ​

js
function optimiseTpf(tpf, opts = {})

Choose the aperture of a target pixel file. Candidates: the pipeline's optimal aperture and that aperture grown by one and by two pixels (EXOTIC's three), threshold masks at 3, 5, 10 and 20 sigma about the target, and circles of radius 1 to 4 px on the target. Each is ranked by the robust scatter of its good cadences about a Savitzky-Golay smooth, relative to its median flux (smoothScatter with relative and robust set, per stretch of continuous data). An aperture holding less than minFlux (default 0.6) of the flux of the pipeline aperture (of the brightest candidate when there is no pipeline aperture) is listed but cannot win: a few bright pixels can have low white noise and still lose a varying fraction of the star's light as the pointing moves. EXOTIC's own number (standard deviation, in flux units) is reported as exotic for comparison.

  • param opts { x, y: the target's pixel position in the cutout (default: the brightest pixel near the centre), radii, thresholds, dtHours = 0.5, minFlux = 0.6 }
  • returns { tried: [{ name, npix, scatter, exotic, flux (median), mask, n, eligible }], best, lc: tpfLightCurve of the best with a good index list, target: { x, y }, image: the median image }

segmentScatter ​

js
function segmentScatter(t, f, dtHours = 0.5, relative = true, robust = false, gap = 0)

smoothScatter on each stretch of data between gaps longer than gap days (default: an hour, or five cadences if longer), combined as an RMS weighted by length.

addStars ​

js
function addStars(data, w, h, stars)

Add Gaussian stars to a frame, each integrated over the pixels (not sampled at their centres). stars: [{ x, y, flux, sigma }]. data is modified in place.

addNoise ​

js
function addNoise(data, rng, read = 5, gain = 1)

Add Gaussian noise (rng from makeRng in stats.js) of variance read^2 + max(0, value) / gain (after any stars are in).

fitSimilarity ​

js
function fitSimilarity(pairs, mirror = false)
text
Least-squares similarity transform taking (x, y) to (X, Y) from pairs [[x, y, X, Y], ...]:
  X = a x - b y + tx,  Y = b x + a y + ty          (mirror: y is negated first, i.e. X = a x + b y + tx, Y = b x - a y + ty)
  • returns { a, b, tx, ty, mirror, scale, rotation [rad, counter-clockwise in image coordinates], rms [px], n }

applySimilarity ​

js
function applySimilarity(T, x, y, out = [0, 0])

Apply a transform from fitSimilarity to a point; writes [X, Y] into out.

matchAsterism ​

js
function matchAsterism(ref, cur, opts = {})

The similarity transform (translation, rotation by any angle including the 180 degrees of a meridian flip, scale, and optionally a mirror) that maps a reference star list onto the stars of another frame, by matching triangles (Groth 1986; Valdes et al. 1995; the idea behind astroalign, which EXOTIC uses): triangles of the brightest nmax stars of each list are compared by their side ratios, each matched pair of triangles votes for three star pairs, the best-voted pairs give a first transform, and all stars within tol px of their predicted place then refine it.

  • param ref, cur [{ x, y }] brightest first
  • param opts { nmax = 14, tol = 2.5 [px], ratioTol = 0.012, scaleTol = 0.05 (allowed change of scale; null = any), mirror = false (also try mirror images), minSide = 12, minFrac = 0.3 (share of the shorter list, counted up to 20 stars, that must match) }
  • returns null when no consistent match, else the transform of fitSimilarity plus { nMatch, votes, pairs: [[iRef, iCur]] }

placeStars ​

js
function placeStars(data, w, h, refPos, T, out, opts = {})

Place stars in a new frame given their reference positions and a transform: each is re-centred from its predicted position; a star whose centroid fails, or lands more than tol px from where the transform refitted to the others puts it, is left at the predicted position.

  • returns { lost, T: the transform refitted to the stars that were found (null with fewer than 2) }

sffDetrend ​

js
function sffDetrend(time, flux, x, y, opts = {})

Remove the roll systematics of a K2 light curve: the flux is divided by a slow trend, and in each window of windowDays the remainder is binned against the star's position along its arc on the detector (the first principal axis of the centroids within the window); the binned relation, interpolated, is the correction. This is iterated. Transits survive because the bins take medians and the trend is a running median longer than a transit.

  • param opts { windowDays = 6, bins = 15, trendDays = 1.5, iters = 3, keep (Uint8Array) }
  • returns { corrected (flux / correction), correction, trend, arclength, rmsBefore, rmsAfter (of flux / trend - 1, robust) }

Also exported ​

medianOf

MIT licensed · Kyle A. Pearson