<!--
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# Measure a delay between two signals

Use the NumPy backend of the published `cuphoton==0.2.2` package. Run
`python -c "from cuphoton.xbeam import ArraySource, CorrelationSpec, correlate_series"`
in the analysis environment. If the checkout lacks xBeam, install the release
with `python -m pip install "cuphoton==0.2.2"` in a dedicated environment.
The workflow runs on a CPU.

Confirm the channel order, sample rate in Hz, common time origin and uniform
spacing. Keep gaps at their original sample indices and mark them invalid.
If clocks or rates differ, establish a shared time grid before interpreting a
peak. Ask how large the delay could plausibly be, in samples or seconds.

## Measure each time interval

Adapt the input loader to the recording. This example reads `signals.npz` with
equal-length real vectors `a` and `b`, scalar `rate_hz` and a positive integer
`max_lag_samples` from the measurement setup. Optional Boolean vectors
`a_valid` and `b_valid` mark usable samples. Choose a window that holds the
signal feature and comfortably exceeds the largest plausible delay. Here each
estimate uses 1,024-sample, non-overlapping windows. Choose the largest group
of one to four windows that divides the available full windows evenly. For a
drift or stability question, set `check_stability = True` below to use at
least two independent intervals when the recording permits. Report any
samples left after the last full window.

```python
import numpy as np
from cuphoton.xbeam import ArraySource, CorrelationSpec, correlate_series

window = 1024
check_stability = False
with np.load("signals.npz") as data:
    rate = float(data["rate_hz"])
    limit = int(data["max_lag_samples"])
    signals, valid = {}, {}
    for name in ("a", "b"):
        values = data[name]
        mask = np.isfinite(values)
        if name + "_valid" in data:
            mask &= data[name + "_valid"]
        complete_samples = (values.size // window) * window
        mask[complete_samples:] = False
        valid[name] = mask
        signals[name] = np.where(mask, values, 0.0).astype(np.float64)

sample_count = signals["a"].size
full_windows, tail = divmod(sample_count, window)
if full_windows == 0 or not 0 < limit < window:
    raise ValueError("Need a full window and a search radius smaller than the window")
if tail:
    print((full_windows * window, sample_count), "unused trailing samples", tail)
max_group = max(1, full_windows // 2) if check_stability else full_windows
group = next(size for size in (4, 3, 2, 1) if size <= max_group and full_windows % size == 0)
if check_stability and full_windows == 1:
    print("Only one complete window; stability cannot be checked")
interval_size = group * window
for start in range(0, full_windows * window, interval_size):
    part = slice(start, start + interval_size)
    for name, values in signals.items():
        block = values[part]
        mask = valid[name][part]
        if mask.any():
            block[mask] -= block[mask].mean()

source = ArraySource(signals, sample_rate_hz=rate, validity=valid)
spec = CorrelationSpec(pairs=(("a", "b"),), window_samples=window,
                       windows_per_result=group, output="lag", lag_mode="linear")
# The second pass reads each interval with `limit` more samples on both sides.
wide = ArraySource({name: np.pad(values, limit) for name, values in signals.items()},
                   sample_rate_hz=rate,
                   validity={name: np.pad(mask, limit) for name, mask in valid.items()})
whole_spec = CorrelationSpec(pairs=spec.pairs, window_samples=interval_size + 2 * limit,
                             hop_samples=interval_size, output="lag", lag_mode="linear")
for result, whole in zip(correlate_series(source, spec),
                         correlate_series(wide, whole_spec), strict=True):
    inside = np.abs(result.lag_samples) <= limit
    lags = result.lag_samples[inside]
    counts = result.lag_valid_samples[0, inside]
    nwin = len(result.window_starts)
    possible = nwin * (window - np.abs(lags))
    interval = (result.sample_start, result.sample_stop)
    if not result.valid[0] or np.any(counts < 0.5 * possible):
        print(interval, "insufficient coverage", "minimum fraction", (counts / possible).min())
        continue
    scores = np.abs(result.lag[0, inside]) * nwin / counts
    if not np.all(np.isfinite(scores)):
        print(interval, "nonfinite correlation")
        continue
    bins = np.flatnonzero(scores >= 0.5 * scores.max())
    adjacent = len(bins) == 2 and bins[1] == bins[0] + 1
    if np.any(np.abs(lags[bins]) == limit) or (len(bins) > 1 and not adjacent):
        print(interval, "unresolved peak")
        continue
    # A pulse can span two windows or two intervals. Include those
    # cross-boundary pairs before accepting a lag from the individual windows.
    whole_inside = np.abs(whole.lag_samples) <= limit
    whole_counts = whole.lag_valid_samples[0, whole_inside]
    if not whole.valid[0] or np.any(whole_counts < 0.5 * (interval_size - np.abs(lags))):
        print(interval, "insufficient full-interval coverage")
        continue
    whole_scores = np.abs(whole.lag[0, whole_inside]) / whole_counts
    whole_bins = np.flatnonzero(whole_scores >= 0.5 * whole_scores.max())
    if not np.all(np.isfinite(whole_scores)) or not np.array_equal(bins, whole_bins):
        print(interval, "unresolved peak across window boundaries")
        continue
    label = "adjacent competing bin" if adjacent else "candidate lag"
    for index in bins:
        lag = int(lags[index])
        print(interval, label, lag, "samples", lag / rate, "s",
              "valid pairs", int(counts[index]), "of", int(possible[index]))
```

