Skip to content

analyze_listmode

Kamil Brylew edited this page Oct 14, 2026 · 3 revisions

MCA List-Mode Analysis

MCA event analysis must distinguish transport version, producer schema, and file finalization. The easiest supported route is Tools → PSD Event Readback…, which accepts NLab NDMA, HDF5, ROOT, and compatible CAEN event files without loading the complete run into memory.

Formats encountered in analysis

Input Event representation
Legacy NDMA v1 marker, zc_offset, zc_estimation, short_energy, energy, timestamp
IIO NDMA v2 opaque transport decoded as marker, zero-crossing fields, charge/trapezoid energy, timestamp
Direct HDF5/ROOT canonical timestamp, long_gate, short_gate, marker and zero-crossing fields
Converted NDMA HDF5 source-version event dtype plus convenience datasets
CAEN accepted only when raw long/short energy fields pass format validation

An identical 16-byte record size does not make legacy and IIO NDMA records interchangeable. Always inspect the NDMA version and capture metadata.

Inspect and iterate with project readers

The PSD reader normalizes discovery while yielding bounded native batches:

from pathlib import Path

from nlab.analysis.psd_file import (
    inspect_psd_event_file,
    iter_psd_event_batches,
)

path = Path("measurements/events.bin")  # .bin, .h5, .hdf5, or .root
info = inspect_psd_event_file(path)

print(info.format_name)
print("channel:", info.channel)
print("records:", info.total_events)

for batch in iter_psd_event_batches(path):
    print(batch.dtype.names, len(batch))
    break

Binary files are memory-mapped and copied one bounded batch at a time. HDF5 is sliced up to committed_events; ROOT uses chunked tree iteration.

Select long and short fields explicitly

The batch keeps names appropriate to its source. Make the choice visible:

def gate_fields(names: tuple[str, ...]) -> tuple[str, str]:
    fields = set(names)
    if {"long_gate", "short_gate"} <= fields:
        return "long_gate", "short_gate"
    if {"trapezoid_energy", "charge_energy"} <= fields:
        return "trapezoid_energy", "charge_energy"
    if {"energy", "short_energy"} <= fields:
        return "energy", "short_energy"
    raise ValueError(f"unsupported event fields: {sorted(fields)}")

For IIO data, whether trapezoid/charge values are the physically intended long/short quantities depends on the qualified producer configuration. Preserve the client schema and hardware configuration with the result.

Bounded PSD accumulation

import numpy as np

energy_edges = np.linspace(0, 65536, 513)
ratio_edges = np.linspace(-1.0, 1.0, 513)
matrix = np.zeros((len(energy_edges) - 1, len(ratio_edges) - 1), dtype=np.uint64)
records = 0

for batch in iter_psd_event_batches(path):
    assert batch.dtype.names is not None
    long_name, short_name = gate_fields(batch.dtype.names)
    long_gate = batch[long_name].astype(np.float64)
    short_gate = batch[short_name].astype(np.float64)

    valid = long_gate != 0
    ratio = np.empty(len(batch), dtype=np.float64)
    ratio.fill(np.nan)
    ratio[valid] = (long_gate[valid] - short_gate[valid]) / long_gate[valid]

    accepted = valid & np.isfinite(ratio)
    update, _, _ = np.histogram2d(
        long_gate[accepted],
        ratio[accepted],
        bins=(energy_edges, ratio_edges),
    )
    matrix += update.astype(np.uint64)
    records += len(batch)

print("records scanned:", records)
print("events in PSD matrix:", int(matrix.sum()))

The chosen energy axis remains raw. Apply a documented calibration afterward; do not overwrite source fields or silently reuse an MCA histogram binning shift.

Timestamp checks

Timestamps are uint64 ticks. Current NLab list-mode ticks are 8 ns, but fine coincidence timing additionally depends on the named zero-crossing schema.

Within each stream, count backwards/duplicate transitions before calculating rate. Subtract in uint64-safe bounded form rather than converting absolute timestamps to float first; floats above 2^53 cannot preserve adjacent ticks.

For paired-channel validation, use Developer → Validate Two-Channel Timing…. Its nearest-neighbour diagnostic is not a coincidence count. For live pairing and the exact Q2.14 timing equation, see Coincidence Measurement.

Final-frame zero padding

IP121 always transports complete 1,024-record frames. When acquisition stops part-way through a frame, unused slots may be all zero. The ABI provides no exact valid-record count, and a real event can also contain zeros.

Therefore:

  • raw conversion preserves every slot;
  • run summaries count transported records, not exact accepted pulses;
  • analysis may report/exclude a trailing all-zero run only as an explicit, documented policy;
  • zero payload must never be treated as an infallible stream terminator.

Integrity before physics

Before using a distribution, verify:

  1. NDMA version or structured schema is recognized.
  2. Binary payload is aligned to complete records/frames.
  3. .run.json exists and reports the expected continuity state.
  4. IIO sidecar SHA-256, frame count, DMA fault, and list deadtime are valid.
  5. HDF5 analysis does not read beyond committed_events; final work requires capture_complete=true.
  6. Coincidence channel files agree with the common session manifest.

Legacy NDMA v1 captures cannot prove transport continuity and remain unverified. See Capture Files and Integrity for detailed metadata.

Energy spectra

Select the energy field and any right shift from the producer/configuration or a documented comparison with a hardware histogram. Do not infer a shift from field width or apply the MCA histogram binning selector twice. Keep overflow counts separate from in-range bins.

For fitted spectra, calibrated overlays, background subtraction, variance propagation, and export, use the MCA Peak Analysis Workbench described in Analysis Tools.

Common mistakes

  • Decoding IIO NDMA v2 with the legacy v1 dtype.
  • Treating padding count as accepted-pulse count.
  • Ignoring run/driver continuity metadata.
  • Converting large absolute timestamps to float before subtraction.
  • Assuming zc_offset is signed or heuristically unwrapping it.
  • Treating long_gate/short_gate names as a complete producer specification.
  • Loading a complete HDF5/ROOT run when bounded iteration is available.

Clone this wiki locally