Skip to content

Dark count rate (DCR)

The DCR map is the per-pixel dark-count rate in counts per second: accumulated dark counts divided by the time the sensor was actually collecting.

DCR = sum(counts) / (nframes * n_files * live_per_frame)

Two calls, like every analysis: process_dcr unpacks the dark .bin files and saves the map in cps to processed/<name>_<tag>_dcr.npy; plot_dcr loads it, saves <name>_<tag>_dcr_heatmap.png and <name>_<tag>_dcr_distribution.png to results/dcr/, and returns the map.

from dapkel.functions import dcr_analysis

# one quadrant, counting mode, 100 ns open shutter
dcr_analysis.process_dcr(path, 1000, "S0C", open_shutter_time_s=100e-9)
dcr = dcr_analysis.plot_dcr(path, "S0C")

# timestamping mode, Poisson-corrected
dcr_analysis.process_dcr(
    path, 1000, "S0T", open_shutter_time_s=8e-6, pileup_correct=True
)
dcr_analysis.plot_dcr(path, "S0T")

Counting mode vs timestamping mode

What "a count" is depends on the acquisition program, and it decides which field of the unpacked data is read. There is no mode argument: the mode comes from the last letter of the tag (core.reduce.readout_mode), so tag is required.

  • Count mode — ...C tags (S0C, ORC). Each pixel has a real 9-bit photon counter per frame, and the map is its sum.
  • Timestamp mode — ...T tags (S0T, ORT). There is no counter: the chip timestamps the first hit instead, and unpack returns the low bits of the coarse timestamp in the photon_counts slot. The count is therefore the number of frames carrying a valid timestamp, (ts > 0).sum(axis=2) — the same definition hitmap_analysis uses.

Summing the counter field on *T data inflates the DCR ~40-50×

Those bits are coarse >> 1, so a fired pixel contributes a few hundred instead of 1, and the result still looks like a plausible DCR map. On real 24 V S0T data the median came out at 247 kcps — nearly twice the 125 kcps that one-hit-per-8-µs-frame physically allows. Because the mode is read off the tag rather than passed beside it, S0T data can no longer be summed as counts by mistake.

Saturation and pileup_correct

Timestamping records at most one count per pixel per frame, so the raw rate is really an occupancy and it saturates at 1 / open_shutter_time_s — 125 kcps at an 8 µs shutter. It under-reports well before the ceiling: at 50 % occupancy it reads ~30 % low.

pileup_correct=True inverts the censoring under Poisson statistics, since a frame fires with probability p = 1 - exp(-r·w):

r = -ln(1 - hits/total_frames) / open_shutter_time_s

It is off by default — the raw occupancy rate is what the sensor measured — and process_dcr prints a warning naming the ceiling whenever the hottest pixel gets past 5 % of it. Counting mode has no such ceiling and ignores the flag.

Live time is not frame time

The normalisation uses the live time per frame, which depends on the firmware — see core.timing.resolve_live_time.

  • short_exposure (current firmware, the default) — each ~9 µs frame is mostly readout and only the user-set open_shutter_time_s is photon-sensitive. That window sits inside the cycle without extending it and is settable from ~50 ns up to the full 9 µs, so a wrong guess is a rate error of up to two decades. Pass the open_shutter_time_s the run used (the default is 500e-9); resolve_live_time raises on None rather than guessing. Nothing in the data reveals it, which is why it is one of the few timescales still asked for — and note it is not the TDC full scale, which the coincidence pipeline measures for itself.
  • long_exposure (legacy) — the whole frame is live, so the per-frame time is exp_time_s + 9 µs overhead, or the 9 µs free-running cycle when exp_time_s is None.

Under the legacy firmware the exposure argument passed to Kelpie_v2.exe maps to an actual frame period with 9 µs of overhead: 0 → 9 µs, 10 µs → 19 µs.

Quadrants

Every program gives a (32, 32) map: a SPAD quadrant tag — S0C...S3C in counting mode, S0T...S3T in timestamping mode — reads one micropixel per 2×2 macropixel, ORC / ORT all four at once. Interleaving the four quadrant maps onto the (64, 64) micropixel grid is archived (archive/core/reduce.py), since no current measurement needs it.

The SPAD indices run clockwise (S0 S1 / S3 S2), not row-major; the layout is documented under cross-talk and enforced by tests/test_spad_geometry.py.