Within each interval, the example subtracts each channel's valid-sample
mean and compares the magnitude of the mean product per valid pair. It
reports an isolated integer lag when its score exceeds twice every other
score and a correlation over the interval and `max_lag_samples` more samples
on each side confirms the same peak. The printed
support counts refer to the original non-overlapping windows. When two
adjacent bins compete, report both lags and their support. A fractional
delay can produce such a peak. The two values are diagnostic samples of the
curve. Estimating a sub-sample delay or a formal interval requires further
analysis. These coverage and peak thresholds are illustrative choices for
broadband signals. Inspect the lag curve for periodic or broader peaks, and
revisit the allowed range if a competing bin meets the search boundary.

## Check a narrow search against noise

The peak rule compares one score with the others inside the search range, so
a search of a few lags gives it little to reject. With a radius of two
samples, independent noise yields a candidate lag in about one recording in
ten and two adjacent competing bins in about one in fifteen. When the radius
is below 20 samples, run this control after the example and before reporting
a lag. It shifts channel B far outside the search range, so no real delay
remains, and counts for each interval how often the same rule still finds
one isolated lag.

```python
interval_spec = CorrelationSpec(pairs=spec.pairs, window_samples=interval_size,
                                output="lag", lag_mode="linear")

def isolated(a, b, a_ok, b_ok):
    control = ArraySource({"a": a, "b": b}, sample_rate_hz=rate,
                          validity={"a": a_ok, "b": b_ok})
    picks = []
    for one in (spec, interval_spec):  # per window, then the full interval
        out = next(iter(correlate_series(control, one)))
        keep = np.abs(out.lag_samples) <= limit
        pairs = np.maximum(out.lag_valid_samples[0, keep], 1)
        score = np.abs(out.lag[0, keep]) / pairs
        picks.append(out.lag_samples[keep][score >= 0.5 * score.max()])
    return len(picks[0]) == 1 and np.array_equal(*picks) and abs(picks[0][0]) < limit

rng = np.random.default_rng(0)
for start in range(0, full_windows * window, interval_size):
    part = slice(start, start + interval_size)
    shifts = rng.integers(interval_size // 4, 3 * interval_size // 4, 300)
    passed = sum(isolated(signals["a"][part], np.roll(signals["b"][part], s),
                          valid["a"][part], np.roll(valid["b"][part], s))
                 for s in shifts)
    print((start, start + interval_size), "control passed the peak rule in",
          passed, "of", len(shifts), "trials")
```

The share of passing trials estimates how often the rule reports a lag when
there is none. If more than 3 of 300 trials pass in an interval, report its
lag as unresolved, or widen the search to 20 samples or more and accept only
a peak that stays isolated there and lies within the plausible delay.

For the ordered pair `("a", "b")`, **+7 means B arrives seven samples later than
A**. Reversing the order in `pairs` should reverse the sign with the same
magnitude and support. Report the channel order, supplied rate, sample
intervals, lag in samples and seconds, and peak coverage. Compare independent
intervals before reporting a common delay. Inconsistent peaks, competing
periods or an isolated peak in noise can leave the delay unresolved. A
correlation peak alone cannot distinguish clock offset from propagation time.

For HDF5 inputs and the definitions of lag and per-lag support, see the
[cuPhoton 0.2.2 signal correlation guide](https://github.com/NVIDIA/cuPhoton/blob/v0.2.2/docs/guide/correlate.qmd).

---

Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

The license files are attached. [Apache 2.0](https://knowen.md/f/d1b26c59-a154-4da4-a063-aca638c651b1) · [CC BY 4.0](https://knowen.md/f/7f7aaa6a-a0bf-4460-9b22-48da4ce0fdc9)

The attached ZIP contains the pinned supporting files cleared for import. Applicable license notices are attached or included when cleared.