Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/multirecord-write-checks.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
**Write multi-segment records completely or not at all**
``MultiRecord.wrsamp`` wrote the main header and the earlier segments
before finding that a later segment could not be written, which left a
partly written record. It now writes the files into a temporary folder in
``write_dir``, and moves them into place only once every segment has been
written. A segment without the signal to write, or without
``samps_per_frame`` when writing expanded signals, now raises a
``ValueError`` that names the segment, instead of a ``TypeError``. A
relative ``wfdb_archive`` path is now relative to ``write_dir``, as it is
for ``Record.wrsamp``.
96 changes: 83 additions & 13 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import posixpath
import re
import tempfile

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -1202,22 +1203,91 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
N/A

"""
# Validate segment cohesion before writing anything.
# Validate the segments before writing anything.
self._check_segment_cohesion()
self._check_segment_signals(expanded)

with archive_for_writing(wfdb_archive) as archive:
# Perform field validity and cohesion checks, and write the
# header file.
self.wrheader(write_dir=write_dir, wfdb_archive=archive)
# Perform record validity and cohesion checks, and write the
# associated segments. Empty segments ('~') have no files.
for seg in self.segments:
if seg is not None:
seg.wrsamp(
expanded=expanded,
write_dir=write_dir,
wfdb_archive=archive,
if wfdb_archive is not None:
# An archive opened from a path is discarded if writing fails
with archive_for_writing(wfdb_archive, write_dir) as archive:
self._write_segments(expanded, write_dir, archive)
return

# Write the files into a temporary directory first, and move them into
# write_dir only once every segment has been written, so that a segment
# that cannot be written leaves no partly written record behind.
# (in write_dir itself, so that the files can be moved, not copied)
with tempfile.TemporaryDirectory(
dir=write_dir or os.curdir, prefix=".wfdb-"
) as staging:
self._write_segments(expanded, staging, None)
for name in os.listdir(staging):
os.replace(os.path.join(staging, name), os.path.join(write_dir, name))

def _write_segments(self, expanded, write_dir, wfdb_archive):
"""Write the multi-segment header, and the files of each segment.

Parameters
----------
expanded : bool
Whether to write each segment's expanded signal.
write_dir : str
The directory in which to write the files.
wfdb_archive : WFDBArchive or None
The archive to write the files into, if any.

Returns
-------
N/A

"""
# Perform field validity and cohesion checks, and write the header file.
self.wrheader(write_dir=write_dir, wfdb_archive=wfdb_archive)
# Perform record validity and cohesion checks, and write the associated
# segments. Empty segments ('~') have no files.
for seg in self.segments:
if seg is not None:
seg.wrsamp(
expanded=expanded, write_dir=write_dir, wfdb_archive=wfdb_archive
)

def _check_segment_signals(self, expanded):
"""Check that each segment has the signal that is to be written.

Parameters
----------
expanded : bool
Whether each segment's expanded signal is to be written.

Returns
-------
N/A

"""
for seg_num, segment in enumerate(self.segments):
# Empty segments, and the layout header of a variable layout
# record, have no signal files
if segment is None or (
segment.file_name is not None
and all(f == "~" for f in segment.file_name)
):
continue
name = f"Segment {seg_num} ({segment.record_name})"
if expanded:
if segment.e_d_signal is None and segment.e_p_signal is None:
raise ValueError(
f"{name} has no expanded signal (e_d_signal or e_p_signal) "
"to write with expanded=True"
)
if segment.samps_per_frame is None:
raise ValueError(
f"{name} has no samps_per_frame, which is needed to "
"write its expanded signal"
)
elif segment.d_signal is None and segment.p_signal is None:
raise ValueError(
f"{name} has no signal (d_signal or p_signal) to write"
)

def _check_segment_cohesion(self):
"""Check the cohesion of the segments field with the other fields.
Expand Down
68 changes: 68 additions & 0 deletions tests/test_multi_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,71 @@ def test_unspecified_samps_per_frame_is_accepted_when_expanded(self, tmp_path):
smooth_frames=False,
)
assert record_write.segments[0].samps_per_frame == [1]

@pytest.mark.parametrize("expanded", [False, True])
def test_invalid_later_segment_writes_no_files(self, tmp_path, expanded):
"""A segment that fails to be written leaves no partial record (#557)."""
record = wfdb.rdrecord(
self.record_path, m2s=False, physical=False, smooth_frames=not expanded
)
segment = record.segments[1]
if expanded:
segment.e_d_signal[0] = segment.e_d_signal[0][:-3]
else:
segment.fmt = ["999"] * segment.n_sig

with pytest.raises(ValueError):
record.wrsamp(write_dir=str(tmp_path), expanded=expanded)

assert list(tmp_path.iterdir()) == []

def test_segment_without_samps_per_frame_when_expanded(self, tmp_path):
record = wfdb.rdrecord(
self.record_path, m2s=False, physical=False, smooth_frames=False
)
record.segments[1].samps_per_frame = None

with pytest.raises(ValueError, match=r"Segment 1 \(041s02\) has no samps"):
record.wrsamp(write_dir=str(tmp_path), expanded=True)

assert list(tmp_path.iterdir()) == []

@pytest.mark.parametrize("expanded", [False, True])
def test_segment_without_a_signal(self, tmp_path, expanded):
record = wfdb.rdrecord(
self.record_path, m2s=False, physical=False, smooth_frames=not expanded
)
segment = record.segments[1]
segment.d_signal = segment.p_signal = None
segment.e_d_signal = segment.e_p_signal = None

with pytest.raises(ValueError, match=r"Segment 1 \(041s02\) has no"):
record.wrsamp(write_dir=str(tmp_path), expanded=expanded)

assert list(tmp_path.iterdir()) == []

def test_write_to_the_current_directory(self, tmp_path, monkeypatch):
"""The default write_dir is the current directory, with no files left over."""
record = wfdb.rdrecord(self.record_path, m2s=False, physical=False)
monkeypatch.chdir(tmp_path)

record.wrsamp()

assert sorted(p.name for p in tmp_path.iterdir()) == [
"041s.hea",
"041s01.dat",
"041s01.hea",
"041s02.dat",
"041s02.hea",
]

def test_archive_path_is_relative_to_write_dir(self, tmp_path, monkeypatch):
record = wfdb.rdrecord(self.record_path, m2s=False, physical=False)
monkeypatch.chdir(tmp_path)
(tmp_path / "out").mkdir()

record.wrsamp(write_dir="out", wfdb_archive="041s.wfdb")

assert [p.name for p in (tmp_path / "out").iterdir()] == ["041s.wfdb"]
assert not (tmp_path / "041s.wfdb").exists()
assert wfdb.rdrecord("out/041s.wfdb").sig_len == record.sig_len
Loading