Deep references and ZOGY
Reference stacks, PSFs and ZOGY difference imaging (Deep references and ZOGY).
AsteroidPipeline._reproject_and_scale Method
_reproject_and_scale(image, wcs_header, magzp, target_header, shape, target_magzp)Worker-side helper for build_reference's workers path: rebuilds both WCS solutions locally from plain header strings (never receives a WCSTransform itself — see build_reference's docstring for why) before calling Reproject.reproject.
AsteroidPipeline.build_reference Method
build_reference(frames, target_wcs, shape; workers=nothing) -> (image, sigma, mask)Build a deep, static-sky reference image on the pixel grid of target_wcs from frames, each a (image, wcs, magzp, sigma) tuple (raw FITS pixel order — see load_frame).
Every frame is reprojected onto the target grid with Reproject.reproject (bilinear), rescaled to target_magzp by 10^(-0.4*(magzp - target_magzp)), and combined per pixel with the median, which rejects whatever moved between epochs (asteroids, satellite trails, cosmic rays). Reprojection dominates the runtime.
By default (workers=nothing) frames are reprojected one at a time: not with Threads.@threads, since wcslib, which WCS.jl wraps, isn't thread-safe. With workers (process ids from Distributed.addprocs, each with @everywhere using AsteroidPipeline already done) frames go through pmap; a WCSTransform holds C pointers that can't cross processes, so each WCS is sent as a FITS header string and rebuilt on the worker. On a 30-frame ZTF reference, 8 workers ran 3.2× faster with identical output. build_reference never starts or stops workers itself.
sigma is the reference's per-pixel background RMS, 1.2533 * median(sigma_i) / sqrt(n): the standard error of the median under Gaussian noise. It ignores the noise correlation interpolation introduces, which is adequate for ZOGY's normalization.
mask is true where at least one frame had a valid sample; elsewhere image is 0. A frame's rotated footprint leaves a thin border uncovered, so callers must exclude !mask pixels from detection.
AsteroidPipeline.load_frame Method
load_frame(path) -> (image, wcs, magzp, sigma)Read a FITS science frame for use with build_reference or ZOGY differencing. image is in raw FITS pixel order ((NAXIS1, NAXIS2), not detect_sources's (y, x) convention — see the note in src/pipeline.jl), matching what Reproject.jl and WCS.jl both expect. sigma is the background RMS estimated on the native (pre-reprojection) pixel grid, since resampling correlates neighbouring pixels and would bias a naive RMS computed after the fact.
AsteroidPipeline._shift_bilinear Method
_shift_bilinear(stamp, dx, dy) -> Matrix{Float64}Resample stamp shifted by (dx, dy) pixels via bilinear interpolation, extrapolating with 0 beyond the stamp edge. Used to sub-pixel-align star stamps onto a common centroid before combining.
AsteroidPipeline.estimate_psf Method
estimate_psf(image; stamp_size=25, threshold=20.0, min_separation=40.0,
saturate=Inf, fallback::Bool=true) -> Matrix{Float64}Estimate an empirical point-spread function from image (raw FITS pixel order, matching load_frame) by stacking bright, isolated stars.
Stars are found with detect_sources at threshold sigma (well above the detection threshold used for the science search itself, since these must be high-S/N enough to define the PSF cleanly), then filtered to ones with no neighbour within min_separation pixels and no pixel above saturate in their stamp — a blended or saturated star would bias the combined PSF's shape. Each surviving stamp is background-subtracted, its sub-pixel centroid found from the flux-weighted first moment, resampled onto that centre with bilinear interpolation so misaligned integer-pixel cutouts don't smear the stack, and normalized to unit sum. The final PSF is the pixel-wise median across stamps (again to resist any residual blend or cosmic ray a single star's stamp might carry), renormalized to unit sum.
An empirical PSF is used rather than an analytic model (e.g. Gaussian or Moffat) because ZOGY needs the real PSF shape, wings included, and this keeps estimate_psf usable on any survey's data without fitting a model family per instrument. But a field sparser or more crowded than expected can leave zero stars passing the isolation/saturation filter at the given min_separation; when that happens, min_separation is halved and the search retried, up to relaxation_attempts times (default 2, i.e. min_separation, then /2, then /4) before giving up on the empirical approach — a field with a few usable stars at a tighter isolation radius still gives the real PSF shape, which a fallback to an analytic model never can, so this is tried first rather than jumping straight to it. If even the most relaxed attempt finds nothing and fallback is true (the default), a warning is emitted and fit_moffat_psf is used instead — an analytic fit trades the real PSF's exact shape for something usable at all. fallback=false keeps the hard failure instead.
AsteroidPipeline.fit_moffat_psf Method
fit_moffat_psf(image; stamp_size=25, threshold=20.0, saturate=Inf) -> Matrix{Float64}Estimate a point-spread function from image (same convention as estimate_psf) by fitting an analytic Moffat profile to bright stars, rather than stacking star cutouts empirically. Used as estimate_psf's fallback when no stars pass its stricter isolation/saturation filter (e.g. a crowded or sparse field), so this function deliberately reuses only the unfiltered front half of that filter chain — detect_sources at threshold sigma, plus the same border margin check — and drops the min_separation isolation requirement, which is usually what emptied estimate_psf's star list in the first place. That's a reasonable trade for a fit but not for a stack: a median stack of blended-star stamps bakes the neighbour directly into the combined PSF's shape, whereas a Moffat fit has only 6 free parameters and can't absorb a companion star into them — and a bad stamp shows up as a poor fit residual rather than silently corrupting the result.
For each candidate star, a circular Moffat profile I(r) = A * (1 + (r/α)^2)^(-β) + B — the standard atmospheric-seeing PSF model, with heavier wings than a Gaussian, which ZOGY's matched filter depends on — is fit to its stamp_size cutout via LsqFit.curve_fit, with free amplitude A, centre (x0, y0), core width α, power-law index β, and background offset B. The median α and β across all stars whose fit converges (resistant to any one star's bad fit, the same reasoning behind estimate_psf's own use of a median stack) parameterize the returned PSF: that Moffat shape evaluated on a stamp_size grid centred at zero offset, normalized to unit sum — the same convention estimate_psf returns, so this drops directly into zogy_subtract's psf_n/psf_r wherever the empirical estimate would.
Errors if no candidate star is found at all, or if every fit fails to converge — no usable star means no PSF, and that stays a hard failure even here.
sourceAsteroidPipeline._astrometric_scatter Method
_astrometric_scatter(n_sources, r_sources; match_radius=3.0) -> (sigma_x, sigma_y)Standard deviation of the pixel-position offsets between sources in n_sources and their nearest counterpart in r_sources within match_radius pixels — an empirical estimate of residual registration error between the two images. Returns (0.0, 0.0) if fewer than 5 pairs match, too few to trust a scatter estimate.
AsteroidPipeline._convolve_variance Method
_convolve_variance(V, k) -> Matrix{Float64}k² ⊗ V: how a linear filter k propagates per-pixel variance V. For independent per-pixel noise, Var[sum_y k(x-y) D(y)] = sum_y k(x-y)² V(y), i.e. a convolution of V with k squared in real space — not with |k̂|², a different quantity — computed here via the convolution theorem applied to that squared kernel.
AsteroidPipeline._gradient Method
_gradient(image) -> (dIdx, dIdy)Central-difference gradient (forward/backward at the edges), for the ZOGY astrometric noise term, which needs ∂S/∂x and ∂S/∂y.
AsteroidPipeline._pad_kernel Method
_pad_kernel(kernel, shape) -> Matrix{Float64}Zero-pad kernel (odd-sized, peak at its centre) to shape with its peak wrapped to array index (1, 1), the layout fft/ifft require for convolution: place it centred, then ifftshift.
AsteroidPipeline._variance_map Method
_variance_map(image_sub, sigma, gain) -> Matrix{Float64}Per-pixel variance: background RMS plus Poisson shot noise from above-background counts, σ² + max(image_sub, 0) / gain. image_sub must already be background-subtracted (by the same convention zogy_subtract itself uses, so the two agree on where "above background" starts).
AsteroidPipeline.zogy_subtract Method
zogy_subtract(n_image, r_image; psf_n, psf_r, sigma_n, sigma_r,
gain_n=1.0, gain_r=1.0, f_n=1.0, f_r=1.0,
n_sources=nothing, r_sources=nothing) -> (D, S_corr)Proper image subtraction (Zackay, Ofek & Gal-Yam 2016, ApJ 830, 27) between a science frame n_image ("new") and a reference frame r_image, both raw FITS pixel order on the same grid (e.g. n_image from load_frame, r_image from build_reference) with matching PSFs psf_n, psf_r (see estimate_psf) and background RMS sigma_n, sigma_r.
Computed entirely in Fourier space (FFTW.fft), all as `Δ̂ = σ_n²F_r²|P̂_r|²
σ_r²F_n²|P̂_n|²`:
D̂ = (F_r P̂_r N̂ − F_n P̂_n R̂) / √Δ̂— the difference image proper: PSF matching and subtraction combined into one deconvolution, avoiding the correlated-noise artifacts of "convolve-then-subtract" methods.Ŝ = F_D conj(P̂_D) D̂withP̂_D = F_r F_n P̂_r P̂_n / (F_D √Δ̂)andF_D = F_n F_r / √(σ_n²F_r² + σ_r²F_n²)—Dmatched-filtered by its own PSF, which is what makes a pixel's value inSproportional to the flux of a point source centred there.S_corr = S / √(V(S_N) + V(S_R) + V_ast(S_N) + V_ast(S_R))—Snormalized by its own propagated variance (photon noise from both images plus, whenn_sources/r_sourcesare given, sub-pixel astrometric registration error), so that under the null hypothesis (no source)S_corrhas zero mean and unit variance everywhere and its value at any pixel is directly a detection significance in sigma. This is whatdetect_sourcesruns on in the difference-imaging path ofrun_pipeline.
n_image and r_image need not be background-subtracted: each has its median subtracted first. An FFT's DC term is the sum of the image, so a few ADU of unmatched sky would otherwise swamp S_corr everywhere.
f_n, f_r are relative flux scales, 1 when build_reference has put the reference on the science frame's zeropoint. gain_n, gain_r (e-/ADU) give the Poisson variance in V_N, V_R.
Astrometric registration noise (V_ast) is included only when n_sources and r_sources (tables with x, y columns, from detect_sources on n_image/r_image) are passed. Without them S_corr overstates the significance near bright stars wherever registration isn't perfect, so a warning (once per session) fires; run_pipeline always passes both.