Pixel masking

Hot/warm pixel masking is not implemented yet. When per-board mask files become available, masked pixels will read as NaN — which is why every statistic in core.plots is already NaN-aware. Plain np.median / np.percentile propagate NaN, and a single masked pixel would otherwise turn vmax into NaN and flatten the entire heatmap to one colour with no error raised.

API

dcr_analysis

Dark count rate (DCR) maps, per quadrant or for the full sensor.

process_dcr   raw '.bin' -> processed/<name>_<tag>_dcr.npy (cps)
plot_dcr      that array -> results/dcr/ heatmap and sorted distribution

DCR is accumulated dark counts divided by the time the sensor was actually collecting. That live time is NOT the frame period: under the current short_exposure firmware only the user-set open_shutter_time_s of each ~9 us frame is photon-sensitive.

What a count is follows from the tag ('core.reduce'): the photon counter for ...C programs, frames carrying a valid timestamp for ...T ones. In timestamp mode only the first dark count of a frame is recorded, so the rate saturates at one per open_shutter_time_s (125 kcps at an 8 µs window) and under-reports below it; pileup_correct=True inverts that censoring under Poisson statistics.

See docs/guide/dcr.md.

process_dcr

process_dcr(path: str, nframes: int, tag: str, *, pileup_correct: bool = False, firmware_version: str = 'short_exposure', open_shutter_time_s: float | None = 5e-07, exp_time_s: float | None = None, max_files: int | None = None) -> str

Unpack the dark '.bin' files, compute the DCR map in cps and save it.

Parameters:

Name Type Description Default
path str

Folder with the '.bin' data files.

required
nframes int

Frames the acquisition recorded per '.bin' file.

required
tag str

File tag: 'S0C'... 'S3C', 'S0T'..., 'ORC', 'ORT'.

required
pileup_correct bool

Timestamp tags only. Each frame is a Bernoulli trial - a frame fires with p = 1 - exp(-r * w) because only the first count is recorded - so the occupancy is replaced by its maximum-likelihood -N ln(1 - hits/N) before dividing by the live time. A pixel firing in every frame is clipped to the half-count level, a finite lower bound. The default is False (the raw occupancy rate).

False
firmware_version str

'short_exposure' (default) or 'long_exposure'; see 'core.timing.resolve_live_time'.

'short_exposure'
open_shutter_time_s float | None

Photon-sensitive window per frame, in seconds. The default is 500e-9.

5e-07
exp_time_s float | None

Exposure requested of 'long_exposure' firmware, in seconds. The default is None.

None
max_files int | None

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

None

Returns:

Type Description
str

Path to the saved '.npy'.

