Skip to main content

jwst_psfmc

PSF photometry with MCMC for JWST (and HST) drizzled images.

CI PyPI Python License: MIT


Scientific Background

JWST NIRCam images processed with the drizzle algorithm exhibit spatially correlated pixel-to-pixel noise: photons detected in a single detector pixel are spread across several output pixels during co-addition. If these correlations are ignored in a standard χ² PSF fit, the flux uncertainties are systematically underestimated. Even in full MCMC fitting with correlated-noise likelihoods, neglecting the covariance kernel underestimates flux uncertainties by ~30% in F200W (Zhuang et al. 2026).

jwst_psfmc solves this by:

  1. Measuring the covariance structure directly from source-free sky regions of the drizzled image using an autocorrelation estimator.

  2. Encoding the covariance as a Fourier-space power spectrum, enabling an exact correlated-noise log-likelihood that is O(N log N) per MCMC step.

  3. Running an ensemble MCMC sampler (emcee) to obtain full posterior distributions for the four model parameters:

    Parameter Description
    flux Total source flux (same units as the image)
    dx Sub-pixel x-shift of the PSF centroid (native pixels)
    dy Sub-pixel y-shift of the PSF centroid (native pixels)
    bkg Flat residual background level

The PSF is shifted with exact Fourier-space interpolation (no interpolation kernel artefacts) and downsampled from the 4× oversampled PSF model by block-summing.

Pixel-correlation whitening

Correlated noise, measured and removed. Left to right: a source-free F444W sky patch, its autocorrelation, and the radial profile of that autocorrelation — before (top) and after (bottom) dividing the Fourier amplitudes by the square root of the kernel power spectrum. The nearest-neighbour correlation collapses from 0.611 to 0.038, while the noise level is untouched — both panels read a 3σ-clipped RMS of 0.011, and the unclipped variance is conserved exactly since the kernel spectrum has unit mean. Removing the correlation without removing the noise is the whole point. Produced by examples/demo_covariance_kernel.ipynb.


Installation

pip install jwst-psfmc

Or from source:

git clone https://github.com/mingyangzhuang/jwst_psfmc.git
cd jwst_psfmc
pip install -e ".[dev]"

To run the notebooks in examples/, add the notebooks extra:

pip install "jwst-psfmc[notebooks]"

Dependencies: numpy, scipy, astropy, photutils, emcee, corner, matplotlib, tqdm


Example Data

The example FITS files (difference images, error maps, covariance kernels, and PSF models) live in examples/data/ and examples/PSF/ inside the repository. They are not bundled with the PyPI package — clone the repo to use them:

git clone https://github.com/mingyangzhuang/jwst_psfmc.git
cd jwst_psfmc/examples
jupyter notebook demo_psf_photometry.ipynb
File Description
examples/data/example1_f200w_diff.fits Difference image — non-detection
examples/data/example1_f200w_diff_error.fits Uncertainty map — non-detection
examples/data/example1_f200w_cov_kernel.fits Covariance kernel — non-detection
examples/data/example2_f200w_diff.fits Difference image — detection
examples/data/example2_f200w_diff_error.fits Uncertainty map — detection
examples/data/example2_f200w_cov_kernel.fits Covariance kernel — detection
examples/PSF/example1_f200w_PSF_4_c.fits 4× oversampled PSF model — non-detection
examples/PSF/example2_f200w_PSF_4_c.fits 4× oversampled PSF model — detection

Quick Start

There are two demos, mirroring the two notebooks in examples/: first measure the covariance kernel from the image itself, then fit a source with it. The API takes NumPy arrays throughout — load your FITS files however you prefer.

Demo 1 — Estimating the covariance kernel

The kernel is measured from a source-free region of the same difference image, so it describes the noise the source is actually sitting in.

from astropy.io import fits
from astropy.stats import sigma_clipped_stats
import numpy as np
import jwst_psfmc as jpm

