Skip to content

Hitmaps and photon rate

A hitmap is the per-pixel occupancy of the sensor — how often each macropixel registered a photon over the acquisition. How that is measured depends on which Kelpie program wrote the data, so there are two modes, matched to what unpack actually returns.

The two modes

There is no mode argument: the mode follows from the last letter of the tag (core.reduce.readout_mode), so the program that wrote the files decides what a count is and the two can never disagree. A tag that ends in neither T nor C is a ValueError.

Timestamp mode — ...T tags (ORT, S0T)

Every frame, each macropixel reports the timestamp of the first photon it saw (from one of its four micropixels); the later photons are not read out. This is a single first-arrival time per macropixel. It is not an array-wide "who fired first" ranking, and one macropixel's timestamp is not comparable to another's.

The hitmap therefore counts, per pixel, the number of frames carrying a valid timestamp — i.e. how often that macropixel fired. Validity is time_series > 0: unpack leaves non-fired slots at <= 0, so the threshold follows from the decoding and is not a tunable.

photon_counts is not a photon count in ORT

In this mode unpack's photon_counts is not a count — those bits are the low bits of the coarse timestamp (see unpack). Validity must come from time_series, never from photon_counts.

Count mode — ...C tags (ORC, S0C)

No timestamp is recorded; the data holds per-pixel photon counts, and the hitmap sums those over every frame. This is the same quantity DCR accumulates before dividing by the acquisition time.

Every program gives a (32, 32) map. Interleaving four S<n> quadrant maps onto the (64, 64) micropixel grid is archived (archive/core/reduce.py).

Photon rate

The raw map is photon counts. The rate is that divided by the acquisition's wall-clock time, the same way in both modes:

hits / (nframes * n_files * frame_s),   frame_s = max(live_per_frame, 9 µs)

in Hz. Under short_exposure firmware frame_s is the 9 µs cycle (core.timing.FREE_RUNNING_US), whatever the shutter: the shutter can be made shorter, but each frame still takes a full cycle, so a ...T pixel — one photon per frame at most — tops out at ~111 kHz per macropixel. Under long_exposure the whole, longer cycle is live and is used as is. The shutter is still recorded in the sidecar; it no longer enters the rate.

The live time depends on the firmware

Two versions, selected with firmware_version (core.timing.resolve_live_time):

firmware_version live per frame notes
"short_exposure" (default) open_shutter_time_s the cycle is always 9 µs; the photon-sensitive window sits inside it without extending it, and is settable from ~50 ns to the full 9 µs. Nothing in the data reveals it, so it is asked for (default 500e-9); resolve_live_time raises without it
"long_exposure" exp_time_s + 9 µs you set X, the firmware adds 9 µs, and essentially the whole cycle is live

These two names are the whole vocabulary — the same strings DCR takes, listed in core.timing.FIRMWARE_VERSIONS. The older "short_window" / "full_window" spellings are gone rather than aliased: two names for one setting is how a caller ends up passing the pair that only one of two functions accepts.

frame_rate_cnt.txt is not used, on purpose

The acquisition exe writes a frame_rate_cnt.txt beside the data. Nothing in dapkel reads it: it is produced by an exe we do not control, so no analysis result is allowed to depend on it. The cycle length is a property of the firmware and the requested exposure, and Kelpie_run.m states it directly: exp_time_s = 0 → 9 µs, 1e-6 → 10 µs, 2e-6 → 11 µs.

It is worth knowing what the counter says, though, because it disagrees with the nominal figure — which matters wherever the cycle is the live time, i.e. under long_exposure. It is a 200 MHz tick count over the whole run, latched by the firmware after the acquisition reports done, and across every sample folder on disk it fits

ticks = nframes * N + 138 + window/5ns

exactly — the 138 (690 ns) a fixed per-run overhead, the exposure window appearing once per run rather than per frame, and N the frame period. N comes out at 1937–1954 ticks = 9.685–9.770 µs, so the real cycle is 685–770 ns per frame longer than the nominal 9 µs, and a rate normalised by 9 µs runs ~7.8 % high. N does not track the window (a 50 → 500 ns window moves it by 14 ticks, not 90), which is the direct evidence that the window sits inside the cycle rather than extending it. What the extra ~700 ns per frame is has not been established.

What the number means

In timestamp mode only the first photon of a frame is timestamped, so the map saturates at one photon per frame — ~111 kHz at the nominal 9 µs cycle — and under-reports as it approaches that. It is a detection rate per second of acquisition, not a corrected photon flux during the open shutter.

nframes is yours to supply, not the file's

The rate is proportional to 1 / nframes, and the frame count cannot be trusted to the file. Every sample .bin is a whole power-of-two number of frames — 32 MiB (16 384) or 16 MiB (8 192) — which is not what a 10 000-frame acquisition should produce, so the relation between the number you enter and the file you get is not established (the exe dumps a fixed DDR3 region larger than the acquisition; see core.io).

Both this package's unpack and the reference kelpie_data_ddr3.m read only the first nframes frames, so passing the number you acquired with gives exactly the frames MATLAB gives. That is why nframes is a required argument everywhere and is stored in the sidecar: it is the acquisition setting, and the rate is only right if it matches what the camera actually recorded.

