Skip to content

Coincidences and timing jitter (delta-t)

A daplis-style pipeline for coincidence / timing-jitter analysis of the Kelpie ORT (timestamp) program, in two calls like every analysis:

  1. unpack decodes each .bin file into the per-frame, per-pixel TDC code (time_series, the MATLAB time_mat).
  2. process_coincidences converts the codes of the chosen pixels to picoseconds, differences every pixel pair frame by frame, and bins the differences onto a fixed native grid as it finds them, saving only the counts to processed/.
  3. plot_coincidences rebins that grid in memory, fits the coincidence peak and saves the figure to results/coincidences/.
from dapkel.functions import coincidences as co

signal = [(6, 10), (6, 11), (7, 10)]     # blobs read off the hitmap
idler = [(21, 22), (21, 23), (22, 22)]

co.process_coincidences(path, 10_000, [signal, idler],
                   daughterboard_number="D0", motherboard_number="M0")
counts, centers, fit = co.plot_coincidences(path)

pixels is two groups [group_a, group_b]; a bare (row, col) is a one-pixel group. With mode="all_pairs" (the default) every A × B combination is a pair — use it when it is not known which pixel of a blob catches the photon; "1v1" zips the groups element-wise. Each pair is one row of the saved grid, labelled "ra,ca-rb,cb".

Timing model

Each acquisition window is ~9 µs, but the ring-oscillator TDC measures only within one period of the reference clock. The recorded time_series value is the oscillator code on that range, and the timestamp is

t = code * CODE_S             with  CODE_S ≈ 71.6 ps  (core.timing.CODE_S)

on average. The ring sets that code width, so it does not change with the clock — only the number of codes does, as 1/f:

clock full scale codes
50 MHz 20 ns ~279
10 MHz 100 ns ~1397
5 MHz 200 ns ~2794
2 MHz 500 ns ~6985

That full scale bounds a difference, so it is also the accidental triangle's half-base — see the triangle background.

No entry point asks you for it. The largest code a run produced is the range its TDC swept, so it is measured from the data (core.timing.full_scale_from_max_code). That replaced three parameters that used to ask for the same number under different names — open_shutter_time_s, full_scale_s and support_s — one of which was not even the right quantity: the open shutter time is how long the SPAD waits for a photon, and an 8 µs shutter on a 10 MHz clock still yields ~100 ns timestamps, because the free-running oscillator has no cycle counter. It belongs to rate normalisation (DCR, hitmaps) and nothing else.

The actual bin widths come from the board's 8-tap calibration — see TDC calibration. With apply_TDC_calibration=True (the default, which needs daughterboard_number and motherboard_number) every code is converted with core.calibration.codes_to_ps before differencing. The taps belong to the ring, not the clock, so the same table serves a run at any clock and there is nothing to select: an S0T...S3T tag gets that SPAD's table, ORT the mean of the four. apply_TDC_calibration=False uses the nominal CODE_S.

Units

Every time parameter in the package is in seconds, with an _s suffix. There are three of them here, and they are all display or fit choices: bin_width_s, plot_window_s, fit_window_s. Histogram bin centres, edges and plot axes are in picoseconds — that is the scale the TDC lives on — and the conversion happens on entry.

Differences are binned in picoseconds whether or not a calibration was applied; uncalibrated codes are converted with the nominal CODE_S on the way in. There is no raw-code artifact, because there would be nothing to do with one: a calibration maps a code to a time, and a stored difference has lost both of its codes, so it could never be calibrated after the fact.

There is one timestamp per photon, per window, per macropixel.

Fitting the peak: the background is a triangle

This is the part that most affects the number you report.

The accidental-coincidence background under an ORT delta-t peak is triangular, not flat, because the free-running oscillator has no cycle counter. Fitting a Gaussian on a flat background over a wide window therefore inflates the fitted sigma — you measure the background's slope as if it were jitter.

plot_coincidences picks the model for you, and takes no background argument. The pedestal is either still in the histogram, and then it is the triangle, or subtract_background=True has measured it away and the residual is flat about zero — one decision, not two:

histogram model fitted over
raw (default) Gaussian on a triangular background, the measured full scale seeding the half-base the whole plotted window
lag-subtracted residual Gaussian on a zero baseline (not fitted) fit_window_s (default 5 ns) around the peak

A fit that fails — including one whose sigma the covariance cannot tell from zero, which a wrong background model produces — comes back with fit["ok"] False and a RuntimeWarning, so a plot without a curve always says why.

plot_coincidences returns (counts, centers, fit): the fitted histogram, the bin centres in picoseconds and a dict of amp, mu, sigma, fwhm, jitter_per_detector (sigma / √2), each with its _err, the background level bkg (0 on a residual), fit_range, car (peak-to-background, raw histogram only), n and ok — enough to re-fit by hand with any model without touching disk. The fit models themselves are private, and the two-Gaussian (narrow core on broad tails) model is retired to the repository's archive/ folder.

The full derivation, with the demonstration that the triangle is intrinsic rather than an artefact, is in the triangular background note.

Before you analyse: check the data

