Skip to content

dapkel.core

The shared substrate every analysis is built on. Anything copied into two analysis modules belongs here instead — tests/test_api_surface.py fails if a function name is defined twice.

See Adding an analysis for the contract.

core.io — finding and sizing raw files

io

Stage 0: locating and sizing the raw Kelpie '.bin' files.

Every analysis starts by picking the '.bin' files that belong to a measurement. The frame count is never read off a file's size: the exe dumps a fixed DDR3 region larger than the acquisition, so it is the caller's nframes.

find_bin_files

find_bin_files(path: str, tag: str, *, require_separator: bool = False) -> list[str]

Find and naturally sort the '.bin' files for a readout tag.

"Naturally" means ordered by the digits in the file name, so ..._2.bin sorts before ..._10.bin.

Parameters:

Name Type Description Default
path str

Path to the folder with the '.bin' data files.

required
tag str

Filename fragment selecting the files (e.g. 'ORT', 'S0C', 'S2T'), or '' to match every '.bin' file in the path.

required
require_separator bool

When True the tag must be preceded by an underscore (pattern '*_<tag>*.bin' instead of '*<tag>*.bin'). The DCR quadrant tags need this so that, for example, 'S0C' cannot also match a file whose name merely contains those characters. The default is False.

False

Returns:

Type Description
list[str]

Naturally sorted list of paths to the matching '.bin' files.

Raises:

Type Description
FileNotFoundError

Raised when no '.bin' files match the tag in the path.

Source code in src/dapkel/core/io.py
def find_bin_files(
    path: str, tag: str, *, require_separator: bool = False
) -> list[str]:
    """Find and naturally sort the '.bin' files for a readout tag.

    "Naturally" means ordered by the digits in the file name, so ``..._2.bin``
    sorts before ``..._10.bin``.

    Parameters
    ----------
    path : str
        Path to the folder with the '.bin' data files.
    tag : str
        Filename fragment selecting the files (e.g. ``'ORT'``, ``'S0C'``,
        ``'S2T'``), or ``''`` to match every '.bin' file in the path.
    require_separator : bool, optional
        When True the tag must be preceded by an underscore (pattern
        ``'*_<tag>*.bin'`` instead of ``'*<tag>*.bin'``). The DCR quadrant
        tags need this so that, for example, ``'S0C'`` cannot also match a
        file whose name merely contains those characters. The default is
        False.

    Returns
    -------
    list[str]
        Naturally sorted list of paths to the matching '.bin' files.

    Raises
    ------
    FileNotFoundError
        Raised when no '.bin' files match the tag in the path.
    """
    if tag:
        pattern = f"*_{tag}*.bin" if require_separator else f"*{tag}*.bin"
    else:
        pattern = "*.bin"

    files = sorted(
        glob.glob(os.path.join(path, pattern)),
        key=lambda fp: int(
            "".join(filter(str.isdigit, os.path.basename(fp))) or "0"
        ),
    )
    if not files:
        raise FileNotFoundError(
            f"No .bin files matching '{pattern}' found in:\n  {path}"
        )
    return files

core.timing — frame period and live time

timing

Stage 1: resolving how much wall-clock time an acquisition represents.

Counts become rates only once you know how long the sensor was actually collecting, and that depends on the firmware. These helpers previously lived in 'dcr_analysis' as private functions that 'hitmap_analysis' imported across the module boundary; they are shared API, so they live here.

Also the single home for the ORT timing scale. Every time parameter in this package is in seconds and named with an _s suffix; picoseconds appear only as internal working units, because that is the scale the TDC lives on. Convert at the boundary with 'to_ps' / 'to_s'.

Two timescales are easy to conflate and must not be:

  • open_shutter_time_s - the photon-sensitive window per frame. An acquisition setting, nothing in the data reveals it, so it is asked for. It sets the rate normalisation and nothing else.
  • the TDC full scale - the ORT measurement range, i.e. one period of the reference clock. The timestamp is a code on this range, so it is what the accidental (triangle) background's half-base follows.

They coincide only when the shutter is one clock period, and an 8 µs shutter on a 10 MHz clock still yields ~100 ns timestamps: the free-running oscillator has no cycle counter, so timestamps fold into the full scale. So the full scale is never taken from the shutter. It is measured from the data - the largest code present is the range the TDC swept - which is why no analysis entry point in this package asks for it. See 'full_scale_from_max_code'.

The one place a clock period is genuinely irreducible is building the TDC calibration ('dapkel.functions.tdc_calibration'): the density test fixes only the relative tap widths, so an externally known duration has to set the absolute scale. That parameter is called clock_period_s and it appears nowhere else. Everything downstream leans on 'CODE_S' instead, which was itself measured against known clocks.

to_ps

to_ps(seconds: float) -> float

Convert seconds to picoseconds.

Parameters:

Name Type Description Default
seconds float

A time in seconds (the package-wide parameter convention).

required

Returns:

Type Description
float

The same time in picoseconds (the internal working unit).

Source code in src/dapkel/core/timing.py
def to_ps(seconds: float) -> float:
    """Convert seconds to picoseconds.

    Parameters
    ----------
    seconds : float
        A time in seconds (the package-wide parameter convention).

    Returns
    -------
    float
        The same time in picoseconds (the internal working unit).
    """
    return float(seconds) * 1e12

to_s

to_s(picoseconds: float) -> float

Convert picoseconds to seconds.

Parameters:

Name Type Description Default
picoseconds float

A time in picoseconds (the internal working unit).

required

Returns:

Type Description
float

The same time in seconds (the package-wide parameter convention).

Source code in src/dapkel/core/timing.py
def to_s(picoseconds: float) -> float:
    """Convert picoseconds to seconds.

    Parameters
    ----------
    picoseconds : float
        A time in picoseconds (the internal working unit).

    Returns
    -------
    float
        The same time in seconds (the package-wide parameter convention).
    """
    return float(picoseconds) * 1e-12

full_scale_from_max_code

full_scale_from_max_code(max_code: int, *, code_s: float = CODE_S) -> float

Return the TDC full scale a run swept, from the largest code it produced.

The reference clock stops the ring, so the largest code present in a run is its measurement range - there is no need to be told the clock. This is the only resolution path in the package: a stated shutter is not the full scale (see the module docstring), and a remembered clock frequency is one more thing to get wrong.

Accuracy is set by 'CODE_S', the nominal code width, which carries the ring's few-percent frequency spread; and by sample size, since the largest code is an extreme value and runs a little low (~1.4 % at 10 MHz for a populated tail). Both are irrelevant to its two uses - seeding a triangle half-base that the fit then refines, and bounding a histogram.

Parameters:

Name Type Description Default
max_code int

Largest raw TDC code observed, i.e. time_series[time_series > 0].max() over the run.

required
code_s float

Width of one code, in seconds. The default is 'CODE_S'.

CODE_S

Returns:

Type Description
float

The full scale in seconds.

Raises:

Type Description
ValueError