# ── 1. Load a difference image and a source mask ───────────────────────────
# Build the mask with jpm.get_source_mask() on the reference AND science
# images *before* subtraction — a well-subtracted source leaves no residual
# to detect, so masking the difference image alone under-masks badly.
diff = fits.getdata("examples/data/example3_f444w_diff.fits").astype(float)
mask = fits.getdata("examples/data/example3_f444w_mask.fits").astype(bool)

# ── 2. Find the largest source-free square ─────────────────────────────────
squares = jpm.find_zero_squares(mask.astype(np.int64), a=60,
                                all_sizes=True, max_nonzero=5)
# Many squares tie at the largest size, so break the tie explicitly rather
# than relying on argsort's unstable quicksort.
order = np.lexsort((squares[:, 1], squares[:, 0], -squares[:, 2]))
top, left, size = squares[order[0]].astype(int)
patch = diff[top:top + size, left:left + size].copy()

# Replace any NaN with noise at the local level, then remove the offset
nan_mask = ~np.isfinite(patch)
if nan_mask.any():
    mean, _, std = sigma_clipped_stats(patch[np.isfinite(patch)], sigma=3)
    patch[nan_mask] = np.random.RandomState(42).randn(nan_mask.sum()) * std + mean
    patch = patch - mean

# ── 3. Estimate the kernel and its power spectrum ──────────────────────────
cov_kernel = jpm.estimate_cov_kernel(patch, size=125)
power_spectrum = jpm.kernel_power_spectrum(cov_kernel, patch.shape)

# ── 4. Check it: whitening should remove the correlation, not the noise ────
white = jpm.whiten_image(patch, power_spectrum=power_spectrum)
before = jpm.estimate_cov_kernel(patch, size=15)
after = jpm.estimate_cov_kernel(white, size=15)
c = before.shape[0] // 2
print(f"nearest-neighbour correlation: {before[c, c+1]:.3f} -> {after[c, c+1]:.3f}")
print(f"RMS ratio (whitened / original): {white.std() / patch.std():.4f}")

fits.writeto("example3_f444w_cov_kernel.fits", cov_kernel, overwrite=True)

On the bundled F444W example this prints a nearest-neighbour correlation falling from 0.611 to 0.038 at an RMS ratio of 0.9981 — the correlation removed, the noise level intact. That is the check that the kernel describes this image; see the figure in Scientific Background for the same result in pictures.

Demo 2 — PSF photometry with MCMC

from astropy.io import fits
import numpy as np
import jwst_psfmc as jpm

# ── 1. Load your data ──────────────────────────────────────────────────────
data    = fits.getdata("examples/data/example2_f200w_diff.fits")
err     = fits.getdata("examples/data/example2_f200w_diff_error.fits")
kernel  = fits.getdata("examples/data/example2_f200w_cov_kernel.fits")  # from demo 1
psf_raw = fits.getdata("examples/PSF/example2_f200w_PSF_4_c.fits")

# ── 2. Extract a 9×9 stamp centred on the source ───────────────────────────
cy, cx = data.shape[0] // 2, data.shape[1] // 2
stamp     = data[cy-4:cy+5, cx-4:cx+5]
stamp_err = err[cy-4:cy+5, cx-4:cx+5]

# ── 3. Prepare MCMC inputs ─────────────────────────────────────────────────
fit_args = jpm.prepare_for_fitting(
    data=stamp, err=stamp_err,
    psf_os=psf_raw, cov_kernel=kernel,
    dx_init=0.0, dy_init=0.0,
    oversamp=4, native_shape=(11, 11), nwalkers=48,
)

# ── 4. Run MCMC ────────────────────────────────────────────────────────────
sampler = jpm.run_mcmc(**fit_args, nsteps=2000, ncores=4, progress=True)

# ── 5. Summarise posterior ─────────────────────────────────────────────────
summary = jpm.summarize_emcee(sampler, burnin=500, thin=4)
print(f"flux = {summary['flux']['median']:.4f} "
      f"+{summary['flux']['plus_1sigma']:.4f} / "
      f"-{summary['flux']['minus_1sigma']:.4f}")

