diff --git a/changelog.d/warn-replacing-other-files.rst b/changelog.d/warn-replacing-other-files.rst new file mode 100644 index 00000000..f23c8938 --- /dev/null +++ b/changelog.d/warn-replacing-other-files.rst @@ -0,0 +1,8 @@ +**Warn when a renamed record would replace another record's signal files** + ``Record.wrsamp`` names the header after ``record_name`` and the signal + files by ``file_name``, so writing a record that was read under a new + ``record_name``, next to the original, replaced the original's signal + files without any sign. It now warns when writing would replace an existing + signal file that the record's own header in ``write_dir`` does not list. The + documentation of ``wrsamp`` and ``file_name`` now explains this, with an + example of saving a copy under a new name. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 535ad94a..5c096d59 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -6,6 +6,7 @@ import re import shutil import tempfile +import warnings import numpy as np import pandas as pd @@ -724,8 +725,10 @@ class Record(BaseRecord, _header.HeaderMixin, _signal.SignalMixin): base_datetime : datetime.datetime, optional The date and time at the beginning of the record, equivalent to `datetime.combine(base_date, base_time)`. - file_name : str, optional - The name of the file used for analysis. + file_name : list, optional + The name of the signal file of each signal. The signals are written + to these files, which are not renamed when `record_name` is changed: + to save a copy of a record under a new name, set both. fmt : list, optional A list of strings giving the WFDB format of each file used to store each 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): `skew` attribute is not changed, and a value assigned to it after reading is written to the header. + The header file is named after `record_name`, and the signal files are + named by `file_name`. A record that was read keeps the signal file + names of the original, so to save a copy under a new name, change + both, or the copy's signals are written to the original's files. A + warning is given when writing would replace an existing signal file + that is not listed by this record's own header in `write_dir`. + Parameters ---------- expanded : bool, optional @@ -915,6 +925,15 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): ------- N/A + Examples + -------- + Save a copy of record 100 as record '100_copy': + + >>> record = wfdb.rdrecord('sample-data/100', physical=False) + >>> record.record_name = '100_copy' + >>> record.file_name = ['100_copy.dat'] * record.n_sig + >>> record.wrsamp() + """ converted = None 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): checksums[ch] = old_val self.checksum = checksums + if wfdb_archive is None and has_signal_files and self.file_name: + self._warn_about_replacing_other_files(write_dir) + with archive_for_writing(wfdb_archive, write_dir) as archive: # Perform field validity and cohesion checks, and write the # header file. @@ -978,6 +1000,51 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): if converted: setattr(self, converted, None) + def _warn_about_replacing_other_files(self, write_dir): + """Warn if writing would replace signal files of another record. + + A signal file that already exists is this record's own if the + record's header in `write_dir` lists it, as when a record is written + again. Otherwise it belongs to another record, as when a record that + was read is given a new `record_name` but keeps the original's + `file_name`. + + Parameters + ---------- + write_dir : str + The directory in which the files are to be written. + + Returns + ------- + N/A + + """ + record_name = self.record_name or "" + existing = [ + file_name + for file_name in dict.fromkeys(self.file_name) + if file_name + and file_name != "~" + and os.path.exists(os.path.join(write_dir, file_name)) + ] + if not existing: + return + try: + header = rdheader(os.path.join(write_dir, record_name)) + own = set(getattr(header, "file_name", None) or []) + except Exception: + # No readable header of this record, so no file is its own yet + own = set() + others = [file_name for file_name in existing if file_name not in own] + if others: + warnings.warn( + f"Writing record {record_name!r} replaces existing signal files " + f"{', '.join(others)}, which are named by `file_name`, not " + "`record_name`. To write a copy of a record under a new name, " + "set `file_name` too.", + stacklevel=3, + ) + def _arrange_fields(self, channels, sampfrom, smooth_frames): """Arrange/edit object fields to reflect user channel and/or signal range input. diff --git a/tests/test_record.py b/tests/test_record.py index 53112fbe..98e8a801 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -636,7 +636,8 @@ def test_wrsamp_physical_only_record_second_write(self, temp_path): np.testing.assert_array_equal(record_write.d_signal, expected_d_signal) assert record.d_signal is None - def test_wrsamp_expanded_physical_only_record(self, temp_path): + def test_wrsamp_expanded_physical_only_record(self, tmp_path): + # Its own directory: the record shares its signal file name with others record = wfdb.rdrecord("sample-data/test01_00s_frame", smooth_frames=False) expected_e_d_signal = wfdb.rdrecord( "sample-data/test01_00s_frame", @@ -646,9 +647,9 @@ def test_wrsamp_expanded_physical_only_record(self, temp_path): assert record.e_d_signal is None - record.wrsamp(write_dir=temp_path, expanded=True) + record.wrsamp(write_dir=str(tmp_path), expanded=True) record_write = wfdb.rdrecord( - os.path.join(temp_path, "test01_00s_frame"), + os.path.join(tmp_path, "test01_00s_frame"), smooth_frames=False, physical=False, ) @@ -765,12 +766,13 @@ def test_3b(self, source): # -------------- 4. Skew and multiple samples/frame -------------- # - def test_4a(self, temp_path): + def test_4a(self, tmp_path): """Format 16, multi-samples per frame, skew, digital. Target file created with: rdsamp -r sample-data/test01_00s_skewframe | cut -f 2- > record-4a """ + # Its own directory: the record shares its signal file name with others record = wfdb.rdrecord("sample-data/test01_00s_skewframe", physical=False) sig = record.d_signal # The WFDB library rdsamp does not return the final N samples for all @@ -788,10 +790,10 @@ def test_4a(self, temp_path): smooth_frames=False, ignore_skew=True, ) - record_no_skew.wrsamp(write_dir=temp_path, expanded=True) + record_no_skew.wrsamp(write_dir=str(tmp_path), expanded=True) # Read the written record record_write = wfdb.rdrecord( - os.path.join(temp_path, "test01_00s_skewframe"), + os.path.join(tmp_path, "test01_00s_skewframe"), physical=False, ) @@ -2086,3 +2088,81 @@ def test_multi_segment(self, tmp_path): np.testing.assert_array_equal( written.segments[0].d_signal, record.segments[0].d_signal ) + + +class TestWarnAboutReplacingOtherFiles: + """Writing a renamed copy next to the original warns (#153).""" + + @staticmethod + def read_100(tmp_path): + record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100) + record.wrsamp(write_dir=str(tmp_path)) + return record + + def test_renamed_copy_with_the_original_file_names_warns(self, tmp_path): + record = self.read_100(tmp_path) + record.record_name = "100_cloned" + + with pytest.warns( + UserWarning, match=r"replaces existing signal files 100\.dat" + ): + record.wrsamp(write_dir=str(tmp_path)) + + @pytest.mark.parametrize( + "change", ["none", "rename both", "rename in another folder", "archive"] + ) + def test_no_warning(self, tmp_path, recwarn, change): + record = self.read_100(tmp_path) + write_dir = tmp_path + archive = None + if change != "none": + record.record_name = "100_copy" + if change == "rename both": + record.file_name = ["100_copy.dat"] * record.n_sig + elif change == "rename in another folder": + write_dir = tmp_path / "other" + write_dir.mkdir() + elif change == "archive": + archive = "100_copy.wfdb" + + record.wrsamp(write_dir=str(write_dir), wfdb_archive=archive) + + assert not [w for w in recwarn if "replaces existing" in str(w.message)] + + def test_renamed_record_whose_name_is_a_prefix_warns(self, tmp_path): + """A file named like the new record name can still be another's.""" + record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100) + record.record_name = "100_extra" + record.file_name = ["100_extra.dat"] * record.n_sig + record.wrsamp(write_dir=str(tmp_path)) + record.record_name = "100" + + with pytest.warns( + UserWarning, match=r"replaces existing signal files 100_extra" + ): + record.wrsamp(write_dir=str(tmp_path)) + + def test_own_header_listing_other_files_warns(self, tmp_path): + """Files that this record's existing header does not list are not its.""" + self.read_100(tmp_path) + record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100) + record.record_name = "other" + record.file_name = ["other.dat"] * record.n_sig + record.wrsamp(write_dir=str(tmp_path)) + record.file_name = ["100.dat"] * record.n_sig + + with pytest.warns( + UserWarning, match=r"replaces existing signal files 100\.dat" + ): + record.wrsamp(write_dir=str(tmp_path)) + + def test_signal_files_named_with_a_suffix_do_not_warn(self, tmp_path, recwarn): + """Signal files whose names start with the record name are its own.""" + record = wfdb.rdrecord("sample-data/100", physical=False, sampto=100) + record.record_name = "rec_0001" + record.file_name = ["rec_0001e.dat"] * record.n_sig + record.wrsamp(write_dir=str(tmp_path)) + + record.wrsamp(write_dir=str(tmp_path)) + + assert not [w for w in recwarn if "replaces existing" in str(w.message)]