Compute once, plot many times

Analysis and plotting are decoupled. process_hitmap writes the array to processed/<name>_<tag>_hitmap.npy with a .meta.json sidecar recording the frame count, the firmware version and the resolved live time; plot_hitmap reads that back, never re-unpacks the binary data, saves the counts map and the photon-rate map to results/hitmap/, and returns both, (counts, rate) - the rate in Hz. Retrying a colormap costs a load, not a full re-read of the raw files. See Adding an analysis for the stage rules.

from dapkel.functions import hitmap_analysis as hm

# short-exposure firmware: 9 µs cycle, 100 ns open shutter inside it
hm.process_hitmap(path, 10_000, "ORT", open_shutter_time_s=100e-9)

# long-exposure firmware: you set X, the firmware adds 9 µs
hm.process_hitmap(path, 10_000, "ORT",
                  firmware_version="long_exposure", exp_time_s=91e-6)

# two figures, <name>_ort_hitmap.png (counts) and <name>_ort_hitmap_rate.png
counts, rate = hm.plot_hitmap(path, "ORT")   # rate in Hz

Because the sidecar stores the frame count and the live time, a saved hitmap can still be turned into a rate months later without remembering the original call arguments.

API

hitmap_analysis

Per-pixel sensor occupancy (hitmaps), in counts and in photon rate.

process_hitmap   raw '.bin' -> processed/<name>_<tag>_hitmap.npy
plot_hitmap      that array -> results/hitmap/ the counts map and the rate map

The tag says what a count is ('core.reduce'): ...T programs (ORT, S0T) count frames carrying a valid first-photon timestamp - at most one per pixel per frame - and ...C programs (ORC, S0C) sum the photon counter.

The rate divides by the acquisition's wall-clock time, nframes * n_files * frame_s, where frame_s is the 9 us frame cycle (or the live time, if longer, under long_exposure firmware) - not the open shutter. A ...T pixel records at most one photon per frame, so the rate tops out at one per cycle (~111 kHz) whatever the shutter. See docs/guide/hitmap.md.

process_hitmap

