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

# Run the cuPhoton transient chain on your own images

The chain takes a target image and its reference from FITS files to a catalog of
candidates with positions, fluxes, error bars and, with a checkpoint, a real/bogus
score. The configuration, the code and `summary.json` call the reference `template`.
The chain resamples it onto the target's grid. The chain is the example package
`examples/transient-chain/` of a cuPhoton source checkout. The wheel does not ship it.
The chain needs an NVIDIA GPU. Configuration, input checks and file loading run on a
CPU. Do those first. To read one cutout use `cuphoton-read-fits`. To reproject without
subtracting use `cuphoton-align-fits`. There the reference or template is the
destination grid. Here it is the image resampled onto the target.

## Set up one working directory

```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. Where you cannot install, say so
and stop. Without a GPU the CPU checks still run, and need only the `catalog` extra.

```bash
uv venv --python 3.12 --seed .venv-cuphoton && . .venv-cuphoton/bin/activate
python -m pip install "cuphoton[gpu,catalog]==0.2.2"
```

Add the `dragon` extra (Python 3.12 or 3.13) or the `mpi` extra for those executors.
Every later block runs code from the example. Fetch it at the release tag of the
installed version, from the URL below as written, into a new directory. Never reuse
an older checkout, build the URL from user input, or turn off TLS certificate
verification.

```bash
VERSION=$(python -c "import importlib.metadata as m; print(m.version('cuphoton'))")
URL=https://github.com/NVIDIA/cuPhoton
SRC=$(mktemp -d "$PWD/cuPhoton-v$VERSION.XXXXXX") &&
git -C "$SRC" init -q &&
git -C "$SRC" fetch --quiet --depth 1 "$URL" "refs/tags/v$VERSION" &&
git -C "$SRC" checkout --quiet --detach FETCH_HEAD &&
export SRC && git -C "$SRC" rev-parse HEAD   # the release commit, for the report
python -m pip install -e "$SRC/examples/transient-chain"   # optional, launch.py finds the package itself
[ -e chain.yaml ] || cp "$SRC/examples/transient-chain/config-generic.yaml" chain.yaml
```

Run every later block from this directory, in this shell. It holds `chain.yaml`,
`selections.json` and the output directory `out/`. A new shell has no `SRC`. Run this
block again there. It fetches a new checkout and keeps an existing `chain.yaml`.

## Describe the files to the generic adapter

`chain.yaml` is a copy of `config-generic.yaml`, not of `config.yaml`. Replace its
`survey.params`. A key you leave out takes the adapter default, not the shipped
value. Restate everything your files need. The `*_hdu`, `*_path_key` and
`variance_kind` keys go under both `target` and `template`.

| Key | Default | Rule |
| --- | --- | --- |
| `target.path_key`, `template.path_key` | `image`, `template` | name of the selections key that holds the path |
| `image_hdu`, `mask_hdu`, `variance_hdu` | null | an index or an `EXTNAME`. Null selects the first 2-D image of the file that the path key names |
| `mask_path_key`, `variance_path_key` | null | set only when the plane is in another file |
| `variance_kind` | `variance` | `inverse_variance` for a weight map, `none` to ignore the plane |
| `template.on_target_grid` | `false` | `false` reprojects the reference through its WCS |
| `identity` | `exposure_id`, `ccd_id`, `band` | selections keys that fill those catalog columns |
| `mask_policy` | `strict` | `none`, `strict`, `{bits: N}`, `{planes: [...]}`, `hsc-masklite` |

- A plane in the image's own file needs its `*_hdu` and no path key. With both null
  the plane is absent and nothing warns.
- An `EXTNAME` selects the first HDU with that name and ignores `EXTVER`. When names
  repeat, as in a multi-detector file, give the index that
  `cuphoton.core.fits_io.inspect_fits_images` reports as `hdu`.
- A weight map read as `variance` loads without error and inverts every weight in
  the fit. `config-generic.yaml` ships `inverse_variance` for the target. A replaced
  block loses it.
- `strict` marks any nonzero mask value bad. When some bits are informational, pass
  `{bits: N}` with `N` the sum of the bad flag values. `{planes: [...]}` and
  `hsc-masklite` need `MP_<NAME>` cards in the mask header. The mask must be an
  integer plane.
- `on_target_grid: true` needs a reference with the target's shape and ignores its
  WCS. The star refinement is then skipped and no PSF width is measured. Set
  `xfit.psf_sigma_px`. It enables forced photometry on every row, the `kfit` term,
  and `corr` when the reference has a variance plane.
- The variance planes and the PSF width decide what `psf_flux` holds (refer to its
  row under "Read the results"). Without a reference variance plane the `corr` error
  term is left out.

## Write the selections file

One entry per target image, with the identity keys and every path key the block
names. Write absolute paths. A relative path resolves against the directory each
process starts in.

```json
{"selections": [{"exposure_id": 412, "ccd_id": "C07", "band": "r",
  "image": "/data/sci_0412_c07.fits", "template": "/data/ref_c07.fits"}]}
