diff --git a/changelog.d/write-flattened-records.rst b/changelog.d/write-flattened-records.rst new file mode 100644 index 00000000..500756ea --- /dev/null +++ b/changelog.d/write-flattened-records.rst @@ -0,0 +1,6 @@ +**Write flattened multi-segment records** + Records returned by ``rdrecord`` with ``m2s=True`` can now be written after + assigning a new record name and signal file names. Missing write metadata is + filled in, and incompatible or unknown formats are converted to format 32. + The caller's record is not changed. Records with conflicting source units + require an explicit ``units`` value. diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 4fd02cf7..533a4b67 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -945,6 +945,14 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): warning is given when writing would replace an existing signal file that is not listed by this record's own header in `write_dir`. + Records flattened from multi-segment records are prepared for writing + on a copy, leaving this object unchanged. Channels without a known + format, or with incompatible formats sharing a file, use format 32. + This can increase the output file size. Missing samples use that + format's digital missing marker; channels with no samples have + placeholder gain and baseline values. If the source segments have + conflicting units, set `units` explicitly first. + Parameters ---------- expanded : bool, optional @@ -983,6 +991,24 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): self.wrsamp(expanded=expanded, write_dir=staging) return + if getattr(self, "source_segments", None) is not None: + writable = copy.copy(self) + for field, value in vars(self).items(): + if isinstance(value, list): + setattr(writable, field, value.copy()) + writable.source_segments = None + writable._prepare_flattened_write(expanded) + if not expanded and writable.d_signal is None: + writable.d_signal = writable.adc() + elif expanded and writable.e_d_signal is None: + writable.e_d_signal = writable.adc(expanded=True) + writable.set_d_features(expanded=expanded) + writable.set_defaults() + writable.wrsamp( + expanded=expanded, write_dir=write_dir, wfdb_archive=wfdb_archive + ) + return + converted = None if not expanded and self.d_signal is None and self.p_signal is not None: self.d_signal = self.adc() @@ -1048,6 +1074,73 @@ def wrsamp(self, expanded=False, write_dir="", wfdb_archive=None): if converted: setattr(self, converted, None) + def _prepare_flattened_write(self, expanded): + """Complete write metadata for a record flattened from a MultiRecord.""" + if self.units is None: + raise ValueError( + "Flattened record has inconsistent units; set units before writing" + ) + self.units = [unit if unit is not None else "NU" for unit in self.units] + + formats_complete = self.fmt is not None and all( + fmt is not None for fmt in self.fmt + ) + formats_share_files = False + if formats_complete and self.file_name is not None: + formats_by_file = {} + for name, fmt in zip(self.file_name, self.fmt): + if name in formats_by_file and formats_by_file[name] != fmt: + formats_share_files = True + break + formats_by_file[name] = fmt + complete_gain = self.adc_gain is not None and all( + gain is not None for gain in self.adc_gain + ) + complete_baseline = self.baseline is not None and all( + value is not None for value in self.baseline + ) + + if self.p_signal is not None or self.e_p_signal is not None: + if not ( + formats_complete + and not formats_share_files + and complete_gain + and complete_baseline + ): + self.fmt = ["32"] * self.n_sig + self.adc_gain, self.baseline = self.calc_adc_params() + return + + if not formats_complete or formats_share_files: + old_formats = self.fmt or [None] * self.n_sig + new_nan = _signal._digi_nan("32") + signals = self.e_d_signal if expanded else self.d_signal.T + recoded = [] + for signal, fmt in zip(signals, old_formats): + old_nan = ( + _signal._digi_nan(fmt) + if fmt is not None + else np.iinfo(signal.dtype).min + ) + signal = signal.astype("int64", copy=True) + if old_nan is not None: + signal[signal == old_nan] = new_nan + recoded.append(signal) + if expanded: + self.e_d_signal = recoded + else: + self.d_signal = np.column_stack(recoded) + self.fmt = ["32"] * self.n_sig + + self.adc_gain = [ + gain if gain is not None else 1.0 + for gain in (self.adc_gain or [None] * self.n_sig) + ] + self.baseline = [ + value if value is not None else 0 + for value in (self.baseline or [None] * self.n_sig) + ] + def _warn_about_replacing_other_files(self, write_dir): """Warn if writing would replace signal files of another record. diff --git a/tests/test_multi_record.py b/tests/test_multi_record.py index 4687b567..2593bde6 100644 --- a/tests/test_multi_record.py +++ b/tests/test_multi_record.py @@ -1,3 +1,4 @@ +import copy import os import stat @@ -236,6 +237,105 @@ def test_round_trip(self, tmp_path): for segment, expected_signal in zip(record_write.segments, expected_signals): np.testing.assert_array_equal(segment.d_signal, expected_signal) + @pytest.mark.parametrize("physical", [True, False]) + @pytest.mark.parametrize("expanded", [True, False]) + def test_write_flattened_fixed_record(self, tmp_path, physical, expanded): + """A fixed-layout record can be written after flattening.""" + record = wfdb.rdrecord( + "sample-data/multi-segment/fixed1/v102s", + sampfrom=74990, + sampto=75010, + physical=physical, + smooth_frames=not expanded, + ) + record.record_name = "flat" + record.file_name = ["flat.dat"] * record.n_sig + original = copy.deepcopy(record) + + record.wrsamp(write_dir=str(tmp_path), expanded=expanded) + reread = wfdb.rdrecord( + str(tmp_path / "flat"), physical=physical, smooth_frames=not expanded + ) + + if physical: + field = "e_p_signal" if expanded else "p_signal" + else: + field = "e_d_signal" if expanded else "d_signal" + np.testing.assert_equal(getattr(reread, field), getattr(record, field)) + assert record == original + assert record.source_segments == original.source_segments + + @pytest.mark.parametrize("expanded", [True, False]) + def test_write_flattened_variable_record(self, tmp_path, expanded): + """Missing channels and an empty segment survive physical writing.""" + path = "sample-data/multi-segment/p000878/p000878-2137-10-26-16-57" + record = wfdb.rdrecord( + path, + sampfrom=3700, + sampto=3800, + smooth_frames=not expanded, + ) + record.record_name = "flat" + record.file_name = ["flat.dat"] * record.n_sig + original_record = copy.deepcopy(record) + + record.wrsamp(write_dir=str(tmp_path), expanded=expanded) + reread = wfdb.rdrecord(str(tmp_path / "flat"), smooth_frames=not expanded) + + assert reread.fmt == ["32"] * record.n_sig + original = record.e_p_signal if expanded else record.p_signal.T + written = reread.e_p_signal if expanded else reread.p_signal.T + for expected, actual in zip(original, written): + np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-9) + assert record == original_record + assert record.source_segments == original_record.source_segments + + @pytest.mark.parametrize("expanded", [True, False]) + def test_write_flattened_variable_digital_record(self, tmp_path, expanded): + """Unknown-format missing samples get the new format's marker.""" + path = "sample-data/multi-segment/p000878/p000878-2137-10-26-16-57" + record = wfdb.rdrecord( + path, + sampfrom=3700, + sampto=3800, + physical=False, + smooth_frames=not expanded, + ) + original = ( + record.e_d_signal[0].copy() if expanded else record.d_signal[:, 0].copy() + ) + record.record_name = "flat" + record.file_name = ["flat.dat"] * record.n_sig + original_record = copy.deepcopy(record) + + record.wrsamp(write_dir=str(tmp_path), expanded=expanded) + reread = wfdb.rdrecord( + str(tmp_path / "flat"), physical=False, smooth_frames=not expanded + ) + + assert reread.fmt == ["32"] * record.n_sig + output = reread.e_d_signal if expanded else reread.d_signal.T + valid = original != -128 + np.testing.assert_array_equal(output[0][valid], original[valid]) + np.testing.assert_array_equal(output[0][~valid], -(2**31)) + for channel in output[1:]: + np.testing.assert_array_equal(channel, -(2**31)) + assert record == original_record + assert record.source_segments == original_record.source_segments + + def test_write_flattened_record_requires_resolved_units(self, tmp_path): + """Do not silently label a channel whose source units conflict.""" + path = "sample-data/multi-segment/p000878/p000878-2137-10-26-16-57" + record = wfdb.rdrecord(path, sampfrom=3700, sampto=3800) + record.record_name = "flat" + record.file_name = ["flat.dat"] * record.n_sig + record.units = None + + with pytest.raises(ValueError, match="inconsistent units"): + record.wrsamp(write_dir=str(tmp_path)) + + assert list(tmp_path.iterdir()) == [] + def test_segment_length_mismatch_writes_no_files(self, tmp_path): record = wfdb.rdrecord(self.record_path, m2s=False, physical=False) record.seg_len[1] -= 1