Raised when max_code is not positive, which means no pixel ever carried a valid timestamp.

Source code in src/dapkel/core/timing.py
def full_scale_from_max_code(max_code: int, *, code_s: float = CODE_S) -> float:
    """Return the TDC full scale a run swept, from the largest code it produced.

    The reference clock stops the ring, so the largest code present in a run
    *is* its measurement range - there is no need to be told the clock. This is
    the only resolution path in the package: a stated shutter is not the full
    scale (see the module docstring), and a remembered clock frequency is one
    more thing to get wrong.

    Accuracy is set by 'CODE_S', the nominal code width, which carries the
    ring's few-percent frequency spread; and by sample size, since the largest
    code is an extreme value and runs a little low (~1.4 % at 10 MHz for a
    populated tail). Both are irrelevant to its two uses - seeding a triangle
    half-base that the fit then refines, and bounding a histogram.

    Parameters
    ----------
    max_code : int
        Largest raw TDC code observed, i.e. ``time_series[time_series > 0].max()``
        over the run.
    code_s : float, optional
        Width of one code, in seconds. The default is 'CODE_S'.

    Returns
    -------
    float
        The full scale in seconds.

    Raises
    ------
    ValueError
        Raised when ``max_code`` is not positive, which means no pixel ever
        carried a valid timestamp.
    """
    if max_code <= 0:
        raise ValueError(
            f"max_code must be positive, got {max_code} - no valid timestamp "
            "was found, so the TDC full scale cannot be measured."
        )
    if max_code > MAX_TS_CODE:
        warnings.warn(
            f"The largest code seen ({max_code}) exceeds what the "
            f"{COARSE_BITS}-bit coarse counter can express ({MAX_TS_CODE}), so "
            "the reference clock is too slow and the codes have wrapped. The "
            "timestamps are not trustworthy.",
            UserWarning,
            stacklevel=2,
        )
    return float(max_code) * code_s

resolve_live_time

resolve_live_time(firmware_version: str, *, open_shutter_time_s: float | None = None, exp_time_s: float | None = None) -> tuple[float, str]

Return the live (photon-sensitive) seconds per frame, and their source.

A photon rate is counts / (nframes * n_files * live_per_frame). How much of each frame is live depends on the firmware:

  • 'short_exposure' - the current firmware: each ~9 µs frame is mostly readout and only the open shutter window open_shutter_time_s is live. It is settable from ~50 ns to the full 9 µs, so it is asked for, never assumed.
  • 'long_exposure' - the legacy firmware: the whole exp_time_s + 9 µs cycle is live (exp_time_s=None is the free-running 9 µs).

The cycle is never read from the frame_rate_cnt.txt the acquisition exe writes: that exe is not ours, so no analysis may depend on its output.

Parameters:

Name Type Description Default
firmware_version str

One of 'FIRMWARE_VERSIONS'.

required
open_shutter_time_s float | None

Photon-sensitive window per frame, in seconds. Required for 'short_exposure'. The default is None.

None
exp_time_s float | None

Exposure requested of 'long_exposure' firmware, in seconds; the firmware adds 9 µs. The default is None.

None

Returns:

Type Description
tuple[float, str]

The live seconds per frame and a human-readable source string.

Raises:

Type Description
ValueError

Raised on an unknown firmware_version, or 'short_exposure' without open_shutter_time_s.

Source code in src/dapkel/core/timing.py
def resolve_live_time(
    firmware_version: str,
    *,
    open_shutter_time_s: float | None = None,
    exp_time_s: float | None = None,
) -> tuple[float, str]:
    """Return the live (photon-sensitive) seconds per frame, and their source.

    A photon rate is ``counts / (nframes * n_files * live_per_frame)``. How much
    of each frame is live depends on the firmware:

    * ``'short_exposure'`` - the current firmware: each ~9 µs frame is mostly
      readout and only the open shutter window ``open_shutter_time_s`` is live.
      It is settable from ~50 ns to the full 9 µs, so it is asked for, never
      assumed.
    * ``'long_exposure'`` - the legacy firmware: the whole ``exp_time_s + 9 µs``
      cycle is live (``exp_time_s=None`` is the free-running 9 µs).

    The cycle is never read from the ``frame_rate_cnt.txt`` the acquisition exe
    writes: that exe is not ours, so no analysis may depend on its output.

    Parameters
    ----------
    firmware_version : str
        One of 'FIRMWARE_VERSIONS'.
    open_shutter_time_s : float | None, optional
        Photon-sensitive window per frame, in seconds. Required for
        ``'short_exposure'``. The default is None.
    exp_time_s : float | None, optional
        Exposure requested of ``'long_exposure'`` firmware, in seconds; the
        firmware adds 9 µs. The default is None.

    Returns
    -------
    tuple[float, str]
        The live seconds per frame and a human-readable source string.

    Raises
    ------
    ValueError
        Raised on an unknown ``firmware_version``, or ``'short_exposure'``
        without ``open_shutter_time_s``.
    """
    if firmware_version == "short_exposure":
        if open_shutter_time_s is None:
            raise ValueError(
                "firmware_version='short_exposure' needs open_shutter_time_s "
                "(the photon-sensitive window per frame, in seconds, e.g. 500e-9)."
            )
        return (
            open_shutter_time_s,
            f"short_exposure: {open_shutter_time_s * 1e9:.1f} ns window",
        )
    if firmware_version == "long_exposure":
        live = (exp_time_s or 0.0) + FREE_RUNNING_US * 1e-6
        return live, f"long_exposure: {live * 1e6:.3f} µs cycle"
    raise ValueError(
        f"firmware_version must be one of {FIRMWARE_VERSIONS}, got "
        f"{firmware_version!r}"
    )

core.calibration — TDC codes to picoseconds

calibration

Applying the compact TDC calibration: a code in, picoseconds out, any clock.

The ring-oscillator TDC has TAPS_PER_LAP = 8 taps, and 'unpack' builds the code as (coarse - 1) * 8 + (8 - fine): code k is tap k % 8 of lap k // 8. The coarse counter adds no non-linearity, so one calibration is just the eight tap widths of every pixel - (32, 32, 8) per SPAD - and the time of a code is

