User guide¶
This page walks through the SDK from end to end. For a focused tour see the Quickstart on the home page; for hands-on code see the Examples.
Opening a file¶
The File class is the single entry point. It auto-detects the
format from the file suffix:
from invisensing import File
f = File("acquisition.dat") # DAT, native Rust reader
f = File("acquisition.h5") # HDF5 via h5py
f = File("acquisition.tdms") # TDMS via npTDMS
f = File("acquisition.sgy") # SEG-Y via segyio
If your file has no recognised suffix, pass format= explicitly:
Use it as a context manager — the underlying file handle is closed cleanly even when an exception is raised:
with File("acquisition.dat") as f:
...
# file descriptor released here, not whenever `f` is collected
Outside a with block, call f.close() yourself. It is idempotent
(closing twice, or closing after a with, is a no-op) and it releases
the descriptor at the call, not at collection time:
A File that is neither closed nor used as a context manager emits a
ResourceWarning when it is finally collected. Like the one CPython's
built-in open() emits, it is silent by default and shows up under
python -W default, python -X dev and pytest. It matters on a
long-running process that walks a data tree — a labelling server, a
dashboard backend: one leaked descriptor per file ends in EMFILE, and
on an NFS/CIFS mount an open handle also blocks the file from being
deleted or replaced.
What a closed file still knows¶
Closing gives up the descriptor, not what was read from it. The
header is parsed once, at open, and stays on the object, so a closed
File still describes its recording:
with File("acquisition.dat") as f:
data = f.read_all()
# outside the block: the handle is gone, the description is not
dt = 1.0 / f.trig_frequency_real_hz # fine
axis = np.arange(f.num_lines) * dt # fine
f.mode, f.dtype, f.shape, f.is_interleaved, repr(f) # all fine
That is deliberate: asking a file you have already closed what its sample rate was is a normal thing to do, not a mistake, and raising there would break correct scripts for nothing.
What does raise ValueError after close() is anything that would have
to touch the file again — read_lines(), read_all(), rewind(),
seek_lines(), iterating the file — plus lines_left, which is the
position of a read cursor on a handle that no longer exists (use
num_lines to describe the file itself). numpy arrays already returned
by read_lines() or the channel extractors own their memory and stay
valid — closing never invalidates data you already hold, and the channel
extractors still accept a buffer you read before closing:
f = File("acquisition.dat")
buf = f.read_lines(1000)
f.close() # release the handle as early as you can
i, q = f.get_i(buf), f.get_q(buf) # arithmetic on your array, no file
One caveat: do not share a File across threads. Closing a .dat
while another thread is inside read_lines() on the same object cannot
release the descriptor immediately — the native reader is borrowed for
the length of that read — so the release is deferred to the end of that
read. close() still returns without raising and emits a
ResourceWarning saying so, rather than reporting a file as closed
while its handle is still open.
Inspecting metadata¶
Every File exposes the parsed header as plain Python
properties — no struct unpacking, no flag bit-twiddling:
with File("acquisition.dat") as f:
f.line_size # samples per pulse on the wire
f.positions_per_line # spatial fibre positions per pulse
f.sample_size # bytes per sample (2, 4, 8…)
f.sample_rate # Hz
f.trig_frequency # Hz, the REQUESTED trigger rate (int)
f.trig_frequency_real_hz # Hz, the rate the card really fired at (float)
f.trig_frequency_is_exact # True when both are equal (or unknown)
f.trig_clock_hz # card rational (int), or None when unknown
f.trig_period_ticks # real rate = trig_clock_hz / trig_period_ticks
f.line_time_ns(i) # acquisition time of pulse i, int ns since epoch
f.num_lines # total trigger pulses recorded
f.lines_left # pulses behind the read cursor
f.duration # seconds (= num_lines / trig_frequency_real_hz)
f.distance # metres of fibre covered per pulse
f.light_speed_in_fiber_m_s # m/s the metres are labelled with (2e8 on old files)
f.fiber_group_index # its fibre group index (1.4682; 1.49896229 on old files)
f.range # ADC voltage range (V)
f.timestamp # start time as the format spells it
f.content_type_name # what the samples are ("dui_coherent_phase", "hw_amplitude"…)
f.quantity, f.unit # "phase", "rad" — from the content type
f.card # card code: "p18", "p21", "s125", "s500", or None
f.format_version # 1 for data format v1, 0 before
f.duration_s # whole seconds the writer recorded, or None
f.spatial_step_m # metres between two positions
f.temporal_step_s # seconds between two lines
f.sibling_path # the other file of a split pair, or None
f.compression # HDF5: "NONE" / "ZSTD" / "ZSTD_LOSSY_1E4"
f.trailing_bytes # DAT cut mid-line: bytes not read (0 normally)
f.dtype # numpy dtype of the wire samples
f.shape # (num_lines, line_size)
f.spatial_shape # (num_lines, positions_per_line)
# Flag predicates — properties, work in if/while idioms.
if f.is_demodulated and f.is_interleaved:
...
f.is_demodulated, f.is_interleaved, f.is_float, f.is_phase
f.is_unsigned, f.is_ac, f.is_hiz
The fibre group index (since 1.7.0)¶
A DAS times the round trip of a pulse; the speed of light in the fibre
v turns that time into metres, one position spanning v / (2 ·
sample_rate). v = c / n, with n the fibre's group index (the
"IOR" an OTDR is programmed with). The Audace acquisition takes n as a
parameter — default 1.4682, Corning SMF-28e+ at 1550 nm — derives one
whole speed v = round(c / n) m/s, half away from zero, and writes it into
every file:
| Format | Speed | Index |
|---|---|---|
| DAT | header bytes 124..128, u32 | — (the index of the speed) |
| HDF5 | root attribute light_speed_in_fiber_m_s, u32 |
attribute fiber_group_index, f64, exactly as configured |
| TDMS | property light_speed_in_fiber_m_s |
property fiber_group_index |
| SEG-Y | textual line FIBER GROUP INDEX: n (LIGHT SPEED v M/S) |
the same line |
Every metre the SDK reports — distance, spatial_step_m,
gauge_length_m, trigger_delay — is at the file's speed, exposed as
f.light_speed_in_fiber_m_s (int) and f.fiber_group_index (float):
| n | v (m/s) | step at 62.5 / 125 / 250 / 500 / 1000 MS/s |
|---|---|---|
| 1.4682 (default) | 204 190 477 | 1.633524 / 0.816762 / 0.408381 / 0.204190 / 0.102095 m |
| 1.49896229 (legacy) | 200 000 000 | 1.6 / 0.8 / 0.4 / 0.2 / 0.1 m |
Old recordings. A file written before the field carries no speed: it was acquired at the legacy 2·10⁸ m/s (index 1.49896229) and reads exactly as with 1.6.0, bit for bit. When its fibre is known, label it at its index:
with File("phase/2026-06-01_10-00-00.dat", fiber_group_index=1.4682) as f:
f.fiber_group_index # 1.4682
f.recorded_fiber_group_index # 1.49896229 — what the file says
f.spatial_step_m # 1.633524 at 62.5 MS/s (1.6 as recorded)
The samples never change — the card samples time — only their labels: the
speed becomes round(c / n); the spatial step is the pitch at the new
speed (an archive export's zone spacing is scaled by v' / v); a gauge of
k whole positions becomes k · v' / (2 · sample_rate); the trigger
pre-roll is scaled to the nearest metre. The strain factors follow the
gauge. f.header is the relabelled header (Header.with_fiber_group_index),
so f.export_dat() writes the new speed. Any index from 1 to 100 is
accepted; below 1, above 100, NaN or infinite raise ValueError.
light_speed_of_group_index(n) and group_index_of_light_speed(v) are the
acquisition's own conversions (the latter gives back 1.4682 and 1.49896229
exactly, c / v for any other speed); LEGACY_LIGHT_SPEED_IN_FIBER_M_S,
LEGACY_FIBER_GROUP_INDEX and DEFAULT_FIBER_GROUP_INDEX name the two
indexes.
Requested vs. real trigger frequency¶
A card fires on a divided clock: it hits the requested rate exactly only
when that rate divides its clock. A 250 MHz card asked for 75 kHz fires
every 3333 ticks, at 250e6 / 3333 = 75007.5008 Hz (+100 ppm); timing
the lines on 75 000 Hz drifts by 0.36 s per hour. Since 1.3.0 the SDK
reads the card's exact rational from the recordings that carry it (HDF5
attributes trig_clock_hz, trig_period_ticks, trig_frequency_real_hz;
header bytes 88..96 of a .dat):
| Property | Meaning |
|---|---|
trig_frequency |
the requested rate, an int (unchanged) |
trig_frequency_real_hz |
the rate the card fired at, a float — trig_clock_hz / trig_period_ticks, else HDF5's trig_frequency_real_hz, else float(trig_frequency) |
trig_frequency_is_exact |
True when real == requested, and when the real rate is unknown |
trig_clock_hz, trig_period_ticks |
the card's rational, or None (older files, external trigger, TDMS, SEG-Y) |
line_time_ns(i) |
header.acquisition_ns + ⌊i · ticks · 10⁹ / clock⌋ (else ⌊i · 10⁹ / trig_frequency⌋), an exact int |
duration |
num_lines / trig_frequency_real_hz |
Compute time axes and durations on trig_frequency_real_hz (or with
line_time_ns); keep trig_frequency for sizing (pulses per block) and
labels. At an exact rate and on every file without the rational, the
results are bit-for-bit those of 1.2.x. A rational more than 1 % (and
more than 1 Hz) away from trig_frequency cannot describe the file and
is ignored (trig_clock_hz is then None; the stored values stay in
f.header.trig_clock_hz / f.header.trig_period_ticks).
Corrected line times (since 1.4.0)¶
The card's oscillator is a few ppm off the host clock (and far more when its external 10 MHz reference is missing), and shots the card loses shift every later line: counting lines from the start drifts by tens of ms an hour. The Audace acquisition measures that drift and publishes a time map that every module of the chain evaluates the same way; the recorder writes the part of it covering each HDF5 file into its attributes. The SDK reads it:
| Property / method | Meaning |
|---|---|
line_time_ns(i) |
on a file with time_correction == "cardclock-v1": the corrected time of line i on the file's axis (time_map_line / time_map_ns / time_map_period_fs: from node k on, ns[k] + ⌊(i − line[k]) · period_fs[k] / 10⁶⌋), the very integer the acquisition gave it; else the count, as in 1.3.0 |
line_time_ns(i, nominal=True) |
the count, as 1.3.0 computed it (from timestamp_nominal_ns when the file carries it) |
times_ns(start=0, count=None) |
the same times as an int64 numpy vector (native core, exact), never past the file's last line; MemoryError if it cannot be allocated |
time_correction |
"cardclock-v1", "none" (timed by the count), or None (the file does not say: older files) |
time_correction_state |
the least favourable state over the file ("tracking", "prior", "slewing", "suspect", "provisional"…) |
time_uncertainty_ns |
estimated uncertainty (1 σ) of the corrected time |
trig_frequency_measured_hz |
the card's cadence measured against the host clock |
duration |
on a corrected file, measured on its corrected times (first to last line) |
timestamp_ns (and header.acquisition_ns) of a corrected HDF5 is the
corrected time of its first line; timestamp_nominal_ns is the count. A
DAT keeps its format: its start time is the corrected one when
f.header.time_corrected is True (bit TIME_FLAG_CORRECTED of header
bytes 100..104), and lines count from there. TDMS and SEG-Y carry neither
an absolute time nor the time flags (header.acquisition_ns is 0): their
lines are timed from the start of the file.
Keep trig_frequency_real_hz as the sampling rate along time (spectra,
filters, Nyquist): the correction moves the time labels, not the samples.
Every file written before the time map is timed exactly as 1.3.0 timed it.
The node's clock at the run's START¶
Every line's time is anchored on the node's clock when the run started. An HDF5 file recorded since 2026-11-22 says whether that clock was trusted:
| Property | Meaning |
|---|---|
host_clock_synchronized |
HostClockSync.SYNCHRONIZED, NOT_SYNCHRONIZED or UNKNOWN (attribute host_clock_synchronized); .synchronized gives True / False / None |
start_time_guard |
how the START passed the console's time guard: StartTimeGuard.OPEN, WAIVED (a node offline with no time source), LIFTED or LIFTED_PERMANENT (a forced START, past a guard an administrator lifted), UNKNOWN (attribute start_time_guard); .forced gives True / False / None |
Both are None on a file that does not record them: HDF5 files written
before 2026-11-22, and every DAT, SEG-Y and TDMS file. Those formats have no
place for them: the manifest beside the files does (run-….json of a
continuous recording, save-….json of a buffered save, with the time of
each file's first and last line, t_start_ns and t_last_ns); read it as
JSON. A value this SDK does not know reads UNKNOWN, never synchronised.
What a file holds (Mode enum)¶
file.mode comes from the file's content type — what the samples
are, one value per quantity, sample type and producing chain
(invisensing.content). A file written before the content type existed
(content_type == 0) is read from its header flags, exactly as before;
so are the few files written before data format v1 whose content type
does not describe them (Header.mode_from_flags: a sw_custom file of an
older Sandbox, a console archive export under a paired content type
without the INTERLEAVED flag).
Since data format v1 a recording holds one quantity per file: an
interleaved product (I/Q, arctan/magnitude, phase/amplitude) is written as
two files, same name, sibling directories, and f.sibling_path finds the
other one. The paired modes are the files written before.
from invisensing import Mode
with File("acquisition.h5") as f:
mode = f.mode
if mode is Mode.RAW: ...
elif mode is Mode.PHASE: ...
elif mode is Mode.AMPLITUDE: ...
elif mode is Mode.ARCTAN: ...
elif mode in (Mode.I, Mode.Q): ...
elif mode is Mode.IQ: ...
elif mode is Mode.ARCTAN_MAGNITUDE: ...
elif mode is Mode.PHASE_AMPLITUDE: ...
Mode |
Layout per pulse | What it is |
|---|---|---|
RAW |
[s₀, s₁, …, s_{N-1}] |
Raw ADC codes, no demodulation |
PHASE |
[φ₀, φ₁, …] |
A phase in radians (f32): the card's, or a software demodulation's (content_type_name says which) |
AMPLITUDE |
[a₀, a₁, …] |
An amplitude: the card's √(I²+Q²) (u16, or f32), or a software front end's (f32) |
ARCTAN |
[arctan₀, arctan₁, …] |
The card's wrapped arctan(Q/I), i16, 32767 ↔ +π |
I, Q |
[I₀, I₁, …] |
The card's I or Q, i16 |
CUSTOM |
A script's output | |
VARIANCE, LOG_VARIANCE |
Zone variances exported from the console's archives (get_variance, get_log_variance) |
|
IQ |
[I₀, Q₀, I₁, Q₁, …] |
I/Q pairs (files written before data format v1) |
ARCTAN_MAGNITUDE |
[arctan₀, √₀, arctan₁, √₁, …] |
arctan(Q/I) + √(I²+Q²) pairs (same) |
PHASE_AMPLITUDE |
[φ₀, a₀, φ₁, a₁, …] |
Phase + amplitude pairs (same) |
The SDK is mode-faithful, not mode-translating
The library never silently re-derives one product from
another. The acquisition's demodulation chain is not reproducible in
software from an earlier tap, so the channel you can extract is the
one the acquisition wrote. Calling the wrong extractor raises a
ValueError that names both modes:
Extracting channels¶
Every extractor has the same shape: (rows, positions_per_line),
typed with the most natural dtype for the lane. Each one accepts an
optional pre-read buffer so you can reuse it across extractors
without double-advancing the cursor:
with File("iq.dat") as f:
chunk = f.read_lines(1000)
i = f.get_i(chunk) # reuses the buffer
q = f.get_q(chunk) # same — no extra file read
iq = f.get_iq(chunk) # same again
Default extractors — wire dtype¶
Fast, no copy beyond the de-interleave, no precision loss on round-trip writes.
Mode |
Method | dtype | Notes |
|---|---|---|---|
RAW |
read_lines() |
int16 |
ADC codes |
IQ |
get_i() / get_q() |
int16 |
One lane each |
IQ |
get_iq() |
complex64 |
I + j·Q packed |
ARCTAN_MAGNITUDE |
get_arctan() |
int16 |
Fixed-point: 32767 ↔ +π |
ARCTAN_MAGNITUDE |
get_magnitude() |
uint16 |
Bitcast from wire i16 |
PHASE |
get_phase() |
float32 |
Radians (already converted) |
Physical-unit extractors — float32¶
When you start doing DSP, you typically want volts and radians, not
fixed-point codes. The _volts / _radians family does the
scaling for you:
Mode |
Method | dtype | Unit | Scaling |
|---|---|---|---|---|
IQ |
get_i_volts() / get_q_volts() |
float32 |
V | i16 × range / 32768 |
IQ |
get_iq_volts() |
complex64 |
V | real/imag both in volts |
ARCTAN_MAGNITUDE |
get_arctan_radians() |
float32 |
rad | i16 × π / 32768 |
ARCTAN_MAGNITUDE |
get_magnitude_volts() |
float32 |
V | u16 × range / 32768 |
with File("iq.dat") as f:
iq_v = f.get_iq_volts() # complex64, volts
envelope_v = np.abs(iq_v) # volts
phase_rad = np.angle(iq_v) # radians, wrapped
Memory cost of physical units
Default extractors keep the wire dtype — a 4 GB i16 capture
becomes a 4 GB numpy array. The _volts / _radians family
allocates a new float32 buffer (2× the size for i16/u16
inputs, 8× for the complex64 get_iq_volts). For
multi-GB captures, prefer the wire dtype + an explicit
.astype(np.float32) * scale inside your processing loop.
Get every channel in one call¶
For ad-hoc scripts, channels() returns a dict keyed by mode:
with File("iq.dat") as f:
ch = f.channels()
# {"i": int16, "q": int16, "iq": complex64}
with File("arctan_mag.dat") as f:
ch = f.channels()
# {"arctan": int16, "magnitude": uint16}
Phase as strain, in nm/m (since 1.6.0)¶
A differential phase measured over a gauge of g metres of fibre is a
strain. File(path, phase_unit="nanostrain") reads every phase sample as
strain, in nm/m, while it is read:
from invisensing import File
with File("phase/2026-11-12_10-00-00.h5", phase_unit="nanostrain") as f:
f.gauge_length_m # 9.6 — the gauge the producer applied
f.nanostrain_per_rad # float32(110.37 / 9.6) — the factor applied
f.unit, f.quantity # "nm/m", "strain" (f.mode stays Mode.PHASE)
strain = f.get_phase() # float32, nm/m
Where NANOSTRAIN_PER_RAD_METRE comes from
The DAS phase over a gauge L relates to the strain ε by
ΔΦ = 2β(n + Cε)·ε·L, with β = 2π/λ, n the refractive index of the
fibre core and Cε the photo-elastic coefficient. At λ = 1550.12 nm and
n = 1.46 this gives 110.37 nm/m per rad/m
(invisensing.NANOSTRAIN_PER_RAD_METRE). It is a constant of the SDK,
not a parameter. Its n is the core's phase index: it does not follow
the fibre group index the file's metres are labelled at
(f.fiber_group_index). The gauge length, a distance, does.
The gauge length is the one the producer applied — the distance
between the two ends of the differential gauge, a whole number of the
stream's positions — never the length the configuration asked for. Audace
writes it on a phase only, and only from the release that adds it: DAT
header bytes 120..124
(float32), HDF5 root attribute and TDMS property gauge_length_m
(float64), SEG-Y textual line GAUGE LENGTH: <m> METRES. A DAT's float32
is read back as the float64 the other formats store, so the DAT and the
HDF5 of one recording give the same strain to the bit.
File.gauge_length_m is None without one.
Refusals. Opening with phase_unit="nanostrain" raises ValueError
(the message names the content type) when:
- the file holds no phase — raw samples, I/Q, the card's arctan, amplitudes, a script's output, zone variances;
- the phase does not record its gauge length — every recording made before the Audace release that writes it (strain and strain rate need a recording made with that release or a later one), a MOZART / MOZART_PLUS phase (its gauge is set by the optics, not by software), a file read from its flags (content type 0). No gauge length is ever assumed: read such a file in radians.
What is converted. Every read path: read_lines, read_all,
iteration, get_phase, channels, the legacy get_lines. A buffer you
pass back to an extractor (f.get_phase(block)) is taken as read — it is
never converted twice. On a file of phase/amplitude pairs (written before
data format v1) only the phase lanes are converted; get_amplitude() is
the amplitude as stored, and f.unit reads "nm/m+count".
quantization_step_rad and quantization_max_error_rad of a
ZSTD_LOSSY_1E4 file stay in radians (times nanostrain_per_rad they are
in nm/m). export_dat() writes the file's own samples, in radians.
Precision. The factor NANOSTRAIN_PER_RAD_METRE / gauge_length_m is
computed once in float64 and rounded once to float32; each phase sample
then takes one float32 multiply by it (round to nearest even), so the
result is exactly phase * np.float32(110.37 / g) and the dtype stays
float32. A float64 phase (a third-party HDF5) is converted in float64
with the float64 factor.
Speed. The multiply runs in place on the buffer just read, in the Rust
core, with AVX-512F or AVX2 kernels chosen at run time — each one
bit-identical to the scalar loop — and the GIL released on large reads.
invisensing._core.simd_level() names the kernel in use;
INVISENSING_SIMD=scalar|avx2|avx512 caps it for a process. It is
memory-bound: about the speed of numpy's in-place np.multiply(a, f,
out=a), four times faster than a / g * K, which allocates two
temporaries.
Phase as strain rate, in nm/m/s (since 1.6.0)¶
A phase file holds the accumulated (unwrapped) phase of each line, not a
per-line increment. File(path, phase_unit="strain_rate") reads every
phase sample as the strain rate of its line, in nm/m/s: the strain
increment from the previous line times the line rate.
strain_rate[n] [nm/m/s] = (strain[n] − strain[n−1]) [nm/m] × f_trig [Hz]
= (phase[n] − phase[n−1]) [rad] × NANOSTRAIN_PER_RAD_METRE / gauge_length_m × f_trig
strain is the phase_unit="nanostrain" reading above, and f_trig the
rate the card really fired at, File.trig_frequency_real_hz — the
requested trig_frequency on a file that does not carry the exact clock
(see Requested vs. real trigger frequency).
from invisensing import File
with File("phase/2026-11-12_10-00-00.h5", phase_unit="strain_rate") as f:
f.strain_rate_per_rad # float32(110.37 / 9.6 × f_trig) — the factor applied
f.unit, f.quantity # "nm/m/s", "strain rate" (f.mode stays Mode.PHASE)
rate = f.get_phase() # float32, nm/m/s — rate[0] is NaN
f.time_gaps # ((10, 11), ...) — the lines after lost shots
A phase ramp of a rad per line reads a × 110.37 / g × f_trig nm/m/s
on every line; a sine sin(ωt) reads 2 f_trig sin(ω / 2f_trig) ·
cos(ω(t − 1/2f_trig)) × 110.37 / g, i.e. ω cos(ωt) × 110.37 / g half a
period earlier, to first order in ω / f_trig.
Line 0 is NaN. The first line of a file has no previous line: its phase lanes read NaN. A file is read on its own; the previous file of the same recording is never opened.
Gaps are NaN. On an HDF5 stamped from the card's time map
(File.time_correction == "cardclock-v1"), File.time_gaps lists, as
(first, end) ranges, the lines that come more than 1.5 line periods
after the previous one on the corrected time axis — the line after shots
the card lost. Their increment spans several periods: they read NaN, never
an increment divided by one period. A file timed by its count (DAT, TDMS,
SEG-Y, an HDF5 without the time map) carries no gap: every increment is
taken as one period. A drift of the card's oscillator is no gap (the line
rate stays trig_frequency_real_hz, like a spectrum's sampling rate).
Blocks and seeks are seamless. Every read path (read_lines,
read_all, iteration, get_phase, channels, get_lines) carries the
last line it read, as stored, to the next read: reading the file in blocks
of any size gives the bits of read_all(). After seek_lines(k) or
rewind(), the next read first reads line k − 1 back (nothing for
line 0), so an oscilloscope that seeks one line per frame gets the same
values as a straight read.
Refusals. Those of phase_unit="nanostrain" (no phase, no gauge
length), and a file whose trigger frequency is unknown (trig_frequency
0): a ValueError at open.
Precision. The factor NANOSTRAIN_PER_RAD_METRE / gauge_length_m ×
f_trig is computed once in float64 and rounded once to float32; each phase
sample then takes one float32 subtraction of the previous line's stored
phase and one float32 multiply by the factor, in that order — exactly
(x[n] - x[n-1]) * np.float32(110.37 / g * f_trig), never x[n]·f −
x[n−1]·f, never a fused multiply-add. A float64 phase is converted in
float64. Pairs: only the phase lanes; the amplitude keeps its bits.
export_dat() writes radians.
Speed. One in-place pass in the Rust core (subtract, multiply, keep the
line for the next block) with the AVX-512F / AVX2 / scalar kernels of the
strain, bit-identical to each other. Memory-bound: on a 268 MB float32
block it runs at memcpy speed (≈ 11 GB/s on one core of an AVX-512
server), ≈ 3.7× numpy's np.diff(a, axis=0) * f.
Streaming large files¶
read_lines(n) advances a cursor in the file. Iterate to process
captures larger than memory:
For one-pulse-at-a-time processing, iterate the file directly:
For small files, read_all() returns everything in one allocation:
rewind() resets the cursor:
File formats — what each backend does¶
The File facade dispatches to a format-specific backend. All four
funnel through the same Header so the channel extractors above are
format-agnostic.
DAT — native Rust¶
128-byte header + raw little-endian samples. Read by the native
invisensing._core.DatReader — no third-party dep, no Python
overhead in the hot loop. The most common format and the fastest
path.
HDF5 — via h5py¶
Audace HDF5 files (.h5 since data format v1, .hdf5 before; both
are read) store the samples as a (num_traces, samples_per_trace)
dataset named acoustic_data, typed by the content type (int16,
uint16, float32; on older files by bytes_per_sample and the FLOAT
attribute). Every header field is mirrored as a scalar attribute — with
data format v1 also format_version, card, duration_s and the steps
in f64, gauge_length_m on a phase with a known gauge (from the
Audace release that writes it), and light_speed_in_fiber_m_s (u32) with
fiber_group_index (f64) since the fibre group index (absent: the legacy
2·10⁸ m/s). Lines are read slice by slice: a multi-GB capture never has
to fit in RAM.
Recordings written with the FileWriter's compression = ZSTD store the
dataset in chunks through the standard pipeline byte shuffle + zstd
(HDF5 filter 32015). invisensing imports hdf5plugin, a dependency,
so they open like any other file; outside it, run import hdf5plugin
before opening one with h5py, or the file does not open.
TDMS — via npTDMS¶
Single channel acoustic_data (lines flattened row-major) under one
group — Audace for files of data format v1, AudaceGroup in older ones.
Header fields travel as file-level properties.
SEG-Y — via segyio¶
One trace per line (trigger), whose samples run along the fibre:
samples_per_trace = line_size. Header fields not expressible in the
SEG-Y binary header are written as KEY: value lines of the textual
header (e.g. C16 - CONTENT-TYPE: dui_coherent_phase (19), C21 HEADER
FLAGS (raw bits): 0xNNNNNNNN, C24 CARD: p21, C26 FIBER GROUP INDEX:
1.4682 (LIGHT SPEED 204190477 M/S)). The SDK reads the 3200
bytes itself — in ASCII, what the acquisition writes, or EBCDIC — and
parses them back into a Header. Unsigned 16-bit samples are stored as
4-byte integers (BYTES PER SAMPLE: 2) and read back as uint16.
Writing files¶
export_dat() writes a 2-D numpy array out as an Audace .dat file
(128-byte header + raw samples):
from invisensing import export_dat
import numpy as np
samples = np.random.randn(10_000, 512).astype("float32")
export_dat(
"out.dat",
samples,
sample_rate=250_000_000,
trig_frequency=2_000,
range_v=1.0,
timestamp="2026-05-25_12:34:56",
)
Without a content type the FLOAT flag is set automatically when
data.dtype.kind == 'f'. To write a file of data format v1, say what the
samples are — content_type= (and card=) — or copy a source file's
whole header:
export_dat("phase.dat", samples, sample_rate=250_000_000, trig_frequency=2_000,
content_type=17, card="p21") # dui_phase, f32
with File("phase/2026-11-03_10-00-00.h5") as f:
f.export_dat("excerpt.dat", start=1000, count=500)
# or: export_dat("x.dat", my_array, header=f.header)
A v1 file keeps only the AC and HIZ flags, carries the steps (kept or
derived), the card code, the speed of light in the fibre and the duration
of the lines written; the data must be of the content type's sample type.
fiber_group_index=n stamps the speed of n (header bytes 124..128); with
header=, the header is relabelled at n first, as
File(path, fiber_group_index=n) does. A header of content type 0 (or
of pairs, or an unknown value) is copied as it is. A recording whose card
fired at an inexact rate is refused: a DAT never carries one.
Performance & safety notes¶
Performance¶
- DAT reads stream through a
BufReader<File>; the innerread_exactruns with the GIL released. - The typed-conversion path allocates an uninitialised
Vec<T>and fills it with onecopy_nonoverlapping. Skips the 4 GB of pointless DRAM writes avec![0; n]would do on a 4 GB read. - De-interleave kernels read via
as_slice()and iterate withchunks_exact(2)— LLVM auto-vectorises into SSE/AVX gather-extract instructions on x86_64. - HDF5 / TDMS / SEG-Y loading is C-backed by their respective libraries; the de-interleave step always runs through the same Rust kernels, so channel-extraction perf doesn't depend on the source format.
- The phase to strain conversion (
phase_unit="nanostrain") is one in-place multiply per sample with AVX-512F / AVX2 kernels chosen at run time, bit-identical to the scalar loop (see above); the strain rate (phase_unit="strain_rate") one in-place subtract-then-multiply pass on the same tiers.
Safety¶
- Strict header validation at open:
line_size > 0,sample_size ∈ {1, 2, 4, 8},INTERLEAVED ⇒ even line_size. Downstream maths can assume positive sizes everywhere. - Bounded
unsafe: three small blocks in the Rust extension, each one documented and exercised by 1-million-sample correctness tests — plus the SIMD strain kernels (calls of#[target_feature]functions once the CPU is known to run the feature, unaligned loads and stores within one-vector chunks), checked bit for bit against the scalar loop. - No
mmap: deliberate. Memory-mapped files turn I/O errors into SIGBUS (segfault) instead of Python exceptions, which is unacceptable in a long-running lab process. - Thread safety: each
Fileowns its own backend; sharing a singleFileacross Python threads is not supported. Open one per thread for parallel reads — they don't compete for any internal state.
Legacy SDK compatibility¶
The original invisensing.File module is preserved unchanged:
import invisensing.File as iFile
file = iFile.File("acquisition.dat")
file.get_line_size(), file.get_trigger_frequency()
file.is_demodulated(), file.is_acquisition_ac()
while file.get_lines_left() > 0:
data = file.get_lines(5)
process(data)
iFile.export("out.dat", data, file.get_timestamp(),
file.get_trigger_frequency(), file.get_sample_rate(),
file.get_range())
The legacy class delegates to the same Rust-backed implementation as
the modern File, so legacy scripts run at the new speed without any
modification.