Source code in src/dapkel/functions/dcr_analysis.py
def process_dcr(
    path: str,
    nframes: int,
    tag: str,
    *,
    pileup_correct: bool = False,
    firmware_version: str = "short_exposure",
    open_shutter_time_s: float | None = 500e-9,
    exp_time_s: float | None = None,
    max_files: int | None = None,
) -> str:
    """Unpack the dark '.bin' files, compute the DCR map in cps and save it.

    Parameters
    ----------
    path : str
        Folder with the '.bin' data files.
    nframes : int
        Frames the acquisition recorded per '.bin' file.
    tag : str
        File tag: ``'S0C'``... ``'S3C'``, ``'S0T'``..., ``'ORC'``, ``'ORT'``.
    pileup_correct : bool, optional
        Timestamp tags only. Each frame is a Bernoulli trial - a frame fires
        with ``p = 1 - exp(-r * w)`` because only the first count is recorded -
        so the occupancy is replaced by its maximum-likelihood
        ``-N ln(1 - hits/N)`` before dividing by the live time. A pixel firing
        in every frame is clipped to the half-count level, a finite lower
        bound. The default is False (the raw occupancy rate).
    firmware_version : str, optional
        ``'short_exposure'`` (default) or ``'long_exposure'``; see
        'core.timing.resolve_live_time'.
    open_shutter_time_s : float | None, optional
        Photon-sensitive window per frame, in seconds. The default is
        ``500e-9``.
    exp_time_s : float | None, optional
        Exposure requested of ``'long_exposure'`` firmware, in seconds. The
        default is None.
    max_files : int | None, optional
        Use at most this many files. The default is None (all).

    Returns
    -------
    str
        Path to the saved '.npy'.
    """
    live_s, live_source = timing.resolve_live_time(
        firmware_version,
        open_shutter_time_s=open_shutter_time_s,
        exp_time_s=exp_time_s,
    )
    mode = reduce.readout_mode(tag)
    pileup_correct = pileup_correct and mode == "timestamp"
    print(f"\n> > > Computing the '{tag}' DCR map (mode='{mode}') < < <\n")
    counts, n_files = reduce.count_map(
        path, tag, nframes=nframes, max_files=max_files
    )
    total_frames = int(nframes) * n_files
    if pileup_correct:
        p = np.minimum(counts / total_frames, 1.0 - 0.5 / total_frames)
        counts = -total_frames * np.log1p(-p)
    dcr = counts / (total_frames * live_s)

    # A saturated *pixel* is normal in a DCR map; it is the number attached to
    # it that stops being a rate, so this is a note rather than an error.
    ceiling = 1.0 / live_s
    if mode == "timestamp" and not pileup_correct and np.nanmax(dcr) > 0.05 * ceiling:
        print(
            f"  ! timestamp mode saturates at {ceiling:.3g} cps; the hottest "
            f"pixel is at {np.nanmax(dcr) / ceiling * 100:.0f}% of that and "
            f"{int((dcr > 0.5 * ceiling).sum())} are past 50%, so those read "
            "low. Pass pileup_correct=True for the Poisson-corrected rate."
        )

    out_path = store.save_map(
        dcr,
        path,
        kind=_KIND,
        tag=tag,
        meta={
            "mode": mode,
            "pileup_correct": pileup_correct,
            "n_files": n_files,
            "nframes": int(nframes),
            "firmware_version": firmware_version,
            "open_shutter_time_s": open_shutter_time_s,
            "exp_time_s": exp_time_s,
            "frame_live_s": live_s,
            "live_time_source": live_source,
            "unit": "cps",
        },
        quiet=True,
    )
    print(
        f"  median {np.nanmedian(dcr):.0f}  max {np.nanmax(dcr):.0f} cps\n\n"
        f"> > > DCR map saved to {out_path} < < <"
    )
    return out_path

plot_dcr

plot_dcr(path: str, tag: str, *, cmap: str | None = None) -> ndarray

Load a saved DCR map and save its heatmap and sorted distribution.

Parameters:

Name Type Description Default
path str

Data folder that 'process_dcr' was run on.

required
tag str

The tag it was run with.

required
cmap str | None

Matplotlib colormap name for the heatmap. The default is None - the active style's.

None

Returns:

Type Description
ndarray

The DCR map, in counts per second.

Raises:

Type Description
FileNotFoundError

Raised when no saved DCR map exists for tag.

Source code in src/dapkel/functions/dcr_analysis.py
def plot_dcr(path: str, tag: str, *, cmap: str | None = None) -> np.ndarray:
    """Load a saved DCR map and save its heatmap and sorted distribution.

    Parameters
    ----------
    path : str
        Data folder that 'process_dcr' was run on.
    tag : str
        The tag it was run with.
    cmap : str | None, optional
        Matplotlib colormap name for the heatmap. The default is None - the
        active style's.

    Returns
    -------
    np.ndarray
        The DCR map, in counts per second.

    Raises
    ------
    FileNotFoundError
        Raised when no saved DCR map exists for ``tag``.
    """
    dcr, _ = store.load_map(path, kind=_KIND, tag=tag)
    name = store.map_file_name(
        os.path.basename(os.path.normpath(path)), _KIND, tag
    ).removesuffix(".npy")
    results_dir = store.results_dir(path, _KIND)

    median, maximum, _ = plots.map_stats(dcr)
    fig = plots.sensor_map(
        dcr,
        title=(
            f"DCR map  {dcr.shape[0]}×{dcr.shape[1]} SPADs\n"
            f"median {median:.0f}  max {maximum:.0f}  cps"
        ),
        cmap=cmap,
    )
    store.save_figure(fig, results_dir, f"{name}_heatmap.png")
    plt.close(fig)

    fig = plots.sorted_distribution(
        dcr,
        ylabel="DCR  (cps)",
        title="Sorted DCR distribution",
        logy=True,  # DCR spans decades
        fmt=".0f",
        unit="cps",
    )
    store.save_figure(fig, results_dir, f"{name}_distribution.png")
    plt.close(fig)
    return dcr