Run data_quality.process_time_codes and plot_time_codes on a pixel or two first. When the TDC never stops, unpack still returns a full array of plausible integers and this whole pipeline still produces a peak-shaped histogram — it is simply meaningless. See Data quality.

Stage 1: histogram straight off the .bin

process_coincidences bins the differences onto a fixed native grid as it finds them and keeps only the counts:

processed/
  <dataset>_<tag>_coincidences.npy       <- (n_pairs, n_cells) int64, tag lower-cased
  <dataset>_<tag>_coincidences.meta.json <- grid, pair labels, totals, progress

The size is set by the grid, not by the data. A 256-pair run on the default grid is 106 MB whether it came from 100 files or 10 000 — where keeping every difference took 3.22 GB for the same run, and 135 GB for a larger one. That is what makes every pair plottable at once. The tag is in the name, so several programs (ORT, S0T, ...) recorded into one folder keep their own artifact and their own figures.

Choosing the grid

One argument, bin_width_s (cell width):

data default cell why
uncalibrated (apply_TDC_calibration=False) one code, ~71.6 ps the codes are integers, so counts-per-code is a re-encoding, not a summary — exactly lossless
calibrated 1/10 code, ~7.2 ps the per-pixel calibration smears the code lattice; 7.2 ps is ~5× finer than the jitter

The half-range is not a parameter. It is the run's own TDC full scale — the largest code in the first file — with a 20 % margin for the extreme-value bias of reading that off one file. A difference cannot exceed the full scale, so that covers the whole physical support at any clock without being told the clock; a fixed 200 ns was 10× too wide at 50 MHz and 2.5× too narrow at 2 MHz. Anything landing outside is reported as n_outside rather than dropped silently, so an under-sized grid announces itself instead of quietly clipping the triangle.

Re-binning is free, and exact

plot_window_s becomes a slice and bin_width_s a reduce, both in memory — nothing is read but the one saved array:

co.plot_coincidences(
    path,
    pairs=["6,10-21,22"],
    bin_width_s=71e-12,
    plot_window_s=10e-9,        # omit for the whole measured support
)

The binning is always snapped onto the grid, and the snap is not cosmetic:

  • the width goes to a whole number of cells, or bins hold 9 then 10 then 9 cells and a smooth distribution picks up an ~11% sawtooth;
  • that number is made odd. Bins are centred on zero, so their edges sit at half-integer multiples of the width — odd puts those edges on cell boundaries, even puts them through cell centres, splitting a cell at every boundary. Measured on a real 3.22 GB run: exactly zero difference from histogramming every stored difference at 9, 11 and 13 cells per bin, ~1% at 8, 10 and 12;
  • the window goes to a whole number of bins, so zero is a bin centre whatever the window is.

So this is not an approximation of a histogram of the raw differences — it is the same histogram, in every bin.

The figure is results/coincidences/<dataset>_<tag>_<label>_coincidences.png, label (default "spdc") also heading the title.

What you give up

No per-event data survives, so there is nothing that needs individual differences — time ordering, splitting by acquisition, higher-order correlations. It also does not make stage 1 meaningfully faster: unpacking dominates either way. The win is artifact size and replot latency. The retired per-event (feather) path is in the repository's archive/ folder.

Crash insurance, and resuming

The grid is rewritten every 50 files (the module constant _FLUSH_EVERY, not a parameter — checkpoint cadence cannot change the numbers), so a run that dies leaves a valid artifact covering everything up to its last checkpoint, and the next call resumes from it (resume=True, the default) when it was computed from the same inputs — files, pairs, mode, grid, calibration and lags. There is only ever one file, so two runs cannot interleave. plot_coincidences on an incomplete artifact plots what is there and says how many files it covers.

The sidecar records files_done and total_in_grid. The array is moved into place before the sidecar, so a crash between the two moves could pair a newer array with an older sidecar; resuming on that would re-count files and inflate the total. The resume path checks the array against total_in_grid and starts over rather than continue from something inconsistent.

A complete artifact, or one computed from different inputs, is never touched without rewrite=True — process_coincidences raises FileExistsError instead.

Measuring the background instead of fitting it

subtract_background=True histograms the frame-shifted pixel pairs alongside the real ones, one grid plane per lag, so the accidental triangle can be subtracted bin-for-bin rather than fitted — see Removing the accidental background by shifting frames.

# the lags cost one small grid plane each; the .bin decoding is paid once
co.process_coincidences(path, 10_000, [signal, idler],
                   daughterboard_number="D0", motherboard_number="M0",
                   subtract_background=True)
counts, centers, fit = co.plot_coincidences(
    path, subtract_background=True, fit_window_s=2e-9)

Overwriting: the five-second countdown

rewrite=True routes through store.confirm_rewrite. On a fresh run it does nothing at all. When something really is about to be destroyed it names each target with its size and timestamp, then counts down five seconds before proceeding:

!!  rewrite=True - the following data WILL BE OVERWRITTEN:
!!    .../processed/SPDC_ort_coincidences.npy  (106.0 MB, written 2026-07-30 02:11)
!!  Press Ctrl-C within 5 s to abort and copy it somewhere safe.

