Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions changelog.d/record-data-shift-time.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**Shift the selected start time of RecordData**
``RecordData.shift_time(datetime.timedelta(...))`` returns an independent
result with a shifted start date and time. Complete timestamps move
together, time-only values wrap within the day, and date-only values accept
whole-day shifts and gain midnight so they can be written. The source
header retains its original timestamp; writing uses the shifted selected
timestamp. Comments, annotations, and counter fields are unchanged.
13 changes: 12 additions & 1 deletion docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ files that either reader accepts.
.. autoclass:: wfdb.io.RecordData
:no-index:
:members: to_physical, to_digital, to_legacy_record, select,
with_values, with_channels, with_comments, write
with_values, with_channels, with_comments, shift_time, write

.. autoclass:: wfdb.io.UniformSignals
:no-index:
Expand Down Expand Up @@ -620,6 +620,17 @@ return independent arrays. They update the selected view and leave
Changing a unit label does not rescale the samples or change gain and
baseline; use it to correct a mislabeled header, not to convert units.

``RecordData.shift_time(timedelta(...))`` changes the selected start date and
time without changing samples. A time-only value wraps within the day, so
whole-day shifts have no visible effect without a date. A date-only value
accepts whole-day shifts and gains a midnight time because WFDB headers
cannot write a date without a time. The result has independent arrays, and
``source_header`` still contains the original timestamp. A written record
uses the shifted timestamp; the in-memory result still exposes the original
through provenance. Comments, annotations, and counter fields are unchanged.
For de-identification, review comments separately with ``with_comments`` and
do not share the result's source provenance if it is sensitive.

.. code-block:: python