# ── 6. Visualise ───────────────────────────────────────────────────────────
fig_trip, _ = jpm.plot_psf_fit_triptych(
    stamp, stamp_err, fit_args["psf_os"], oversamp=4,
    native_shape=fit_args["native_shape"],
    psf_prepare_fraction=fit_args["psf_prepare_fraction"],
    summary=summary, fig_title="Detection example — F200W",
)
fig_trip.savefig("triptych.pdf", bbox_inches="tight")

fig_chains, _ = jpm.plot_chains(sampler, burnin=500)
fig_corner, _ = jpm.plot_corner(sampler, burnin=500, thin=4)

# ── 7. Save / reload results ───────────────────────────────────────────────
jpm.save_emcee_results("example2_f200w_mcmc.npz", sampler)
res = jpm.load_emcee_results("example2_f200w_mcmc.npz")
print(res["summary"])

prepare_for_fitting estimates the default flux upper bound and the walker initialization scale from the pixels included in the likelihood. Use flux_prior_bounds=(low, high) to set an explicit open interval in the fit's flux units. Signed bounds are supported for difference images. For reproducible emcee fits, pass the same seed to both prepare_for_fitting and run_mcmc. The preparation and sampler use independent streams derived from that seed.

Data, model and residual for a detection

Data, best-fit model and residual for a detected transient — AT 2025amoq, F200W, 9×9 px stamp. A residual flat at the noise level is the sign of a good fit; coherent structure there points to a centroid or PSF mismatch rather than a bad flux.

Four-parameter posterior for the detection

The four-parameter posterior for the same detection (plot_corner). Flux is 21.276 (+0.425 / -0.428) with a significance of 50σ. The contours are nearly round apart from a mild flux–bkg anticorrelation; a skewed flux histogram or a strong flux–dx/dy tilt would instead point to poor convergence or a misregistered PSF.


Deriving a flux upper limit from a non-detection

Residual small-scale background fluctuations can mimic low-level source emission at 1–2σ. We use a two-run workflow:

  1. Detection check — broad priors (±1 pix on dx/dy) to confirm the source is genuinely absent.
  2. Upper limit — tight priors (±0.1 pix) to derive the 3σ bound from the posterior flux distribution.

Two conventions for the 3σ bound are supported:

Convention Definition
99.7th percentile The flux below which 99.7 % of the posterior samples fall. Assumes nothing about the shape of the posterior.
max(median, 0) + 3 × σ Gaussian-equivalent form. The median is clamped at zero so a downward noise fluctuation cannot produce a limit deeper than the noise allows.

They agree for a near-Gaussian posterior; where they diverge, trust the percentile. State which one you used.

data_nd   = fits.getdata("examples/data/example1_f200w_diff.fits")
err_nd    = fits.getdata("examples/data/example1_f200w_diff_error.fits")
kernel_nd = fits.getdata("examples/data/example1_f200w_cov_kernel.fits")
psf_nd    = fits.getdata("examples/PSF/example1_f200w_PSF_4_c.fits")

cy, cx = data_nd.shape[0] // 2, data_nd.shape[1] // 2
stamp_nd     = data_nd[cy-4:cy+5, cx-4:cx+5]
stamp_err_nd = err_nd[cy-4:cy+5, cx-4:cx+5]

# ── Run 1: broad priors (detection check) ─────────────────────────────
fit_nd_broad = jpm.prepare_for_fitting(data=stamp_nd, err=stamp_err_nd,
                                       psf_os=psf_nd, cov_kernel=kernel_nd)
sampler_nd_broad = jpm.run_mcmc(**fit_nd_broad, nsteps=2000, ncores=4,
                                progress=True)

# Confirm non-detection: flux median consistent with zero within 1σ
summary_broad = jpm.summarize_emcee(sampler_nd_broad, burnin=500, thin=4)
is_absent = abs(summary_broad['flux']['median']) < summary_broad['flux']['plus_1sigma']
print(f'Non-detection confirmed: {is_absent}')

# ── Run 2: tight priors (upper limit) ─────────────────────────────────
fit_nd_tight = jpm.prepare_for_fitting(data=stamp_nd, err=stamp_err_nd,
                                       psf_os=psf_nd, cov_kernel=kernel_nd,
                                       pos_prior_half_width=0.1)  # ±0.1 pix
