Skip to content

Support TDT stores that are only saved in .sev files #1906

Open

Description

@h-mayorquin

Coming from SpikeInterface/spikeinterface#3025. TdtRawIO builds the signal streams from the .tsq entries, so a store saved only in .sev files comes back empty with a dummy sampling rate and dtype:

mask = is_stream_event & matches_store_name & matches_channel
data_index = tsq[mask].copy()
self._sigs_index[seg_index][global_chan_index] = data_index
size = info["NumPoints"] * data_index.size
if stream_index not in self._sigs_lengths[seg_index]:
self._sigs_lengths[seg_index][stream_index] = size
else:
if self._sigs_lengths[seg_index][stream_index] != size:
raise ValueError(f"The sig lengths for {seg_index=}, {stream_index=} is not of size {size}")
# signal start time, relative to start of segment
if len(data_index["timestamp"]):
t_start = data_index["timestamp"][0]
else:
# if no signal present use segment t_start as dummy value
t_start = self._seg_t_starts[seg_index]
if stream_index not in self._sigs_t_start[seg_index]:
self._sigs_t_start[seg_index][stream_index] = t_start
else:
if self._sigs_t_start[seg_index][stream_index] != t_start:
raise ValueError(f"The t_start for {seg_index=}, {stream_index=} is not of time {t_start}")
# sampling_rate and dtype
if len(data_index):
_sampling_rate = float(data_index["frequency"][0])
_dtype = data_formats_map[data_index["dataformat"][0]]
else:
# if no signal present use dummy values
_sampling_rate = 1.0
_dtype = "int"

With tdt/dataset_0_single_block from gin, Wav5 has its four .sev files but reads as 0 samples at 1.0 Hz with dtype int (RSn1 and RSn2 too, but their .sev files are not in the test data).

The .Tbk already has the sampling rate and the data format of the store (24414.0625 Hz and float32 for Wav5), and the number of samples is the size of the .sev files minus their 40-byte header. When a store has no .sev files either we should raise or warn instead of returning an empty stream.