read = wfdb.read_signals("sample-data/100", layout="uniform")
Expand Down
62 changes: 57 additions & 5 deletions src/wfdb/io/_record_data_edits.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Validated edits of selected record data and its private read model."""

import copy
import datetime
import operator
import re
from dataclasses import replace
Expand Down Expand Up @@ -349,7 +350,7 @@ def replace_record_channel_metadata(read, names, units):
if any(not unit or re.search(r"\s", unit) for unit in units):
raise ValueError("units must be nonempty and contain no whitespace")
_require_printable_ascii(units)
return _replace_record_text(read, names=names, units=units)
return _replace_record_metadata(read, names=names, units=units)


def replace_record_comments(read, comments):
Expand All @@ -360,11 +361,54 @@ def replace_record_comments(read, comments):
if any(comment != comment.strip(" #") for comment in comments):
raise ValueError("comments must not start or end with spaces or '#'")
_require_printable_ascii(comments)
return _replace_record_text(read, comments=comments)
return _replace_record_metadata(read, comments=comments)


def shift_record_time(read, delta):
"""Shift the selected start date or time without changing its source."""
if not isinstance(delta, datetime.timedelta):
raise TypeError("delta must be a datetime.timedelta")
base_date = read.metadata.base_date
base_time = read.metadata.base_time
if base_date is None and base_time is None:
raise ValueError("Cannot shift a record without a base date or time")
if base_date is not None and base_time is None:
if delta.seconds or delta.microseconds:
raise ValueError("A date-only record can shift by whole days only")
try:
shifted_date = base_date + delta
except OverflowError as error:
raise ValueError("Shifted date is outside years 1 to 9999") from error
# A WFDB header cannot write a date without a time. Normalize the
# date-only input to midnight so the edited result can be saved.
return _replace_record_metadata(read, timing=(shifted_date, datetime.time(0)))
if base_time.tzinfo is not None:
raise ValueError("WFDB base times cannot have time zones")
if base_date is None:
day_us = 24 * 60 * 60 * 1_000_000
clock_us = (
base_time.hour * 3600 + base_time.minute * 60 + base_time.second
) * 1_000_000 + base_time.microsecond
delta_us = (
delta.days * 24 * 60 * 60 + delta.seconds
) * 1_000_000 + delta.microseconds
clock_us = (clock_us + delta_us) % day_us
hour, clock_us = divmod(clock_us, 3600 * 1_000_000)
minute, clock_us = divmod(clock_us, 60 * 1_000_000)
second, microsecond = divmod(clock_us, 1_000_000)
shifted_time = datetime.time(hour, minute, second, microsecond)
return _replace_record_metadata(read, timing=(None, shifted_time))
try:
shifted = datetime.datetime.combine(base_date, base_time) + delta
except OverflowError as error:
raise ValueError("Shifted date is outside years 1 to 9999") from error
return _replace_record_metadata(read, timing=(shifted.date(), shifted.time()))


def _replace_record_text(read, *, names=None, units=None, comments=None):
"""Copy arrays and change only the selected view's header text."""
def _replace_record_metadata(
read, *, names=None, units=None, comments=None, timing=None
):
"""Copy arrays and change only the selected view's header metadata."""
model = read._model
expanded = isinstance(read.signals, ExpandedSignals)
if read.signals.kind == "digital":
Expand All @@ -388,6 +432,8 @@ def _replace_record_text(read, *, names=None, units=None, comments=None):
record.units = list(units)
if comments is not None:
record.comments = list(comments)
if timing is not None:
record.base_date, record.base_time = timing
field = ("e_" if expanded else "") + (
"p_signal" if read.signals.kind == "physical" else "d_signal"
)
Expand All @@ -411,8 +457,14 @@ def _replace_record_text(read, *, names=None, units=None, comments=None):
selected_comments = (
model.selected_header.comments if comments is None else comments
)
fields = model.selected_header.record_fields
if timing is not None:
fields = replace(fields, base_date=timing[0], base_time=timing[1])
header = replace(
model.selected_header, signals=selected, comments=selected_comments
model.selected_header,
record_fields=fields,
signals=selected,
comments=selected_comments,
)
metadata = _metadata_for_view(
header.record_fields,
Expand Down
33 changes: 30 additions & 3 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Explicit representations of loaded WFDB signal values."""

import copy
import datetime
import os
from dataclasses import dataclass, replace
from typing import Literal
Expand Down Expand Up @@ -85,9 +86,9 @@ class RecordData:
segments. Conversions return another ``RecordData`` and leave this one
unchanged. Use ``write`` to save the selected values.
Construct results through ``read_signals`` or ``read_segments``. Use
``select``, ``with_values``, ``with_channels``, and ``with_comments`` for
validated edits; ``dataclasses.replace`` cannot construct a complete
result with source provenance.
``select``, ``with_values``, ``with_channels``, ``with_comments``, and
``shift_time`` for validated edits; ``dataclasses.replace`` cannot
construct a complete result with source provenance.
"""

signals: UniformSignals | ExpandedSignals
Expand Down Expand Up @@ -382,6 +383,32 @@ def with_comments(self, comments: list[str] | tuple[str, ...]) -> "RecordData":

return replace_record_comments(self, comments)

def shift_time(self, delta: datetime.timedelta) -> "RecordData":
"""Return a copy with its selected start date or time shifted.

A complete date and time shift together. A time without a date wraps
within the day; whole days in ``delta`` have no visible effect. A date
without a time accepts whole-day shifts only and gains a midnight
time, because WFDB cannot write a date without a time. The original
``source_header`` keeps its timestamp, while a written header uses the
shifted one. This method does not change comments, annotations, or
counter fields; comments that identify someone need a separate edit.
The returned arrays and masks are independent of this object.

Parameters
----------
delta : datetime.timedelta
Signed amount to add to the selected start date or time.

Returns
-------
RecordData
An independent result with the shifted selected start.
"""
from wfdb.io._record_data_edits import shift_record_time

return shift_record_time(self, delta)

def write(
self,
path: str | os.PathLike,
Expand Down
209 changes: 209 additions & 0 deletions tests/test_record_data_shift_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
"""Validated shifts of a selected RecordData timestamp."""

import datetime
from dataclasses import replace

import numpy as np
import pytest

import wfdb
from wfdb.io._read_model import _metadata_for_view
from wfdb.io.signal_values import _from_read_model, _from_record


def _timestamped_record(tmp_path, *, base_date, base_time):
"""Write a small record with a known start and no identifying comment."""
path = tmp_path / "source"
wfdb.write_signals(
path,
np.arange(4, dtype=np.int16).reshape(4, 1),
fs=2,
kind="digital",
formats="16",
channel_names=["I"],
units=["mV"],
adc_gain=[200],
baseline=[0],
missing="none",
base_date=base_date,
base_time=base_time,
comments=["Reviewed"],
)
return path


@pytest.mark.parametrize("kind", ["physical", "digital"])
@pytest.mark.parametrize("layout", ["uniform", "expanded"])
def test_complete_timestamp_shift_round_trips_and_keeps_source(tmp_path, kind, layout):
"""The written header contains the shifted microsecond time, not the source."""
source_date = datetime.date(2020, 5, 6)
source_time = datetime.time(23, 59, 59, 123456)
path = _timestamped_record(tmp_path, base_date=source_date, base_time=source_time)
read = wfdb.read_signals(path, kind=kind, layout=layout)
delta = datetime.timedelta(days=3, seconds=2, microseconds=654321)
shifted = read.shift_time(delta)
expected = datetime.datetime.combine(source_date, source_time) + delta

assert shifted.metadata.base_datetime == expected
assert shifted.source_header == read.source_header
assert shifted.source_header.base_datetime == datetime.datetime.combine(
source_date, source_time
)
assert shifted.source_selection == read.source_selection
assert shifted.metadata.comments == read.metadata.comments
source_arrays = (
read.signals.values if layout == "expanded" else (read.signals.values,)
)
shifted_arrays = (
shifted.signals.values if layout == "expanded" else (shifted.signals.values,)
)
for original, result in zip(source_arrays, shifted_arrays):
np.testing.assert_array_equal(result, original)
assert not np.shares_memory(result, original)
if kind == "digital":
np.testing.assert_array_equal(
np.ma.getmaskarray(result), np.ma.getmaskarray(original)
)

destination = tmp_path / "shifted"
shifted.write(destination)
header_text = destination.with_suffix(".hea").read_text()
assert "06/05/2020" not in header_text
assert "23:59:59.123456" not in header_text
restored = wfdb.read_signals(destination, kind=kind, layout=layout)
assert restored.metadata.base_datetime == expected


def test_time_only_shift_wraps_and_ignores_whole_days(tmp_path):
"""No calendar date is invented when a clock time crosses midnight."""
path = _timestamped_record(
tmp_path, base_date=None, base_time=datetime.time(23, 30, 0, 123456)
)
read = wfdb.read_signals(path, kind="digital", layout="uniform")
shifted = read.shift_time(datetime.timedelta(days=-3, hours=2))
assert shifted.metadata.base_date is None
assert shifted.metadata.base_time == datetime.time(1, 30, 0, 123456)
assert shifted.source_header.base_time == datetime.time(23, 30, 0, 123456)
assert read.shift_time(datetime.timedelta(days=10)).metadata.base_time == (
read.metadata.base_time
)
shifted.write(tmp_path / "shifted")
restored = wfdb.read_signals(tmp_path / "shifted", kind="digital", layout="uniform")
assert restored.metadata.base_date is None
assert restored.metadata.base_time == shifted.metadata.base_time


def test_shift_copies_digital_missing_mask_and_prior_edits(tmp_path):
"""A time change keeps current sample edits without sharing their mask."""
path = _timestamped_record(
tmp_path, base_date=datetime.date(2020, 5, 6), base_time=datetime.time(12)
)
read = wfdb.read_signals(path, kind="digital", layout="uniform")
mask = np.zeros(read.signals.values.shape, dtype=bool)
mask[1, 0] = True
edited = read.with_values(np.ma.array(read.signals.values, mask=mask))
shifted = edited.shift_time(datetime.timedelta(hours=1))
np.testing.assert_array_equal(shifted.signals.values.mask, mask)
assert not np.shares_memory(shifted.signals.values.mask, edited.signals.values.mask)
assert shifted._edited_values
shifted.signals.values.mask[1, 0] = False
assert edited.signals.values.mask[1, 0]


def _date_only_view(read, date):
"""Make a partial timestamp view; WFDB files require time before date."""
model = read._model
fields = replace(
model.selected_header.record_fields, base_date=date, base_time=None
)
header = replace(model.selected_header, record_fields=fields)
metadata = _metadata_for_view(
fields,
header.signals,
header.comments,
model.kind,
"uniform",
)
return _from_read_model(replace(model, selected_header=header, metadata=metadata))


def test_date_only_accepts_whole_days_and_checks_range(tmp_path):
"""Date-only views cannot interpret a sub-day shift."""
path = _timestamped_record(
tmp_path, base_date=datetime.date(2020, 5, 6), base_time=datetime.time(0)
)
read = wfdb.read_signals(path, kind="physical", layout="uniform")
date_only = _date_only_view(read, datetime.date(2020, 5, 6))
shifted = date_only.shift_time(datetime.timedelta(days=-3))
assert shifted.metadata.base_date == datetime.date(2020, 5, 3)
assert shifted.metadata.base_time == datetime.time(0)
shifted.write(tmp_path / "date_only")
restored = wfdb.read_signals(
tmp_path / "date_only", kind="physical", layout="uniform"
)
assert restored.metadata.base_date == datetime.date(2020, 5, 3)
assert restored.metadata.base_time == datetime.time(0)
with pytest.raises(ValueError, match="whole days only"):
date_only.shift_time(datetime.timedelta(hours=1))
at_limit = _date_only_view(read, datetime.date(9999, 12, 31))
with pytest.raises(ValueError, match="outside years 1 to 9999"):
at_limit.shift_time(datetime.timedelta(days=1))


def test_missing_time_bad_delta_and_full_date_overflow(tmp_path):
"""Invalid shifts fail when called and leave the original unchanged."""
read = wfdb.read_signals(
"sample-data/100", kind="physical", layout="uniform", stop=4
)
with pytest.raises(ValueError, match="without a base date or time"):
read.shift_time(datetime.timedelta(days=1))
with pytest.raises(TypeError, match="datetime.timedelta"):
read.shift_time(3600)
path = _timestamped_record(
tmp_path,
base_date=datetime.date(9999, 12, 31),
base_time=datetime.time(23, 59, 59),
)
dated = wfdb.read_signals(path, kind="physical", layout="uniform")
with pytest.raises(ValueError, match="outside years 1 to 9999"):
dated.shift_time(datetime.timedelta(seconds=2))
assert dated.metadata.base_date == datetime.date(9999, 12, 31)


@pytest.mark.parametrize(
"target", [datetime.date(2100, 1, 1), datetime.date(1500, 1, 1)]
)
def test_shifted_distant_dates_write_and_make_dataframe_indexes(tmp_path, target):
"""De-identified dates outside pandas' nanosecond range remain usable."""
source = datetime.datetime(2020, 5, 6, 12, 0, 0)
path = _timestamped_record(
tmp_path, base_date=source.date(), base_time=source.time()
)
read = wfdb.read_signals(path, kind="digital", layout="uniform")
delta = datetime.datetime.combine(target, source.time()) - source
shifted = read.shift_time(delta)
shifted.write(tmp_path / "shifted")
restored = wfdb.read_signals(tmp_path / "shifted", kind="digital", layout="uniform")
assert restored.metadata.base_date == target
chunks = list(wfdb.iter_dataframes(tmp_path / "shifted", 2))
assert chunks[0].index[0].to_pydatetime() == datetime.datetime.combine(
target, source.time()
)
assert all(
chunk.index.unit == ("us" if target.year < 1677 else "ns") for chunk in chunks
)


def test_legacy_backed_record_data_can_shift_time(tmp_path):
"""The compatibility adapter retains provenance and uses current arrays."""
path = _timestamped_record(
tmp_path, base_date=datetime.date(2020, 5, 6), base_time=datetime.time(12)
)
modern = wfdb.read_signals(path, kind="digital", layout="uniform")
legacy = _from_record(modern.to_legacy_record(), "digital", False)
assert legacy._model is None
shifted = legacy.shift_time(datetime.timedelta(days=1))
assert shifted._model is None
assert shifted.source_header == legacy.source_header
assert shifted.metadata.base_date == datetime.date(2020, 5, 7)
assert not np.shares_memory(shifted.signals.values, legacy.signals.values)
Loading