The pause is a plain time.sleep, so Ctrl-C raises straight out of the analysis with the data on disk untouched. This is aimed at the common accident: a rewrite=True left in the script from the previous acquisition, silently eating an overnight run. Set store.REWRITE_DELAY_S = 0 in an unattended pipeline that has its own guard.

API

coincidences

Coincidence / timing-jitter (delta-t) analysis for the timestamping programs.

process_coincidences   raw '.bin' -> processed/<name>_<tag>_coincidences.npy
plot_coincidences      that grid  -> results/coincidences/ the fitted peak

In every frame where both pixels of a pair hold a timestamp, t_b - t_a is one entry of the delta-t distribution; correlated pairs (SPDC signal/idler) pile up at zero. Stage 1 bins those differences onto a fixed native grid as it finds them and keeps only the counts - one row per pixel pair, one column per grid cell - so the artifact is sized by the grid (~100 MB), not by the run, and stage 2 can rebin it to any width or window in memory. Uncalibrated data lands on a one-code grid and is lossless; a calibration smears the code lattice, so each difference moves by at most half a cell (~3.6 ps at the default), far below the detector jitter.

The ORT accidental background is a TRIANGLE, not flat: the free-running oscillator has no cycle counter, so two uncorrelated phases difference into a triangle that is zero at +/- one TDC full scale - 20 ns at 50 MHz, 100 ns at 10 MHz, 500 ns at 2 MHz. 'plot_coincidences' fits Gaussian + triangle on the raw histogram, or measures the triangle away entirely with subtract_background (below) and fits Gaussian + constant on the residual - the model follows from the data, it is not a choice. See docs/ort_triangle_background.md.

The full scale is measured, never asked for: the largest code a run holds is the range its TDC swept ('core.timing.full_scale_from_max_code'). Nor is the open shutter time it - an 8 us shutter on a 10 MHz clock still yields ~100 ns timestamps - so that belongs to rate normalisation and not here.

Background subtraction. An SPDC pair is always in one frame, so pairing pixel A in frame i with pixel B in frame i + k (k >= 1) samples the accidentals only, at the same rates. Subtract the mean of a few such lags from lag 0 and the triangle cancels bin for bin, leaving the peak on a zero baseline: a model-free coincidence count, and a test of whether the pedestal was accidental at all. It does not improve CAR - the residual keeps the Poisson noise of what it removed. See docs/guide/background_subtraction.md.

UNITS: every time parameter is in seconds with an _s suffix; differences, grids and plot axes are in picoseconds ('core.timing.to_ps'), whether or not a calibration was applied - uncalibrated codes are converted with the nominal 'timing.CODE_S' on the way in, because a saved difference of two codes could never be calibrated afterwards.

Check a fresh acquisition with 'dapkel.functions.data_quality' first. See docs/guide/coincidences.md.

process_coincidences

process_coincidences(path: str, nframes: int, pixels: Sequence[Sequence[Pixel]], *, tag: str = 'ORT', mode: str = 'all_pairs', bin_width_s: float | None = None, apply_TDC_calibration: bool = True, daughterboard_number: str | None = None, motherboard_number: str | None = None, subtract_background: bool = False, background_lags: int | Sequence[int] = _BACKGROUND_LAGS, max_files: int | None = None, rewrite: bool = False, resume: bool = True) -> str

Unpack the timestamps, histogram every pair's delta-t and save the grid.

Writes processed/<name>_<tag>_coincidences.npy: (n_pairs, n_cells) int64 counts on a native grid centred on zero (zero is a cell centre by construction) spanning the run's measured full scale, plus a sidecar with the grid, the pair labels and progress. With subtract_background a leading lag axis is added, lag 0 - the ordinary histogram - first.

The grid is rewritten every 50 files, so a run that dies leaves a valid artifact up to its last checkpoint and resume continues it.

Parameters:

Name Type Description Default
path str

Folder with the timestamping '.bin' files.

required
nframes int

Frames the acquisition recorded per '.bin' file.

required
pixels Sequence[Sequence[tuple[int, int]]]

Two groups [group_a, group_b] - e.g. the signal and idler blobs read off the hitmap. A bare (row, col) is a one-pixel group.

required
tag str

File tag. 'S0T'...'S3T' read one micropixel and get that SPAD's calibration; 'ORT' reads all four and gets the mean of theirs. The default is 'ORT'.

'ORT'
mode str

'all_pairs' (default): every A x B combination - use it when it is not known which pixel of a blob catches the photon. '1v1': zip the groups element-wise (equal lengths).

'all_pairs'
bin_width_s float | None

Width of one grid cell, in seconds. The default is None: one TDC code ('timing.CODE_S') uncalibrated, where that is exact, and a tenth of one with a calibration.

None
apply_TDC_calibration bool

Convert codes with the board's packaged compact calibration before differencing, correcting the ring's DNL at whatever clock the run used. The default is True, which needs daughterboard_number and motherboard_number. False uses the nominal code width.