Activity

  1. drkotireddysaripalli commented on Oct 9, 2026

    @drkotireddysaripalli

    A repair also needs to reach the chunk-reading path. At current master f568f506, supplying the correct length/rate/dtype still leaves _sigs_index empty for an SEV-only store. _get_analogsignal_chunk then accesses data_index[bl]["offset"] and raises IndexError: index 0 is out of bounds for axis 0 with size 0.

    Here is a synthetic version-3, four-channel float32 fixture with 17 known samples per channel. It exercises the real parse_header() and chunk reader; the private metadata assignments deliberately isolate the remaining chunk dependency and are not a proposed parser fix. No recorded data is needed.

    Self-contained reproduction (Python 3.12 / NumPy 2.1.3)
    import struct
    from pathlib import Path
    from tempfile import TemporaryDirectory
    import numpy as np
    from neo.rawio.tdtrawio import TdtRawIO, tsq_dtype, tbk_field_types
    
    with TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
        folder = Path(tmp)
        stem = folder / "Tank_Block"
        n, fs = 17, 24414.0625
        fields = dict(StoreName="Wav5", HeadName="Synthetic", Enabled=1,
                      CircType=0, NumChan=4, StrobeMode=0, TankEvType=33041,
                      NumPoints=4, DataFormat=0, SampleFreq=fs)
        types = dict(tbk_field_types)
        stem.with_suffix(".Tbk").write_bytes(b"\n".join(
            f"NAME={k};TYPE={types[k]};VALUE={v};".encode()
            for k, v in fields.items()))
        stem.with_suffix(".Tdx").write_bytes(b"")
        stem.with_suffix(".tev").write_bytes(bytes(40))
        tsq = np.zeros(3, dtype=tsq_dtype)
        tsq[1]["evname"], tsq[1]["timestamp"] = b"\x01", 100.
        tsq[-1]["evname"], tsq[-1]["timestamp"] = b"\x02", 100. + n / fs
        tsq.tofile(stem.with_suffix(".tsq"))  # block markers; no Wav5 entries
        expected = np.column_stack([
            1000 * c + np.arange(n) for c in range(1, 5)]).astype("<f4")
        for c in range(4):
            payload = expected[:, c].tobytes()
            header = struct.pack("<Q3sB4sHHHHBBH12s",
                40 + len(payload), b"SEV", 3, b"Wav5", c + 1, 4, 4,
                0, 0, 1, 2, bytes(12))
            (folder / f"Tank_Block_Wav5_Ch{c + 1}.sev").write_bytes(header + payload)
    
        reader = TdtRawIO(dirname=stem.with_suffix(".Tbk"))
        reader.parse_header()
        assert reader.get_signal_size(0, 0, 0) == 0
        assert reader.get_signal_sampling_rate(0) == 1.
        assert reader.get_analogsignal_chunk(0, 0, stream_index=0).shape == (0, 4)
    
        # Diagnostic only: repair metadata, leave the TSQ indexes unchanged.
        reader._sigs_lengths[0][0] = n
        reader._sig_dtype_by_group[0] = np.dtype("<f4")
        reader.header["signal_channels"]["sampling_rate"] = fs
        reader.header["signal_channels"]["dtype"] = "float32"
        try:
            reader.get_analogsignal_chunk(0, 0, i_start=0, i_stop=3, stream_index=0)
        except IndexError as exc:
            assert "index 0 is out of bounds" in str(exc)
            print(str(exc))
        else:
            raise AssertionError("Expected the unchanged chunk path to need a TSQ offset")
        # The known contiguous payload remains readable without a TSQ offset.
        got = np.column_stack([
            reader._sigs_data_buf[0][c][40:52].view("<f4") for c in range(4)])
        np.testing.assert_array_equal(got, expected[:3])
        for buf in [reader._tev_datas[0], *reader._sigs_data_buf[0].values()]:
            buf._mmap.close()

    For this simple contiguous case, a sample slice [i_start:i_stop) can be read from each SEV payload at byte offsets 40 + i_start * itemsize : 40 + i_stop * itemsize. A dedicated contiguous-SEV path would avoid inventing TSQ blocks and handle a final partial block such as these 17 samples with NumPoints=4. That needs to remain distinct from streams whose real TSQ offsets describe the data.

    The local check covered float32/17 samples and int16/20 samples, single- and multi-block entry modes, full/first/interior/cross-boundary/final/empty slices, and channel order [3, 0]. All 24 diagnostic direct slices matched the known payload; 24 corresponding TSQ-backed control reads also matched. These are focused synthetic checks, not a complete implementation or the upstream suite.

    Two scope boundaries matter:

    • For a contiguous file, the sample count is (file_size - 40) // dtype.itemsize, with a divisibility check before accepting a truncated payload. The byte count alone is not the sample count. TDT's format guidance identifies per-channel SEV files and sampling-rate overrides; its RS4 documentation also describes segmented files and logs with starting/ending samples and gaps. Those variants need an explicit policy rather than assuming every SEV is one gap-free stream starting at block time.
    • The current master already incorporates the UCF missing-file guard from TdtRawIO: detect SEV vs TEV using the UCF flag instead of silent per-channel fallback #1835. Removing channel 1 or 4 in either entry mode raised NeoReadWriteError in this check. That existing guard should be preserved rather than reintroducing TEV fallback for a UCF store.

    For reproducibility, tdt==0.7.6 recognized the synthetic sampling rate and all known payload samples, but its default read returned one extra trailing zero in these fixtures. The comparisons above therefore use the generated payload and physical sample count, not the SDK's returned length. Legacy headers, hourly segmentation, logs/gaps, timing alignment and unit scaling were not validated.

    Affiliation: Chief Scientist PinnacleAI(R), Pinnacle Blooms Network of Bharath Healthcare P LIMITED, https://www.pinnacleblooms.org/verify

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions