Skip to content

Commit 05db3a2

Browse files
authored
Warn when a renamed record would replace another record's signal files (#675)
Fixes #153. `Record.wrsamp` names the header after `record_name`, but the signal files by `file_name`. So the example in the issue, reading record 100, setting `record_name = "100_cloned"` and writing it, gives `100_cloned.hea` and `100.dat`. Next to the original record, that silently replaces the original's `100.dat`. This is by design, since a record's signals may be split across several files or shared with other records. This PR makes it visible rather than changing it. - **A warning in the risky case:** `wrsamp` warns, before writing anything, when it would replace an existing signal file that the record's own header in `write_dir` doesn't list. The warning names the files, and points at the user's own `wrsamp()` call: ``` UserWarning: Writing record '100_cloned' replaces existing signal files 100.dat, which are named by `file_name`, not `record_name`. To write a copy of a record under a new name, set `file_name` too. ``` It isn't given in these cases: - rewriting a record's own files (its header lists them); - writing a renamed copy to another folder, or into a `.wfdb` archive; - rewriting files whose names don't match the record name, such as `rec_0001e.dat` for record `rec_0001`, as in MIMIC-IV-WDB. It is given for a file named like the record but belonging to another one, such as `100_extra.dat` when record `100_extra` is renamed to `100`. It's a warning, not an error, so code that does this on purpose keeps working. - **Documentation:** the `wrsamp` docstring explains how files are named, with an example of saving a copy under a new name. The `file_name` description said only "The name of the file used for analysis", and now explains the same. Naming new files after the record by default could be part of the API redesign in #672 (for example a `copy(record_name=...)` method), rather than a change to `wrsamp`. ## Testing - New tests: the case from the issue, a renamed record whose name is a prefix of another's, and a record whose own header lists other files all warn; the four cases above don't. The first fails on `main`. - `pytest -m "not network"`, run serially with this warning turned into an error, passes. Two existing tests wrote a record that shares its signal file with another sample record into the directory their class shares, so they replaced another test's file; they now use their own directories. Network tests, ruff and the docs build pass. <sub>@tompollard 🟥 red 🦥 sloth · aspen</sub>
2 parents f59c445 + a989032 commit 05db3a2

3 files changed

Lines changed: 163 additions & 8 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
**Warn when a renamed record would replace another record's signal files**
2+
``Record.wrsamp`` names the header after ``record_name`` and the signal
3+
files by ``file_name``, so writing a record that was read under a new
4+
``record_name``, next to the original, replaced the original's signal
5+
files without any sign. It now warns when writing would replace an existing
6+
signal file that the record's own header in ``write_dir`` does not list. The
7+
documentation of ``wrsamp`` and ``file_name`` now explains this, with an
8+
example of saving a copy under a new name.

‎src/wfdb/io/record.py‎

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import re
77
import shutil
88
import tempfile
9+
import warnings
910