True
daughterboard_number str | None

Daughterboard id, e.g. 'D0'. The default is None.

None
motherboard_number str | None

Motherboard id, e.g. 'M0'. The default is None.

None
subtract_background bool

Also histogram frame-shifted pairs (background_lags), one grid plane each, so 'plot_coincidences' can measure and subtract the accidentals. Costs one differencing pass and one plane of grid per lag; the '.bin' decoding, which dominates, is paid once. The default is False.

False
background_lags int | Sequence[int]

Frame offsets for the accidental estimate, all >= 1 (lag 0 is the signal and always included). The default is (1, ..., 8).

_BACKGROUND_LAGS
max_files int | None

Use at most this many files. The default is None (all).

None
rewrite bool

Overwrite a complete artifact for this data set - after a 5 s countdown naming it ('store.confirm_rewrite'). The default is False, which raises instead.

False
resume bool

Continue an incomplete artifact computed from the same inputs. The default is True.

True

Returns:

Type Description
str

Path to the saved '.npy'.

Raises:

Type Description
FileExistsError

Raised when an artifact exists and rewrite is False - complete, or computed from different inputs.

ValueError

Raised on a bad mode or background_lags, or a calibration request without a board.

Source code in src/dapkel/functions/coincidences.py
def process_coincidences(
    path: str,
    nframes: int,
    pixels: Sequence[Sequence[Pixel]],
    *,
    tag: str = "ORT",
    mode: str = "all_pairs",
    bin_width_s: float | None = None,
    apply_TDC_calibration: bool = True,
    daughterboard_number: str | None = None,
    motherboard_number: str | None = None,
    subtract_background: bool = False,
    background_lags: int | Sequence[int] = _BACKGROUND_LAGS,
    max_files: int | None = None,
    rewrite: bool = False,
    resume: bool = True,
) -> str:
    """Unpack the timestamps, histogram every pair's delta-t and save the grid.

    Writes ``processed/<name>_<tag>_coincidences.npy``: ``(n_pairs, n_cells)``
    int64 counts on a native grid centred on zero (zero is a cell centre by
    construction) spanning the run's measured full scale, plus a sidecar with
    the grid, the pair labels and progress. With ``subtract_background`` a
    leading lag axis is added, lag 0 - the ordinary histogram - first.

    The grid is rewritten every 50 files, so a run that dies leaves a valid
    artifact up to its last checkpoint and ``resume`` continues it.

    Parameters
    ----------
    path : str
        Folder with the timestamping '.bin' files.
    nframes : int
        Frames the acquisition recorded per '.bin' file.
    pixels : Sequence[Sequence[tuple[int, int]]]
        Two groups ``[group_a, group_b]`` - e.g. the signal and idler blobs read
        off the hitmap. A bare ``(row, col)`` is a one-pixel group.
    tag : str, optional
        File tag. ``'S0T'``...``'S3T'`` read one micropixel and get that SPAD's
        calibration; ``'ORT'`` reads all four and gets the mean of theirs. The
        default is ``'ORT'``.
    mode : str, optional
        ``'all_pairs'`` (default): every A x B combination - use it when it is
        not known which pixel of a blob catches the photon. ``'1v1'``: zip the
        groups element-wise (equal lengths).
    bin_width_s : float | None, optional
        Width of one grid cell, in seconds. The default is None: one TDC code
        ('timing.CODE_S') uncalibrated, where that is exact, and a tenth of one
        with a calibration.
    apply_TDC_calibration : bool, optional
        Convert codes with the board's packaged compact calibration before
        differencing, correcting the ring's DNL at whatever clock the run used.
        The default is True, which needs ``daughterboard_number`` and
        ``motherboard_number``. False uses the nominal code width.
    daughterboard_number : str | None, optional
        Daughterboard id, e.g. ``'D0'``. The default is None.
    motherboard_number : str | None, optional
        Motherboard id, e.g. ``'M0'``. The default is None.
    subtract_background : bool, optional
        Also histogram frame-shifted pairs (``background_lags``), one grid plane
        each, so 'plot_coincidences' can measure and subtract the accidentals. Costs
        one differencing pass and one plane of grid per lag; the '.bin'
        decoding, which dominates, is paid once. The default is False.
    background_lags : int | Sequence[int], optional
        Frame offsets for the accidental estimate, all >= 1 (lag 0 is the
        signal and always included). The default is ``(1, ..., 8)``.
    max_files : int | None, optional
        Use at most this many files. The default is None (all).
    rewrite : bool, optional
        Overwrite a *complete* artifact for this data set - after a 5 s
        countdown naming it ('store.confirm_rewrite'). The default is False,
        which raises instead.
    resume : bool, optional
        Continue an incomplete artifact computed from the same inputs. The
        default is True.

    Returns
    -------
    str
        Path to the saved '.npy'.

    Raises
    ------
    FileExistsError
        Raised when an artifact exists and ``rewrite`` is False - complete, or
        computed from different inputs.
    ValueError
        Raised on a bad ``mode`` or ``background_lags``, or a calibration
        request without a board.
    """
    if subtract_background:
        extra = (
            [background_lags]
            if isinstance(background_lags, (int, np.integer))
            else list(background_lags)
        )
        lags = [0, *(int(k) for k in extra)]
        if len(lags) < 2 or min(lags[1:]) < 1 or len(set(lags)) != len(lags):
            raise ValueError(
                "background_lags must be distinct frame offsets >= 1 (lag 0 is "
                f"the signal); got {background_lags!r}"
            )
    else:
        lags = [0]

    files = io.find_bin_files(path, tag)[:max_files]
    pair_list = pixel_pairs.pair_list(pixels, mode)
    labels = [pixel_pairs.pair_label(a, b) for a, b in pair_list]
    all_pixels = list(dict.fromkeys(p for pair in pair_list for p in pair))

    taps = None
    board = None
    if apply_TDC_calibration:
        if daughterboard_number is None or motherboard_number is None:
            raise ValueError(
                "apply_TDC_calibration=True but no board was given. Pass "
                "daughterboard_number and motherboard_number, or set "
                "apply_TDC_calibration=False for the nominal code width."
            )
        board = f"{daughterboard_number}_{motherboard_number}"
        taps = calibration.board_taps(daughterboard_number, motherboard_number, tag)
    if bin_width_s is None:
        bin_width_s = timing.CODE_S / (_GRID_SUBDIV if taps is not None else 1)

    # The largest code is what the reference clock left in the data: the TDC
    # full scale, hence the widest a difference can be. One file is enough - it
    # is set by the clock, not the count - and the margin covers the rest.
    ts0, _ = unpack(files[0], nframes, compute_time_series=True)
    max_code = int(ts0[ts0 > 0].max()) if (ts0 > 0).any() else 0
    support_s = _SUPPORT_MARGIN * timing.full_scale_from_max_code(max_code)
    zero_index = int(np.ceil(support_s / bin_width_s))
    n_bins = 2 * zero_index + 1
    grid_ps = timing.to_ps(bin_width_s)

    counts_path = _counts_file(path, tag)
    # Everything that must match for a partial run to be resumed. Files are
    # fingerprinted by (name, size): progress is "the first N of them".
    digest = hashlib.sha1()
    for fp in files:
        digest.update(f"{os.path.basename(fp)}:{os.path.getsize(fp)};".encode())
    signature = {
        "n_files": len(files),
        "files_digest": digest.hexdigest(),
        "labels_digest": hashlib.sha1("|".join(labels).encode()).hexdigest(),
        "mode": mode,
        "nframes": int(nframes),
        "bin_width_s": float(bin_width_s),
        "support_s": float(support_s),
        "calibration": board,
        "lags": lags,
    }

    counts = np.zeros(
        (len(labels), n_bins) if len(lags) == 1 else (len(lags), len(labels), n_bins),
        dtype=np.int64,
    )
    start = total = outside = 0
    existing = store.read_meta(counts_path) if os.path.isfile(counts_path) else {}
    if existing.get("signature") == signature and not existing.get("complete"):
        if resume:
            saved, _ = store.load_map(npy_path=counts_path)
            # The sidecar is moved into place after the array, so a crash
            # between the two can pair a newer array with an older sidecar.
            # Resuming on that would count files twice; start over instead.
            if saved.shape == counts.shape and int(saved.sum()) == existing.get(
                "total_in_grid"
            ):
                counts = saved
                start = int(existing["files_done"])
                total = int(existing["total"])
                outside = int(existing["n_outside"])
                print(f"\n> > > Resuming at file {start} of {len(files)} < < <")
            else:
                print("\n  The saved grid disagrees with its sidecar; starting over.")
    elif os.path.isfile(counts_path):
        if not rewrite:
            raise FileExistsError(
                f"{counts_path} exists"
                + (
                    f" and covers all {len(files)} file(s)"
                    if existing.get("signature") == signature
                    else " but was computed from different inputs"
                )
                + ". Pass rewrite=True to replace it."
            )
        store.confirm_rewrite([counts_path])

    def _checkpoint(files_done: int, complete: bool) -> None:
        """Write the grid and its sidecar, each via a temporary moved into place."""
        meta = {
            "signature": signature,
            "labels": labels,
            "unit": "ps",
            "tag": tag,
            "calibration": board,
            "bin_width_s": float(bin_width_s),
            "grid_ps": float(grid_ps),
            "support_s": float(support_s),
            "max_code": max_code,
            "n_bins": n_bins,
            "zero_index": zero_index,
            "files_done": int(files_done),
            "n_files": len(files),
            "complete": complete,
            "total": int(total),
            "n_outside": int(outside),
            "total_in_grid": int(counts.sum()),
        }
        if len(lags) > 1:
            # Lag k pairs frame i with i + k, so it loses the last k frames of
            # every file; the subtraction rescales by this.
            meta["lags"] = lags
            meta["frames_used"] = [
                max(int(nframes) - k, 0) * int(files_done) for k in lags
            ]
        tmp_npy = counts_path + ".tmp.npy"
        tmp_meta = store.meta_path(counts_path) + ".tmp"
        np.save(tmp_npy, counts)
        with open(tmp_meta, "w", encoding="utf-8") as fh:
            json.dump(meta, fh, indent=2)
        os.replace(tmp_npy, counts_path)
        os.replace(tmp_meta, store.meta_path(counts_path))

    print(
        f"\n> > > Histogramming delta-t from {len(files) - start} '{tag}' file(s) "
        f"onto {'x'.join(map(str, counts.shape))} cells of "
        f"{bin_width_s * 1e12:.2f} ps spanning +/-{support_s * 1e9:.1f} ns "
        f"({counts.nbytes / 1024**2:.0f} MB)"
        + (f", lags {lags}" if len(lags) > 1 else "")
        + " < < <\n"
    )
    planes = counts if len(lags) > 1 else counts[np.newaxis]
    for i, fp in enumerate(tqdm(files[start:], desc=tag), start=start + 1):
        ts, _ = unpack(fp, nframes, compute_time_series=True)
        pixel_ts = _pixel_timestamps(ts, all_pixels, taps)
        for plane, lag in zip(planes, lags, strict=True):
            n = max(int(nframes) - lag, 0)
            for row, (a, b) in enumerate(pair_list):
                # B shifted by 'lag' frames: lag 0 is the coincidence, lag > 0 a
                # pure accidental sample. NaN where either pixel did not fire.
                d = pixel_ts[b][lag : lag + n] - pixel_ts[a][:n]
                d = d[np.isfinite(d)]
                if not d.size:
                    continue
                # np.add.at, not bincount: one file adds a handful of entries
                # per pair, and bincount would pay for the whole grid each time.
                idx = np.rint(d / grid_ps).astype(np.int64) + zero_index
                keep = (idx >= 0) & (idx < n_bins)
                total += d.size
                outside += d.size - int(np.count_nonzero(keep))
                np.add.at(plane[row], idx[keep], 1)
        if i % _FLUSH_EVERY == 0:
            _checkpoint(i, False)
    _checkpoint(len(files), True)

    print(
        f"\n> > > {total} difference(s) across {len(labels)} pair(s) binned; "
        f"{outside} outside +/-{support_s * 1e9:.1f} ns. Saved to "
        f"{counts_path} < < <"
    )
    if len(lags) > 1:
        per_lag = counts.sum(axis=(1, 2))
        print(
            f"  lag 0: {per_lag[0]}; shifted lags: {per_lag[1:].mean():.0f} on "
            f"average -> a raw excess of {per_lag[0] - per_lag[1:].mean():.0f}."
        )
    if outside:
        print(
            f"  NOTE: {100 * outside / max(total, 1):.2f}% of differences fell "
            "outside the grid (counted, not binned): the run's timestamps reach "
            "further than its first file suggested."
        )
    return counts_path