sampler_nd_tight = jpm.run_mcmc(**fit_nd_tight, nsteps=2000, ncores=4,
                                progress=True)

flat_flux = sampler_nd_tight.get_chain(discard=500, thin=4, flat=True)[:, 0]

# Convention A — posterior quantile (distribution-free)
ul_percentile = float(np.percentile(flat_flux, 99.7))

# Convention B — Gaussian-equivalent; median clamped at zero.
flux_median = float(np.median(flat_flux))
flux_sigma = float(np.std(flat_flux, ddof=1))
ul_3sigma = max(flux_median, 0.0) + 3.0 * flux_sigma

print(f"3-sigma upper limit (99.7th percentile):     {ul_percentile:.4f}")
print(f"3-sigma upper limit (max(median,0) + 3sigma): {ul_3sigma:.4f}")

Broad and tight flux posteriors with both 3-sigma upper limits

The two-run upper-limit workflow, for the epoch where AT 2025amoq is absent. Broad priors (blue) confirm the source is genuinely not there; tightening the centroid priors to ±0.1 px (orange) narrows the posterior tail and sets the bound. Both 3σ conventions are drawn; they differ by ~6 % here.


Optional Nautilus sampler

Install version 0.3.0 or later with pip install "jwst-psfmc[nautilus]>=0.3.0" from PyPI, or use pip install -e ".[nautilus]" from a source checkout. The fitting inputs, uniform prior bounds, and Fourier-space likelihood are shared with the default emcee backend.

import matplotlib.pyplot as plt
import numpy as np

result = jpm.run_mcmc(**fit_args, sampler="nautilus", seed=42)
summary = jpm.summarize_posterior(result)
fig_corner, _ = jpm.plot_corner(result)

jpm.save_nautilus_results("example2_f200w_nautilus.npz", result)
result = jpm.load_nautilus_results("example2_f200w_nautilus.npz")

flux = result["samples"][:, 0]
weights = np.exp(result["log_w"])
fig, ax = plt.subplots()
ax.hist(flux, weights=weights, bins=30, density=True)
ax.set(xlabel="Flux (image units)", ylabel="Posterior density")

Nautilus uses its own default for n_live, targets n_eff=10_000 effective samples, and discards exploration samples. It uses one worker by default. Set ncores=4 to run four worker processes, including in a notebook. nsteps, burnin, and thin apply to the emcee workflow.

For the non-detection example, run Nautilus with **fit_nd_tight to reuse the tight position priors. Compute the 99.7% posterior upper limit with the original weights, and check that the result is stable across seeds and larger values of n_live and n_eff.

result_nd = jpm.run_mcmc(**fit_nd_tight, sampler="nautilus", seed=42)
flux_nd = result_nd["samples"][:, 0]
order = np.argsort(flux_nd)
cumulative_weight = np.cumsum(np.exp(result_nd["log_w"][order]))
index = np.searchsorted(cumulative_weight, 0.997 * cumulative_weight[-1])
upper_limit = flux_nd[order[index]]

Full Worked Examples

There are two notebooks, one per demo above, and both run end to end against the bundled example data. Clone the repository to use them — the FITS files live in examples/ and are not shipped inside the installed package — and install the notebooks extra for Jupyter itself: pip install "jwst-psfmc[notebooks]".

Covariance kernel estimation

See examples/demo_covariance_kernel.ipynb for a step-by-step demonstration of measuring the pixel-to-pixel covariance of a JWST difference image (F444W example):

  • Source masking and locating source-free sky regions (get_source_mask, find_zero_squares)
  • Autocorrelation-based kernel estimation (estimate_cov_kernel)
  • Cosine-bell windowing (SplitCosineBellWindow) and the Fourier power spectrum (kernel_power_spectrum)
  • Whitening the sky patch (whiten_image) and confirming what it does: because the kernel spectrum has unit mean, the RMS is preserved (ratio 0.9981), while the nearest-neighbour pixel correlation falls from 0.611 to 0.038

PSF photometry with MCMC

See examples/demo_psf_photometry.ipynb for a step-by-step notebook covering both regimes, using two epochs of the same source:

  • Loading and inspecting the JWST cutout data
  • Estimating and visualising the covariance kernel and its power spectrum
  • Non-detection (example1) — the two-run workflow, and a 3σ upper limit reported under both the 99.7th-percentile and median + 3σ conventions
  • Detection (example2) — flux posterior, detection significance, and the total flux corrected for PSF energy falling outside the stamp (summarize_flux_from_chain); in this example ~23 % of the PSF lies outside the 9×9 cutout, so the correction matters
  • Diagnosing convergence via chain traces and autocorrelation times
  • Producing corner plots and residual triptychs
  • Saving and reloading posteriors (save_emcee_results / load_emcee_results)

Point sources and Sérsic models

The generic fitting API accepts a CompositeModel with point, Sérsic and constant-background components. A prepared fit records the PSF response convention, parameter definitions, covariance and input hashes. Use save_model_results to preserve the posterior in NPZ and save_model_snapshot to preserve one evaluated model and its residuals in FITS. Reload the snapshot with load_model_snapshot and use plot_model_fit, plot_decomposition or plot_residual_diagnostics.

The Sérsic galaxy fitting notebook measures a sky prior from an annulus, checks the renderer against an independent continuous reference, and compares radius error coverage with diagonal ERR and finite pixel covariance.

Two source-checkout examples show signed point-source fits on real difference images and a point-plus-host fit on a mock direct image with fixed geometry. The generic noise API also supports masked dense fits with a finite covariance or fully observed periodic FFT fits. For ep01 F444W 30 mas, the real-star tests found strong PSF and covariance sensitivity for bright points with weak, compact hosts. The example lists its fixed-morphology assumptions and does not claim that regime is calibrated.

Module Overview

For registered single-filter epochs, the joint fitting guide covers shared host parameters, per-frame transient flux and background, and block covariance for differences that share a reference.

Module Contents
jwst_psfmc.psf PSF shifting, downsampling, model evaluation
jwst_psfmc.covariance Covariance kernel estimation, power spectrum, whitening, Fourier-space pre-computation
jwst_psfmc.mcmc MCMC preparation, log-prob, run_mcmc, posterior summaries
jwst_psfmc.io Save/load .npz results
jwst_psfmc.plot Triptych, chain traces, corner plot

Citation

If you use jwst_psfmc in your research, please cite:

Zhuang, M.-Y., Hu, L., Pierel, J. D. R., et al. 2026, NEXUS: Transient Searches and First Results from Year One Observations, arXiv:2609.06985


License

MIT — see LICENSE.

Metadata

Release files for jwst-psfmc 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jwst-psfmc 0.4.1
File Size Uploaded Provenance Actions
jwst_psfmc-0.4.1.tar.gz 143.6 kB With provenance Details for jwst_psfmc-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for jwst-psfmc 0.4.1
File Interpreter ABI Platform Actions
jwst_psfmc-0.4.1-py3-none-any.whl Python 3 none any Details for jwst_psfmc-0.4.1-py3-none-any.whl

Total release size: 236.0 kB

Release files / jwst_psfmc-0.4.1.tar.gz

Download URL jwst_psfmc-0.4.1.tar.gz
Size 143.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c3922681d108ddfee3e9c5d10948b741eb7d3bb78bd8cd483e4a7d75a98cbdbd
BLAKE2b-256 checksum
How to use checksums
1cbf543a0bfbd93530098d0da7832b8f302493781de13c3b65ff0de4c521ee42
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Release files / jwst_psfmc-0.4.1-py3-none-any.whl

Download URL jwst_psfmc-0.4.1-py3-none-any.whl
Size 92.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a6d8e28ca9726e6fa585e61bd117630acce8da1127dea50c240744fb984497c0
BLAKE2b-256 checksum
How to use checksums
eb33446e6e5b9f11e3c3893c380565d5ca6092a128975a50f6c2d8c1ed21ec92
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Security for jwst-psfmc 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for jwst_psfmc-0.4.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page