Repository navigation
Description
Describe the bug
MicromedRawIO has three related problems with recordings from newer Micromed software. I found them reading a clinical archive of about 14.7k recordings, where 909 files carry a TRONCA table and 3,433 are header version 5 (no data from it is included here; the reproduction below is synthetic).
- The samples before the first
trace_offsetare never read. Segments are built from the table entries only (seg_limits = [trace_offset of each entry] + [n_samples]), so file samples[0, first trace_offset)belong to no segment. Nothing is raised or logged. In the archive the firsttrace_offsetis above 0 in 747 of the 909 files (median 3 min of signal lost, longest 15.8 h). - Event times are wrong for such files.
_get_event_timestampsreturnsstart + seg_start0(the first segment'sseg_start) for every segment. An eventstartis an index into the data block, the same coordinate astrace_offset, while a segment's time axis starts atseg_start / sampling_rate. The event of file samplesin segmentktherefore belongs atseg_start_k + (s - trace_offset_k). - Header version 5 is refused (
NotImplementedError). Relaxing the check is not enough: in version 5 files the zone names are padded with NULs (b"IMPED_B\x00") instead of spaces (b"IMPED_B "), so the.strip(" ")name comparison raisesNeoReadWriteError: expected the zone name to match. With the version check relaxed and the names stripped of both, every version 5 file I tried reads with the same channel names and exactly the same data as an independent reader (0.0 V difference). This is related to Intergrate changes to add micromed V5 reading #1858.
To Reproduce
The files below are written by a small generator (no patient data), so no test file is needed.
Generator (write_trc)
import struct
import numpy as np
ZONES = ["ORDER", "LABCOD", "NOTE", "FLAGS", "TRONCA", "IMPED_B", "IMPED_E", "MONTAGE", "COMPRESS",
"AVERAGE", "HISTORY", "DVIDEO", "EVENT A", "EVENT B", "TRIGGER"]
def write_trc(path, codes, fs=256, version=4, tronca=(), notes=(), triggers=()):
"""codes: (n_samples, n_channels) uint16 ADC codes. tronca: [(seg_start, trace_offset)]; notes: [(start, text)]."""
codes = np.asarray(codes, dtype="<u2")
n_samples, n_chan = codes.shape
zone = {z: bytes(16) for z in ZONES}
zone["ORDER"] = np.arange(n_chan, dtype="<u2").tobytes()
labcod = bytearray(n_chan * 128)
for c in range(n_chan):
struct.pack_into("<6s6s5ihxxxxxxxxH", labcod, c * 128 + 2, f"Ch{c + 1}".encode(), b"",
0, 65535, 32768, -4096, 4096, 0, 1) # logical 0..65535, ground 32768, +-4096 uV, unit uV, rate x1
zone["LABCOD"] = bytes(labcod)
note = bytearray((len(notes) + 2) * 44) # trailing unused slots have start 0
for i, (start, text) in enumerate(notes):
struct.pack_into("<I40s", note, i * 44, start, text.encode("cp1252"))
zone["NOTE"] = bytes(note)
table = bytearray((len(tronca) + 1) * 8) # a (0, 0) pair ends the table
for i, (seg_start, trace_offset) in enumerate(tronca):
struct.pack_into("<II", table, i * 8, seg_start, trace_offset)
zone["TRONCA"] = bytes(table)
trig = bytearray((len(triggers) + 2) * 6)
for i, (start, label) in enumerate(triggers):
struct.pack_into("<IH", trig, i * 6, start, label)
zone["TRIGGER"] = bytes(trig)
zone["EVENT A"] = zone["EVENT B"] = bytes(12)
pad = b" " if version == 4 else b"\x00" # version 4 pads zone names with spaces, version 5 with NULs
table_end = 176 + 16 * len(ZONES)
position, entries = table_end, b""
for z in ZONES:
entries += struct.pack("<8sII", z.encode().ljust(8, pad), position, len(zone[z]))
position += len(zone[z])
header = bytearray(table_end)
struct.pack_into("<6b", header, 128, 9, 3, 124, 10, 30, 15) # a date
struct.pack_into("<IHHHH", header, 138, position, n_chan, 1, fs, 2)
header[175] = version
header[176:] = entries
blob = bytes(header) + b"".join(zone[z] for z in ZONES) + codes.tobytes()
with open(path, "wb") as f:
f.write(blob)import numpy as np
from neo.rawio.micromedrawio import MicromedRawIO
codes = np.random.default_rng(0).integers(30000, 35000, (3000, 4)) # 3000 samples at 256 Hz, 4 channels
# 1000 samples (file samples 0-999), then a pause: the second piece starts at file sample 1000 and clock sample 3560
write_trc("a.TRC", codes, tronca=[(3560, 1000)], notes=[(500, "A"), (1500, "B")])
reader = MicromedRawIO("a.TRC")
reader.parse_header()
print(reader.segment_count(0), reader.get_signal_size(0, 0, 0), reader.get_signal_t_start(0, 0, 0))
ts, _, labels = reader.get_event_timestamps(0, 0, 1)
print(labels, reader.rescale_event_timestamp(ts, "float64", 1))
write_trc("v5.TRC", codes, version=5)
MicromedRawIO("v5.TRC").parse_header()Output on current master (0.14.6-105-ge899f3e):
1 2000 13.90625 # file samples 0-999 are not in any segment
['B'] [19.765625] # note A is gone; note B at (1500 + 3560) / 256, but its sample is at 13.90625 + 500 / 256 = 15.859 s
NotImplementedError: `header_version 5 is not implemented in neo yet
Expected behaviour
- A file whose first
trace_offsetis above 0 has a first segment for[0, first trace_offset), starting at time 0 (the clock and the file agree before the first entry). A table whose firsttrace_offsetis 0 is unchanged. - Event times are on the same axis as the signal of their segment:
(seg_start_k + start - trace_offset_k) / sampling_rate. For a file without a table, or with a constantseg_start - trace_offset(as inFile_mircomed2_2segments.TRC, table[(5, 0), (24837, 24832)]) the result is the same as today, which is why the current tests do not see it. - Header version 5 files are read.
Why I think the coordinates are these
File_mircomed2_2segments.TRC in the test data has the table [(5, 0), (24837, 24832)], and test_micromed_multi_segments asserts that its segments equal traces1[int(t_start * sr):] of the unsplit recording, i.e. seg_start is the clock position of the sample at trace_offset. Note positions follow trace_offset rather than the clock: in the archive, the recorder writes a note "Recording pause" at exactly the trace_offset of the cut in 978 of 1,195 cuts, and where the first seg_start lies past the end of the data, 430 of 431 later notes are below the sample count.
Environment:
- OS: Linux
- Python version: 3.12
- Neo version: master (0.14.6-105-ge899f3e), also 0.14.3
- NumPy version: 2.5
Additional context
I have a fix for all three with tests that build their own files, and will open a PR referencing this issue.
Activity