plot_coincidences

plot_coincidences(path: str, tag: str = 'ORT', *, bin_width_s: float = CODE_S, plot_window_s: float | None = None, fit_window_s: float | None = 5e-09, pairs: Sequence[str] | None = None, label: str = 'spdc', title: str | None = None, subtract_background: bool = False) -> tuple[ndarray, ndarray, dict]

Rebin the saved grid, fit the coincidence peak and save the figure.

Nothing is read but the one saved array, and the rebinning is in memory, so changing bin_width_s or plot_window_s costs milliseconds. The binning is snapped onto the grid - a whole, odd number of cells per bin and a whole number of bins per window - which is what makes the rebin exact.

The fit model is not a parameter: on the raw histogram it is Gaussian + triangle with the measured full scale seeding the half-base; with subtract_background it is a Gaussian on a zero baseline within fit_window_s of the peak, there being no background left. The curve and the residual panel cover only the fitted range.

Parameters:

Name Type Description Default
path str

Data folder that 'process_coincidences' was run on.

required
tag str

The tag it was run with. The default is 'ORT'.

'ORT'
bin_width_s float

Histogram bin width, in seconds. The default is one TDC code.

CODE_S
plot_window_s float | None

Half-range around zero, in seconds. The default is None: the measured TDC full scale, the whole support the triangle fit wants.

