Coincidences and timing jitter (delta-t)¶
A daplis-style pipeline for coincidence / timing-jitter analysis of the Kelpie
ORT (timestamp) program, in two calls like every analysis:
unpackdecodes each.binfile into the per-frame, per-pixel TDC code (time_series, the MATLABtime_mat).process_coincidencesconverts the codes of the chosen pixels to picoseconds, differences every pixel pair frame by frame, and bins the differences onto a fixed native grid as it finds them, saving only the counts toprocessed/.plot_coincidencesrebins that grid in memory, fits the coincidence peak and saves the figure toresults/coincidences/.
from dapkel.functions import coincidences as co
signal = [(6, 10), (6, 11), (7, 10)] # blobs read off the hitmap
idler = [(21, 22), (21, 23), (22, 22)]
co.process_coincidences(path, 10_000, [signal, idler],
daughterboard_number="D0", motherboard_number="M0")
counts, centers, fit = co.plot_coincidences(path)
pixels is two groups [group_a, group_b]; a bare (row, col) is a one-pixel
group. With mode="all_pairs" (the default) every A × B combination is a pair —
use it when it is not known which pixel of a blob catches the photon; "1v1"
zips the groups element-wise. Each pair is one row of the saved grid, labelled
"ra,ca-rb,cb".
Timing model¶
Each acquisition window is ~9 µs, but the ring-oscillator TDC measures only
within one period of the reference clock. The recorded time_series value is
the oscillator code on that range, and the timestamp is
on average. The ring sets that code width, so it does not change with the clock — only the number of codes does, as 1/f:
| clock | full scale | codes |
|---|---|---|
| 50 MHz | 20 ns | ~279 |
| 10 MHz | 100 ns | ~1397 |
| 5 MHz | 200 ns | ~2794 |
| 2 MHz | 500 ns | ~6985 |
That full scale bounds a difference, so it is also the accidental triangle's half-base — see the triangle background.
No entry point asks you for it. The largest code a run produced is the
range its TDC swept, so it is measured from the data
(core.timing.full_scale_from_max_code).
That replaced three parameters that used to ask for the same number under
different names — open_shutter_time_s, full_scale_s and support_s — one of
which was not even the right quantity: the open shutter time is how long the
SPAD waits for a photon, and an 8 µs shutter on a 10 MHz clock still yields
~100 ns timestamps, because the free-running oscillator has no cycle counter. It
belongs to rate normalisation (DCR, hitmaps) and nothing
else.
The actual bin widths come from the board's 8-tap calibration — see
TDC calibration. With apply_TDC_calibration=True (the
default, which needs daughterboard_number and motherboard_number) every code
is converted with
core.calibration.codes_to_ps before
differencing. The taps belong to the ring, not the clock, so the same table
serves a run at any clock and there is nothing to select: an S0T...S3T tag
gets that SPAD's table, ORT the mean of the four. apply_TDC_calibration=False
uses the nominal CODE_S.
Units¶
Every time parameter in the package is in seconds, with an _s suffix.
There are three of them here, and they are all display or fit choices:
bin_width_s, plot_window_s, fit_window_s. Histogram bin centres, edges and
plot axes are in picoseconds — that is the scale the TDC lives on — and the
conversion happens on entry.
Differences are binned in picoseconds whether or not a calibration was
applied; uncalibrated codes are converted with the nominal CODE_S on the way
in. There is no raw-code artifact, because there would be nothing to do with
one: a calibration maps a code to a time, and a stored difference has lost
both of its codes, so it could never be calibrated after the fact.
There is one timestamp per photon, per window, per macropixel.
Fitting the peak: the background is a triangle¶
This is the part that most affects the number you report.
The accidental-coincidence background under an ORT delta-t peak is triangular, not flat, because the free-running oscillator has no cycle counter. Fitting a Gaussian on a flat background over a wide window therefore inflates the fitted sigma — you measure the background's slope as if it were jitter.
plot_coincidences picks the model for you, and takes no background
argument. The pedestal is either still in the histogram, and then it is the
triangle, or subtract_background=True has measured it away and the residual is
flat about zero — one decision, not two:
| histogram | model | fitted over |
|---|---|---|
| raw (default) | Gaussian on a triangular background, the measured full scale seeding the half-base | the whole plotted window |
| lag-subtracted residual | Gaussian on a zero baseline (not fitted) | fit_window_s (default 5 ns) around the peak |
A fit that fails — including one whose sigma the covariance cannot tell from
zero, which a wrong background model produces — comes back with fit["ok"]
False and a RuntimeWarning, so a plot without a curve always says why.
plot_coincidences returns (counts, centers, fit): the fitted histogram, the bin
centres in picoseconds and a dict of amp, mu, sigma, fwhm,
jitter_per_detector (sigma / √2), each with its _err, the background level
bkg (0 on a residual), fit_range, car (peak-to-background, raw histogram only), n and ok — enough to
re-fit by hand with any model without touching disk. The fit models themselves
are private, and the two-Gaussian (narrow core on broad tails) model is retired
to the repository's archive/ folder.
The full derivation, with the demonstration that the triangle is intrinsic rather than an artefact, is in the triangular background note.
Before you analyse: check the data¶
Run data_quality.process_time_codes
and plot_time_codes on a
pixel or two first. When the TDC never stops, unpack still returns a full
array of plausible integers and this whole pipeline still produces a
peak-shaped histogram — it is simply meaningless. See
Data quality.
Stage 1: histogram straight off the .bin¶
process_coincidences bins the differences onto a fixed native grid as it finds
them and keeps only the counts:
processed/
<dataset>_<tag>_coincidences.npy <- (n_pairs, n_cells) int64, tag lower-cased
<dataset>_<tag>_coincidences.meta.json <- grid, pair labels, totals, progress
The size is set by the grid, not by the data. A 256-pair run on the default
grid is 106 MB whether it came from 100 files or 10 000 — where keeping every
difference took 3.22 GB for the same run, and 135 GB for a larger one. That is
what makes every pair plottable at once. The tag is in the name, so several
programs (ORT, S0T, ...) recorded into one folder keep their own artifact
and their own figures.
Choosing the grid¶
One argument, bin_width_s (cell width):
| data | default cell | why |
|---|---|---|
uncalibrated (apply_TDC_calibration=False) |
one code, ~71.6 ps | the codes are integers, so counts-per-code is a re-encoding, not a summary — exactly lossless |
| calibrated | 1/10 code, ~7.2 ps | the per-pixel calibration smears the code lattice; 7.2 ps is ~5× finer than the jitter |
The half-range is not a parameter. It is the run's own TDC full scale — the
largest code in the first file — with a 20 % margin for the extreme-value bias
of reading that off one file. A difference cannot exceed the full scale, so that
covers the whole physical support at any clock without being told the clock; a
fixed 200 ns was 10× too wide at 50 MHz and 2.5× too narrow at 2 MHz. Anything
landing outside is reported as n_outside rather than dropped silently, so an
under-sized grid announces itself instead of quietly clipping the triangle.
Re-binning is free, and exact¶
plot_window_s becomes a slice and bin_width_s a reduce, both in memory —
nothing is read but the one saved array:
co.plot_coincidences(
path,
pairs=["6,10-21,22"],
bin_width_s=71e-12,
plot_window_s=10e-9, # omit for the whole measured support
)
The binning is always snapped onto the grid, and the snap is not cosmetic:
- the width goes to a whole number of cells, or bins hold 9 then 10 then 9 cells and a smooth distribution picks up an ~11% sawtooth;
- that number is made odd. Bins are centred on zero, so their edges sit at half-integer multiples of the width — odd puts those edges on cell boundaries, even puts them through cell centres, splitting a cell at every boundary. Measured on a real 3.22 GB run: exactly zero difference from histogramming every stored difference at 9, 11 and 13 cells per bin, ~1% at 8, 10 and 12;
- the window goes to a whole number of bins, so zero is a bin centre whatever the window is.
So this is not an approximation of a histogram of the raw differences — it is the same histogram, in every bin.
The figure is results/coincidences/<dataset>_<tag>_<label>_coincidences.png,
label (default "spdc") also heading the title.
What you give up¶
No per-event data survives, so there is nothing that needs individual
differences — time ordering, splitting by acquisition, higher-order
correlations. It also does not make stage 1 meaningfully faster: unpacking
dominates either way. The win is artifact size and replot latency. The retired
per-event (feather) path is in the repository's archive/ folder.
Crash insurance, and resuming¶
The grid is rewritten every 50 files (the module constant _FLUSH_EVERY, not
a parameter — checkpoint cadence cannot change the numbers), so a run that dies
leaves a valid artifact covering everything up to its last checkpoint, and the
next call resumes from it (resume=True, the default) when it was computed from
the same inputs — files, pairs, mode, grid, calibration and lags. There is only
ever one file, so two runs cannot interleave. plot_coincidences on an incomplete
artifact plots what is there and says how many files it covers.
The sidecar records files_done and total_in_grid. The array is moved into
place before the sidecar, so a crash between the two moves could pair a newer
array with an older sidecar; resuming on that would re-count files and inflate
the total. The resume path checks the array against total_in_grid and starts
over rather than continue from something inconsistent.
A complete artifact, or one computed from different inputs, is never touched
without rewrite=True — process_coincidences raises FileExistsError instead.
Measuring the background instead of fitting it¶
subtract_background=True histograms the frame-shifted pixel pairs alongside
the real ones, one grid plane per lag, so the accidental triangle can be
subtracted bin-for-bin rather than fitted — see
Removing the accidental background by shifting frames.
# the lags cost one small grid plane each; the .bin decoding is paid once
co.process_coincidences(path, 10_000, [signal, idler],
daughterboard_number="D0", motherboard_number="M0",
subtract_background=True)
counts, centers, fit = co.plot_coincidences(
path, subtract_background=True, fit_window_s=2e-9)
Overwriting: the five-second countdown¶
rewrite=True routes through
store.confirm_rewrite. On a fresh run it
does nothing at all. When something really is about to be destroyed it names
each target with its size and timestamp, then counts down five seconds before
proceeding:
!! rewrite=True - the following data WILL BE OVERWRITTEN:
!! .../processed/SPDC_ort_coincidences.npy (106.0 MB, written 2026-07-30 02:11)
!! Press Ctrl-C within 5 s to abort and copy it somewhere safe.
The pause is a plain time.sleep, so Ctrl-C raises straight out of the
analysis with the data on disk untouched. This is aimed at the common accident:
a rewrite=True left in the script from the previous acquisition, silently
eating an overnight run. Set store.REWRITE_DELAY_S = 0 in an unattended
pipeline that has its own guard.
API¶
coincidences ¶
Coincidence / timing-jitter (delta-t) analysis for the timestamping programs.
process_coincidences raw '.bin' -> processed/<name>_<tag>_coincidences.npy
plot_coincidences that grid -> results/coincidences/ the fitted peak
In every frame where both pixels of a pair hold a timestamp, t_b - t_a is
one entry of the delta-t distribution; correlated pairs (SPDC signal/idler) pile
up at zero. Stage 1 bins those differences onto a fixed native grid as it
finds them and keeps only the counts - one row per pixel pair, one column per
grid cell - so the artifact is sized by the grid (~100 MB), not by the run, and
stage 2 can rebin it to any width or window in memory. Uncalibrated data lands
on a one-code grid and is lossless; a calibration smears the code lattice, so
each difference moves by at most half a cell (~3.6 ps at the default), far
below the detector jitter.
The ORT accidental background is a TRIANGLE, not flat: the free-running
oscillator has no cycle counter, so two uncorrelated phases difference into a
triangle that is zero at +/- one TDC full scale - 20 ns at 50 MHz, 100 ns at
10 MHz, 500 ns at 2 MHz. 'plot_coincidences' fits Gaussian + triangle on the raw
histogram, or measures the triangle away entirely with subtract_background
(below) and fits Gaussian + constant on the residual - the model follows
from the data, it is not a choice. See docs/ort_triangle_background.md.
The full scale is measured, never asked for: the largest code a run holds is the range its TDC swept ('core.timing.full_scale_from_max_code'). Nor is the open shutter time it - an 8 us shutter on a 10 MHz clock still yields ~100 ns timestamps - so that belongs to rate normalisation and not here.
Background subtraction. An SPDC pair is always in one frame, so pairing
pixel A in frame i with pixel B in frame i + k (k >= 1) samples the
accidentals only, at the same rates. Subtract the mean of a few such lags from
lag 0 and the triangle cancels bin for bin, leaving the peak on a zero
baseline: a model-free coincidence count, and a test of whether the pedestal
was accidental at all. It does not improve CAR - the residual keeps the Poisson
noise of what it removed. See docs/guide/background_subtraction.md.
UNITS: every time parameter is in seconds with an _s suffix; differences,
grids and plot axes are in picoseconds ('core.timing.to_ps'), whether or not a
calibration was applied - uncalibrated codes are converted with the nominal
'timing.CODE_S' on the way in, because a saved difference of two codes could
never be calibrated afterwards.
Check a fresh acquisition with 'dapkel.functions.data_quality' first.
See docs/guide/coincidences.md.
process_coincidences ¶
process_coincidences(path: str, nframes: int, pixels: Sequence[Sequence[Pixel]], *, tag: str = 'ORT', mode: str = 'all_pairs', bin_width_s: float | None = None, apply_TDC_calibration: bool = True, daughterboard_number: str | None = None, motherboard_number: str | None = None, subtract_background: bool = False, background_lags: int | Sequence[int] = _BACKGROUND_LAGS, max_files: int | None = None, rewrite: bool = False, resume: bool = True) -> str
Unpack the timestamps, histogram every pair's delta-t and save the grid.
Writes processed/<name>_<tag>_coincidences.npy: (n_pairs, n_cells)
int64 counts on a native grid centred on zero (zero is a cell centre by
construction) spanning the run's measured full scale, plus a sidecar with
the grid, the pair labels and progress. With subtract_background a
leading lag axis is added, lag 0 - the ordinary histogram - first.
The grid is rewritten every 50 files, so a run that dies leaves a valid
artifact up to its last checkpoint and resume continues it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Folder with the timestamping '.bin' files. |
required |
nframes
|
int
|
Frames the acquisition recorded per '.bin' file. |
required |
pixels
|
Sequence[Sequence[tuple[int, int]]]
|
Two groups |
required |
tag
|
str
|
File tag. |
'ORT'
|
mode
|
str
|
|
'all_pairs'
|
bin_width_s
|
float | None
|
Width of one grid cell, in seconds. The default is None: one TDC code ('timing.CODE_S') uncalibrated, where that is exact, and a tenth of one with a calibration. |
None
|
apply_TDC_calibration
|
bool
|
Convert codes with the board's packaged compact calibration before
differencing, correcting the ring's DNL at whatever clock the run used.
The default is True, which needs |
True
|
daughterboard_number
|
str | None
|
Daughterboard id, e.g. |
None
|
motherboard_number
|
str | None
|
Motherboard id, e.g. |
None
|
subtract_background
|
bool
|
Also histogram frame-shifted pairs ( |
False
|
background_lags
|
int | Sequence[int]
|
Frame offsets for the accidental estimate, all >= 1 (lag 0 is the
signal and always included). The default is |
_BACKGROUND_LAGS
|
max_files
|
int | None
|
Use at most this many files. The default is None (all). |
None
|
rewrite
|
bool
|
Overwrite a complete artifact for this data set - after a 5 s countdown naming it ('store.confirm_rewrite'). The default is False, which raises instead. |
False
|
resume
|
bool
|
Continue an incomplete artifact computed from the same inputs. The default is True. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the saved '.npy'. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
Raised when an artifact exists and |
ValueError
|
Raised on a bad |
Source code in src/dapkel/functions/coincidences.py
148 149 150 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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | |
plot_coincidences ¶
plot_coincidences(path: str, tag: str = 'ORT', *, bin_width_s: float = CODE_S, plot_window_s: float | None = None, fit_window_s: float | None = 5e-09, pairs: Sequence[str] | None = None, label: str = 'spdc', title: str | None = None, subtract_background: bool = False) -> tuple[ndarray, ndarray, dict]
Rebin the saved grid, fit the coincidence peak and save the figure.
Nothing is read but the one saved array, and the rebinning is in memory, so
changing bin_width_s or plot_window_s costs milliseconds. The
binning is snapped onto the grid - a whole, odd number of cells per bin and
a whole number of bins per window - which is what makes the rebin exact.
The fit model is not a parameter: on the raw histogram it is Gaussian +
triangle with the measured full scale seeding the half-base; with
subtract_background it is a Gaussian on a zero baseline within
fit_window_s of the peak, there being no background left. The curve
and the residual panel cover only the fitted range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Data folder that 'process_coincidences' was run on. |
required |
tag
|
str
|
The tag it was run with. The default is |
'ORT'
|
bin_width_s
|
float
|
Histogram bin width, in seconds. The default is one TDC code. |
CODE_S
|
plot_window_s
|
float | None
|
Half-range around zero, in seconds. The default is None: the measured TDC full scale, the whole support the triangle fit wants. |
None
|
fit_window_s
|
float | None
|
Half-range around the peak, in seconds - the subtracted fit's range and
the window the model-free coincidence count is summed over. Wide enough
to reach past the peak's diffusion tails (~3 ns), so the fit sees them
end. Ignored by the triangle fit. The default is |
5e-09
|
pairs
|
Sequence[str] | None
|
Pool only these pixel-pair labels ( |
None
|
label
|
str
|
Short label for the title and file name ( |
'spdc'
|
title
|
str | None
|
Override for the plot title. The default is None. |
None
|
subtract_background
|
bool
|
Subtract the frame-shifted accidentals before fitting and save the
three-panel diagnostic beside the fit; read its middle panel before
quoting anything. Needs a grid processed with
|
False
|
Returns:
| Name | Type | Description |
|---|---|---|
counts |
ndarray
|
The fitted histogram - the residual with |
centers |
ndarray
|
Bin centres in picoseconds, to re-fit without re-reading anything. |
fit |
dict
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
Raised when no saved grid exists for |
ValueError
|
Raised when |
Source code in src/dapkel/functions/coincidences.py
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 | |