process_hitmap(path: str, nframes: int, tag: str = 'ORT', *, 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 '.bin' files, accumulate the hitmap and save it.

Writes processed/<name>_<tag>_hitmap.npy (photons; at most one per pixel per frame for a ...T tag) with a .meta.json sidecar recording the frame count and the live time, which is everything 'plot_hitmap' needs for the rate map.

Parameters:

Name Type Description Default
path str

Folder with the '.bin' data files.

required
nframes int

Frames the acquisition recorded per '.bin' file. Sets the rate's denominator, nframes * n_files * frame_s. Do not infer it from the file size - the exe dumps a fixed, larger DDR3 region.

required
tag str

File tag: 'ORT', 'ORC', 'S0C', 'S2T'... The default is 'ORT'.

'ORT'
firmware_version str

'short_exposure' (default, only open_shutter_time_s of each frame is live) or 'long_exposure' (the whole exp_time_s + 9 µs cycle is); see 'core.timing.resolve_live_time'.

'short_exposure'
open_shutter_time_s float | None

Photon-sensitive window per frame, in seconds; settable from ~50 ns to 9 µs, so it cannot be guessed. 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/hitmap_analysis.py
def process_hitmap(
    path: str,
    nframes: int,
    tag: str = "ORT",
    *,
    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 '.bin' files, accumulate the hitmap and save it.

    Writes ``processed/<name>_<tag>_hitmap.npy`` (photons; at most one per pixel
    per frame for a ``...T`` tag) with a ``.meta.json`` sidecar recording the frame count and
    the live time, which is everything 'plot_hitmap' needs for the rate map.

    Parameters
    ----------
    path : str
        Folder with the '.bin' data files.
    nframes : int
        Frames the acquisition recorded per '.bin' file. Sets the rate's
        denominator, ``nframes * n_files * frame_s``. Do not infer
        it from the file size - the exe dumps a fixed, larger DDR3 region.
    tag : str, optional
        File tag: ``'ORT'``, ``'ORC'``, ``'S0C'``, ``'S2T'``... The default is
        ``'ORT'``.
    firmware_version : str, optional
        ``'short_exposure'`` (default, only ``open_shutter_time_s`` of each
        frame is live) or ``'long_exposure'`` (the whole ``exp_time_s + 9 µs``
        cycle is); see 'core.timing.resolve_live_time'.
    open_shutter_time_s : float | None, optional
        Photon-sensitive window per frame, in seconds; settable from ~50 ns to
        9 µs, so it cannot be guessed. 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,
    )
    print(f"\n> > > Computing the '{tag}' hitmap < < <\n")
    counts, n_files = reduce.count_map(
        path, tag, nframes=nframes, max_files=max_files
    )
    total_frames = int(nframes) * n_files
    out_path = store.save_map(
        counts,
        path,
        kind=_KIND,
        tag=tag,
        meta={
            "mode": reduce.readout_mode(tag),
            "n_files": n_files,
            "nframes": int(nframes),
            "total_frames": total_frames,
            "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,
            "live_time_s": total_frames * live_s,
        },
        quiet=True,
    )
    print(
        f"  total {np.nansum(counts):.0f}  median {np.nanmedian(counts):.0f}  "
        f"max {np.nanmax(counts):.0f}\n\n> > > Hitmap saved to {out_path} < < <"
    )
    return out_path

plot_hitmap

plot_hitmap(path: str, tag: str = 'ORT', *, cmap: str | None = None, clip_colorbar_to: float | None = 99.0) -> tuple[ndarray, ndarray]

Load a saved hitmap and save its counts and photon-rate maps.

Writes two figures to results/hitmap: the photon counts map and the photon-rate map, hits / (nframes * n_files * frame_s) in Hz. frame_s is the 9 µs frame cycle ('core.timing.FREE_RUNNING_US'), or the sidecar's live time per frame when that is longer (long_exposure firmware). The shutter does not enter: it can be shorter, but a frame still takes a cycle. Derivation: docs/guide/hitmap.md.

In timestamp mode only the first photon of a frame is timestamped, so the rate saturates at one per cycle - ~111 kHz per macropixel - and under-reports as it approaches that.

Parameters:

Name Type Description Default
path str

Data folder that 'process_hitmap' was run on.

required
tag str

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

'ORT'
cmap str | None

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

None
clip_colorbar_to float | None

Percentile the colour scale is clipped at, so a few hot pixels do not flatten the rest into one shade. The default is 99. None runs the scale to the true maximum - the value quoted in the title either way.

99.0

Returns:

Name Type Description
counts ndarray

The (32, 32) photon counts map - first photons for a ...T tag, the photon counter for a ...C one.

rate ndarray

The (32, 32) photon-rate map, in Hz.

Raises:

Type Description
FileNotFoundError

Raised when no saved hitmap exists for tag.

Source code in src/dapkel/functions/hitmap_analysis.py
def plot_hitmap(
    path: str,
    tag: str = "ORT",
    *,
    cmap: str | None = None,
    clip_colorbar_to: float | None = 99.0,
) -> tuple[np.ndarray, np.ndarray]:
    """Load a saved hitmap and save its counts and photon-rate maps.

    Writes two figures to ``results/hitmap``: the photon counts map and
    the photon-rate map, ``hits / (nframes * n_files * frame_s)`` in Hz.
    ``frame_s`` is the 9 µs frame cycle ('core.timing.FREE_RUNNING_US'), or
    the sidecar's live time per frame when that is longer (``long_exposure``
    firmware). The shutter does not enter: it can be shorter, but a frame still
    takes a cycle. Derivation: ``docs/guide/hitmap.md``.

    In timestamp mode only the *first* photon of a frame is timestamped, so the
    rate saturates at one per cycle - ~111 kHz per macropixel - and
    under-reports as it approaches that.

    Parameters
    ----------
    path : str
        Data folder that 'process_hitmap' was run on.
    tag : str, optional
        The tag it was run with. The default is ``'ORT'``.
    cmap : str | None, optional
        Matplotlib colormap name. The default is None - the active style's.
    clip_colorbar_to : float | None, optional
        Percentile the colour scale is clipped at, so a few hot pixels do not
        flatten the rest into one shade. The default is 99. None runs the scale
        to the true maximum - the value quoted in the title either way.

    Returns
    -------
    counts : np.ndarray
        The (32, 32) photon counts map - first photons for a ``...T`` tag,
        the photon counter for a ``...C`` one.
    rate : np.ndarray
        The (32, 32) photon-rate map, in Hz.

    Raises
    ------
    FileNotFoundError
        Raised when no saved hitmap exists for ``tag``.
    """
    hitmap, meta = store.load_map(path, kind=_KIND, tag=tag)
    # A frame takes at least one 9 µs cycle, however short its shutter.
    frame_s = max(meta["frame_live_s"], timing.FREE_RUNNING_US * 1e-6)
    rate = hitmap / (meta["total_frames"] * frame_s)
    name = store.map_file_name(
        os.path.basename(os.path.normpath(path)), _KIND, tag
    ).removesuffix(".npy")
    results_dir = store.results_dir(path, _KIND)

    for data, clabel, title, suffix in (
        (hitmap, "photons", "Hitmap", ""),
        (rate, "Hz", "Photon rate", "_rate"),
    ):
        median, maximum, total = plots.map_stats(data)
        stats = f"median {median:.3g}  max {maximum:.3g}"
        if not suffix:
            stats += f"  total {total:.3g}"
        fig = plots.sensor_map(
            data,
            title=f"{title}\n{stats}  [{clabel}]",
            clabel=clabel,
            cmap=cmap,
            clip_colorbar_to=clip_colorbar_to,
        )
        store.save_figure(fig, results_dir, f"{name}{suffix}.png")
        plt.close(fig)

    print(
        f"  {meta['total_frames']} frames x {frame_s * 1e6:.3g} us "
        f"= {meta['total_frames'] * frame_s * 1e3:.3f} ms;  rate median "
        f"{np.nanmedian(rate):.3g}  max {np.nanmax(rate):.3g} Hz"
    )
    return hitmap, rate