t(k) = (k // 8) * lap + sum(taps[:k % 8]) + taps[k % 8] / 2

with lap = sum(taps). Nothing in it depends on the reference clock, which only decides how many laps a run sweeps, so one table serves every clock and there is no code range for it to fall short of. 'dapkel.functions.tdc_calibration' builds the tables; the packaged ones live in dapkel/params/calibration_data.

board_taps

board_taps(daughterboard_number: str, motherboard_number: str, tag: str) -> ndarray

Load the packaged tap widths a run with this file tag should use.

Reads {daughterboard}_{motherboard}_TDC_COMPACT_*.npy from dapkel/params/calibration_data; a SPAD's table is named after its program (..._S2T.npy) or in the older form ..._SPAD2_S2.npy. A single-micropixel tag ('S2T') gets that SPAD's table; anything else ('ORT') the mean of the four - as does a single-SPAD tag whose table is missing, with a note.

Parameters:

Name Type Description Default
daughterboard_number str

Daughterboard id, e.g. 'D0'.

required
motherboard_number str

Motherboard id, e.g. 'M0'.

required
tag str

The file tag the run was selected with.

required

Returns:

Type Description
ndarray

The (32, 32, 8) tap widths in picoseconds.

Raises:

Type Description
FileNotFoundError

Raised when no compact calibration is packaged for the board.

Source code in src/dapkel/core/calibration.py
def board_taps(
    daughterboard_number: str, motherboard_number: str, tag: str
) -> np.ndarray:
    """Load the packaged tap widths a run with this file tag should use.

    Reads ``{daughterboard}_{motherboard}_TDC_COMPACT_*.npy`` from
    ``dapkel/params/calibration_data``; a SPAD's table is named after its
    program (``..._S2T.npy``) or in the older form ``..._SPAD2_S2.npy``. A
    single-micropixel tag (``'S2T'``)
    gets that SPAD's table; anything else (``'ORT'``) the mean of the four - as
    does a single-SPAD tag whose table is missing, with a note.

    Parameters
    ----------
    daughterboard_number : str
        Daughterboard id, e.g. ``'D0'``.
    motherboard_number : str
        Motherboard id, e.g. ``'M0'``.
    tag : str
        The file tag the run was selected with.

    Returns
    -------
    np.ndarray
        The (32, 32, 8) tap widths in picoseconds.

    Raises
    ------
    FileNotFoundError
        Raised when no compact calibration is packaged for the board.
    """
    board = f"{daughterboard_number}_{motherboard_number}"
    data_dir = _resource_files("dapkel.params").joinpath("calibration_data")
    tables = {}
    for entry in sorted(data_dir.iterdir(), key=lambda t: t.name):
        if entry.name.startswith(f"{board}_TDC_COMPACT_") and entry.name.endswith(
            ".npy"
        ):
            with entry.open("rb") as fh:
                tables[entry.name] = np.load(fh)
    if not tables:
        raise FileNotFoundError(
            f"No packaged compact TDC calibration for board {board} (looked for "
            f"{board}_TDC_COMPACT_*.npy in dapkel/params/calibration_data). Build "
            "one with 'tdc_calibration.process_tdc_calibration'."
        )

    spad = _SPAD_TAG.search(tag or "")
    if spad:
        n = spad.group(1)
        mine = [
            name
            for name in tables
            if re.search(rf"_(SPAD{n}_S{n}|S{n}T)\.npy$", name, re.IGNORECASE)
        ]
        if len(mine) == 1:
            return tables[mine[0]]
        print(
            f"  NOTE: no compact calibration for SPAD{spad.group(1)} on board "
            f"{board}; using the mean of {len(tables)} SPAD table(s)."
        )
    return np.mean(list(tables.values()), axis=0)

codes_to_ps

codes_to_ps(codes: ndarray, taps: ndarray) -> ndarray

Convert one pixel's TDC codes to picoseconds with its 8 tap widths.

Each code maps to the centre of its tap - the bin-centre CDF of the density test, one value per code, reproduced from 8 numbers.

Parameters:

Name Type Description Default
codes ndarray

Integer-valued TDC codes (any shape), all >= 0.

required
taps ndarray

The pixel's (8,) tap widths in picoseconds.

required

Returns:

Type Description
ndarray

Times in picoseconds, same shape as codes.

Source code in src/dapkel/core/calibration.py
def codes_to_ps(codes: np.ndarray, taps: np.ndarray) -> np.ndarray:
    """Convert one pixel's TDC codes to picoseconds with its 8 tap widths.

    Each code maps to the *centre* of its tap - the bin-centre CDF of the
    density test, one value per code, reproduced from 8 numbers.

    Parameters
    ----------
    codes : np.ndarray
        Integer-valued TDC codes (any shape), all >= 0.
    taps : np.ndarray
        The pixel's ``(8,)`` tap widths in picoseconds.

    Returns
    -------
    np.ndarray
        Times in picoseconds, same shape as ``codes``.
    """
    taps = np.asarray(taps, dtype=np.float64)
    centre = np.cumsum(taps) - taps / 2.0
    codes = np.asarray(codes).astype(np.int64)
    return (codes // TAPS_PER_LAP) * taps.sum() + centre[codes % TAPS_PER_LAP]

core.pairs — which pixel pairs, and what they are called

pairs

Which pixel pairs an analysis is about, and what they are called.

Every coincidence analysis starts by turning two detector groups into an ordered list of pairs and a label per pair. That enumeration decides the row order of every stage-1 artifact, so two analyses are only comparable if they build it the same way - which is why it lives here rather than in each of them.

The label format "ra,ca-rb,cb" is a stored contract: it is the row name in every delta-t counts sidecar (labels). Do not reformat it.

as_pixel_list

as_pixel_list(group: Pixel | Sequence[Pixel]) -> list[Pixel]

Normalise a detector spec - one (row, col) or a sequence - to a list.

Source code in src/dapkel/core/pairs.py
def as_pixel_list(group: Pixel | Sequence[Pixel]) -> list[Pixel]:
    """Normalise a detector spec - one ``(row, col)`` or a sequence - to a list."""
    if (
        len(group) == 2
        and isinstance(group[0], (int, np.integer))
        and isinstance(group[1], (int, np.integer))
    ):
        return [(int(group[0]), int(group[1]))]
    return [(int(r), int(c)) for r, c in group]

pair_label

pair_label(a: Pixel, b: Pixel) -> str

Return the canonical "ra,ca-rb,cb" name of one pixel pair.

Source code in src/dapkel/core/pairs.py
def pair_label(a: Pixel, b: Pixel) -> str:
    """Return the canonical ``"ra,ca-rb,cb"`` name of one pixel pair."""
    return f"{a[0]},{a[1]}-{b[0]},{b[1]}"

pair_list

pair_list(pixels: Sequence[Sequence[Pixel]], mode: str = 'all_pairs') -> list[tuple[Pixel, Pixel]]

Enumerate the ordered (pixel_a, pixel_b) pairs of two groups.

Parameters:

Name Type Description Default
pixels Sequence[Sequence[tuple[int, int]]]

Two groups [group_a, group_b]; a bare (row, col) is accepted for a one-pixel group.

required
mode str

'all_pairs' (default) for every A-B combination, or '1v1' to zip the groups element-wise.

'all_pairs'

Returns:

Type Description
list[tuple[tuple[int, int], tuple[int, int]]]

The pairs, in the order every artifact stores them in.

Raises:

Type Description
ValueError

Raised on an unknown mode, or unequal groups under '1v1'.

Source code in src/dapkel/core/pairs.py
def pair_list(
    pixels: Sequence[Sequence[Pixel]], mode: str = "all_pairs"
) -> list[tuple[Pixel, Pixel]]:
    """Enumerate the ordered ``(pixel_a, pixel_b)`` pairs of two groups.

    Parameters
    ----------
    pixels : Sequence[Sequence[tuple[int, int]]]
        Two groups ``[group_a, group_b]``; a bare ``(row, col)`` is accepted
        for a one-pixel group.
    mode : str, optional
        ``'all_pairs'`` (default) for every A-B combination, or ``'1v1'`` to
        zip the groups element-wise.

    Returns
    -------
    list[tuple[tuple[int, int], tuple[int, int]]]
        The pairs, in the order every artifact stores them in.

    Raises
    ------
    ValueError
        Raised on an unknown ``mode``, or unequal groups under ``'1v1'``.
    """
    if mode not in ("all_pairs", "1v1"):
        raise ValueError(f"mode must be 'all_pairs' or '1v1', got {mode!r}")

    group_a = as_pixel_list(pixels[0])
    group_b = as_pixel_list(pixels[1])
    if mode == "1v1":
        if len(group_a) != len(group_b):
            raise ValueError(
                "mode='1v1' needs equal-length groups "
                f"(got {len(group_a)} and {len(group_b)})."
            )
        return list(zip(group_a, group_b, strict=True))
    return [(a, b) for a in group_a for b in group_b]

core.reduce — folding frames into a map, and the SPAD layout

reduce

Stage 1: folding a set of '.bin' files down to one sensor map.

Every count-like analysis in dapkel is the same loop - unpack each file, pull one (32, 32) slab out of the frames, add it up - differing only in which slab it pulls. That loop lives here once; the analyses supply the extraction.

What a count is follows from the acquisition program, which the file tag names by its last letter: ...T programs (ORT, S0T) timestamp, so a count is a frame carrying a valid timestamp (at most one per pixel per frame); ...C programs (ORC, S0C) count, so the per-pixel photon counter is summed. In timestamp mode that counter field does not exist - 'unpack' returns low bits of the coarse timestamp there - so reading a T tag as counts would overstate the rate ~50x. Deriving the mode from the tag makes that impossible.

Every program reads a (32, 32) array: ORT/ORC all four micropixels of a macropixel at once, S<n>T/S<n>C one of them. (Assembling four S<n> quadrants into the (64, 64) micropixel grid is archived: archive/core/reduce.py.)

readout_mode

readout_mode(tag: str) -> str

Return 'timestamp' or 'count' for a file tag, from its last letter.

Raises:

Type Description
ValueError

Raised when the tag ends in neither T nor C (trailing digits ignored), so the program - and hence what a count is - is unknown.

Source code in src/dapkel/core/reduce.py
def readout_mode(tag: str) -> str:
    """Return ``'timestamp'`` or ``'count'`` for a file tag, from its last letter.

    Raises
    ------
    ValueError
        Raised when the tag ends in neither ``T`` nor ``C`` (trailing digits
        ignored), so the program - and hence what a count is - is unknown.
    """
    letter = tag.upper().rstrip("0123456789_")[-1:]
    mode = {"T": "timestamp", "C": "count"}.get(letter)
    if mode is None:
        raise ValueError(
            f"tag {tag!r} names neither a timestamping ('...T', e.g. 'ORT', "
            "'S0T') nor a counting ('...C', e.g. 'ORC', 'S0C') program, so "
            "what a count is cannot be decided. Pass the acquisition's tag."
        )
    return mode

accumulate_frames

accumulate_frames(files: list[str], extract: Extract, *, nframes: int, need_time_series: bool = True, label: str = '') -> ndarray

Unpack every file and sum an extracted (32, 32) slab over all of them.

Parameters:

Name Type Description Default
files list[str]

Paths to the '.bin' files to unpack and accumulate.

required
extract callable

extract(time_series, photon_counts) -> np.ndarray returning the (32, 32) contribution of one file. time_series is None when need_time_series is False.

required
nframes int

Frames per file - the acquisition setting. Never infer it from the file size: the exe dumps a fixed DDR3 region larger than the run.

required
need_time_series bool

Whether extract uses the timestamps. False lets 'unpack' skip the coarse/fine decoding, about two thirds of its work. The default is True.

True
label str

Label used in the progress bar. The default is "".

''

Returns:

Type Description
ndarray

The summed (32, 32) map, float64.

Source code in src/dapkel/core/reduce.py
def accumulate_frames(
    files: list[str],
    extract: Extract,
    *,
    nframes: int,
    need_time_series: bool = True,
    label: str = "",
) -> np.ndarray:
    """Unpack every file and sum an extracted (32, 32) slab over all of them.

    Parameters
    ----------
    files : list[str]
        Paths to the '.bin' files to unpack and accumulate.
    extract : callable
        ``extract(time_series, photon_counts) -> np.ndarray`` returning the
        (32, 32) contribution of one file. ``time_series`` is None when
        ``need_time_series`` is False.
    nframes : int
        Frames per file - the acquisition setting. Never infer it from the
        file size: the exe dumps a fixed DDR3 region larger than the run.
    need_time_series : bool, optional
        Whether ``extract`` uses the timestamps. False lets 'unpack' skip the
        coarse/fine decoding, about two thirds of its work. The default is True.
    label : str, optional
        Label used in the progress bar. The default is "".

    Returns
    -------
    np.ndarray
        The summed (32, 32) map, float64.
    """
    total = np.zeros((32, 32), dtype=np.float64)
    for fp in tqdm(files, desc=label or None):
        ts, pc = unpack(fp, nframes, compute_time_series=need_time_series)
        total += extract(ts, pc)
    return total

count_map

count_map(path: str, tag: str, *, nframes: int, max_files: int | None = None) -> tuple[ndarray, int]

Accumulate the (32, 32) per-pixel count map of one program's files.

Parameters:

Name Type Description Default
path str

Folder with the '.bin' files.

required
tag str

File tag, e.g. 'ORT', 'ORC', 'S0C', 'S2T'. Its last letter decides what a count is (see the module docstring).

required
nframes int

Frames per file.

required
max_files int | None

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

None

Returns:

Name Type Description
counts ndarray

The (32, 32) map, float64.

n_files int

Files accumulated, so nframes * n_files frames per pixel.

Raises:

Type Description
FileNotFoundError

Raised when no file matches tag.

Source code in src/dapkel/core/reduce.py
def count_map(
    path: str, tag: str, *, nframes: int, max_files: int | None = None
) -> tuple[np.ndarray, int]:
    """Accumulate the (32, 32) per-pixel count map of one program's files.

    Parameters
    ----------
    path : str
        Folder with the '.bin' files.
    tag : str
        File tag, e.g. ``'ORT'``, ``'ORC'``, ``'S0C'``, ``'S2T'``. Its last
        letter decides what a count is (see the module docstring).
    nframes : int
        Frames per file.
    max_files : int | None, optional
        Use at most this many files. The default is None (all).

    Returns
    -------
    counts : np.ndarray
        The (32, 32) map, float64.
    n_files : int
        Files accumulated, so ``nframes * n_files`` frames per pixel.

    Raises
    ------
    FileNotFoundError
        Raised when no file matches ``tag``.
    """
    timestamp = readout_mode(tag) == "timestamp"
    if timestamp:
        extract = lambda ts, pc: (ts > 0).sum(axis=2)  # noqa: E731
    else:
        extract = lambda ts, pc: pc.sum(axis=2)  # noqa: E731
    files = io.find_bin_files(path, tag)[:max_files]
    counts = accumulate_frames(
        files, extract, nframes=nframes, need_time_series=timestamp, label=tag
    )
    return counts, len(files)

code_histogram

code_histogram(files: list[str], *, nframes: int, label: str = '') -> ndarray

Accumulate the (32, 32, n_codes) per-pixel TDC-code histogram.

For every pixel, how often each integer code occurs over all frames with a valid timestamp (time_series > 0). The code axis is allocated at the widest the frame format can express ('timing.MAX_TS_CODE') and trimmed to the largest code any pixel produced, so the code count comes out of the run rather than out of a stated clock and nothing can overflow.

Parameters:

Name Type Description Default
files list[str]

Paths to the '.bin' files.

required
nframes int

Frames per file.

required
label str

Label used in the progress bar. The default is "".

''

Returns:

Type Description
ndarray

The (32, 32, n_codes) int64 histogram.

Source code in src/dapkel/core/reduce.py
def code_histogram(
    files: list[str], *, nframes: int, label: str = ""
) -> np.ndarray:
    """Accumulate the (32, 32, n_codes) per-pixel TDC-code histogram.

    For every pixel, how often each integer code occurs over all frames with a
    valid timestamp (``time_series > 0``). The code axis is allocated at the
    widest the frame format can express ('timing.MAX_TS_CODE') and trimmed to
    the largest code any pixel produced, so the code count comes out of the
    run rather than out of a stated clock and nothing can overflow.

    Parameters
    ----------
    files : list[str]
        Paths to the '.bin' files.
    nframes : int
        Frames per file.
    label : str, optional
        Label used in the progress bar. The default is "".

    Returns
    -------
    np.ndarray
        The (32, 32, n_codes) int64 histogram.
    """
    n_alloc = timing.MAX_TS_CODE + 1
    # One bincount per file histograms all 1024 pixels at once:
    # linear index = pixel * n_alloc + code.
    pix_index = np.arange(1024, dtype=np.int64).reshape(32, 32, 1)
    counts = np.zeros(1024 * n_alloc, dtype=np.int64)
    for fp in tqdm(files, desc=label or None):
        ts, _ = unpack(fp, nframes, compute_time_series=True)
        code = ts.astype(np.int64)
        valid = (ts > 0) & (code < n_alloc)
        counts += np.bincount(
            (pix_index * n_alloc + code)[valid], minlength=1024 * n_alloc
        )
    counts = counts.reshape(32, 32, n_alloc)
    used = np.nonzero(counts.sum(axis=(0, 1)))[0]
    return counts[:, :, : int(used[-1]) + 1] if used.size else counts

core.plots — the two figure shapes

plots

Stage 2: the two figure shapes every analysis draws.

A sensor map (a 2D image of the array) and a sorted-percentile distribution cover every plot in the package bar the TDC QA panel. Both used to be copied per analysis, which is how three heatmaps ended up with three different figure sizes and two different NaN policies.

Figure sizing follows the package rule: square sensor maps set 16x16 in code, everything else takes figure.figsize from the active style (the dapkel style ships 16x10). So 'sensor_map' is explicit and 'sorted_distribution' is not.

All statistics here are NaN-aware. Plain np.median/np.percentile propagate NaN, so a single masked pixel would turn vmax into NaN and flatten the whole image to one colour with no error - see 'docs/adding_an_analysis.md'.

map_stats

map_stats(data: ndarray, *, scale: float = 1.0) -> tuple[float, float, float]

Return the NaN-aware (median, max, total) of a sensor map.

Parameters:

Name Type Description Default
data ndarray

The map.

required
scale float

Multiplied into the data first, for unit conversion (e.g. 100.0 to turn a ratio into a percentage). The default is 1.0.

1.0

Returns:

Type Description
tuple[float, float, float]

Median, maximum and sum, all ignoring NaN. An all-NaN map gives (nan, nan, 0.0) rather than raising.

Source code in src/dapkel/core/plots.py
def map_stats(
    data: np.ndarray, *, scale: float = 1.0
) -> tuple[float, float, float]:
    """Return the NaN-aware ``(median, max, total)`` of a sensor map.

    Parameters
    ----------
    data : np.ndarray
        The map.
    scale : float, optional
        Multiplied into the data first, for unit conversion (e.g. 100.0 to
        turn a ratio into a percentage). The default is 1.0.

    Returns
    -------
    tuple[float, float, float]
        Median, maximum and sum, all ignoring NaN. An all-NaN map gives
        ``(nan, nan, 0.0)`` rather than raising.
    """
    scaled = data * scale
    if not np.any(np.isfinite(scaled)):
        return float("nan"), float("nan"), 0.0
    return (
        float(np.nanmedian(scaled)),
        float(np.nanmax(scaled)),
        float(np.nansum(scaled)),
    )

sensor_map

sensor_map(data: ndarray, *, title: str, clabel: str | None = None, cmap: str | None = None, scale: float = 1.0, xlabel: str = 'Column', ylabel: str = 'Row', clip_colorbar_to: float | None = _VMAX_PERCENTILE) -> Figure

Render a sensor map as a square 2D image with a colour bar.

By default the colour scale is clipped at the 99th percentile so a handful of hot pixels cannot wash out the rest of the array. The clip only affects the colour scale - callers title their figures from 'map_stats', which always reports the true maximum, so a clipped bar ending below the titled max is expected.

Parameters:

Name Type Description Default
data ndarray

The (rows, cols) map to draw.

required
title str

Full figure title. Callers build this themselves - the wording is measurement-specific - typically from 'map_stats'.

required
clabel str | None

Colour-bar label. The default is None (no label).

None
cmap str | None

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

None
scale float

Multiplied into the data before drawing. The default is 1.0.

1.0
xlabel str

Axis labels. The defaults are 'Column' and 'Row'.

'Column'
ylabel str

Axis labels. The defaults are 'Column' and 'Row'.

'Column'
clip_colorbar_to float | None

Percentile (0-100) used as the colour-scale ceiling. The default is 99 - the historical behaviour. Pass None to let the scale run to the true maximum, which shows the hot pixels at the cost of compressing everything else.

_VMAX_PERCENTILE

Returns:

Type Description
Figure

The figure. Nothing is written to disk.

Source code in src/dapkel/core/plots.py
def sensor_map(
    data: np.ndarray,
    *,
    title: str,
    clabel: str | None = None,
    cmap: str | None = None,
    scale: float = 1.0,
    xlabel: str = "Column",
    ylabel: str = "Row",
    clip_colorbar_to: float | None = _VMAX_PERCENTILE,
) -> plt.Figure:
    """Render a sensor map as a square 2D image with a colour bar.

    By default the colour scale is clipped at the 99th percentile so a handful
    of hot pixels cannot wash out the rest of the array. The clip only affects
    the colour scale - callers title their figures from 'map_stats', which
    always reports the true maximum, so a clipped bar ending below the titled
    max is expected.

    Parameters
    ----------
    data : np.ndarray
        The (rows, cols) map to draw.
    title : str
        Full figure title. Callers build this themselves - the wording is
        measurement-specific - typically from 'map_stats'.
    clabel : str | None, optional
        Colour-bar label. The default is None (no label).
    cmap : str | None, optional
        Matplotlib colormap name. The default is None - use the active
        style's ``image.cmap``.
    scale : float, optional
        Multiplied into the data before drawing. The default is 1.0.
    xlabel, ylabel : str, optional
        Axis labels. The defaults are ``'Column'`` and ``'Row'``.
    clip_colorbar_to : float | None, optional
        Percentile (0-100) used as the colour-scale ceiling. The default is
        99 - the historical behaviour. Pass None to let the scale run to the
        true maximum, which shows the hot pixels at the cost of compressing
        everything else.

    Returns
    -------
    plt.Figure
        The figure. Nothing is written to disk.
    """
    scaled = data * scale
    vmax = (
        float(np.nanpercentile(scaled, clip_colorbar_to))
        if clip_colorbar_to is not None and np.any(np.isfinite(scaled))
        else None
    )

    # Square figure for the sensor map (kept explicit, per the package rule);
    # fonts and colormap come from the active matplotlib style.
    #
    # Constrained layout, because a square image inside a non-square figure
    # leaves the colour bar sitting against the right edge of the canvas: its
    # label was drawn *outside* and every saved map lost it. Constrained rather
    # than 'tight_layout' because the bar is the case tight layout handles
    # worst - it measures the axes it knows about and the bar is added after -
    # and it sizes the figure once here rather than at save time, so the
    # written '.png' is the size this module asked for.
    fig, ax = plt.subplots(
        figsize=SENSOR_MAP_FIGSIZE, layout="constrained"
    )

    im = ax.imshow(
        scaled, cmap=cmap, aspect="equal", vmax=vmax, origin="lower"
    )
    # 'fraction' is what keeps the bar proportional to the image rather than to
    # the figure; the label then needs 'labelpad' to clear the tick numbers.
    bar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
    if clabel:
        bar.set_label(clabel, labelpad=10)

    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    return fig

sorted_distribution

sorted_distribution(data: ndarray, *, ylabel: str, title: str, xlabel: str = 'Pixel percentile  (%)', logy: bool = False, scale: float = 1.0, fmt: str = '.3g', unit: str = '') -> Figure

Plot per-pixel values sorted low-to-high against their percentile.

Non-finite values are dropped before sorting, so masked or undefined pixels neither plot nor skew the median and mean lines.

Parameters:

Name Type Description Default
data ndarray

The map whose values are ranked.

required
ylabel str

Y-axis label, including the unit (e.g. 'DCR (cps)').

required
title str

Figure title.

required
xlabel str

X-axis label. The default is 'Pixel percentile (%)'.

'Pixel percentile (%)'
logy bool

Use a logarithmic y-axis, appropriate when the values span decades (DCR does). The default is False.

False
scale float

Multiplied into the data first. The default is 1.0.

1.0
fmt str

Format spec for the median/mean values in the legend. The default is '.3g'.

'.3g'
unit str

Unit appended to the legend entries (e.g. 'cps', '%'). The default is "".

''

Returns:

Type Description
Figure

The figure. Nothing is written to disk.

Source code in src/dapkel/core/plots.py
def sorted_distribution(
    data: np.ndarray,
    *,
    ylabel: str,
    title: str,
    xlabel: str = "Pixel percentile  (%)",
    logy: bool = False,
    scale: float = 1.0,
    fmt: str = ".3g",
    unit: str = "",
) -> plt.Figure:
    """Plot per-pixel values sorted low-to-high against their percentile.

    Non-finite values are dropped before sorting, so masked or undefined
    pixels neither plot nor skew the median and mean lines.

    Parameters
    ----------
    data : np.ndarray
        The map whose values are ranked.
    ylabel : str
        Y-axis label, including the unit (e.g. ``'DCR  (cps)'``).
    title : str
        Figure title.
    xlabel : str, optional
        X-axis label. The default is ``'Pixel percentile  (%)'``.
    logy : bool, optional
        Use a logarithmic y-axis, appropriate when the values span decades
        (DCR does). The default is False.
    scale : float, optional
        Multiplied into the data first. The default is 1.0.
    fmt : str, optional
        Format spec for the median/mean values in the legend. The default is
        ``'.3g'``.
    unit : str, optional
        Unit appended to the legend entries (e.g. ``'cps'``, ``'%'``). The
        default is "".

    Returns
    -------
    plt.Figure
        The figure. Nothing is written to disk.
    """
    values = (data * scale).ravel()
    values = values[np.isfinite(values)]

    # Figure size comes from the active style (non-square), per the package
    # rule; only the square sensor maps set their own.
    fig, ax = plt.subplots()

    suffix = f" {unit}" if unit else ""
    if values.size:
        median = float(np.median(values))
        mean = float(values.mean())
        ordered = np.sort(values)
        percentile = np.linspace(0, 100, ordered.size)

        plot = ax.semilogy if logy else ax.plot
        plot(
            percentile, ordered, ".", markersize=2, alpha=0.7,
            label="_nolegend_",
        )
        ax.axhline(
            median, linestyle="--", linewidth=2,
            label=f"Median  {median:{fmt}}{suffix}",
        )
        ax.axhline(
            mean, linestyle="--", linewidth=1,
            label=f"Mean    {mean:{fmt}}{suffix}",
        )
        ax.legend()

    ax.set_xlim(0, 100)
    ax.set_xticks([0, 25, 50, 75, 100])
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_title(title)
    ax.grid(True, which="both")
    fig.tight_layout()
    return fig

core.store — the stage 1 / stage 2 boundary

store

Persistence: the boundary between stage 1 (data) and stage 2 (figures).

The layout under a data folder is::

<data folder>/
  *.bin            stage 0 - raw, read-only, dapkel never writes here
  processed/       stage 1 - arrays ('.npy') + metadata ('.meta.json')
  results/<kind>/  stage 2 - figures only

One rule follows from it: stage 2 gets its data by loading a stage-1 artifact, never by re-unpacking '.bin' files. Retrying a colormap costs a 'load_map', not a full re-read of the raw data.

Every array is saved with a .meta.json sidecar recording how it was acquired (frame counts, live time, tag), so a saved map can still be turned into a rate months later without the original call arguments.

See 'docs/adding_an_analysis.md' for the contract.

processed_dir

processed_dir(path: str, *, create: bool = True) -> str

Return (and by default create) the processed/ folder of a dataset.

Parameters:

Name Type Description Default
path str

The data folder holding the '.bin' files.

required
create bool

Create the folder if missing. The default is True.

True

Returns:

Type Description
str

Path to <folder>/processed.

Source code in src/dapkel/core/store.py
def processed_dir(path: str, *, create: bool = True) -> str:
    """Return (and by default create) the ``processed/`` folder of a dataset.

    Parameters
    ----------
    path : str
        The data folder holding the '.bin' files.
    create : bool, optional
        Create the folder if missing. The default is True.

    Returns
    -------
    str
        Path to ``<folder>/processed``.
    """
    out = os.path.join(path, PROCESSED_DIR)
    if create:
        os.makedirs(out, exist_ok=True)
    return out

results_dir

results_dir(path: str, kind: str, *, create: bool = True) -> str

Return (and by default create) the figure folder for one analysis.

Parameters:

Name Type Description Default
path str

The data folder holding the '.bin' files.

required
kind str

Analysis name, used as the sub-folder (e.g. 'dcr', 'hitmap').

required
create bool

Create the folder if missing. The default is True.

True

Returns:

Type Description
str

Path to <folder>/results/<kind>.

Source code in src/dapkel/core/store.py
def results_dir(path: str, kind: str, *, create: bool = True) -> str:
    """Return (and by default create) the figure folder for one analysis.

    Parameters
    ----------
    path : str
        The data folder holding the '.bin' files.
    kind : str
        Analysis name, used as the sub-folder (e.g. ``'dcr'``, ``'hitmap'``).
    create : bool, optional
        Create the folder if missing. The default is True.

    Returns
    -------
    str
        Path to ``<folder>/results/<kind>``.
    """
    out = os.path.join(path, RESULTS_DIR, kind)
    if create:
        os.makedirs(out, exist_ok=True)
    return out

map_file_name

map_file_name(dataset: str, kind: str, tag: str = '') -> str

Build the '.npy' file name for a stage-1 array.

Parameters:

Name Type Description Default
dataset str

Name of the dataset, normally the data folder's base name.

required
kind str

Analysis name (e.g. 'dcr', 'hitmap', 'crosstalk').

required
tag str

Readout/quadrant tag distinguishing artifacts of the same kind. The default is "". Lower-cased, so 'ORT' and 'ort' are one file.

''

Returns:

Type Description
str

'<dataset>_<tag>_<kind>.npy', or '<dataset>_<kind>.npy' when no tag is given.

Source code in src/dapkel/core/store.py
def map_file_name(dataset: str, kind: str, tag: str = "") -> str:
    """Build the '.npy' file name for a stage-1 array.

    Parameters
    ----------
    dataset : str
        Name of the dataset, normally the data folder's base name.
    kind : str
        Analysis name (e.g. ``'dcr'``, ``'hitmap'``, ``'crosstalk'``).
    tag : str, optional
        Readout/quadrant tag distinguishing artifacts of the same kind. The
        default is "". Lower-cased, so ``'ORT'`` and ``'ort'`` are one file.

    Returns
    -------
    str
        ``'<dataset>_<tag>_<kind>.npy'``, or ``'<dataset>_<kind>.npy'`` when
        no tag is given.
    """
    tag = tag.lower().strip("_")
    parts = [dataset, tag, kind] if tag else [dataset, kind]
    return "_".join(parts) + ".npy"

meta_path

meta_path(npy_path: str) -> str

Return the sidecar '.meta.json' path for a saved '.npy'.

Source code in src/dapkel/core/store.py
def meta_path(npy_path: str) -> str:
    """Return the sidecar '.meta.json' path for a saved '.npy'."""
    return npy_path.removesuffix(".npy") + ".meta.json"

read_meta

read_meta(npy_path: str) -> dict

Read a saved array's '.meta.json' sidecar.

Parameters:

Name Type Description Default
npy_path str

Path to the saved '.npy'.

required

Returns:

Type Description
dict

The metadata, or an empty dict when the sidecar is missing or unreadable - callers treat metadata as best-effort.

Source code in src/dapkel/core/store.py
def read_meta(npy_path: str) -> dict:
    """Read a saved array's '.meta.json' sidecar.

    Parameters
    ----------
    npy_path : str
        Path to the saved '.npy'.

    Returns
    -------
    dict
        The metadata, or an empty dict when the sidecar is missing or
        unreadable - callers treat metadata as best-effort.
    """
    path = meta_path(npy_path)
    if os.path.isfile(path):
        try:
            with open(path, encoding="utf-8") as fh:
                return json.load(fh)
        except (OSError, ValueError):
            pass
    return {}

save_map

save_map(data: ndarray, path: str, *, kind: str, tag: str = '', meta: dict | None = None, file_name: str | None = None, quiet: bool = False) -> str

Save a stage-1 array into processed/ with a metadata sidecar.

Parameters:

Name Type Description Default
data ndarray

The array to save.

required
path str

The data folder; the array lands in its processed/ sub-path.

required
kind str

Analysis name (e.g. 'dcr'), used in the file name.

required
tag str

Readout/quadrant tag. The default is "".

''
meta dict | None

Acquisition metadata written alongside as '.meta.json'. The default is None (an empty sidecar is still written, recording kind and tag).

None
file_name str | None

Explicit '.npy' file name, overriding the derived one. Used where a naming scheme is already established (the TDC tap tables). The default is None.

None
quiet bool

Suppress the "saved to" printout. The default is False.

False

Returns:

Type Description
str

Path the array was saved to.

Source code in src/dapkel/core/store.py
def save_map(
    data: np.ndarray,
    path: str,
    *,
    kind: str,
    tag: str = "",
    meta: dict | None = None,
    file_name: str | None = None,
    quiet: bool = False,
) -> str:
    """Save a stage-1 array into ``processed/`` with a metadata sidecar.

    Parameters
    ----------
    data : np.ndarray
        The array to save.
    path : str
        The data folder; the array lands in its ``processed/`` sub-path.
    kind : str
        Analysis name (e.g. ``'dcr'``), used in the file name.
    tag : str, optional
        Readout/quadrant tag. The default is "".
    meta : dict | None, optional
        Acquisition metadata written alongside as '.meta.json'. The default
        is None (an empty sidecar is still written, recording kind and tag).
    file_name : str | None, optional
        Explicit '.npy' file name, overriding the derived one. Used where a
        naming scheme is already established (the TDC tap tables). The default is
        None.
    quiet : bool, optional
        Suppress the "saved to" printout. The default is False.

    Returns
    -------
    str
        Path the array was saved to.
    """
    out_dir = processed_dir(path)
    dataset = os.path.basename(os.path.normpath(path))
    name = file_name or map_file_name(dataset, kind, tag)
    out_path = os.path.join(out_dir, name)

    np.save(out_path, data)
    with open(meta_path(out_path), "w", encoding="utf-8") as fh:
        json.dump({"kind": kind, "tag": tag, **(meta or {})}, fh, indent=2)

    if not quiet:
        print(f"\n> > > Saved to {out_path} < < <")
    return out_path

load_map

load_map(path: str | None = None, *, kind: str = '', tag: str = '', npy_path: str | None = None, file_name: str | None = None) -> tuple[ndarray, dict]

Load a stage-1 array and its metadata back from processed/.

Parameters:

Name Type Description Default
path str | None

The data folder to look under. May be None when npy_path is given. The default is None.

None
kind str

Analysis name, used to derive the file name. The default is "".

''
tag str

Readout/quadrant tag. The default is "".

''
npy_path str | None

Explicit path to a saved '.npy', bypassing the derivation entirely. The default is None.

None
file_name str | None

Explicit file name within processed/. The default is None.

None

Returns:

Type Description
tuple[ndarray, dict]

The array and its metadata (an empty dict when no sidecar exists).

Raises:

Type Description
ValueError

Raised when neither npy_path nor folder is given.

FileNotFoundError

Raised when the '.npy' does not exist, with the path that was tried.

Source code in src/dapkel/core/store.py
def load_map(
    path: str | None = None,
    *,
    kind: str = "",
    tag: str = "",
    npy_path: str | None = None,
    file_name: str | None = None,
) -> tuple[np.ndarray, dict]:
    """Load a stage-1 array and its metadata back from ``processed/``.

    Parameters
    ----------
    path : str | None, optional
        The data folder to look under. May be None when ``npy_path`` is
        given. The default is None.
    kind : str, optional
        Analysis name, used to derive the file name. The default is "".
    tag : str, optional
        Readout/quadrant tag. The default is "".
    npy_path : str | None, optional
        Explicit path to a saved '.npy', bypassing the derivation entirely.
        The default is None.
    file_name : str | None, optional
        Explicit file name within ``processed/``. The default is None.

    Returns
    -------
    tuple[np.ndarray, dict]
        The array and its metadata (an empty dict when no sidecar exists).

    Raises
    ------
    ValueError
        Raised when neither ``npy_path`` nor ``folder`` is given.
    FileNotFoundError
        Raised when the '.npy' does not exist, with the path that was tried.
    """
    if npy_path is None:
        if path is None:
            raise ValueError("give either 'path' or 'npy_path'")
        dataset = os.path.basename(os.path.normpath(path))
        name = file_name or map_file_name(dataset, kind, tag)
        npy_path = os.path.join(path, PROCESSED_DIR, name)

    if not os.path.isfile(npy_path):
        raise FileNotFoundError(
            f"No saved '{kind or 'array'}' found at:\n  {npy_path}\n"
            f"Run the matching process_* first."
        )
    return np.load(npy_path), read_meta(npy_path)

save_figure

save_figure(fig: Figure, results_dir: str, file_name: str) -> str

Save a figure into the results path.

Parameters:

Name Type Description Default
fig Figure

Figure to save.

required
results_dir str

Folder the figure should be saved into. Created if missing.

required
file_name str

Name of the '.png' file to save the figure as.

required

Returns:

Type Description
str

Path the figure was saved to.

Source code in src/dapkel/core/store.py
def save_figure(fig: plt.Figure, results_dir: str, file_name: str) -> str:
    """Save a figure into the results path.

    Parameters
    ----------
    fig : plt.Figure
        Figure to save.
    results_dir : str
        Folder the figure should be saved into. Created if missing.
    file_name : str
        Name of the '.png' file to save the figure as.

    Returns
    -------
    str
        Path the figure was saved to.
    """
    os.makedirs(results_dir, exist_ok=True)
    out_path = os.path.join(results_dir, file_name)
    fig.savefig(out_path)
    print(f"\n> > > Plot is saved as {file_name} in {results_dir} < < <")
    return out_path

confirm_rewrite

confirm_rewrite(paths: str | Sequence[str], *, delay: float | None = None) -> bool

Warn, then pause, before existing artifacts are overwritten.

Call this from any analysis whose rewrite=True is about to destroy stage-1 data. Nothing is printed and nothing is waited for on a fresh run (no target exists), so the pause only ever costs something when there is genuinely something to lose - typically a rewrite=True left in the script from the previous acquisition.

The countdown is a plain time.sleep, so Ctrl-C during it raises 'KeyboardInterrupt' out of the analysis and the data on disk is untouched.

Parameters:

Name Type Description Default
paths str | Sequence[str]

Artifact(s) about to be overwritten. Files and directories are both accepted; entries that do not exist are ignored. Pass every target, including part-file folders, so the warning names them all.

required
delay float | None

Seconds to count down. The default is None, meaning 'REWRITE_DELAY_S' (5 s). Pass 0 to warn without pausing.

None

Returns:

Type Description
bool

True if something existed and is about to be overwritten, False on a fresh run.

Source code in src/dapkel/core/store.py
def confirm_rewrite(
    paths: str | Sequence[str], *, delay: float | None = None
) -> bool:
    """Warn, then pause, before existing artifacts are overwritten.

    Call this from any analysis whose ``rewrite=True`` is about to destroy
    stage-1 data. Nothing is printed and nothing is waited for on a fresh run
    (no target exists), so the pause only ever costs something when there is
    genuinely something to lose - typically a ``rewrite=True`` left in the
    script from the previous acquisition.

    The countdown is a plain ``time.sleep``, so Ctrl-C during it raises
    'KeyboardInterrupt' out of the analysis and the data on disk is untouched.

    Parameters
    ----------
    paths : str | Sequence[str]
        Artifact(s) about to be overwritten. Files and directories are both
        accepted; entries that do not exist are ignored. Pass every target,
        including part-file folders, so the warning names them all.
    delay : float | None, optional
        Seconds to count down. The default is None, meaning
        'REWRITE_DELAY_S' (5 s). Pass 0 to warn without pausing.

    Returns
    -------
    bool
        True if something existed and is about to be overwritten, False on a
        fresh run.
    """
    targets = [paths] if isinstance(paths, str) else list(paths)
    existing = [p for p in targets if os.path.exists(p)]
    if not existing:
        return False

    wait = REWRITE_DELAY_S if delay is None else float(delay)

    print("\n" + "!" * 72)
    print("!!  rewrite=True - the following data WILL BE OVERWRITTEN:")
    for p in existing:
        print(f"!!    {_describe_target(p)}")
    if wait > 0:
        print(
            f"!!  Press Ctrl-C within {wait:.0f} s to abort and copy it "
            "somewhere safe."
        )
    print("!" * 72)

    remaining = wait
    while remaining > 0:
        print(f"  overwriting in {remaining:.0f} s ...", flush=True)
        step = min(1.0, remaining)
        time.sleep(step)
        remaining -= step
    if wait > 0:
        print("  overwriting now.\n")
    return True