```

Each item is named `<ccd_id>-v<exposure_id>`. `--only C07` or `--only C07/412` selects
items. Tokens are case-sensitive. An exposure number alone or an item name matches
nothing.

## Check the inputs on a CPU

The preflight checks required keys and paths for all selections. It decodes one
target and reference pair, starting with the first. Set `SELECTION_INDEX` to the
zero-based index of another pair to check its HDUs, masks, variance and WCS.
Check a representative pair for each distinct file layout and grid.

The chain takes each mask and variance plane as registered with its image and never
reads the plane's own WCS. The loop prints the HDU each plane resolved to. It stops
when a plane has another shape, or its celestial WCS puts the center or a corner
more than 0.01 pixel off. A plane without a celestial WCS passes on shape alone.

```python
import json, os, sys
from pathlib import Path
import numpy as np
from astropy.wcs import WCS
sys.path.insert(0, os.environ["SRC"] + "/examples/transient-chain")  # not needed once installed
from transient_chain.config import load_config
from transient_chain.fitsio import PlaneReader, hdu_index, inspect_plane
from transient_chain.surveys import make_adapter
from transient_chain.workload import prepare_workload

spec = prepare_workload(Path("selections.json"), Path("chain.yaml"), None)
print(spec.manifest_payload["items"])
cfg = load_config("chain.yaml")
adapter = make_adapter(cfg["survey"])
index = int(os.environ.get("SELECTION_INDEX", "0"))
entry = json.loads(Path("selections.json").read_text())["selections"][index]
print("Checking selection", index, entry)

def plane(p, kind):  # one plane's header, resolved as the generic adapter resolves it
    hdu, key = p[f"{kind}_hdu"], p.get(f"{kind}_path_key")
    if kind != "image" and (hdu is None and not key or p.get(f"{kind}_kind") == "none"):
        return None
    path = entry[key or p["path_key"]]
    return inspect_plane(path, hdu_index(path, hdu))

for role in ("target", "template") if adapter.name == "generic" else ():
    p = getattr(adapter, f"{role}_p")
    image = plane(p, "image")
    ny, nx = image.shape
    x = np.array([0, nx - 1, 0, nx - 1, (nx - 1) / 2])
    y = np.array([0, 0, ny - 1, ny - 1, (ny - 1) / 2])
    for kind in ("image", "mask", "variance"):
        aux = plane(p, kind)
        if aux is None:
            continue
        print(role, kind, aux.path.name, "HDU", aux.hdu, aux.header.get("EXTNAME"),
              aux.header.get("EXTVER"), aux.shape)
        if aux.shape != image.shape:
            raise ValueError(f"{role} {kind} has shape {aux.shape}, its image {image.shape}")
        ours, theirs = WCS(image.header), WCS(aux.header)
        if ours.has_celestial and theirs.has_celestial:
            ax, ay = theirs.celestial.world_to_pixel(ours.celestial.pixel_to_world(x, y))
            if not np.all(np.hypot(ax - x, ay - y) <= 0.01):
                raise ValueError(f"{role} {kind} is more than 0.01 pixel off its image's grid")
reader = PlaneReader("astropy", device=False)
target = adapter.load_target(entry, reader)
provider = adapter.template(entry, target, reader,
                            mapping_grid_step=cfg["align"]["mapping_grid_step"])
template, template_bad, coverage = provider.build()
print(target.shape, template.shape, np.isfinite(template).mean())
print(target.variance is not None, provider.has_variance,
      None if target.bad is None else int(target.bad.sum()))
if provider.has_variance:
    print(provider.resampling(np.array([target.shape[1] / 2]),
                              np.array([target.shape[0] / 2])).is_translation)
```

`load_config` rejects unknown blocks and keys and stops at the first problem.
`make_adapter` rejects unknown `survey.params` keys. `prepare_workload` counts every
entry with a missing key or file and lists the first ten. The third argument is the
checkpoint directory.
None of the three checks the values in `survey.params`. A wrong `variance_kind`,
`mask_policy` or `EXTNAME` fails only in the loader calls after them, and only when
that plane is read. Before spending GPU time, confirm that:

- the variance flags match the planes you supplied, and `np.nanmedian(target.variance)`
  is near the squared pixel scatter of the sky. A reciprocal value means the wrong
  `variance_kind`.
- the bad-pixel count matches the flags you meant to mask.
- the finite fraction of the resampled reference matches the overlap you expect, 1.0
  for full coverage, and the same stars sit at the same pixels in both arrays.
- with a reference variance plane, `is_translation` is true. If it is false, decide
  with the user before the launch (next section).

## Decide on a rotated or rescaled reference

With both variance planes and a PSF width (`psf_sigma_source` not null) the `corr`
term is active. It is defined only where the reference maps to the target by a shift.
A reference that is rotated or has another pixel scale then gets NaN for every
`<q>_err`, `uq_valid` false, and counts under `uq.undefined_factor` and
`uq.rotated_grid`. Fluxes and positions are still written. Without a PSF width,
`uq.excluded` records `corr: no PSF width` and the errors are fit-only. The CPU check
reads the header mapping alone. On the GPU the star refinement composes its fitted
affine with it (`diagnostics.align.refine.affine.A` in `summary.json`). A fitted
matrix more than 0.001 from the identity, as when a header's pixel scale is off,
gives the same NaN error bars and `uq.rotated_grid` count.

When `is_translation` is false and both variance planes exist, do not choose for the
user. List these options with their costs and ask. If you cannot ask, keep the
configuration, and report the NaN error bars, the `uq.rotated_grid` count and the
options:

- Use a reference with the target's pixel scale and orientation. A shift is fine.
- Drop the reference variance plane. The error bars are defined, `uq.excluded`
  records `corr`, and they omit the reference noise.
- Resample the reference onto the target grid beforehand and set `on_target_grid:
  true` with `xfit.psf_sigma_px`. The error bars are defined, but they leave out the
  pixel correlation from the earlier resampling, and the refinement is skipped.
- Set `uq.enabled=false`. The chain then reports fit-only errors.

## Set these keys for new data

| Key | Shipped in `config-generic.yaml` | Set it when |
| --- | --- | --- |
| `align.xcorr_window_px` | `512` | the target is smaller. The chain accepts a larger window, and the alignment diagnostic then uses an off-center crop or the whole image |
| `stamps.stamp_size` | `51` | it must equal the checkpoint's `image_size`. Candidates within half a stamp of the edge are dropped |
| `xfit.psf_sigma_px` | null | the refinement cannot measure the width from matched stars |
| `align.star_fwhm_px`, `align.star_threshold_sigma`, `align.match_radius_px` | `4.0`, `20.0`, `8.0` | seeing, depth or astrometric accuracy differ |
| `subtract.basis_sigmas` | `[1.5, 3.0, 6.0]` | the two PSF widths differ from the shipped case. Keep `basis_sigmas` the same length as `basis_degrees` |
| `io.reader` | `auto` | `astropy` forces host decoding. `xdr` fails on RICE, scaled or quantized files |
| `classify.noise_reference_sigma` | `114.705...`, for the checkpoint the example was developed with (none ships) | you change checkpoints. Alternatively set `classify.apply_noise_match: false` to score unscaled stamps |

The file marks the required keys, such as `stamps.stamp_size`. They have no default.
Override one value for one run with `--set BLOCK.KEY=VALUE`, nested keys included,
such as `--set survey.params.template.on_target_grid=true`.

## Launch

```bash
python "$SRC/examples/transient-chain/launch.py" --executor local \
    --config chain.yaml --selections selections.json --output-dir out

dragon -s -t tcp -o tcp "$SRC/examples/transient-chain/launch.py" --executor dragon \
    --config chain.yaml --selections selections.json --output-dir runs --name run1 --max-workers 4