None
fit_window_s float | None

Half-range around the peak, in seconds - the subtracted fit's range and the window the model-free coincidence count is summed over. Wide enough to reach past the peak's diffusion tails (~3 ns), so the fit sees them end. Ignored by the triangle fit. The default is 5e-9.

5e-09
pairs Sequence[str] | None

Pool only these pixel-pair labels ("ra,ca-rb,cb"). The default is None (every pair).

None
label str

Short label for the title and file name ('spdc', 'hbt'). The default is 'spdc'.

'spdc'
title str | None

Override for the plot title. The default is None.

None
subtract_background bool

Subtract the frame-shifted accidentals before fitting and save the three-panel diagnostic beside the fit; read its middle panel before quoting anything. Needs a grid processed with subtract_background=True. The default is False.

False

Returns:

Name Type Description
counts ndarray

The fitted histogram - the residual with subtract_background.

centers ndarray

Bin centres in picoseconds, to re-fit without re-reading anything.

fit dict

amp, mu, sigma, sigma_err, bkg, fwhm, jitter_per_detector (each with _err), car (peak-to- background, raw histogram only), n and ok; with subtract_background also model_free, subtraction and subtraction_png.

Raises:

Type Description
FileNotFoundError

Raised when no saved grid exists for tag.

ValueError