1011
import numpy as np
1112
import pandas as pd
@@ -724,8 +725,10 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin):
724725
base_datetime : datetime.datetime, optional
725726
The date and time at the beginning of the record, equivalent to
726727
`datetime.combine(base_date, base_time)`.
727-
file_name : str, optional
728-
The name of the file used for analysis.
728+
file_name : list, optional
729+
The name of the signal file of each signal. The signals are written
730+
to these files, which are not renamed when `record_name` is changed:
731+
to save a copy of a record under a new name, set both.
729732
fmt : list, optional
730733
A list of strings giving the WFDB format of each file used to store each
731734
channel. Accepted formats are: '80','212','16','24', and '32'. There are
@@ -897,6 +900,13 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
897900
`skew` attribute is not changed, and a value assigned to it after
898901
reading is written to the header.
899902
903+
The header file is named after `record_name`, and the signal files are
904+
named by `file_name`. A record that was read keeps the signal file
905+
names of the original, so to save a copy under a new name, change
906+
both, or the copy's signals are written to the original's files. A
907+
warning is given when writing would replace an existing signal file
908+
that is not listed by this record's own header in `write_dir`.
909+
900910
Parameters
901911
----------
902912
expanded : bool, optional
@@ -915,6 +925,15 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
915925
-------
916926
N/A
917927
928+
Examples
929+
--------
930+
Save a copy of record 100 as record '100_copy':
931+
932+
>>> record = wfdb.rdrecord('sample-data/100', physical=False)
933+
>>> record.record_name = '100_copy'
934+
>>> record.file_name = ['100_copy.dat'] * record.n_sig
935+
>>> record.wrsamp()
936+
918937
"""
919938
converted = None
920939
if not expanded and self.d_signal is None and self.p_signal is not None:
@@ -961,6 +980,9 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
961980
checksums[ch] = old_val
962981
self.checksum = checksums
963982

983+
if wfdb_archive is None and has_signal_files and self.file_name:
984+
self._warn_about_replacing_other_files(write_dir)
985+
964986
with archive_for_writing(wfdb_archive, write_dir) as archive:
965987
# Perform field validity and cohesion checks, and write the
966988
# header file.
@@ -978,6 +1000,51 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None):
9781000
if converted:
9791001
setattr(self, converted, None)
9801002

1003+
def _warn_about_replacing_other_files(self, write_dir):
1004+
"""Warn if writing would replace signal files of another record.
1005+
1006+
A signal file that already exists is this record's own if the
1007+
record's header in `write_dir` lists it, as when a record is written
1008+
again. Otherwise it belongs to another record, as when a record that
1009+
was read is given a new `record_name` but keeps the original's
1010+
`file_name`.
1011+
1012+
Parameters
1013+
----------
1014+
write_dir : str
1015+
The directory in which the files are to be written.
1016+
1017+
Returns
1018+
-------
1019+
N/A
1020+
1021+
"""
1022+
record_name = self.record_name or ""
1023+
existing = [
1024+
file_name
1025+
for file_name in dict.fromkeys(self.file_name)
1026+
if file_name
1027+
and file_name != "~"
1028+
and os.path.exists(os.path.join(write_dir, file_name))
1029+
]
1030+
if not existing:
1031+
return
1032+
try:
1033+
header = rdheader(os.path.join(write_dir, record_name))
1034+
own = set(getattr(header, "file_name", None) or [])
1035+
except Exception:
1036+
# No readable header of this record, so no file is its own yet
1037+
own = set()
1038+
others = [file_name for file_name in existing if file_name not in own]
1039+
if others:
1040+
warnings.warn(
1041+
f"Writing record {record_name!r} replaces existing signal files "
1042+
f"{', '.join(others)}, which are named by `file_name`, not "
1043+
"`record_name`. To write a copy of a record under a new name, "
1044+
"set `file_name` too.",
1045+
stacklevel=3,
1046+
)
1047+
9811048
def _arrange_fields(self, channels, sampfrom, smooth_frames):
9821049
"""Arrange/edit object fields to reflect user channel and/or signal range input.
9831050

‎tests/test_record.py‎

Lines changed: 86 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -636,7 +636,8 @@ def test_wrsamp_physical_only_record_second_write(self, temp_path):
636636
np.testing.assert_array_equal(record_write.d_signal, expected_d_signal)
637637
assert record.d_signal is None
638638

639-
def test_wrsamp_expanded_physical_only_record(self, temp_path):
639+
def test_wrsamp_expanded_physical_only_record(self, tmp_path):
640+
# Its own directory: the record shares its signal file name with others
640641
record = wfdb.rdrecord("sample-data/test01_00s_frame", smooth_frames=False)
641642
expected_e_d_signal = wfdb.rdrecord(
642643
"sample-data/test01_00s_frame",
@@ -646,9 +647,9 @@ def test_wrsamp_expanded_physical_only_record(self, temp_path):
646647

647648
assert record.e_d_signal is None
648649

649-
record.wrsamp(write_dir=temp_path, expanded=True)
650+
record.wrsamp(write_dir=str(tmp_path), expanded=True)
650651
record_write = wfdb.rdrecord(
651-
os.path.join(temp_path, "test01_00s_frame"),
652+
os.path.join(tmp_path, "test01_00s_frame"),
652653
smooth_frames=False,
653654
physical=False,
654655
)
@@ -765,12 +766,13 @@ def test_3b(self, source):
765766

766767
# -------------- 4. Skew and multiple samples/frame -------------- #
767768

768-
def test_4a(self, temp_path):
769+
def test_4a(self, tmp_path):
769770
"""Format 16, multi-samples per frame, skew, digital.
770771
771772
Target file created with:
772773
rdsamp -r sample-data/test01_00s_skewframe | cut -f 2- > record-4a
773774
"""
775+
# Its own directory: the record shares its signal file name with others
774776
record = wfdb.rdrecord("sample-data/test01_00s_skewframe", physical=False)
775777
sig = record.d_signal
776778
# The WFDB library rdsamp does not return the final N samples for all
@@ -788,10 +790,10 @@ def test_4a(self, temp_path):
788790
smooth_frames=False,
789791
ignore_skew=True,
790792
)
791-
record_no_skew.wrsamp(write_dir=temp_path, expanded=True)
793+
record_no_skew.wrsamp(write_dir=str(tmp_path), expanded=True)
792794
# Read the written record
793795
record_write = wfdb.rdrecord(
794-
os.path.join(temp_path, "test01_00s_skewframe"),
796+
os.path.join(tmp_path, "test01_00s_skewframe"),
795797
physical=False,
796798
)
797799