CUDA_VISIBLE_DEVICES=0,1,2,3 mpirun -n 4 --map-by slot --bind-to none -x CUDA_VISIBLE_DEVICES \
    cuphoton-openmpi-rank-exec -- python "$SRC/examples/transient-chain/launch.py" --executor mpi \
    --config chain.yaml --selections selections.json --output-dir runs --name run1
```

`local` runs the items in turn on one GPU and rejects `--name` and `--max-workers`.
`dragon` must be started by the `dragon` launcher and places one worker per GPU. `-s`
runs it on one node. For several nodes use the `--wlm` form in
[docs/distributed-execution.md](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/docs/distributed-execution.md).
`mpi` runs one worker per rank. On several nodes every node must see the same
absolute paths. Without `--name` both generate a run id. Without `--checkpoint-dir`
the chain skips classification. The directory must hold an image-only triplet
`checkpoint.pt`. Without `--config` the launcher uses `config.yaml`, which is set up
for one survey's data release. The first item on a new environment spends most of a
minute compiling GPU kernels.

## Read the results

`local` writes `out/items/<item>/catalog.parquet` and `summary.json`, the merged
`out/catalog.parquet` and a run-level `out/summary.json`. `dragon` and `mpi` write the
same under `<output-dir>/<name>/`. The exit status is 1 when any item failed.

| Column | Read it as |
| --- | --- |
| `x`, `y` | integer hotspot pixel, zero-based |
| `ra`, `dec` | header WCS at (`x`, `y`). It is not the fitted source position |
| `source_x`, `source_y` | measured source, in pixels relative to (`x`, `y`) |
| `sign` | +1 brightening, -1 fading |
| `psf_flux`, `psf_flux_err` | difference flux at the source in target units. Forced PSF photometry with a target variance plane and a PSF width. Without the width, a `single` row holds the one-lobe fit's signed flux and fit-only error, and a `dipole` row is NaN. Without the variance plane every row is NaN |
| `fit_model` | `dipole`, or `single` when a one-lobe refit replaced it |
| `quality_flags` | bits of `cuphoton.xfit.DipoleQualityFlag`. 0 means none set |
| `probability`, `decision` | NaN and false without a checkpoint. False is then not a verdict |
| `uq_valid` | every computed `<q>_err` of the row is defined |

`uq_valid` does not say that every error term was available or that the fit is good.
A row can have a finite `psf_flux_err` and `uq_valid` false because a position error is
NaN. A row can have NaN flux columns and `uq_valid` true, because `uq_valid` covers
only the errors that were computed. When `psf_sigma_px` and `psf_sigma_source` in
`summary.json` are null, no forced photometry ran. Keep a finite `psf_flux` and quote
its error as fit-only. Do not fill a NaN `psf_flux` from `lobe_flux`. On a `dipole`
row that is one lobe of a two-lobe fit.

Read `uq_valid` together with `quality_flags` and `uncertainty_valid` in the catalog,
and with `uq_terms` and `uq.excluded` in `summary.json`. `uq.excluded` names each term
left out and why. With `uq.enabled=false`, `uq_valid` is true for every row,
`uq.excluded` is empty and `uq_terms` is `[fit]`. `cuphoton-propagate-uncertainty`
explains each term. The other summary fields and every column are in
[references/OUTPUTS.md](references/OUTPUTS.md).

## Report

Lead with what ran. Without a GPU, stop after the CPU checks, give the launch command,
and say the chain did not run. Then report, in this order:

1. The config choices that change results (HDUs, `variance_kind`, `mask_policy`,
   `on_target_grid`, `xfit.psf_sigma_px`) and what each implies.
2. Output paths, items run and failed, candidates, and rows with `uq_valid` false.
3. Each quoted value with its error and units (pixels relative to `x`, `y`, flux in
   target image units), then `uq_terms` and every `uq.excluded` reason.
4. Every NaN, false flag or fit-only error with its cause. Never fill or drop those
   rows.

## Troubleshooting and checks

[references/OUTPUTS.md](references/OUTPUTS.md) lists the launcher's messages with
their fixes, and the two scripts that check a finished run against a reference
catalog or across repeated exposures. Refer to the
[transient chain guide](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/docs/guide/transient-chain.qmd)
and the [example README](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/examples/transient-chain/README.md)
for every key, column and known issue.

---

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 cleared for import. Applicable license notices are attached or included when cleared.