Skip to content
Open
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
1 change: 1 addition & 0 deletions changelog_entries/794.check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `check_identical_time_series` and `check_redundant_time_series_copies`, which flag TimeSeries in one file that hold identical data. The first (CRITICAL) covers series of different kinds, such as a processed series identical to one in acquisition, and the second (BEST_PRACTICE_VIOLATION) covers redundant copies of the same kind, which should be stored once and linked. HDF5 links to the same dataset are not reported.
19 changes: 19 additions & 0 deletions docs/best_practices/time_series.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,25 @@ the global ``timestamps_reference_time`` of the :ref:`nwb-schema:NWBFile <sec-NW



.. _best_practice_no_identical_series:

Identical TimeSeries
~~~~~~~~~~~~~~~~~~~~

Two :ref:`nwb-schema:sec-TimeSeries` in one file should not hold identical data. When the two are of different kinds,
one of them most likely holds the wrong data. This includes a processed series that is identical to a series in
``acquisition`` (an LFP that is the raw signal, for example), two series of different neurodata types or units, and two
event-like series (constant values at explicit timestamps) that share their timestamps under different names.

When the two series are of the same kind, the second is more likely a redundant copy. If both are meant to hold the
same data, store the data once and link the second series to it, which keeps the file smaller and makes the
relationship explicit. Series that are HDF5 links to the same dataset are not reported, nor are constant data on a
rate-based time base (two empty or all-zero channels, for example). Datasets too large to read whole are compared on
a few sampled blocks, and the message says so.

Check functions: :py:meth:`~nwbinspector.checks._time_series.check_identical_time_series`,
:py:meth:`~nwbinspector.checks._time_series.check_redundant_time_series_copies`

.. _best_practice_time_series_subtypes:

Subtypes
Expand Down
4 changes: 4 additions & 0 deletions src/nwbinspector/checks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,12 @@
)
from ._time_series import (
check_data_orientation,
check_identical_time_series,
check_missing_unit,
check_rate_is_not_zero,
check_rate_is_positive,
check_rate_not_below_threshold,
check_redundant_time_series_copies,
check_regular_timestamps,
check_resolution,
check_time_series_data_is_not_empty,
Expand Down Expand Up @@ -136,6 +138,8 @@
"check_order_of_images_len",
"check_index_series_points_to_image",
"check_time_series_data_is_not_empty",
"check_identical_time_series",
"check_redundant_time_series_copies",
"check_empty_string_for_optional_attribute",
"check_small_dataset_compression",
"check_large_dataset_compression",
Expand Down
199 changes: 197 additions & 2 deletions src/nwbinspector/checks/_time_series.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""Check functions that can apply to any descendant of TimeSeries."""

import weakref
from typing import Optional

import numpy as np
from pynwb import TimeSeries
from pynwb import NWBFile, TimeSeries
from pynwb.ecephys import SpikeEventSeries
from pynwb.image import ImageSeries, IndexSeries

from .._registration import Importance, InspectorMessage, Severity, register_check
from ..utils import get_data_shape, is_ascending_series, is_regular_series
from ..utils import _comparison, get_data_shape, is_ascending_series, is_regular_series


@register_check(importance=Importance.BEST_PRACTICE_VIOLATION, neurodata_type=TimeSeries)
Expand Down Expand Up @@ -302,6 +303,200 @@ def check_time_series_data_is_not_empty(time_series: TimeSeries) -> Optional[Ins
return None


_identical_series_cache: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()


def _same_h5_object(a: _comparison.DataLike, b: _comparison.DataLike) -> bool:
"""True when two datasets are the same HDF5 object (a link), not two copies."""
a5, b5 = _comparison.h5_dataset(a), _comparison.h5_dataset(b)
if a5 is None or b5 is None:
return a is b
try:
return a5.id == b5.id
except Exception:
return a5.name == b5.name and a5.file == b5.file


def _fingerprint(data: _comparison.DataLike) -> tuple[str, bool, bool]:
"""Return (digest, exact, constant) of a dataset. exact is False when only sampled blocks were hashed."""
shape = _comparison.data_shape(data)
dtype = _comparison.data_dtype(data)
parts = [repr((shape, str(dtype)))]
if len(shape) == 0 or int(np.prod(shape, dtype=np.int64)) * dtype.itemsize <= _comparison.FULL_READ_BYTES:
values = np.asarray(data[()] if len(shape) == 0 else data[:])
parts.append(_comparison.digest(values))
return _comparison.digest(np.array(parts)), True, _comparison.is_constant(values)
constant = True
first = None
for selection in _comparison.sample_blocks(data):
values = np.asarray(data[selection])
parts.append(_comparison.digest(values))
if constant:
if not _comparison.is_constant(values):
constant = False
elif first is None:
first = values.reshape(-1)[:1]
elif not np.array_equal(first, values.reshape(-1)[:1], equal_nan=values.dtype.kind == "f"):
constant = False
return _comparison.digest(np.array(parts)), False, constant


def _object_path(obj: _comparison.DataLike) -> str:
parts = []
while obj is not None and not isinstance(obj, NWBFile):
parts.append(obj.name)
obj = obj.parent
return "/".join(reversed(parts))


def _identical_time_series_groups(nwbfile: NWBFile) -> list[dict]:
"""
Groups of TimeSeries in one file whose data are identical, computed once per file and shared by
check_identical_time_series and check_redundant_time_series_copies.

Series are grouped by data shape and dtype, so only series that could match are read, and then by a hash of a
small block at the start, so only series that agree there are read in full (or on sampled blocks). Pairs whose
data are the same HDF5 object (a link) are not reported, nor are constant data on a rate-based time base (for
example two empty or all-zero channels).
"""
try:
return _identical_series_cache[nwbfile]
except (KeyError, TypeError):
pass
by_shape: dict[tuple, list] = {}
for obj in nwbfile.objects.values():
if not isinstance(obj, TimeSeries) or obj.data is None or isinstance(obj.data, TimeSeries):
continue
try:
shape = _comparison.data_shape(obj.data)
except Exception:
continue
if len(shape) == 0 or shape[0] < 2:
continue
by_shape.setdefault((shape, str(_comparison.data_dtype(obj.data))), []).append(obj)

found = []
for series in by_shape.values():
if len(series) < 2:
continue
by_head: dict[str, list] = {}
for time_series in series:
head = _comparison.sample_blocks(time_series.data, block_bytes=64 * 1024, n_blocks=1)[0]
by_head.setdefault(_comparison.digest(np.asarray(time_series.data[head])), []).append(time_series)
by_fingerprint: dict[str, list] = {}
info = {}
for head_group in by_head.values():
if len(head_group) < 2:
continue
for time_series in head_group:
fingerprint, exact, constant = _fingerprint(time_series.data)
info[id(time_series)] = (exact, constant)
by_fingerprint.setdefault(fingerprint, []).append(time_series)
for same in by_fingerprint.values():
distinct: list[TimeSeries] = [] # drop members that are links to an earlier member's data
for time_series in same:
if not any(_same_h5_object(time_series.data, other.data) for other in distinct):
distinct.append(time_series)
if len(distinct) < 2:
continue
constant = info[id(distinct[0])][1]

def time_base(time_series: TimeSeries) -> tuple:
if time_series.timestamps is not None:
return ("timestamps", _fingerprint(time_series.timestamps)[0])
return ("rate", time_series.starting_time, time_series.rate)

if constant:
# Constant data (all ones, all zeros) only count as a duplicate when the series also carry the
# same explicit timestamps, stored separately rather than linked.
by_time_base: dict[tuple, list] = {}
for time_series in distinct:
base = time_base(time_series)
if base[0] == "timestamps":
by_time_base.setdefault(base, []).append(time_series)
subgroups = [
(group, True)
for group in by_time_base.values()
if len(group) > 1
and not all(_same_h5_object(group[0].timestamps, other.timestamps) for other in group[1:])
]
else:
subgroups = [(distinct, len({time_base(t) for t in distinct}) == 1)]
for group, same_time in subgroups:
# A copy is most likely wrong data when the series are of different kinds: an event series
# (constant values at explicit times) under two names, different neurodata types or units, or a
# processed series identical to raw acquisition, which the processing should have changed.
in_acquisition = {nwbfile.acquisition.get(t.name) is t for t in group}
wrong = (
constant
or len({type(t) for t in group}) > 1
or len({getattr(t, "unit", None) for t in group}) > 1
or len(in_acquisition) > 1
)
exact = all(info[id(t)][0] for t in group)
found.append(dict(group=group, exact=exact, constant=constant, same_time=same_time, wrong=wrong))
try:
_identical_series_cache[nwbfile] = found
except TypeError:
pass
return found


def _identical_series_message(found: dict, advice: str) -> InspectorMessage:
group = found["group"]
how = "identical" if found["exact"] else f"identical on {_comparison.N_BLOCKS} sampled blocks of"
time_base = "and the same time base" if found["same_time"] else "but different time bases (timestamps or rate)"
constant = " The data are constant and the timestamps are identical." if found["constant"] else ""
return InspectorMessage(
message=(
f"{len(group)} TimeSeries hold {how} data of shape {_comparison.data_shape(group[0].data)} {time_base}: "
f"{', '.join(_object_path(t) for t in group)}.{constant} {advice}"
)
)


@register_check(importance=Importance.CRITICAL, neurodata_type=NWBFile)
def check_identical_time_series(nwbfile: NWBFile) -> Optional[list[InspectorMessage]]:
"""
Two TimeSeries of different kinds should not hold identical data.

Reported here are identical series that are of different neurodata types or units, a processed series identical
to a series in acquisition, and event-like series (constant values) that share explicit timestamps under
different names. In each case one series most likely holds the wrong data. Identical series of the same kind
are reported by check_redundant_time_series_copies instead.

Best Practice: :ref:`best_practice_no_identical_series`
"""
messages = [
_identical_series_message(
found, "One of them most likely holds the wrong data; if it is meant to be a copy, link it instead."
)
for found in _identical_time_series_groups(nwbfile)
if found["wrong"]
]
return messages or None


@register_check(importance=Importance.BEST_PRACTICE_VIOLATION, neurodata_type=NWBFile)
def check_redundant_time_series_copies(nwbfile: NWBFile) -> Optional[list[InspectorMessage]]:
"""
Two TimeSeries of the same kind should not store the same data twice; store it once and link the second
series to it. Check that both are meant to hold the same data.

Best Practice: :ref:`best_practice_no_identical_series`
"""
messages = [
_identical_series_message(
found,
"If both are meant to hold the same data, store it once and link the other series to it; "
"otherwise one of them holds the wrong data.",
)
for found in _identical_time_series_groups(nwbfile)
if not found["wrong"]
]
return messages or None


@register_check(importance=Importance.BEST_PRACTICE_VIOLATION, neurodata_type=TimeSeries)
def check_rate_not_below_threshold(
time_series: TimeSeries, low_rate_threshold: float = 0.01
Expand Down
Loading
Loading