Raised when subtract_background is asked of a grid without lags.

Source code in src/dapkel/functions/coincidences.py
def plot_coincidences(
    path: str,
    tag: str = "ORT",
    *,
    bin_width_s: float = timing.CODE_S,
    plot_window_s: float | None = None,
    fit_window_s: float | None = 5e-9,
    pairs: Sequence[str] | None = None,
    label: str = "spdc",
    title: str | None = None,
    subtract_background: bool = False,
) -> tuple[np.ndarray, np.ndarray, dict]:
    """Rebin the saved grid, fit the coincidence peak and save the figure.

    Nothing is read but the one saved array, and the rebinning is in memory, so
    changing ``bin_width_s`` or ``plot_window_s`` costs milliseconds. The
    binning is snapped onto the grid - a whole, odd number of cells per bin and
    a whole number of bins per window - which is what makes the rebin exact.

    The fit model is not a parameter: on the raw histogram it is ``Gaussian +
    triangle`` with the measured full scale seeding the half-base; with
    ``subtract_background`` it is a Gaussian on a zero baseline within
    ``fit_window_s`` of the peak, there being no background left. The curve
    and the residual panel cover only the fitted range.

    Parameters
    ----------
    path : str
        Data folder that 'process_coincidences' was run on.
    tag : str, optional
        The tag it was run with. The default is ``'ORT'``.
    bin_width_s : float, optional
        Histogram bin width, in seconds. The default is one TDC code.
    plot_window_s : float | None, optional
        Half-range around zero, in seconds. The default is None: the measured
        TDC full scale, the whole support the triangle fit wants.
    fit_window_s : float | None, optional
        Half-range around the peak, in seconds - the subtracted fit's range and
        the window the model-free coincidence count is summed over. Wide enough
        to reach past the peak's diffusion tails (~3 ns), so the fit sees them
        end. Ignored by the triangle fit. The default is ``5e-9``.
    pairs : Sequence[str] | None, optional
        Pool only these pixel-pair labels (``"ra,ca-rb,cb"``). The default is
        None (every pair).
    label : str, optional
        Short label for the title and file name (``'spdc'``, ``'hbt'``). The
        default is ``'spdc'``.
    title : str | None, optional
        Override for the plot title. The default is None.
    subtract_background : bool, optional
        Subtract the frame-shifted accidentals before fitting and save the
        three-panel diagnostic beside the fit; read its middle panel before
        quoting anything. Needs a grid processed with
        ``subtract_background=True``. The default is False.

    Returns
    -------
    counts : np.ndarray
        The fitted histogram - the residual with ``subtract_background``.
    centers : np.ndarray
        Bin centres in picoseconds, to re-fit without re-reading anything.
    fit : dict
        ``amp``, ``mu``, ``sigma``, ``sigma_err``, ``bkg``, ``fwhm``,
        ``jitter_per_detector`` (each with ``_err``), ``car`` (peak-to-
        background, raw histogram only), ``n`` and ``ok``; with
        ``subtract_background`` also ``model_free``, ``subtraction`` and
        ``subtraction_png``.

    Raises
    ------
    FileNotFoundError
        Raised when no saved grid exists for ``tag``.
    ValueError
        Raised when ``subtract_background`` is asked of a grid without lags.
    """
    counts_path = _counts_file(path, tag, create=False)
    grid, meta = store.load_map(npy_path=counts_path)
    if not meta.get("complete", True):
        print(
            f"  NOTE: {os.path.basename(counts_path)} is incomplete - "
            f"{meta.get('files_done')} of {meta.get('n_files')} file(s)."
        )
    labels = list(meta["labels"])
    pair_axis = grid.ndim - 2
    if pairs is not None:
        missing = [p for p in pairs if p not in labels]
        if missing:
            print(f"  no such pixel-pair row(s): {missing}")
        grid = np.take(
            grid, [labels.index(p) for p in pairs if p in labels], axis=pair_axis
        )
        labels = [p for p in pairs if p in labels]
    grid = grid.sum(axis=pair_axis)  # (n_cells,), or (n_lags, n_cells)
    cell_ps = float(meta["grid_ps"])
    grid_centers = (np.arange(grid.shape[-1]) - int(meta["zero_index"])) * cell_ps

    name = os.path.basename(counts_path).removesuffix("_coincidences.npy")
    results_dir = store.results_dir(path, _KIND)
    # The grid was sized from the run's own largest code, so this is the
    # measured full scale - the triangle's half-base, with no clock stated.
    full_scale_s = timing.full_scale_from_max_code(int(meta["max_code"]))
    if plot_window_s is None:
        plot_window_s = full_scale_s
    bin_width_s, plot_window_s = _snap_binning(
        bin_width_s, plot_window_s, timing.to_s(cell_ps)
    )

    sub = None
    if subtract_background:
        if grid.ndim != 2:
            raise ValueError(
                "subtract_background=True needs lag planes. Reprocess with "
                "process_coincidences(..., subtract_background=True)."
            )
        # One binning over the whole support for the fit and the diagnostic, so
        # the panels cannot disagree about a bin edge.
        lag_counts, lag_centers = _rebin(
            grid,
            grid_centers,
            bin_width_s,
            timing.to_s(float(np.abs(grid_centers).max())),
        )
        sub = _subtract_background(
            lag_counts,
            lag_centers,
            meta["frames_used"],
            name=name,
            results_dir=results_dir,
            bin_width_s=bin_width_s,
            zoom_window_s=plot_window_s,
            fit_window_s=fit_window_s,
            label=label,
        )
        counts, centers = sub["residual"], sub["centers"]
        # Summing a residual's bins *is* the coincidence count; anything outside
        # the peak is noise around zero.
        n = int(round(sub["model_free"]["n"]))
        fit = _fit_peak(
            centers,
            counts,
            fit_window=None if fit_window_s is None else timing.to_ps(fit_window_s),
        )
        fit["car"] = np.nan  # a ratio to a zero baseline is a division by noise
    else:
        signal = grid[0] if grid.ndim == 2 else grid
        counts, centers = _rebin(signal, grid_centers, bin_width_s, plot_window_s)
        n = int(counts.sum())
        print(
            f"\n> > > {int(signal.sum())} difference(s) across {len(labels)} "
            f"pair(s); {n} inside +/-{plot_window_s * 1e9:.2f} ns, rebinned to "
            f"{counts.size} x {bin_width_s * 1e12:.0f} ps < < <"
        )
        fit = _fit_peak(centers, counts, half_base=timing.to_ps(full_scale_s))
        fit["car"] = (fit["amp"] + fit["bkg"]) / fit["bkg"] if fit["bkg"] else np.inf
    fit["n"] = n

    fig, (ax, ax_res) = plt.subplots(
        2, 1, sharex=True, gridspec_kw={"height_ratios": [3, 1]}
    )
    width_ps = timing.to_ps(bin_width_s)
    ax.bar(centers, counts, width=width_ps, label=f"data ({n} pairs)")
    if fit["ok"]:

        def model(x: np.ndarray) -> np.ndarray:
            shape = (
                np.clip(1.0 - np.abs(x) / fit["half_base"], 0.0, None)
                if "half_base" in fit
                else 1.0
            )
            gauss = np.exp(-((x - fit["mu"]) ** 2) / (2.0 * fit["sigma"] ** 2))
            return fit["amp"] * gauss + fit["bkg"] * shape

        # Only where it was fitted: drawn further out, the model claims a
        # baseline nothing constrained.
        start, stop = fit["fit_range"]
        xs = np.linspace(start, stop, 4000)
        ax.plot(
            xs,
            model(xs),
            color="C1",
            label=(
                f"FWHM = {_pm(fit['fwhm'], fit['fwhm_err'])}\n"
                rf"$\sigma$ = {_pm(fit['sigma'], fit['sigma_err'])}"
                "\n"
                r"$\sigma_\mathrm{detector}$ = "
                f"{_pm(fit['jitter_per_detector'], fit['jitter_per_detector_err'])}"
            ),
        )
        fitted = (centers >= start) & (centers <= stop)
        ax_res.bar(
            centers[fitted],
            counts[fitted] - model(centers[fitted]),
            width=width_ps,
        )
    else:
        ax_res.text(
            0.5, 0.5, "no fit", ha="center", va="center", transform=ax_res.transAxes
        )
    _zero_line(ax_res)
    ax_res.set_xlabel("Timestamp difference  (ps)")
    ax_res.set_ylabel("Data - fit")
    ax.set_ylabel(
        "Coincidences - accidentals" if subtract_background else "Coincidences"
    )
    ax.set_title(title or f"{label.upper()} coincidence peak  ({name})")
    ax.legend()
    fig.tight_layout()
    stem = "coincidences_sub" if subtract_background else "coincidences"
    store.save_figure(fig, results_dir, f"{name}_{label}_{stem}.png")

    if fit["ok"]:
        print(
            f"  peak: mu {fit['mu']:.0f} ps  FWHM "
            f"{_pm(fit['fwhm'], fit['fwhm_err'], ' +- ')}  sigma "
            f"{_pm(fit['sigma'], fit['sigma_err'], ' +- ')}  sigma_detector "
            f"{_pm(fit['jitter_per_detector'], fit['jitter_per_detector_err'], ' +- ')}"
            + ("" if subtract_background else f"  peak/bkg {fit['car']:.2f}")
        )
    else:
        print(
            "  no Gaussian peak fit - check the blob selection, and that the run "
            "has proper (stopped, fine) timing."
        )
    if sub is not None:
        fit["model_free"] = sub["model_free"]
        fit["subtraction"] = sub
        fit["subtraction_png"] = sub["png_path"]
    return counts, centers, fit