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 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. |
required |
require_separator
|
bool
|
When True the tag must be preceded by an underscore (pattern
|
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
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 ¶
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
to_s ¶
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
full_scale_from_max_code ¶
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. |
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 |
Source code in src/dapkel/core/timing.py
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 windowopen_shutter_time_sis 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 wholeexp_time_s + 9 µscycle is live (exp_time_s=Noneis 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
|
None
|
exp_time_s
|
float | None
|
Exposure requested of |
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 |
Source code in src/dapkel/core/timing.py
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 ¶
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. |
required |
motherboard_number
|
str
|
Motherboard id, e.g. |
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
codes_to_ps ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Times in picoseconds, same shape as |
Source code in src/dapkel/core/calibration.py
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 ¶
Normalise a detector spec - one (row, col) or a sequence - to a list.
Source code in src/dapkel/core/pairs.py
pair_label ¶
pair_list ¶
Enumerate the ordered (pixel_a, pixel_b) pairs of two groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pixels
|
Sequence[Sequence[tuple[int, int]]]
|
Two groups |
required |
mode
|
str
|
|
'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 |
Source code in src/dapkel/core/pairs.py
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 ¶
Return 'timestamp' or 'count' for a file tag, from its last letter.
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the tag ends in neither |
Source code in src/dapkel/core/reduce.py
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
|
|
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 |
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
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. |
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 |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
Raised when no file matches |
Source code in src/dapkel/core/reduce.py
code_histogram ¶
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
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 ¶
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
|
Source code in src/dapkel/core/plots.py
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 |
None
|
scale
|
float
|
Multiplied into the data before drawing. The default is 1.0. |
1.0
|
xlabel
|
str
|
Axis labels. The defaults are |
'Column'
|
ylabel
|
str
|
Axis labels. The defaults are |
'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
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. |
required |
title
|
str
|
Figure title. |
required |
xlabel
|
str
|
X-axis label. The default is |
'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'
|
unit
|
str
|
Unit appended to the legend entries (e.g. |
''
|
Returns:
| Type | Description |
|---|---|
Figure
|
The figure. Nothing is written to disk. |
Source code in src/dapkel/core/plots.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
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 ¶
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 |
Source code in src/dapkel/core/store.py
results_dir ¶
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. |
required |
create
|
bool
|
Create the folder if missing. The default is True. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Path to |
Source code in src/dapkel/core/store.py
map_file_name ¶
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. |
required |
tag
|
str
|
Readout/quadrant tag distinguishing artifacts of the same kind. The
default is "". Lower-cased, so |
''
|
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in src/dapkel/core/store.py
meta_path ¶
read_meta ¶
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
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 |
required |
kind
|
str
|
Analysis name (e.g. |
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
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 |
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 |
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 |
FileNotFoundError
|
Raised when the '.npy' does not exist, with the path that was tried. |
Source code in src/dapkel/core/store.py
save_figure ¶
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
confirm_rewrite ¶
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. |