diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index a15eacbb..49d043a1 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -321,6 +321,203 @@ def _positive_samples_per_frame(value, channel): return count +def _check_field_value( + field, item, required_channels="all", *, signal_snapshot=None, lookup +): + """Validate an explicit field value with the existing WFDB rules.""" + if signal_snapshot is not None and field in _header.SIGNAL_SPECS.index: + if item is not None and not isinstance(item, list): + raise TypeError("Field `%s` must be a list." % field) + item = ( + [getattr(channel, field) for channel in signal_snapshot.channels] + if field in signal_snapshot.present_fields + else None + ) + if item is None: + raise Exception("Missing field required: %s" % field) + + # We should have a list specifying these automatically. + + # Whether the item should be a list. Watch out for required_channels for + # `segments` + expect_list = True if field in LIST_FIELDS else False + + # Check the type of the field (and of its elements if it should + # be a list) + _check_item_type( + item, + field_name=field, + allowed_types=ALLOWED_TYPES[field], + expect_list=expect_list, + required_channels=required_channels, + ) + + # Individual specific field checks + if field in ["d_signal", "p_signal"]: + check_np_array( + item=item, + field_name=field, + ndim=2, + parent_class=(lambda f: np.integer if f == "d_signal" else np.floating)( + field + ), + ) + elif field in ["e_d_signal", "e_p_signal"]: + for ch in range(len(item)): + check_np_array( + item=item[ch], + field_name=field, + ndim=1, + parent_class=( + lambda f: np.integer if f == "e_d_signal" else np.floating + )(field), + channel_num=ch, + ) + + # Record specification fields + elif field == "record_name": + # Allow letters, digits, hyphens, and underscores. + if re.fullmatch(r"[-\w]+", item) is None: + raise ValueError( + "record_name must only comprise of letters, digits, hyphens, and underscores." + ) + elif field == "n_seg": + if item <= 0: + raise ValueError("n_seg must be a positive integer") + elif field == "n_sig": + if item <= 0: + raise ValueError("n_sig must be a positive integer") + elif field == "fs": + if item <= 0: + raise ValueError("fs must be a positive number") + elif field == "counter_freq": + if item <= 0: + raise ValueError("counter_freq must be a positive number") + elif field == "base_counter": + if item <= 0: + raise ValueError("base_counter must be a positive number") + elif field == "sig_len": + if item < 0: + raise ValueError("sig_len must be a non-negative integer") + + # Signal specification fields + elif field in _header.SIGNAL_SPECS.index: + file_names = ( + [channel.file_name for channel in signal_snapshot.channels] + if signal_snapshot is not None + else lookup("file_name") + ) + formats = ( + [channel.fmt for channel in signal_snapshot.channels] + if signal_snapshot is not None + else lookup("fmt") + ) + if required_channels == "all": + required_channels = range(len(item)) + + for ch in range(len(item)): + # If the element is allowed to be None + if ch not in required_channels: + if item[ch] is None: + continue + + if field == "file_name": + # Check for file_name characters. A null signal (format + # 0), as in the layout header of a variable layout + # multi-segment record, has no file and uses '~'. + if item[ch] == "~" and formats[ch] == "0": + pass + elif re.fullmatch(r"[-\w]+\.?[\w]+", item[ch]) is None: + raise ValueError( + "File names should only contain alphanumerics, hyphens, and an extension. eg. record-100.dat" + ) + # Check that dat files are grouped together + if not util.is_monotonic(file_names): + raise ValueError( + "Signals in a record that share a given file must be consecutive." + ) + elif field == "fmt": + # Format 0 is a null signal, which has no samples and + # no file + if item[ch] == "0" and file_names[ch] == "~": + pass + elif item[ch] not in _signal.DAT_FMTS: + raise ValueError( + "File formats must be valid WFDB dat formats:", + _signal.DAT_FMTS, + ) + elif field == "samps_per_frame": + if item[ch] < 1: + raise ValueError("samps_per_frame values must be positive integers") + elif field == "skew": + if item[ch] < 0: + raise ValueError("skew values must be non-negative integers") + elif field == "byte_offset": + if item[ch] < 0: + raise ValueError("byte_offset values must be non-negative integers") + elif field == "adc_gain": + if item[ch] <= 0: + raise ValueError("adc_gain values must be positive") + elif field == "baseline": + # Original WFDB library 10.5.24 only has 4 bytes for baseline. + if item[ch] < -2147483648 or item[ch] > 2147483648: + raise ValueError( + "baseline values must be between -2147483648 (-2^31) and 2147483647 (2^31 -1)" + ) + elif field == "units": + if re.search(r"\s", item[ch]): + raise ValueError("units strings may not contain whitespaces.") + elif field == "adc_res": + if item[ch] < 0: + raise ValueError("adc_res values must be non-negative integers") + elif field == "block_size": + if item[ch] < 0: + raise ValueError("block_size values must be non-negative integers") + elif field == "sig_name": + if item[ch][:1].isspace() or item[ch][-1:].isspace(): + raise ValueError( + "sig_name strings may not begin or end with whitespace." + ) + if re.search(r"[\x00-\x1f\x7f-\x9f]", item[ch]): + raise ValueError( + "sig_name strings may not contain control characters." + ) + if len(set(item)) != len(item): + raise ValueError("sig_name strings must be unique.") + + # Segment specification fields and comments + elif field in _header.SEGMENT_SPECS.index: + for ch in range(len(item)): + if field == "seg_name": + # Segment names must be alphanumerics or just a single '~' + if item[ch] == "~": + continue + accepted_string = re.match(r"[-\w]+", item[ch]) + if not accepted_string or accepted_string.string != item[ch]: + raise ValueError( + "Non-null segment names may only contain alphanumerics and dashes. Null segment names must be set to '~'" + ) + elif field == "seg_len": + # For records with more than 1 segment, the first + # segment may be the layout specification segment + # with a length of 0 + min_len = 0 if ch == 0 else 1 + if item[ch] < min_len: + raise ValueError( + "seg_len values must be positive integers. Only seg_len[0] may be 0 to indicate a layout segment" + ) + # Comment field + elif field == "comments": + if item[ch].startswith("#"): + print( + "Note: comment strings do not need to begin with '#'. This library adds them automatically." + ) + if re.search("[\t\n\r\f\v]", item[ch]): + raise ValueError( + "comments may not contain tabs or newlines (they may contain spaces and underscores)." + ) + + class BaseRecord: """The base WFDB class extended by the Record and MultiRecord classes. @@ -688,208 +885,19 @@ def check_field( item = ( header_fields[field] if header_fields is not None else getattr(self, field) ) - if signal_snapshot is not None and field in _header.SIGNAL_SPECS.index: - if item is not None and not isinstance(item, list): - raise TypeError("Field `%s` must be a list." % field) - item = ( - [getattr(channel, field) for channel in signal_snapshot.channels] - if field in signal_snapshot.present_fields - else None - ) - if item is None: - raise Exception("Missing field required: %s" % field) - - # We should have a list specifying these automatically. - - # Whether the item should be a list. Watch out for required_channels for - # `segments` - expect_list = True if field in LIST_FIELDS else False - - # Check the type of the field (and of its elements if it should - # be a list) - _check_item_type( + lookup = ( + header_fields.__getitem__ + if header_fields is not None + else lambda name: getattr(self, name) + ) + _check_field_value( + field, item, - field_name=field, - allowed_types=ALLOWED_TYPES[field], - expect_list=expect_list, - required_channels=required_channels, + required_channels, + signal_snapshot=signal_snapshot, + lookup=lookup, ) - # Individual specific field checks - if field in ["d_signal", "p_signal"]: - check_np_array( - item=item, - field_name=field, - ndim=2, - parent_class=(lambda f: np.integer if f == "d_signal" else np.floating)( - field - ), - ) - elif field in ["e_d_signal", "e_p_signal"]: - for ch in range(len(item)): - check_np_array( - item=item[ch], - field_name=field, - ndim=1, - parent_class=( - lambda f: np.integer if f == "e_d_signal" else np.floating - )(field), - channel_num=ch, - ) - - # Record specification fields - elif field == "record_name": - # Allow letters, digits, hyphens, and underscores. - if re.fullmatch(r"[-\w]+", item) is None: - raise ValueError( - "record_name must only comprise of letters, digits, hyphens, and underscores." - ) - elif field == "n_seg": - if item <= 0: - raise ValueError("n_seg must be a positive integer") - elif field == "n_sig": - if item <= 0: - raise ValueError("n_sig must be a positive integer") - elif field == "fs": - if item <= 0: - raise ValueError("fs must be a positive number") - elif field == "counter_freq": - if item <= 0: - raise ValueError("counter_freq must be a positive number") - elif field == "base_counter": - if item <= 0: - raise ValueError("base_counter must be a positive number") - elif field == "sig_len": - if item < 0: - raise ValueError("sig_len must be a non-negative integer") - - # Signal specification fields - elif field in _header.SIGNAL_SPECS.index: - file_names = ( - [channel.file_name for channel in signal_snapshot.channels] - if signal_snapshot is not None - else ( - header_fields["file_name"] - if header_fields is not None - else self.file_name - ) - ) - formats = ( - [channel.fmt for channel in signal_snapshot.channels] - if signal_snapshot is not None - else (header_fields["fmt"] if header_fields is not None else self.fmt) - ) - if required_channels == "all": - required_channels = range(len(item)) - - for ch in range(len(item)): - # If the element is allowed to be None - if ch not in required_channels: - if item[ch] is None: - continue - - if field == "file_name": - # Check for file_name characters. A null signal (format - # 0), as in the layout header of a variable layout - # multi-segment record, has no file and uses '~'. - if item[ch] == "~" and formats[ch] == "0": - pass - elif re.fullmatch(r"[-\w]+\.?[\w]+", item[ch]) is None: - raise ValueError( - "File names should only contain alphanumerics, hyphens, and an extension. eg. record-100.dat" - ) - # Check that dat files are grouped together - if not util.is_monotonic(file_names): - raise ValueError( - "Signals in a record that share a given file must be consecutive." - ) - elif field == "fmt": - # Format 0 is a null signal, which has no samples and - # no file - if item[ch] == "0" and file_names[ch] == "~": - pass - elif item[ch] not in _signal.DAT_FMTS: - raise ValueError( - "File formats must be valid WFDB dat formats:", - _signal.DAT_FMTS, - ) - elif field == "samps_per_frame": - if item[ch] < 1: - raise ValueError( - "samps_per_frame values must be positive integers" - ) - elif field == "skew": - if item[ch] < 0: - raise ValueError("skew values must be non-negative integers") - elif field == "byte_offset": - if item[ch] < 0: - raise ValueError( - "byte_offset values must be non-negative integers" - ) - elif field == "adc_gain": - if item[ch] <= 0: - raise ValueError("adc_gain values must be positive") - elif field == "baseline": - # Original WFDB library 10.5.24 only has 4 bytes for baseline. - if item[ch] < -2147483648 or item[ch] > 2147483648: - raise ValueError( - "baseline values must be between -2147483648 (-2^31) and 2147483647 (2^31 -1)" - ) - elif field == "units": - if re.search(r"\s", item[ch]): - raise ValueError("units strings may not contain whitespaces.") - elif field == "adc_res": - if item[ch] < 0: - raise ValueError("adc_res values must be non-negative integers") - elif field == "block_size": - if item[ch] < 0: - raise ValueError( - "block_size values must be non-negative integers" - ) - elif field == "sig_name": - if item[ch][:1].isspace() or item[ch][-1:].isspace(): - raise ValueError( - "sig_name strings may not begin or end with whitespace." - ) - if re.search(r"[\x00-\x1f\x7f-\x9f]", item[ch]): - raise ValueError( - "sig_name strings may not contain control characters." - ) - if len(set(item)) != len(item): - raise ValueError("sig_name strings must be unique.") - - # Segment specification fields and comments - elif field in _header.SEGMENT_SPECS.index: - for ch in range(len(item)): - if field == "seg_name": - # Segment names must be alphanumerics or just a single '~' - if item[ch] == "~": - continue - accepted_string = re.match(r"[-\w]+", item[ch]) - if not accepted_string or accepted_string.string != item[ch]: - raise ValueError( - "Non-null segment names may only contain alphanumerics and dashes. Null segment names must be set to '~'" - ) - elif field == "seg_len": - # For records with more than 1 segment, the first - # segment may be the layout specification segment - # with a length of 0 - min_len = 0 if ch == 0 else 1 - if item[ch] < min_len: - raise ValueError( - "seg_len values must be positive integers. Only seg_len[0] may be 0 to indicate a layout segment" - ) - # Comment field - elif field == "comments": - if item[ch].startswith("#"): - print( - "Note: comment strings do not need to begin with '#'. This library adds them automatically." - ) - if re.search("[\t\n\r\f\v]", item[ch]): - raise ValueError( - "comments may not contain tabs or newlines (they may contain spaces and underscores)." - ) - def check_read_inputs( self, sampfrom, sampto, channels, physical, smooth_frames, return_res ): @@ -5589,10 +5597,27 @@ class _WriteModel(BaseRecord, _header.HeaderMixin, _signal.SignalMixin): skew: tuple[int | None, ...] | None from_segments: bool - # Keep the existing validation behavior until the final encoder cleanup. - check_field = Record.check_field + # Keep the legacy overwrite warning until the final encoder cleanup. _warn_about_replacing_other_files = Record._warn_about_replacing_other_files + def check_field( + self, + field, + required_channels="all", + *, + signal_snapshot=None, + header_fields: Mapping[str, object] | None = None, + ): + """Validate one field from the model's current explicit values.""" + values = header_fields if header_fields is not None else vars(self) + _check_field_value( + field, + values[field], + required_channels, + signal_snapshot=signal_snapshot, + lookup=values.__getitem__, + ) + def __post_init__(self) -> None: """Initialize the encoder fields from the model's channel snapshot.""" resolved_skew = self.skew diff --git a/tests/test_explicit_field_validation.py b/tests/test_explicit_field_validation.py new file mode 100644 index 00000000..3d8a392f --- /dev/null +++ b/tests/test_explicit_field_validation.py @@ -0,0 +1,21 @@ +"""Writer field checks use the same rules without borrowing Record methods.""" + +import pytest + +import wfdb +from wfdb.io.record import _WriteModel + + +def test_write_model_owns_field_validator(): + """The model defines its own validator rather than binding Record's.""" + assert "check_field" in vars(_WriteModel) + assert _WriteModel.check_field is not wfdb.Record.check_field + + +def test_legacy_check_field_still_checks_current_attributes(): + """The public method continues to use the Record's current values.""" + record = wfdb.Record(fs=125) + record.check_field("fs") + record.fs = -1 + with pytest.raises(ValueError, match="fs must be a positive number"): + record.check_field("fs")