@@ -2086,3 +2088,81 @@ def test_multi_segment(self, tmp_path):
20862088
np.testing.assert_array_equal(
20872089
written.segments[0].d_signal, record.segments[0].d_signal
20882090
)
2091+
2092+
2093+
class TestWarnAboutReplacingOtherFiles:
2094+
"""Writing a renamed copy next to the original warns (#153)."""
2095+
2096+
@staticmethod
2097+
def read_100(tmp_path):
2098+
record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100)
2099+
record.wrsamp(write_dir=str(tmp_path))
2100+
return record
2101+
2102+
def test_renamed_copy_with_the_original_file_names_warns(self, tmp_path):
2103+
record = self.read_100(tmp_path)
2104+
record.record_name = "100_cloned"
2105+
2106+
with pytest.warns(
2107+
UserWarning, match=r"replaces existing signal files 100\.dat"
2108+
):
2109+
record.wrsamp(write_dir=str(tmp_path))
2110+
2111+
@pytest.mark.parametrize(
2112+
"change", ["none", "rename both", "rename in another folder", "archive"]
2113+
)
2114+
def test_no_warning(self, tmp_path, recwarn, change):
2115+
record = self.read_100(tmp_path)
2116+
write_dir = tmp_path
2117+
archive = None
2118+
if change != "none":
2119+
record.record_name = "100_copy"
2120+
if change == "rename both":
2121+
record.file_name = ["100_copy.dat"] * record.n_sig
2122+
elif change == "rename in another folder":
2123+
write_dir = tmp_path / "other"
2124+
write_dir.mkdir()
2125+
elif change == "archive":
2126+
archive = "100_copy.wfdb"
2127+
2128+
record.wrsamp(write_dir=str(write_dir), wfdb_archive=archive)
2129+
2130+
assert not [w for w in recwarn if "replaces existing" in str(w.message)]
2131+
2132+
def test_renamed_record_whose_name_is_a_prefix_warns(self, tmp_path):
2133+
"""A file named like the new record name can still be another's."""
2134+
record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100)
2135+
record.record_name = "100_extra"
2136+
record.file_name = ["100_extra.dat"] * record.n_sig
2137+
record.wrsamp(write_dir=str(tmp_path))
2138+
record.record_name = "100"
2139+
2140+
with pytest.warns(
2141+
UserWarning, match=r"replaces existing signal files 100_extra"
2142+
):
2143+
record.wrsamp(write_dir=str(tmp_path))
2144+
2145+
def test_own_header_listing_other_files_warns(self, tmp_path):
2146+
"""Files that this record's existing header does not list are not its."""
2147+
self.read_100(tmp_path)
2148+
record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100)
2149+
record.record_name = "other"
2150+
record.file_name = ["other.dat"] * record.n_sig
2151+
record.wrsamp(write_dir=str(tmp_path))
2152+
record.file_name = ["100.dat"] * record.n_sig
2153+
2154+
with pytest.warns(
2155+
UserWarning, match=r"replaces existing signal files 100\.dat"
2156+
):
2157+
record.wrsamp(write_dir=str(tmp_path))
2158+
2159+
def test_signal_files_named_with_a_suffix_do_not_warn(self, tmp_path, recwarn):
2160+
"""Signal files whose names start with the record name are its own."""
2161+
record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100)
2162+
record.record_name = "rec_0001"
2163+
record.file_name = ["rec_0001e.dat"] * record.n_sig
2164+
record.wrsamp(write_dir=str(tmp_path))
2165+
2166+
record.wrsamp(write_dir=str(tmp_path))
2167+
2168+
assert not [w for w in recwarn if "replaces existing" in str(w.message)]

0 commit comments

Comments
 (0)