<!--
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# Propagate uncertainty through cuPhoton measurements

Everything here runs on a CPU. Probe the install first.

```bash
python -c "import cuphoton, sys; print(cuphoton.__version__, sys.version.split()[0])"
```

If the import fails, install into a new environment and leave existing ones
alone. The wheels are Linux only, for CPython 3.12 to 3.14.

```bash
uv venv --python 3.12 --seed .venv-cuphoton
.venv-cuphoton/bin/python -m pip install "cuphoton==0.2.2"
```

On macOS or Windows, or where you cannot install, say so and stop before any
step that imports cuPhoton. The two catalog scripts of the last section also
need the `catalog` extra.

With every error bar, report which variance it used, which effects it includes,
which it leaves out and why, and whether it was checked against data. A NaN
error or a false validity flag is a result to report with its cause. Never fill
it from another column or drop the row silently. Label synthetic results as such.

## Establish the variance planes

Each image needs a plane of per-pixel variance in squared image units. Read the
extension name, `BUNIT` and comments first. A weight map is usually inverse
variance, with 0 marking an unusable pixel. Check `sqrt(median variance)`
against the robust scatter of an empty region. Convert a weight map with
`1 / weight`, and set unusable pixels to NaN in the variance and in the image.

A bad pixel that is flagged only in the variance is not always dropped.
`forced_flux_at` and `fit_single_sources` drop a pixel whose variance is not
finite or not positive. `solve_constant_kernel` drops a target pixel whose
variance is not finite, and raises `variance must be strictly positive` on a
zero. `fit_dipoles` needs `mask=` to exclude the pixel. Without it the call
raises `variance must be finite and positive on included pixels`.
The reference image has no such protection. xRep resamples every finite pixel,
and the kernel fit takes no reference variance. A bad reference value left in
the image shifts the kernel, the flux and the error without a warning.

Without a plane the options narrow.

| Call | Without a variance plane |
|---|---|
| `fit_dipoles` | runs, and scales the covariance by the fit's reduced chi-square |
| `fit_single_sources`, `forced_psf_photometry` | not available, `variance` is required |
| `forced_flux_at` | unit weights, and `flux_error` is not a noise estimate |

Reduced-chi-square errors take one noise level from the stamp's residuals. They
are too small where the noise peaks under the source, and they absorb model
mismatch. With a plane the covariance is not rescaled. A reduced chi-square
near 1 then supports the plane. `fit_dipoles` takes `backend="numpy"` on a CPU.

## Follow the noise through the difference

| Step | Call | Returns | Leaves out |
|---|---|---|---|
| Align | `reproject_masked_array` (xRep) | reference variance on the target grid, through squared interpolation weights | covariance between output pixels |
| Subtract | `standardize_constant_kernel_residual` (xPois) | `marginal_residual_variance`, `standardized_residual`, `valid_mask` | pixel covariance and the kernel fit's own uncertainty |
| Measure | `forced_flux_at` (xPois), `fit_single_sources`, `forced_psf_photometry`, `fit_dipoles` (xFit) | `flux_error`, `covariance`, `standard_errors`, `uncertainty_valid` | everything not in the variance passed in |

```python
import numpy as np
from cuphoton.xpois import (GaussianBasisComponent, correlation_factor, empirical_correlation_factor,
                            empty_positions, forced_flux_at, psf_weights, solve_constant_kernel,
                            standardize_constant_kernel_residual, window_stamps)
from cuphoton.xrep import (BBox, ReprojectionSpec, make_wcs_pair_transform, prepare_reprojection,
                           reproject_masked_array, resampling_weights_at)
# target, target_var, ref, ref_var: float64 planes; target_wcs, ref_wcs: astropy WCS
# xy: (N, 2) array of (x, y) pixels; psf_sigma: Gaussian PSF sigma in pixels
ref = np.where(np.isfinite(ref_var) & (ref_var > 0), ref, np.nan)   # keep bad pixels out of the kernel fit
spec = ReprojectionSpec(mapping=make_wcs_pair_transform(target_wcs, ref_wcs),
                        output_bbox=BBox(0, 0, target.shape[1], target.shape[0]))
prepared = prepare_reprojection(spec, source_shape=ref.shape)
aligned = reproject_masked_array(ref, ref_var, np.zeros(ref.shape, bool), spec,
                                 backend="cpu", prepared=prepared)
basis = [GaussianBasisComponent(0.7, 2), GaussianBasisComponent(1.5, 2)]
size = 2 * int(np.ceil(5 * psf_sigma)) + 1            # the window the transient chain uses
keep, h = np.ones(target.shape, bool), size // 2      # a changed source inside the fit pulls the kernel
for x, y in np.rint(xy[np.isfinite(xy).all(axis=1)]).astype(int):
    keep[max(y - h, 0):max(y + h + 1, 0), max(x - h, 0):max(x + h + 1, 0)] = False
fit = solve_constant_kernel(aligned.image, target, basis, kernel_shape=(11, 11),
                            variance=target_var, fit_mask=keep, backend="cpu")
noise = standardize_constant_kernel_residual(fit.residual, kernel=fit.kernel, target_variance=target_var,
                                             reference_variance=aligned.variance)
diff, diff_var = fit.residual, noise.marginal_residual_variance
phot = forced_flux_at(diff, xy, psf_sigma, window=size, variance=diff_var, local_sky=False)
```

Use the basis and kernel size of the user's own subtraction. `fit_mask=keep`
leaves each candidate's window out of the kernel fit. A source that changed
pulls the kernel when it stays in: one half as bright as the reference source
under it came out 13 percent low. `forced_flux_at` defaults to
`local_sky=True`, which subtracts each window's median. Pass `local_sky=False`
on a difference or any background-subtracted image. Errors are NaN where
`uncertainty_valid` or `valid` is false. A forced flux error assumes the
position and PSF width are right. Take the width from stars, never from the
candidate's own fit. For alignment options use `cuphoton-align-fits`.

A reference without a variance plane has no closed form. Delete the line that
sets `ref` to NaN, pass `np.zeros(ref.shape)` as `ref_var`, and skip the
closed-form lines of the next block, which would return a factor of exactly 1.
`diff_var` is then the target plane, and the measured factor also holds the
reference noise.

## Correct for correlated noise

Resampling and kernel convolution correlate neighboring pixels. A variance
plane holds per-pixel variance only, with no covariance between pixels. The
error of a weighted sum of pixels (a PSF flux, a fitted position) is therefore
understated. The correlation factor `f` is the variance of the sum with pixel
covariance included, divided by the variance that the plane predicts. The
corrected error is `error * sqrt(f)`. Never quote a resampled image's
per-pixel error as the error bar. The block computes `f` two ways. The
measured factor comes from forced fluxes at empty positions. The closed form
comes from the kernel, both variance planes and the resampling weights.

```python
# measured: the spread of the same forced flux at empty positions over its own error
valid, scaled = noise.valid_mask, noise.standardized_residual
empty, _ = empty_positions(valid, exclude_xy=xy, window=size, count=500, loud=(scaled, 5.0))
whole = window_stamps(valid, empty, size, fill=0).all(axis=(1, 2))   # every pixel usable
blank = forced_flux_at(diff, empty[whole], psf_sigma, window=size, variance=diff_var, local_sky=False)
pull = (blank.flux / blank.flux_error)[blank.valid]
n, measured, se = pull.size, np.nan, np.nan           # unreliable below 20 usable positions
if n >= 2:
    measured = (1.4826 * np.median(np.abs(pull - np.median(pull)))) ** 2
    se = measured * np.sqrt(2 / (0.3675 * (n - 1)))   # a lower bound where windows overlap
fixed = empirical_correlation_factor(diff, diff_var, psf_weights(psf_sigma, size), empty[whole])
# closed form: from the kernel, both variance planes and the resampling weights
taps = resampling_weights_at(spec, xy[:, 0], xy[:, 1], prepared=prepared, source_shape=ref.shape)
weights = psf_weights(psf_sigma, size, offset=xy - np.rint(xy)) / window_stamps(diff_var, xy, size)
closed = correlation_factor(weights, kernel=fit.kernel, target_variance=target_var,
                            reference_variance=aligned.variance, resampling_weights=taps.weights,
                            positions=xy, residual_variance=diff_var, is_translation=taps.is_translation)
error = phot.flux_error * np.sqrt(np.maximum(closed.factor, 1.0))
```

- **Which to quote.** With both, apply the closed form floored at 1, and
  report the measured factor with `n` and `se`. The measured factor is a
  background value. Compare it with the median closed form at `empty[whole]`
  (the same three calls with `empty[whole]` in place of `xy`), not with the
  candidate's. Where it exceeds 1 and that median by more than two `se`, the
  closed form under-predicts. Use the larger of the measured factor and the
  candidate's closed form there, as the chain does. Rule out a background
  gradient first, which widens the pulls the same way. A sky ramp of one pixel
  sigma to each side of a 128 pixel frame raised a factor of 1.6 to 11.7 under
  a constant background, and `background_degree=1` in `solve_constant_kernel`
  brought it back.
- **One image.** The measured factor needs only an image and its variance
  plane. It works on any resampled image or coadd. Set `valid` to the pixels
  with a finite value and a finite, positive variance, and `scaled` to
  `image / np.sqrt(variance)`. The closed form also needs the kernel, the
  reference plane and the resampling weights. Without them, apply the
  measured factor.
- **Match the estimator.** `f` depends on the weights. Measure it with the
  weights of the estimator whose error it corrects, local variance and mask
  included. The forced flux weights each pixel by PSF over variance. For the
  closed form pass those weights, or `psf_weights` with `derivative="x"` for a
  position. Pass as `residual_variance` the variance the measurement used. If
  that is the target variance plane, `f` also includes the reference noise.
- **Fixed weights.** `fixed.factor` applies one stamp to every window. It
  equals the forced-flux factor only where the variance is uniform across each
  window and no pixel is masked. On windows whose correlated 3 x 3 core has 61
  times the background variance, fixed PSF weights give 8.6 and the forced
  flux 1.3. With `derivative="x"` in the stamp it measures a position's
  factor, under the same condition.
- **Empty windows are background.** They lack a bright candidate's own photon
  noise, its mask, and the noise of a reference source under it. Where those
  shape the weights, use the closed form or label the measured factor as a
  background value. Under a bright reference source the background factor is
  too small (2.2 against 11.6 in one simulation). Only the closed form applies
  there, together with the kernel fit term.
- **Kernel fit.** No factor holds the uncertainty of the fitted kernel, which
  grows with the reference flux under the candidate. With the closed form
  alone the pull width was 1.05 on a reference source 7 times the candidate's
  flux, 1.14 at 20 times and 1.39 at 67 times. Add the term's variance to
  `error ** 2` there, with both calls from `cuphoton.xpois`. First
  `cov = kernel_fit_covariance(fit, reference=aligned.image, target_variance=target_var, reference_variance=aligned.variance, resampling_weights=taps.weights[0])`,
  with the stamp of a position the reference covers, then
  `kernel_fit_variance(cov, reference=aligned.image, positions=xy, weights=np.nan_to_num(weights) * phot.flux_error[:, None, None] ** 2)`.
  The three widths became 1.02, 1.03 and 1.02. A flux offset of 0.2 percent of
  the reference flux remained. That is kernel mismatch, the chain's `kmatch`
  term, and no error bar here includes it.
- **The measurement is noisy.** `se` assumes independent positions, and empty
  windows overlap. On a 96 x 96 frame with 300 positions the scatter was 1.45
  times `se`. Exclude sources with `exclude_xy` and `loud`, and state `n` and
  `se`. Below 20 usable positions report the factor as unreliable, with `n`,
  and do not apply it. The chain measures none there.
- **A factor below 1.** Do not shrink the error bar on that basis. Flooring at
  1 is the chain's policy. For a flux a value well below 1 says the plane
  overstates the noise for those weights. Report it, and check for noise
  counted twice or a plane already inflated for covariance. For a position a
  value below 1 can be right where the noise is smoothed wider than the PSF.

`closed.factor` is NaN for one of three reasons. A measured factor can still
diagnose the noise, labeled as a background measurement. It never replaces an
undefined closed form.

| Cause | Sign | Do |
|---|---|---|
| The grid mapping is not locally a shift, as on a rotated or rescaled reference | `closed.n_rotated` counts the positions. `taps.is_translation` is false where `taps.jacobian` differs from the identity by more than `1e-3` | Report the corrected error as undefined with that cause, and the diagonal error as uncorrected |
| A window pixel is not finite | `closed.n_rotated == 0`, and `taps.weights` is not all zero at the position | Pass `valid=noise.valid_mask` to `correlation_factor`. The factor then covers the usable pixels, and `closed.n_masked` counts the rest |
| The reference does not cover the position | `taps.weights` is all zero there | Nothing restores it, `valid=` included. Report the error as undefined with that cause |

A position that is not finite or lies off the target grid has no closed form
either. `resampling_weights_at` raises on it (`x and y must be finite`,
`positions must lie inside the prepared output grid`). Leave such rows out of
the three calls and report their error as undefined.

## Read the transient chain's error budget

The chain writes `<q>_err = sqrt(fit^2 + corr^2 + kfit^2 + kmatch^2 + mis^2)`
for `center_x`, `center_y`, `positive_x`, `positive_y` and `psf_flux`, with each
term in `<q>_err_<term>`. To configure and launch the chain use
`cuphoton-run-transient-chain`. Term inputs, `uq` keys and summary fields are
in [references/BUDGET.md](references/BUDGET.md).

- Quote `<q>_err`. `<q>_err_fit` alone is not the budget. Open the item's
  `summary.json` first. `uq_terms` lists the terms that went in, and
  `uq.excluded` gives the reason for each one left out. An excluded term is
  written as 0, which does not mean the effect is zero. The `psf_flux` term
  columns are NaN instead where forced photometry did not run. A reference
  without a variance plane excludes `corr`. The `measured` entries under
  `uq.correlation` then hold the measured factor, which the chain does not
  apply.
- `<q>_err` is NaN where fewer than half of the quantity's window is usable, a
  center's lobe lies beyond `uq.max_lobe_reach_px`, the fitted position is off
  the image, its correlation factor is undefined, or its fit error is not
  finite. The term columns keep their values. A finite `<q>_err_fit` beside a
  NaN `<q>_err` is not a substitute. `uq.invalid_window` counts the first
  three causes, `uq.center_reach_exceeded` the second, and
  `uq.undefined_factor` and `uq.rotated_grid` the fourth.
- `uq_valid` says every computed error bar of the row is defined, not that all
  terms were available or that the bars are calibrated. A false row can still
  hold a finite error for one quantity.
- With `uq.enabled: false`, `<q>_err` equals `<q>_err_fit`, the terms are 0,
  no one-lobe refit runs, `uq_valid` is true on every row without any check,
  and the summary holds `"disabled": true`. Present such a catalog as fit-only.
- `sky_err_arcsec` is the absolute astrometry the user supplied. It is in
  arcseconds, reported apart, and never part of a pixel-frame `<q>_err`.

## Check the error bars against data

| Check | How | Reads as |
|---|---|---|
| Pulls on injected sources | inject known fluxes, measure them as the candidates are measured, take `(measured - true) / error` | width near 1 and mean near 0 for calibrated errors |
| Repeat test | `repeat_catalogs.py` on per-item catalogs of repeated exposures | positions only, `psf_flux` is not scored. Chi-square per degree of freedom near 1, per arm with one term removed |
| Reference catalog | `compare_catalogs.py --ours ... --reference ...` | counts, match fractions and the largest relative difference of the dipole parameters per item. For pulls, match individual rows. Add their variances only for independent errors. For shared data, include covariance as described in [the budget reference](references/BUDGET.md#checking-scripts) |

A pull width above 1 points to missing variance, such as covariance, gain, read
noise, PSF or background. Below 1 points to noise counted twice, selection, or
shared noise. A mean away from 0 is a flux bias (a wrong PSF width, leftover
background) that no error bar includes. Give a width with its sampling error.
Injecting into the difference tests fixed-position photometry only. To test
detection or fitted positions, inject into the input exposures and rerun. The
repeat test cannot see noise or bias shared by every exposure. Both scripts
ship in `examples/transient-chain/` of the source at tag `v0.2.2`, not the
wheel, and import pandas at startup. On the base install even `--help` fails
with `ModuleNotFoundError: No module named 'pandas'`. Install
`python -m pip install "cuphoton[catalog]==0.2.2"` before running them.

The bars are first order, assume the variance planes describe the noise, and
do not cover a mismatched PSF model or the absolute astrometry. Sources:
[uncertainty guide](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/docs/guide/uncertainty.qmd),
[uncertainty quantification](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/docs/uncertainty-quantification.md),
[how the error bar is built](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/examples/transient-chain/README.md#how-the-error-bar-is-built).

---

Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

The license files are attached. [Apache 2.0](https://knowen.md/f/d1b26c59-a154-4da4-a063-aca638c651b1) · [CC BY 4.0](https://knowen.md/f/7f7aaa6a-a0bf-4460-9b22-48da4ce0fdc9)

The attached ZIP contains the pinned supporting files and applicable license notices.