diff --git a/README.md b/README.md index 28c46aa..03e6d36 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,20 @@ This validates the declared primary export without requiring or discovering derivatives or summary JSON. The ordinary `open_recording()` contract still requires the complete split export. +## Write a local H5 + +Split Zarr is the published format. For local work, reader 0.5.0 can assemble a +recording into one H5 in the layout the converter read: + +```bash +bdsp-zarr-to-h5 --primary primary.zarr --derivatives derivative.zarr \ + --summary-json summary.json --output recording.h5 +``` + +Signals are written as int16 with a calibration that reproduces every Zarr +sample exactly. The [H5 export guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/bids-zarr/H5_EXPORT.md) +lists what the split format does not carry. + ## Further help The [getting started guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/README.md) covers signals, annotations, features, diff --git a/docs/README.md b/docs/README.md index de05c40..ffb1564 100644 --- a/docs/README.md +++ b/docs/README.md @@ -140,14 +140,41 @@ for native signal arrays or the Zarr reader for lazy native-clock windows. `bdsp.compat.sleep_yoda` retains the `load_standardized_h5` and `PSGReader` compatibility aliases. -## 5. Scope and further reading +## 5. Write a local H5 from a split Zarr recording -The package reads existing recordings and results. It does not perform EDF +Only split Zarr is produced for new recordings. To work with one local H5, +reader 0.5.0 assembles the three artifacts in the layout the converter read: + +```python +import bdsp +from bdsp.zarr_to_h5 import write_h5 + +write_h5( + "/data/recording.h5", + primary="/data/primary.zarr", + derivatives="/data/derivative.zarr", + summary_json="/data/summary.json", +) +record = bdsp.read_h5("/data/recording.h5") +``` + +or `bdsp-zarr-to-h5 --primary ... --derivatives ... --summary-json ... --output ...`. +Signals become int16 with a recovered calibration that reproduces every Zarr +sample exactly (float32 where none exists); annotations, feature time series +and recording summaries are restored in their H5 layout. Metadata the split +format never stored, such as signal filter strings, is listed in the file's +`bdsp_h5_export` attribute instead. See the [H5 export guide](bids-zarr/H5_EXPORT.md). + +## 6. Scope and further reading + +The package reads existing recordings and results and can write the local H5 +described above. It does not perform EDF ingestion, obtain cloud credentials, run models, compute features, or generate reports. Conversion and feature computation have their own producer workflows: - [BDSP data format and repository ownership](bids-zarr/README.md) - [Zarr API and validation reference](bids-zarr/READER_DESIGN.md) +- [Local H5 export from split Zarr](bids-zarr/H5_EXPORT.md) - [H5-to-Zarr converter](https://github.com/bdsp-core/bdsp-psg-conversion) - [Feature producer](https://github.com/bdsp-core/bdsp-sleep-features) - [Historical format migration](bids-zarr/MIGRATION_HISTORY.md) diff --git a/docs/bids-zarr/H5_EXPORT.md b/docs/bids-zarr/H5_EXPORT.md new file mode 100644 index 0000000..1437ba8 --- /dev/null +++ b/docs/bids-zarr/H5_EXPORT.md @@ -0,0 +1,133 @@ +# Writing a local H5 from a split Zarr recording + +New BDSP conversions publish only the split representation: primary Zarr, +derivative Zarr and summary JSON. For local work it is still convenient to have +one H5 per recording in the layout the converter read. `bdsp.zarr_to_h5` +assembles the three artifacts into that file. It reads only local paths, does +not run models or compute features, and never changes its inputs. + +```python +from bdsp.zarr_to_h5 import write_h5 + +report = write_h5( + "/data/recording.h5", + primary="/data/primary.zarr", + derivatives="/data/derivative.zarr", + summary_json="/data/summary.json", +) +print(report.signals_int16, report.signals_float32, report.notes) +``` + +The same from a shell, after `pip install bdsp`: + +```bash +bdsp-zarr-to-h5 --primary primary.zarr --derivatives derivative.zarr \ + --summary-json summary.json --output recording.h5 +``` + +`derivatives` and `summary_json` are optional. Without the derivative the H5 has +no model annotations or feature time series; without the summary JSON it has no +`recording_summary` and no `meas_date`. The output appears only once it is +complete, and an existing file is replaced only with `overwrite=True` +(`--overwrite`). The three artifacts must describe the same subject, session and +duration, and the two stores the same source file; otherwise the call fails. +Read the result with `bdsp.read_h5()` or `bdsp.open_h5()` as before. + +## What goes where + +| H5 | From | Encoding | +| --- | --- | --- | +| root `subject_id`, `session_id`, `duration_sec`, `age`, `sex` | primary `recording.json` | `age` is the published value (capped at 90); `sex` is `Male`/`Female`/`Unknown` | +| root `meas_date` (and `h5_meas_date`) | summary JSON `provenance` | the corrected date where the JSON has one; the archived H5 date is kept as `h5_meas_date` | +| `/signals/` | primary continuous channels with origin `signal` | int16 digital samples with `fs`, `unit`, `phys_min`, `phys_max`, `dig_min`, `dig_max` (below) | +| `/annotations///` | event channels with origin `annotation`, primary and derivative | `starts`, `ends`, `durations` (float32 seconds), `codes` (int16 original codes), `event_map`, `format="event_table"` | +| `/time_series//` | `bdsp.sleep-feature-payload.v1` payload groups | copied as stored: attributes, dtypes, shapes, masks, statuses, `information` | +| `/recording_summary/` | summary JSON `features` and `vectors` | every row and column in its original order; exported vectors under `arrays/` | +| root `bdsp_h5_export` | — | JSON naming the writer, inputs, conversion skips and what the split export does not carry | + +`` is the location the payloads name, normally +`/features/bdsp_sleep_features` (2026-10 conversions) or +`/features/sleep_features`. Features that came from a producer's separate +feature H5 (`/sleep_features/...`, I0007) are written under +`/features/sleep_features`, so every rebuilt H5 has its features under +`/features`. Channels appended to the primary store after conversion, such as +the PAP channels copied from `*_desc-pap.h5`, are included with a +`source_file` attribute naming that file; pass +`include_appended_signals=False` (`--no-appended-signals`) to leave them out. + +### Signal samples and calibration + +A primary store holds each signal as float32 physical values, computed by the +converter as `float32(digital * scale + offset)` in float64, with +`scale` and `offset` from the source calibration and voltages rescaled to +microvolts. The calibration itself is not stored. The writer recovers an int16 +encoding instead of storing float32: + +1. find the quantization lattice of the channel's distinct values; +2. try calibrations in producer conventions — the full int16 digital range + first, then zero-offset, symmetric and zero-based physical ranges with the + fewest significant digits (for a sparsely used range, also spans solved from + its extreme values); +3. accept a calibration only if the converter's formula reproduces **every + sample bit-exactly**, then write the int16 samples. + +A channel declared in mV or V keeps that unit and its own calibration; the +microvolt rescaling is restored through `unit_converted_from`. A channel for +which no exact int16 calibration exists (for example one with missing samples, +`NaN`) is written as float32 with an identity calibration +(`phys_min = dig_min = 0`, `phys_max = dig_max = 1`), and the report notes it. +Either way, every consumer applying the usual digital-to-physical formula gets +the values the Zarr store holds. Different exact calibrations can encode the +same values, so a recovered `phys_min`/`dig_min` need not equal the archived +one; the parity check reports how often they do. + +### Annotation times + +Stores keep onsets and durations as integer microseconds rounded from the +source float32 seconds. The writer converts them back to float32 seconds, so +values round-trip to the source float32 except where that float32 resolves +about a microsecond or less (times below about 16 s), and then within 1 µs. `ends` +is written as `starts + durations`; a source table may have stored a slightly +different float32 `ends` (the converter accepted up to 10 ms). Events are in +start order, and `event_map` lists the codes in ascending order. + +## What cannot be rebuilt + +The split export never stored the following, so no writer can recover them +from Zarr and JSON. They are listed in `bdsp_h5_export.not_in_split_export` +rather than invented: + +- signal `prefilter` and `type` attributes; +- annotation attributes other than `event_map`, such as `rule` and + `rule_description` on `resp_3`/`resp_4`; +- root attributes other than identity, duration, age, sex and dates (for + example `age_in_days`, `metadata_source`, `hypopnea_rule_source`), and an + archived age above 90; +- the feature producer's `package_name`/`package_version` attributes and its + `recording/identity_json` and `provenance/json` datasets; +- groups outside signals, annotations and exported features, such as + `/features/research/spindles`; +- conversion-time skips: channels, tables or families the converter left out + are listed in each store's `source.skipped`, repeated in `bdsp_h5_export`; +- summary arrays that are not exported vectors (withheld or multidimensional + arrays); their rows keep `array_path`, and the report notes each one; +- temporal families exported without a payload by pre-2026-10-20 converters + (none remain in the published cohorts); the report notes each one. + +Original H5 and EDF files remain in `sourcedata/` and are the reference for +these items. + +## Checking a rebuilt H5 against its source + +`bdsp.h5_compare.compare_h5(source_h5, rebuilt_h5)` compares everything the +split export carries: identity and dates, each signal's rate, length and +physical samples (with the converter's formula, so a different exact +calibration still matches), annotation events and codes, every feature family +recursively, and the summary columns and arrays. It returns a JSON-safe report +with `verdict`, `failures` and `not_exported`; it names channels, tables, +features and attributes but never recorded values. Pass `features=` with the +producer's feature H5 for sessions whose features were never merged into the +session H5. The repeatable dataset check is +[`validation/h5_parity.py`](../../validation/README.md#h5-parity-zarr-to-h5), +and the [2026-11-27 review](../../validation/reports/2026-11-27-h5-parity.md) +records the results for all six cohorts. diff --git a/docs/bids-zarr/README.md b/docs/bids-zarr/README.md index db64b4f..adde044 100644 --- a/docs/bids-zarr/README.md +++ b/docs/bids-zarr/README.md @@ -17,7 +17,8 @@ The current storage model separates recorded/expert data from algorithm outputs: | **Derivative summary JSON** | Recording-level feature summaries, statuses, units and exported vectors | `_task-psg_deriv-bdspsleepfeatures.json` | The Python reader combines these into **one logical recording**. Reading does -not merge them into a new H5 or a single larger Zarr store. A `.zarr/` is a +not merge them into a new H5 or a single larger Zarr store; to write one local +H5 from the three artifacts, use [`bdsp.zarr_to_h5`](H5_EXPORT.md). A `.zarr/` is a directory locally and a collection of objects under a prefix on S3, rather than one monolithic file. @@ -32,7 +33,7 @@ Original EDF/H5 inputs remain immutable archives under `sourcedata/`. | --- | --- | | [`bdsp-sleep-features`](https://github.com/bdsp-core/bdsp-sleep-features) | Computes/reuses CAISR and the registered scientific feature panel; writes feature H5, scalar TSV, integrity JSON and, for full runs, a PDF report | | [`bdsp-psg-conversion`](https://github.com/bdsp-core/bdsp-psg-conversion) | Converts the selected session H5 content into primary/derivative Penn TS-Zarr, summary JSON and BIDS metadata; also provides cohort scalar roll-ups. It does not compute missing features or rerun CAISR | -| [`bdsp-python`](https://github.com/bdsp-core/bdsp-python) — this repository | Shared readers: associates the three artifacts, decodes values and exposes lazy reads or explicit materialization. It does not run models, generate reports, discover cloud inputs or repair scoring | +| [`bdsp-python`](https://github.com/bdsp-core/bdsp-python) — this repository | Shared readers: associates the three artifacts, decodes values and exposes lazy reads or explicit materialization; can write one local H5 from the three artifacts. It does not run models, generate reports, discover cloud inputs or repair scoring | | [`sleep-yoda-web`](https://github.com/bdsp-core/sleep-yoda-web) | Offline SY orchestration/assembly, additional retained analyses, reports and viewer assets; serves completed data through the shared reader | | `arpa-h-psg-eeg-ingestion` | Upstream vendor/EDF ingestion and standardization, as identified by the converter's ingestion boundary; separate from H5-to-Zarr export | | `sleep-yoda` desktop | Legacy implementations and compatibility consumers; some retained producers still use pinned desktop code | @@ -419,6 +420,7 @@ revisions, availability and report versions, and | Native storage and payload extension | [Converter file structures](https://github.com/bdsp-core/bdsp-psg-conversion/blob/16c2d95f10dbeed8a1549da48dbd2ef51384fe57/docs/file-structures.md), `zarr_json/feature_payload.py` | | Feature definitions and producer H5 | Producer registry, generated catalog and output contract linked in Section 2 | | Reader schemas, decoding and validation | [`src/bdsp/bids_zarr/`](../../src/bdsp/bids_zarr/), [reader design](READER_DESIGN.md) | +| Local H5 from split Zarr and source parity | [`src/bdsp/zarr_to_h5.py`](../../src/bdsp/zarr_to_h5.py), [`h5_compare.py`](../../src/bdsp/h5_compare.py), [H5 export](H5_EXPORT.md) | | Initial export gap, fix and single-recording parity evidence | [Migration history](MIGRATION_HISTORY.md) | | Storage completeness versus scientific completion | [Enrichment audit](ENRICHMENT_AUDIT.md), [completion workflow](ENRICHMENT_COMPLETION.md) | diff --git a/pyproject.toml b/pyproject.toml index 671b82b..9ec1bc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "hatchling.build" [project] name = "bdsp" -version = "0.4.0" -description = "Python reader for standardized BDSP sleep/PSG Zarr recordings." +version = "0.5.0" +description = "Python reader for standardized BDSP sleep/PSG Zarr recordings, with a local H5 writer." readme = "README.md" requires-python = ">=3.11" license = "Apache-2.0" @@ -41,6 +41,9 @@ validation = [ "boto3>=1.34", ] +[project.scripts] +bdsp-zarr-to-h5 = "bdsp.zarr_to_h5:main" + [project.urls] Homepage = "https://bdsp.io/" Documentation = "https://github.com/bdsp-core/bdsp-python/blob/main/docs/README.md" diff --git a/src/bdsp/__init__.py b/src/bdsp/__init__.py index 0331385..84593b9 100644 --- a/src/bdsp/__init__.py +++ b/src/bdsp/__init__.py @@ -16,4 +16,4 @@ "read_h5", ] -__version__ = "0.4.0" +__version__ = "0.5.0" diff --git a/src/bdsp/h5_compare.py b/src/bdsp/h5_compare.py new file mode 100644 index 0000000..837bfca --- /dev/null +++ b/src/bdsp/h5_compare.py @@ -0,0 +1,464 @@ +"""Compare an H5 written by :mod:`bdsp.zarr_to_h5` with the source H5 it came from. + +The comparison follows what the split Zarr export is meant to preserve: + +* identity, duration, age (capped at 90 as published), sex and recording date; +* every ``/signals`` channel's sampling rate, length and physical float32 + samples, computed with the converter's calibration formula (digital samples + and calibration attributes are reported separately: other exact encodings exist); +* every annotation table's events, codes and ``event_map``; +* every feature time-series group, recursively (attributes, dtypes, values); +* the ``recording_summary`` columns and arrays. + +Anything else in the source H5 is listed under ``not_exported`` rather than +counted as a failure: the split export does not carry it. Results name +channels, tables, features and attributes, never recorded values. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +import h5py +import numpy as np + +from .zarr_to_h5 import SUMMARY_COLUMNS, _unit_factor, physical_values + +__all__ = ["FEATURE_ROOTS", "compare_h5"] + +#: Feature roots in session H5s (current and 2026-10 names) and in a producer's own H5. +FEATURE_ROOTS = ("features/sleep_features", "features/bdsp_sleep_features", "sleep_features") +_AGE_CAP = 90.0 +_SEX = {"m": "Male", "male": "Male", "f": "Female", "female": "Female", + "u": "Unknown", "unknown": "Unknown"} # fmt: skip +_LOADABLE = {"ok", "valid_zero"} +#: An ``ends`` value may differ from starts + durations by this much (converter tolerance). +_END_TOLERANCE_S = 0.011 + + +def _plain(value: Any) -> Any: + """An H5 attribute or value as a JSON-comparable Python value.""" + if isinstance(value, bytes): + return value.decode("utf-8", "replace") + if isinstance(value, np.ndarray): + return [_plain(item) for item in value.tolist()] if value.ndim else _plain(value.item()) + if isinstance(value, np.generic): + return _plain(value.item()) + if isinstance(value, (list, tuple)): + return [_plain(item) for item in value] + return value + + +def _attrs(node) -> dict[str, Any]: + return {name: _plain(value) for name, value in node.attrs.items()} + + +def _text(value: Any) -> str: + value = _plain(value) + return "" if value is None else str(value) + + +def _values(dataset: h5py.Dataset) -> np.ndarray: + if h5py.check_string_dtype(dataset.dtype) is not None: + return np.asarray(dataset.asstr()[()], dtype=object) + return np.asarray(dataset[()]) + + +def _equal(a: np.ndarray, b: np.ndarray) -> bool: + if a.shape != b.shape: + return False + if a.dtype.kind in "fc" or b.dtype.kind in "fc": + try: + return bool(np.array_equal(a.astype(np.float64), b.astype(np.float64), equal_nan=True)) + except (TypeError, ValueError): + return False + return bool(np.array_equal(a, b)) + + +def _same_tree(a: h5py.Group, b: h5py.Group) -> list[str]: + """Paths (relative to ``a``) whose attributes, members, dtype or values differ.""" + problems = [] + if _attrs(a) != _attrs(b): + problems.append(f"{a.name}@attrs") + if set(a) != set(b): + problems.append(f"{a.name}:members") + for name in set(a) & set(b): + x, y = a[name], b[name] + if isinstance(x, h5py.Group) or isinstance(y, h5py.Group): + if isinstance(x, h5py.Group) and isinstance(y, h5py.Group): + problems += _same_tree(x, y) + else: + problems.append(f"{x.name}:kind") + continue + text = h5py.check_string_dtype(x.dtype) is not None + if text != (h5py.check_string_dtype(y.dtype) is not None) or ( + not text and x.dtype != y.dtype + ): + problems.append(f"{x.name}:dtype") + elif _attrs(x) != _attrs(y): + problems.append(f"{x.name}@attrs") + elif not _equal(_values(x), _values(y)): + problems.append(f"{x.name}:values") + return problems + + +def _feature_root(h5: h5py.File) -> h5py.Group | None: + for root in FEATURE_ROOTS: + if isinstance(h5.get(root), h5py.Group): + return h5[root] + return None + + +def _export_info(h5: h5py.File) -> dict[str, Any]: + try: + return json.loads(_text(h5.attrs.get("bdsp_h5_export", "{}"))) + except ValueError: + return {} + + +def _skipped(info: dict[str, Any], kind: str) -> set[str]: + out: set[str] = set() + for skipped in (info.get("skipped_at_conversion") or {}).values(): + out |= set((skipped or {}).get(kind, {})) + return out + + +def _identity(original: h5py.File, exported: h5py.File, failures: list[str]) -> dict: + report: dict[str, str] = {} + + def check(name: str, expected: Any, actual: Any, required: bool = False) -> None: + if expected is None: + report[name] = "absent_in_original" + elif actual is None: + report[name] = "missing_in_export" + if required: + failures.append(f"identity: {name} missing") + elif expected == actual: + report[name] = "equal" + else: + report[name] = "differs" + failures.append(f"identity: {name} differs") + + def number(h5, name): + value = h5.attrs.get(name) + if value is None: + return None + value = float(_plain(value)) + return None if math.isnan(value) else value + + def sex(h5): + value = h5.attrs.get("sex") + return None if value is None else _SEX.get(_text(value).strip().lower(), _text(value)) + + for name in ("subject_id", "session_id"): + check(name, _text(original.attrs.get(name)) or None, + _text(exported.attrs.get(name)) or None, required=True) # fmt: skip + check("duration_sec", number(original, "duration_sec"), number(exported, "duration_sec"), + required=True) # fmt: skip + age = number(original, "age") + check("age", None if age is None else min(age, _AGE_CAP), number(exported, "age")) + check("sex", sex(original), sex(exported)) + date = exported.attrs.get("h5_meas_date", exported.attrs.get("meas_date")) + check("meas_date", _text(original.attrs.get("meas_date")) or None, + _text(date) or None) # fmt: skip + return report + + +def _signals(original: h5py.File, exported: h5py.File, info: dict, failures: list[str]) -> dict: + a, b = original.get("signals", {}), exported.get("signals", {}) + names_a, names_b = set(a), set(b) + skipped = _skipped(info, "signals") + missing = sorted(names_a - names_b) + appended = sorted(n for n in names_b - names_a if "source_file" in b[n].attrs) + extra = sorted(names_b - names_a - set(appended)) + for name in missing: + if name not in skipped: + failures.append(f"signal missing: {name}") + for name in extra: + failures.append(f"signal not in original: {name}") + counts = {"physical_equal": 0, "digital_equal": 0, "calibration_equal": 0, "unit_equal": 0, + "int16": 0} # fmt: skip + attrs_not_exported: set[str] = set() + calibration = ("phys_min", "phys_max", "dig_min", "dig_max") + for name in sorted(names_a & names_b): + x, y = a[name], b[name] + attrs_not_exported |= set(x.attrs) - set(y.attrs) + if float(x.attrs["fs"]) != float(y.attrs["fs"]) or x.shape != y.shape: + failures.append(f"signal rate or length differs: {name}") + continue + if np.array_equal(physical_values(x), physical_values(y)): + counts["physical_equal"] += 1 + else: + failures.append(f"signal samples differ: {name}") + counts["int16"] += y.dtype == np.int16 + counts["digital_equal"] += bool(y.dtype == x.dtype and np.array_equal(x[()], y[()])) + counts["calibration_equal"] += all( + float(x.attrs[k]) == float(y.attrs[k]) for k in calibration + ) + unit_a, unit_b = _text(x.attrs.get("unit", "")), _text(y.attrs.get("unit", "")) + counts["unit_equal"] += unit_a == unit_b + if unit_a != unit_b and _unit_factor(unit_a) == _unit_factor(unit_b) == 1.0: + failures.append(f"signal unit differs: {name}") + return { + "original": len(names_a), + "exported": len(names_b), + "compared": len(names_a & names_b), + "missing_in_export": missing, + "skipped_at_conversion": sorted(skipped & set(missing)), + "appended_from_other_files": appended, + "extra_in_export": extra, + **counts, + "attrs_not_exported": sorted(attrs_not_exported), + } + + +def _tables(h5: h5py.File) -> dict[str, h5py.Group]: + root = h5.get("annotations") + out = {} + if isinstance(root, h5py.Group): + for annotator, group in root.items(): + if isinstance(group, h5py.Group): + for kind, table in group.items(): + if isinstance(table, h5py.Group) and "starts" in table: + out[f"{annotator}/{kind}"] = table + return out + + +def _same_events(x: h5py.Group, y: h5py.Group) -> tuple[bool, dict[str, float]]: + starts = x["starts"][()].astype(np.float64) + order = np.argsort(starts, kind="stable") + starts = starts[order] + columns = {name: x[name][()][order] for name in ("codes", "durations", "ends") if name in x} + exported = {name: y[name][()] for name in ("starts", "codes", "durations", "ends")} + if len(starts) != len(exported["starts"]): + return False, {} + deviation = {} + ok = np.array_equal(columns["codes"].astype(np.int64), exported["codes"].astype(np.int64)) + for name, values in (("starts", starts), ("durations", columns.get("durations"))): + if values is None: + continue + values = values.astype(np.float64) + delta = np.abs(exported[name].astype(np.float64) - values) + limit = 1e-6 + 2 * np.spacing(np.abs(values).astype(np.float32)).astype(np.float64) + deviation[name] = float(delta.max(initial=0)) + ok &= bool((delta <= limit).all()) + if "ends" in columns: + delta = np.abs(exported["ends"].astype(np.float64) - columns["ends"].astype(np.float64)) + deviation["ends"] = float(delta.max(initial=0)) + ok &= bool((delta <= _END_TOLERANCE_S).all()) + try: + maps = [ + {int(k): str(v) for k, v in json.loads(_text(t.attrs["event_map"])).items()} + for t in (x, y) + ] + ok &= maps[0] == maps[1] + except (KeyError, ValueError, TypeError): + ok = False + return bool(ok), deviation + + +def _annotations(original: h5py.File, exported: h5py.File, info: dict, failures: list) -> dict: + a, b = _tables(original), _tables(exported) + skipped = _skipped(info, "annotations") + missing = sorted(set(a) - set(b)) + extra = sorted(set(b) - set(a)) + for name in missing: + if name not in skipped: + failures.append(f"annotation table missing: {name}") + for name in extra: + failures.append(f"annotation table not in original: {name}") + equal, deviation = 0, {"starts": 0.0, "durations": 0.0, "ends": 0.0} + attrs_not_exported: set[str] = set() + for name in sorted(set(a) & set(b)): + same, worst = _same_events(a[name], b[name]) + attrs_not_exported |= set(a[name].attrs) - set(b[name].attrs) + if same: + equal += 1 + else: + failures.append(f"annotation table differs: {name}") + for key, value in worst.items(): + deviation[key] = max(deviation[key], value) + return { + "original": len(a), + "exported": len(b), + "equal": equal, + "missing_in_export": missing, + "skipped_at_conversion": sorted(skipped & set(missing)), + "extra_in_export": extra, + "max_abs_deviation_s": deviation, + "attrs_not_exported": sorted(attrs_not_exported), + } + + +def _summary(a: h5py.Group, b: h5py.Group | None, failures: list[str]) -> dict: + if b is None: + failures.append("recording_summary missing") + return {"rows": int(a["feature_id"].shape[0]), "exported": False} + differ = [] + for column in SUMMARY_COLUMNS: + if column not in a: + continue + if column not in b: + differ.append(column) + continue + x, y = _values(a[column]), _values(b[column]) + if column == "value_boolean": + x, y = x.astype(bool), y.astype(bool) + if not _equal(x, y): + differ.append(column) + for column in differ: + failures.append(f"recording_summary column differs: {column}") + arrays_a = a.get("arrays", {}) + arrays_b = b.get("arrays", {}) + rows = {fid: i for i, fid in enumerate(_values(a["feature_id"]).tolist())} + status = _values(a["status"]).tolist() + missing, not_exported, equal, dtype_differs = [], [], 0, [] + for name in arrays_a: + node = arrays_a[name] + feature = _text(node.attrs.get("feature_id", name)) + if name not in arrays_b: + expected = status[rows[feature]] in _LOADABLE if feature in rows else True + (missing if expected and node.ndim == 1 else not_exported).append(feature) + continue + if _equal(_values(node), _values(arrays_b[name])): + equal += 1 + else: + failures.append(f"recording_summary array differs: {feature}") + if node.dtype != arrays_b[name].dtype: + dtype_differs.append(feature) + for feature in missing: + failures.append(f"recording_summary array missing: {feature}") + return { + "rows": int(a["feature_id"].shape[0]), + "exported_rows": int(b["feature_id"].shape[0]) if "feature_id" in b else 0, + "columns_differ": differ, + "arrays": len(arrays_a), + "arrays_equal": equal, + "arrays_missing": missing, + "arrays_not_in_split_export": not_exported, + "arrays_dtype_differs": dtype_differs, + } + + +def _features(original_root, exported_root, info: dict, failures: list[str]) -> dict: + if original_root is None: + return {"original": False, "exported": exported_root is not None} + if exported_root is None: + failures.append("features missing") + return {"original": True, "exported": False} + report: dict[str, Any] = {"original_root": original_root.name, + "exported_root": exported_root.name} # fmt: skip + a, b = original_root.get("time_series"), exported_root.get("time_series") + if isinstance(a, h5py.Group): + b = b if isinstance(b, h5py.Group) else {} + skipped = _skipped(info, "features") + family_ids = {name: _text(a[name].attrs.get("feature_id", name)) for name in a} + missing = sorted(set(a) - set(b)) + differ = [] + for name in missing: + if family_ids[name] not in skipped: + failures.append(f"feature family missing: {family_ids[name]}") + for name in sorted(set(a) & set(b)): + if _same_tree(a[name], b[name]): + differ.append(family_ids[name]) + failures.append(f"feature family differs: {family_ids[name]}") + extra = sorted(set(b) - set(a)) + for name in extra: + failures.append(f"feature family not in original: {name}") + group_attrs = {k for k in _attrs(a) if _attrs(a)[k] != _attrs(b).get(k)} if b else set() + report["time_series"] = { + "original": len(a), + "exported": len(b), + "equal": len(set(a) & set(b)) - len(differ), + "missing_in_export": [family_ids[n] for n in missing], + "skipped_at_conversion": sorted(skipped & {family_ids[n] for n in missing}), + "extra_in_export": extra, + "group_attrs_differ": sorted(group_attrs), + } + for name in report["time_series"]["group_attrs_differ"]: + failures.append(f"time_series attribute differs: {name}") + summary = original_root.get("recording_summary") + if isinstance(summary, h5py.Group): + exported_summary = exported_root.get("recording_summary") + report["recording_summary"] = _summary( + summary, exported_summary if isinstance(exported_summary, h5py.Group) else None, + failures, + ) + root_attrs = _attrs(original_root) + report["root_attrs_not_exported"] = sorted(set(root_attrs) - set(exported_root.attrs)) + return report + + +def _missing_nodes(original: h5py.File, exported: h5py.File, roots: tuple) -> list[str]: + """Top-most original paths absent from the export, outside signals and annotations.""" + missing: list[str] = [] + + def visit(name: str, _node) -> None: + path = "/" + name + if path.startswith(("/signals", "/annotations")): + return + if any(path == m or path.startswith(m + "/") for m in missing): + return + mapped = path + for source, target in roots: + if source and (path == source or path.startswith(source + "/")): + mapped = target + path[len(source):] + if mapped not in exported: + missing.append(path) + + original.visititems(visit) + return missing + + +def compare_h5( + original: Path | str, + exported: Path | str, + *, + features: Path | str | None = None, +) -> dict[str, Any]: + """Compare ``exported`` (from :func:`bdsp.zarr_to_h5.write_h5`) with its source H5. + + Args: + original: The session H5 the split Zarr export was converted from. + exported: The H5 rebuilt from that split export. + features: The producer's separate feature H5, for sessions whose features + were never merged into the session H5 (I0007); features are then + compared with it instead. + + Returns: + A JSON-serializable report. ``verdict`` is ``"pass"`` when every item the + split export carries matches; ``failures`` lists what does not; and + ``not_exported`` lists source content the split export does not carry. + """ + failures: list[str] = [] + with h5py.File(original, "r") as a, h5py.File(exported, "r") as b: + info = _export_info(b) + report: dict[str, Any] = { + "identity": _identity(a, b, failures), + "signals": _signals(a, b, info, failures), + "annotations": _annotations(a, b, info, failures), + } + if features is not None: + with h5py.File(features, "r") as sidecar: + source_root = _feature_root(sidecar) + report["features"] = _features(source_root, _feature_root(b), info, failures) + report["features"]["compared_with"] = "separate feature H5" + else: + source_root = _feature_root(a) + report["features"] = _features(source_root, _feature_root(b), info, failures) + if source_root is None and _feature_root(b) is not None: + report["features"]["note"] = "export has features the session H5 lacks" + exported_root = _feature_root(b) + mapping = () + if features is None and source_root is not None and exported_root is not None: + mapping = ((source_root.name, exported_root.name),) + report["not_exported"] = { + "root_attrs": sorted(set(a.attrs) - set(b.attrs)), + "nodes": _missing_nodes(a, b, mapping), + } + report["failures"] = failures + report["verdict"] = "pass" if not failures else "fail" + return report diff --git a/src/bdsp/zarr_to_h5.py b/src/bdsp/zarr_to_h5.py new file mode 100644 index 0000000..9cbfa25 --- /dev/null +++ b/src/bdsp/zarr_to_h5.py @@ -0,0 +1,787 @@ +"""Write a local Sleep YODA-style H5 from a split BDSP Zarr recording. + +The split export keeps a recording in a primary Zarr (signals, expert scoring), +a derivative Zarr (model scoring, temporal feature payloads) and a summary JSON +(recording-level features). :func:`write_h5` assembles those artifacts into one +H5 file in the layout the converter read them from:: + + / subject_id, session_id, duration_sec, age, sex, meas_date + /signals/ int16 digital samples + fs, unit, phys/dig min/max + /annotations/// starts, ends, durations (s), codes, event_map + /features//time_series// the original producer groups + /features//recording_summary/ every summary row, arrays/ + +Only content held by the split export can be written. Signals are stored as +int16 when a calibration reproduces every Zarr sample bit-exactly through the +converter's digital-to-physical formula; otherwise they stay float32 with an +identity calibration. Annotation times round-trip through integer microseconds. +Metadata the split export never stored (signal filter strings, annotation rule +descriptions, producer provenance JSON, research groups) is listed in the root +``bdsp_h5_export`` attribute instead of being invented. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import sys +import warnings +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Iterator + +import h5py +import numpy as np + +__all__ = ["H5ExportReport", "main", "physical_values", "write_h5"] + +PAYLOAD_SCHEMA = "bdsp.sleep-feature-payload.v1" +SUMMARY_SCHEMA = "psg_features_sidecar_v0.5" +FEATURE_H5_SCHEMA = "sleep_feature_h5_v1" +#: Where features go when the payloads do not name a session-H5 location. +DEFAULT_FEATURE_ROOT = "/features/sleep_features" +UNDECLARED_UNIT = "(undeclared)" +#: Columns of ``recording_summary``, in the producer's order. +SUMMARY_COLUMNS = ( + "feature_id", "short_name", "display_name", "display_scope", "unit", "source", + "result_kind", "storage_type", "value_shape", "status", "message", + "value_number", "value_integer", "value_boolean", "value_text", "array_path", +) # fmt: skip +#: Declared voltage units the converter rescaled to microvolts, with their factor. +TO_MICROVOLTS = { + "v": 1e6, "volt": 1e6, "volts": 1e6, + "mv": 1e3, "millivolt": 1e3, "millivolts": 1e3, + "uv": 1.0, "uvolt": 1.0, "uvolts": 1.0, +} # fmt: skip +#: Digital ranges tried, most common first, when recovering a calibration. +_DIGITAL_RANGES = ((-32768.0, 32767.0), (-32767.0, 32767.0), (-2048.0, 2047.0)) +#: Significant digits of a physical limit (an EDF header field has 8 characters). +_MAX_DIGITS = 7 +_INT16 = np.iinfo(np.int16) +_COMPRESSION = {"compression": "gzip", "compression_opts": 4} +_STRING = h5py.string_dtype("utf-8") +_NOT_IN_SPLIT_EXPORT = ( + "signal prefilter/type attributes", + "annotation attributes other than event_map (e.g. rule, rule_description)", + "root attributes other than identity, duration, age, sex and dates", + "feature-producer package attributes, recording/identity_json and provenance/json", + "groups outside signals, annotations and exported features (e.g. features/research)", +) + + +@dataclass(frozen=True) +class H5ExportReport: + """What :func:`write_h5` wrote. Notes name channels or features, never values.""" + + path: Path + signals_int16: int + signals_float32: int + annotation_tracks: int + feature_families: int + summary_rows: int + summary_arrays: int + notes: tuple[str, ...] = field(default_factory=tuple) + + @property + def signals(self) -> int: + return self.signals_int16 + self.signals_float32 + + +# --------------------------------------------------------------------------- +# Signal calibration + + +@dataclass(frozen=True) +class _Calibration: + phys_min: float + phys_max: float + dig_min: float + dig_max: float + + def scale_offset(self, factor: float) -> tuple[float, float]: + """The converter's formula (``h5_reader._calibrated``), with its unit factor.""" + scale = (self.phys_max - self.phys_min) / (self.dig_max - self.dig_min) + offset = self.phys_min - self.dig_min * scale + return scale * factor, offset * factor + + +_IDENTITY = _Calibration(0.0, 1.0, 0.0, 1.0) + + +def physical_values(dataset: h5py.Dataset, *, to_microvolts: bool = True) -> np.ndarray: + """A ``/signals`` dataset's physical float32 samples, as the Zarr converter computes them. + + ``physical = digital * scale + offset`` in float64, from the dataset's + ``phys_min/phys_max/dig_min/dig_max``, rescaled to microvolts for declared + voltage units, then rounded to float32. This is the value a converted + primary Zarr stores, so it is the right basis for H5/Zarr parity checks. + """ + attrs = {k: float(dataset.attrs[k]) for k in ("phys_min", "phys_max", "dig_min", "dig_max")} + factor = _unit_factor(_text(dataset.attrs.get("unit", ""))) if to_microvolts else 1.0 + scale, offset = _Calibration(**attrs).scale_offset(factor) + return (dataset[()].astype(np.float64) * scale + offset).astype(np.float32) + + +def _unit_factor(unit: str) -> float: + key = unit.strip().lower().replace("µ", "u").replace("μ", "u").replace("micro", "u") + return TO_MICROVOLTS.get(key, 1.0) + + +def _digits(value: float) -> int: + """Significant decimal digits of ``value`` (0 for zero).""" + if value == 0: + return 0 + return len(f"{abs(value):.12e}".split("e")[0].replace(".", "").rstrip("0")) + + +def _short(value: float, tolerance: float) -> list[float]: + """Roundings of ``value`` within ``tolerance`` with few significant digits, coarsest first.""" + out: list[float] = [] + for decimals in range(-9, 7): + rounded = float(round(value, decimals)) + if abs(rounded - value) <= tolerance and _digits(rounded) <= _MAX_DIGITS: + if rounded not in out: + out.append(rounded) + return out + + +def _decimals(value: float) -> int: + return next(d for d in range(0, 13) if round(value, d) == value) + + +def _fit(values: np.ndarray, step: float, origin: float) -> tuple[float, float, np.ndarray]: + steps = np.round((values - origin) / step) + if steps[-1] == steps[0]: + return step, origin, steps + step, origin = (float(v) for v in np.polyfit(steps, values, 1)) + return step, origin, np.round((values - origin) / step) + + +def _lattice(unique: np.ndarray) -> tuple[float, float, int] | None: + """``(step, origin, steps)`` with every sorted value ``origin + n * step``, ``0 <= n <= steps``. + + Values were rounded to float32 after an exact float64 calibration, so each + lies within half a float32 spacing of its lattice point. The step is seeded + from the smallest gap near zero (or a divisor of it) and refined by least + squares over a value window centred there. Each window is only as wide as + the step fitted so far allows: an error under a quarter step at its edge. + """ + levels = _INT16.max - _INT16.min + count = len(unique) + if count < 2 or count > levels + 1: + return None + tolerance = float(np.spacing(np.float32(np.abs(unique).max()))) + center = int(np.argmin(np.abs(unique))) + seed = unique[max(0, center - 32) : center + 33] + smallest = float(np.diff(seed).min()) if len(seed) > 1 else float(np.diff(unique).min()) + for divisor in range(1, 1025): + step, origin = smallest / divisor, float(unique[center]) + if step <= 16 * tolerance or (unique[-1] - unique[0]) / step > levels + 0.5: + return None # finer steps fit more loosely and need more levels + width, radius = smallest, 0.0 + while True: + radius = max(2 * radius, 0.25 * width * step / tolerance) + low = np.searchsorted(unique, unique[center] - radius, "left") + high = np.searchsorted(unique, unique[center] + radius, "right") + part = unique[low:high] + step, origin, steps = _fit(part, step, origin) + if np.abs(part - (origin + steps * step)).max() > tolerance: + break + if low == 0 and high == count: + origin += steps[0] * step + span = int(steps[-1] - steps[0]) + return (step, origin, span) if span <= levels else None + width = max(width, float(part[-1] - part[0])) + return None + + +def _candidates(unique: np.ndarray, factor: float) -> Iterator[_Calibration]: + """Calibrations to try, most plausible first; each must still be verified exactly. + + Source calibrations come from EDF headers: short decimal physical limits + over a digital range, mostly the full int16 one. With the lattice known, the + span is snapped to a short decimal and every digital alignment of the + lowest value is tried for a short-decimal ``phys_min``. A recording may only + reach every k-th level, so sub-multiples of the observed step are tried too. + """ + integers = bool(np.all(unique == np.round(unique))) + if factor == 1.0 and integers and unique[0] >= 0 and unique[-1] <= 1: + yield _Calibration(0.0, 1.0, 0.0, 1.0) # boolean channels such as cpap_on + if len(unique) == 1: + yield _Calibration(float(unique[0]) / factor, float(unique[0]) / factor + 1.0, 0.0, 1.0) + return + tolerance = 2 * float(np.spacing(np.float32(np.abs(unique).max()))) / factor + lattice = _lattice(unique) + if lattice is not None: + step, origin, steps = lattice[0] / factor, lattice[1] / factor, lattice[2] + for dig_min, dig_max in _DIGITAL_RANGES: + levels = dig_max - dig_min + ranked = [] + for divisor in range(1, 17): + if steps * divisor > levels: + break + raw_span = step / divisor * levels + for span in _short(raw_span, abs(raw_span) * 5e-8)[:2]: + for key, calibration in _decimal_ranges( + origin, span, steps * divisor, dig_min, dig_max, tolerance + ): + ranked.append(((key[0], divisor, *key[1:]), calibration)) + ranked.sort(key=lambda item: item[0]) + yield from (calibration for _, calibration in ranked) + yield from _sparse_candidates(unique, factor, tolerance) + if lattice is not None: + for dig_min, dig_max in _DIGITAL_RANGES: # any exact calibration, however long + if steps <= dig_max - dig_min: + raw_min = origin - round((origin + step * (dig_max - dig_min) / 2) / step) * step + yield _Calibration(raw_min, raw_min + step * (dig_max - dig_min), dig_min, dig_max) + if factor == 1.0 and integers and unique[0] >= _INT16.min and unique[-1] <= _INT16.max: + low, high = float(unique[0]), float(unique[-1]) + yield _Calibration(low, high, low, high) + + +def _digit_counts(values: np.ndarray, decimals: int) -> np.ndarray: + """Significant digits of each value written with at most ``decimals`` decimals.""" + mantissa = np.round(np.abs(values) * 10.0**decimals).astype(np.int64) + counts = np.zeros(len(mantissa), dtype=np.int64) + nonzero = mantissa > 0 + counts[nonzero] = np.floor(np.log10(mantissa[nonzero])).astype(np.int64) + 1 + trailing = nonzero.copy() + for power in range(1, 16): + trailing &= mantissa % 10**power == 0 + if not trailing.any(): + break + counts -= trailing + return counts + + +def _decimal_ranges( + origin: float, span: float, used: int, dig_min: float, dig_max: float, tolerance: float, + limit: int = 64, +) -> list[tuple[tuple, _Calibration]]: + """Short-decimal ranges of ``span`` containing ``origin`` (the lowest value) on their lattice. + + ``origin`` may sit at any digital level that keeps the ``used`` levels above + it in range. Alignments whose ``phys_min`` is a short decimal are ranked by + convention (zero offset, symmetric, zero-based, other), then significant + digits of both limits, then asymmetry about zero. + """ + levels = dig_max - dig_min + unit = span / levels + lows = origin - np.arange(0, levels - used + 1) * unit + if not len(lows): + return [] + span_decimals = _decimals(span) + found = [] + for decimals in range(0, 7): + quantum = 10.0**-decimals + if quantum < 8 * tolerance: + break # finer decimals would match almost every alignment + rounded = np.round(lows / quantum) * quantum + close = np.abs(rounded - lows) <= tolerance + if decimals: # values with fewer decimals were found at a coarser step already + close &= np.round(np.abs(rounded) / quantum) % 10 != 0 + if close.any(): + low = np.round(rounded[close], decimals) + high = np.round(low + span, max(decimals, span_decimals)) + digits = _digit_counts(low, decimals) + _digit_counts(high, max(decimals, span_decimals)) + convention = np.full(len(low), 3) + convention[low == 0] = 2 + convention[np.abs(low + high) <= tolerance] = 1 + convention[np.abs(low - dig_min * unit) <= tolerance] = 0 + found.append((convention, digits, np.abs(low + high) / span, low, high)) + if not found: + return [] + convention, digits, asymmetry, low, high = (np.concatenate(parts) for parts in zip(*found)) + keep = digits <= 2 * _MAX_DIGITS + convention, digits, asymmetry, low, high = (a[keep] for a in (convention, digits, + asymmetry, low, high)) + order = np.lexsort((asymmetry, digits, convention)) + out, seen = [], set() + for i in order: + if low[i] in seen: + continue + seen.add(low[i]) + key = (int(convention[i]), int(digits[i]), float(asymmetry[i])) + out.append((key, _Calibration(float(low[i]), float(high[i]), dig_min, dig_max))) + if len(out) >= limit: + break + return out + + +def _sparse_candidates( + unique: np.ndarray, factor: float, tolerance: float, limit: int = 64 +) -> Iterator[_Calibration]: + """Short-span calibrations solved from the extreme values, for sparsely used ranges. + + With few distinct values several lattices fit, and the coarsest need not be + the producer's. The extremes differ by an integer number of digital levels, + so each level count implies one span; spans of at most four significant + digits are tried, with every alignment of the lowest value. + """ + low, high = float(unique[0]) / factor, float(unique[-1]) / factor + width = high - low + relative = 2 * tolerance / width + found = [] + for index, (dig_min, dig_max) in enumerate(_DIGITAL_RANGES): + levels = dig_max - dig_min + gaps = np.arange(1, levels + 1) + spans = levels * width / gaps + magnitude = np.floor(np.log10(spans)) + for digits in range(1, 5): + quantum = 10.0 ** (magnitude - digits + 1) + rounded = np.round(spans / quantum) * quantum + for i in np.flatnonzero(np.abs(rounded - spans) <= relative * spans): + span = float(f"{rounded[i]:.{digits}g}") + found.append(((digits, index), span, int(gaps[i]), dig_min, dig_max)) + found.sort(key=lambda item: item[0]) + seen = set() + for _, span, gap, dig_min, dig_max in found: + if (span, dig_min) in seen: + continue + seen.add((span, dig_min)) + if len(seen) > limit: + return + for _, calibration in _decimal_ranges(low, span, gap, dig_min, dig_max, tolerance, 8): + yield calibration + + +def _encode_signal(raw: np.ndarray, factor: float) -> tuple[np.ndarray, _Calibration]: + """int16 digital samples and a calibration reproducing ``raw`` exactly, else float32.""" + raw = np.asarray(raw, dtype=np.float32) + if raw.size == 0 or not np.isfinite(raw).all(): + return raw, _IDENTITY + unique = np.unique(raw) + values = unique.astype(np.float64) + tried = set() + for calibration in _candidates(values, factor): + if calibration in tried: + continue + tried.add(calibration) + scale, offset = calibration.scale_offset(factor) + digital = np.round((values - offset) / scale) + if digital[0] < max(calibration.dig_min, _INT16.min): + continue + if digital[-1] > min(calibration.dig_max, _INT16.max): + continue + if np.array_equal((digital * scale + offset).astype(np.float32), unique): + samples = np.round((raw.astype(np.float64) - offset) / scale).astype(np.int16) + if np.array_equal((samples * scale + offset).astype(np.float32), raw): + return samples, calibration + return raw, _IDENTITY + + +# --------------------------------------------------------------------------- +# Zarr and JSON inputs + + +def _text(value: Any) -> str: + return value.decode("utf-8", "replace") if isinstance(value, bytes) else str(value) + + +class _Store: + """One TS-Zarr store opened read-only, with its ``recording.json``.""" + + def __init__(self, path: Path | str): + import zarr + + self.path = Path(path) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message=r"Object at recording\.json") + self.root = zarr.open_group(str(self.path), mode="r") + keys = [key for key in self.root.group_keys() if key.isdecimal()] + if self.root.attrs.get("tsz", {}).get("version") != "1.0": + raise ValueError(f"{self.path.name} is not a TS-Zarr 1.0 store") + self.metadata = json.loads((self.path / "recording.json").read_text(encoding="utf-8")) + self.channels = [self.root[key] for key in sorted(keys, key=int)] + + @property + def identity(self) -> tuple[str, str, float]: + subject = self.metadata.get("subject") or {} + session = self.metadata.get("session") or {} + return str(subject.get("id")), str(session.get("id")), float(session["duration_s"]) + + @property + def source(self) -> dict[str, Any]: + source = self.metadata.get("source") + return source if isinstance(source, dict) else {} + + +def _check_association(primary: _Store, derivative: _Store | None, summary: dict | None) -> None: + if derivative is not None: + if derivative.identity[:2] != primary.identity[:2] or not math.isclose( + derivative.identity[2], primary.identity[2], abs_tol=1e-6 + ): + raise ValueError("primary and derivative describe different recordings") + files = {primary.source.get("file"), derivative.source.get("file")} - {None} + if len(files) > 1: + raise ValueError("primary and derivative declare different source files") + if summary is not None: + if summary.get("schema_version") != SUMMARY_SCHEMA: + raise ValueError(f"summary JSON is not {SUMMARY_SCHEMA}") + subject = summary.get("subject") or {} + if (subject.get("label"), subject.get("session")) != primary.identity[:2]: + raise ValueError("summary JSON describes a different recording") + + +# --------------------------------------------------------------------------- +# H5 writing + + +def _attr(value: Any) -> Any: + """A JSON attribute value (as the payload extension stores it) for h5py.""" + if isinstance(value, np.generic): + return value + if isinstance(value, bool): + return np.bool_(value) + if isinstance(value, int): + return np.int64(value) + if isinstance(value, float): + return np.float64(value) + if isinstance(value, str): + return value + if isinstance(value, list): + if value and all(isinstance(item, str) for item in value): + return np.array(value, dtype=_STRING) + return np.asarray(value) + return json.dumps(value) + + +def _set_attrs(node: h5py.HLObject, attrs: dict[str, Any]) -> None: + for name, value in attrs.items(): + if value is not None: + node.attrs[name] = _attr(value) + + +def _dataset(group: h5py.Group, name: str, data: np.ndarray, *, shuffle: bool = False, **kw): + data = np.asarray(data) + if data.dtype.kind in "OTU": + data, kw["dtype"] = data.astype(object), _STRING + if data.ndim and data.size: + kw = {**_COMPRESSION, "chunks": True, "shuffle": shuffle, **kw} + return group.create_dataset(name, data=data, **kw) + + +def _float(values: list[float]) -> np.ndarray: + """float32 when every value is exactly a float32 (as the producer stores), else float64.""" + array = np.asarray(values, dtype=np.float64) + single = array.astype(np.float32) + return single if np.array_equal(single.astype(np.float64), array, equal_nan=True) else array + + +def _write_signals(h5: h5py.File, primary: _Store, include_appended: bool) -> tuple[int, int, list]: + group = h5.create_group("signals") + counts, notes = [0, 0], [] + for channel in primary.channels: + tsz = channel.attrs["tsz"] + provenance = tsz.get("provenance", {}) + if provenance.get("origin") != "signal" or tsz.get("kind") != "continuous": + continue + if "source_file" in provenance and not include_appended: + continue + name = str(tsz["name"]) + unit = str(tsz.get("unit", "")) + unit = "" if unit == UNDECLARED_UNIT else unit + converted_from = provenance.get("unit_converted_from") + factor = _unit_factor(converted_from) if converted_from else 1.0 + digital, calibration = _encode_signal(channel["raw"][...], factor) + attrs: dict[str, Any] = {"fs": float(tsz["rate_hz"])} + if digital.dtype == np.int16: + attrs["unit"] = converted_from or unit + counts[0] += 1 + else: + attrs["unit"] = unit + if converted_from: + attrs["unit_converted_from"] = converted_from + counts[1] += 1 + notes.append(f"signal {name} kept as float32 (no exact int16 calibration)") + attrs.update( + phys_min=calibration.phys_min, + phys_max=calibration.phys_max, + dig_min=calibration.dig_min, + dig_max=calibration.dig_max, + ) + if offset := int(tsz.get("offset_us", 0)): + attrs["offset_s"] = offset / 1e6 + for key in ("source_file", "declared_unit"): + if key in provenance: + attrs[key] = str(provenance[key]) + dataset = _dataset(group, name, digital) + _set_attrs(dataset, attrs) + return counts[0], counts[1], notes + + +def _write_annotations(h5: h5py.File, stores: list[_Store]) -> int: + root = h5.create_group("annotations") + tracks = 0 + for store in stores: + for channel in store.channels: + tsz = channel.attrs["tsz"] + provenance = tsz.get("provenance", {}) + if provenance.get("origin") != "annotation" or tsz.get("kind") != "event": + continue + annotator, kind = str(tsz["name"]).split("/", 1) + codes = np.asarray(provenance["label_codes"], dtype=np.int64) + names = list(tsz["label_names"]) + starts = channel["events"][...].astype(np.float64) / 1e6 + durations = channel["durations"][...].astype(np.float64) / 1e6 + labels = channel["labels"][...].astype(np.int64) + table = root.require_group(annotator).create_group(kind) + _dataset(table, "starts", starts.astype(np.float32)) + _dataset(table, "ends", (starts + durations).astype(np.float32)) + _dataset(table, "durations", durations.astype(np.float32)) + _dataset(table, "codes", codes[labels].astype(np.int16)) + event_map = {str(int(code)): str(label) for code, label in zip(codes, names)} + table.attrs["event_map"] = json.dumps(event_map) + table.attrs["format"] = "event_table" + tracks += 1 + return tracks + + +def _copy_zarr_group(source, target: h5py.Group) -> None: + _set_attrs(target, dict(source.attrs)) + for name, array in source.arrays(): + dataset = _dataset(target, name, array[...], shuffle=True) + _set_attrs(dataset, dict(array.attrs)) + for name, group in source.groups(): + _copy_zarr_group(group, target.create_group(name)) + + +def _payloads(derivative: _Store | None) -> tuple[dict[str, Any], list[str]]: + """Original family path -> payload source group, and families left without a payload.""" + if derivative is None: + return {}, [] + payloads, unpreserved = {}, [] + for channel in derivative.channels: + tsz = channel.attrs["tsz"] + provenance = tsz.get("provenance", {}) + if provenance.get("origin") != "feature": + continue + reference = provenance.get("feature_payload") or {} + if reference.get("schema") != PAYLOAD_SCHEMA: + unpreserved.append(str(tsz.get("name"))) + continue + payload = derivative.root[reference["path"]] + payloads.setdefault(str(payload.attrs["source_h5_path"]), payload["source"]) + return payloads, unpreserved + + +def _feature_root(paths: list[str]) -> str: + """The session-H5 feature root the payloads came from, or the default one.""" + roots = {path.rsplit("/time_series/", 1)[0] for path in paths if "/time_series/" in path} + if len(roots) == 1 and (root := roots.pop()).startswith("/features/"): + return root + return DEFAULT_FEATURE_ROOT + + +def _write_summary(group: h5py.Group, summary: dict) -> tuple[int, int, list[str]]: + rows = summary.get("features") or {} + columns: dict[str, list] = {name: [] for name in SUMMARY_COLUMNS} + for feature_id, row in rows.items(): + columns["feature_id"].append(feature_id) + for name in SUMMARY_COLUMNS[1:]: + value = row.get(name) + if name == "value_number": + value = math.nan if value is None else float(value) + elif name == "value_integer": + value = int(value or 0) + elif name == "value_boolean": + value = bool(value) + else: + value = "" if value is None else str(value) + columns[name].append(value) + dtypes = {"value_number": np.float64, "value_integer": np.int64, "value_boolean": np.uint8} + for name, values in columns.items(): + data = np.asarray(values, dtype=dtypes.get(name, object)) + _dataset(group, name, data, shuffle=True) + arrays = group.create_group("arrays") + written, notes = 0, [] + vectors = summary.get("vectors") or {} + for feature_id, row in rows.items(): + if row.get("storage_type") != "array": + continue + path = str(row.get("array_path") or "") + if feature_id not in vectors: + if path: + notes.append(f"summary array {feature_id} is not in the summary JSON vectors") + continue + path = path or f"arrays/{feature_id}" + if not path.startswith("arrays/"): + path = f"arrays/{path.rsplit('/', 1)[-1]}" + dataset = _dataset(arrays, path.split("/", 1)[1], _float(vectors[feature_id]["values"]), + shuffle=True) # fmt: skip + dataset.attrs["feature_id"] = feature_id + written += 1 + return len(rows), written, notes + + +def _write_features( + h5: h5py.File, derivative: _Store | None, summary: dict | None, identity: tuple +) -> tuple[int, int, int, list[str]]: + payloads, unpreserved = _payloads(derivative) + notes = [f"feature channel {name} has no payload; its family was not written" + for name in unpreserved] # fmt: skip + has_summary = bool(summary and summary.get("features")) + if not payloads and not has_summary: + return 0, 0, 0, notes + root_path = _feature_root(list(payloads)) + root = h5.require_group(root_path) + _set_attrs(root, {"namespace": root_path, "recording_id": f"{identity[0]}_{identity[1]}", + "schema_version": FEATURE_H5_SCHEMA}) # fmt: skip + families = 0 + if payloads: + series = root.create_group("time_series") + rows = 0 + for path, source in payloads.items(): + target = series.create_group(path.rsplit("/", 1)[-1]) + _copy_zarr_group(source, target) + rows += int(source.attrs.get("row_count", 0)) + families += 1 + series.attrs["feature_count"] = np.int64(families) + series.attrs["row_count"] = np.int64(rows) + rows_written = arrays = 0 + if has_summary: + rows_written, arrays, summary_notes = _write_summary( + root.create_group("recording_summary"), summary + ) + notes += summary_notes + return families, rows_written, arrays, notes + + +def _root_attrs(primary: _Store, summary: dict | None) -> dict[str, Any]: + subject, session, duration = primary.identity + demographics = primary.metadata.get("subject") or {} + attrs: dict[str, Any] = { + "subject_id": subject, + "session_id": session, + "duration_sec": _float([duration])[0], + } + if demographics.get("age_years") is not None: + attrs["age"] = np.float64(demographics["age_years"]) + if demographics.get("sex") is not None: + attrs["sex"] = str(demographics["sex"]) + provenance = (summary or {}).get("provenance") or {} + if provenance.get("meas_date") is not None: + attrs["meas_date"] = str(provenance["meas_date"]) + if provenance.get("h5_meas_date") is not None: + attrs["h5_meas_date"] = str(provenance["h5_meas_date"]) + return attrs + + +def write_h5( + output: Path | str, + primary: Path | str, + derivatives: Path | str | None = None, + summary_json: Path | str | None = None, + *, + include_appended_signals: bool = True, + overwrite: bool = False, +) -> H5ExportReport: + """Assemble one split Zarr recording into a single local H5 file. + + Args: + output: H5 path to write. It appears only once the file is complete. + primary: The recording's primary ``*_task-psg_eeg.zarr`` directory. + derivatives: Its ``*_deriv-bdspsleepfeatures.zarr`` directory, if any. + Without it the H5 has no model annotations or feature time series. + summary_json: Its ``*_deriv-bdspsleepfeatures.json``, if any. Without it + the H5 has no ``recording_summary`` and no ``meas_date``. + include_appended_signals: Keep channels appended to the primary store from + another file after conversion (e.g. PAP channels from ``*_desc-pap.h5``). + Each keeps a ``source_file`` attribute naming that file. + overwrite: Replace an existing ``output``. + + Raises: + FileExistsError: If ``output`` exists and ``overwrite`` is false. + ValueError: If the artifacts do not describe the same recording. + """ + output = Path(output) + if output.exists() and not overwrite: + raise FileExistsError(output) + primary_store = _Store(primary) + derivative_store = _Store(derivatives) if derivatives is not None else None + summary = None + if summary_json is not None: + summary = json.loads(Path(summary_json).read_text(encoding="utf-8")) + _check_association(primary_store, derivative_store, summary) + + from . import __version__ + + stores = [primary_store] + ([derivative_store] if derivative_store else []) + temporary = output.with_name(f".{output.name}.tmp") + temporary.parent.mkdir(parents=True, exist_ok=True) + try: + with h5py.File(temporary, "w") as h5: + _set_attrs(h5, _root_attrs(primary_store, summary)) + int16, float32, notes = _write_signals(h5, primary_store, include_appended_signals) + tracks = _write_annotations(h5, stores) + families, rows, arrays, feature_notes = _write_features( + h5, derivative_store, summary, primary_store.identity + ) + notes += feature_notes + export = { + "writer": f"bdsp {__version__} (bdsp.zarr_to_h5)", + "inputs": { + "primary": primary_store.path.name, + "derivatives": derivative_store.path.name if derivative_store else None, + "summary_json": Path(summary_json).name if summary_json else None, + }, + "source_file": primary_store.source.get("file"), + "converter": primary_store.source.get("converter"), + "skipped_at_conversion": { + store.path.name: store.source.get("skipped", {}) for store in stores + }, + "not_in_split_export": list(_NOT_IN_SPLIT_EXPORT), + "notes": notes, + } + h5.attrs["bdsp_h5_export"] = json.dumps(export) + os.replace(temporary, output) + finally: + temporary.unlink(missing_ok=True) + return H5ExportReport(output, int16, float32, tracks, families, rows, arrays, tuple(notes)) + + +# --------------------------------------------------------------------------- +# Command line + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="bdsp-zarr-to-h5", + description="Write one local H5 from a split BDSP Zarr recording.", + ) + parser.add_argument("--primary", required=True, help="primary *_task-psg_eeg.zarr directory") + parser.add_argument("--derivatives", help="derivative *_deriv-bdspsleepfeatures.zarr directory") + parser.add_argument("--summary-json", help="derivative *_deriv-bdspsleepfeatures.json file") + parser.add_argument("--output", "-o", required=True, help="H5 file to write") + parser.add_argument("--overwrite", action="store_true", help="replace an existing output") + parser.add_argument( + "--no-appended-signals", + action="store_true", + help="leave out channels appended from other files (e.g. PAP sidecar channels)", + ) + args = parser.parse_args(argv) + if args.derivatives is None or args.summary_json is None: + print("note: without --derivatives and --summary-json the H5 has no model " + "annotations or features", file=sys.stderr) # fmt: skip + report = write_h5( + args.output, + args.primary, + args.derivatives, + args.summary_json, + include_appended_signals=not args.no_appended_signals, + overwrite=args.overwrite, + ) + print( + f"wrote {report.path}: {report.signals} signals ({report.signals_int16} int16, " + f"{report.signals_float32} float32), {report.annotation_tracks} annotation tracks, " + f"{report.feature_families} feature families, {report.summary_rows} summary rows" + ) + for note in report.notes: + print(f"note: {note}", file=sys.stderr) + return 0 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/tests/test_zarr_to_h5.py b/tests/test_zarr_to_h5.py new file mode 100644 index 0000000..6eb9988 --- /dev/null +++ b/tests/test_zarr_to_h5.py @@ -0,0 +1,296 @@ +"""Split Zarr -> H5 round trips on synthetic recordings; no converter or cloud access.""" + +from __future__ import annotations + +import json + +import h5py +import numpy as np +import pytest + +zarr = pytest.importorskip("zarr", minversion="3.1") + +import bdsp +from bdsp.h5_compare import compare_h5 +from bdsp.zarr_to_h5 import main, write_h5 + +SCHEMA = "bdsp.sleep-feature-payload.v1" +SUBJECT, SESSION = "sub-T0001123", "ses-1" +ROOT = "/features/bdsp_sleep_features" +#: name -> (fs, unit, phys_min, phys_max, dig_min, dig_max, digital samples) +RNG = np.random.default_rng(7) +SIGNALS = { + "c3-m2": (4.0, "uV", -65536.0, 65534.0, -32768.0, 32767.0, RNG.integers(-300, 300, 80)), + "abd": (4.0, "uV", -3200.0, 3200.0, -32768.0, 32767.0, RNG.integers(-32768, 32768, 80)), + "spo2": (1.0, "%", 0.0, 100.0, -32768.0, 32767.0, + np.round((RNG.integers(88, 100, 20) - 50.00076) / (100 / 65535))), + "ecg": (4.0, "mV", -5.0, 5.0, -32768.0, 32767.0, RNG.integers(-9000, 9000, 80)), + "etco2": (1.0, "mmHg", -328.0, 328.0, -32768.0, 32767.0, np.array([0, 5] * 10)), + "cpap_on": (1.0, "bool", 0.0, 1.0, 0.0, 1.0, np.array([0, 1] * 10)), +} # fmt: skip +TO_UV = {"mV": 1e3} + + +def physical(phys_min, phys_max, dig_min, dig_max, digital, unit): + """The converter's calibration (bdsp-psg-conversion common/h5_reader.py).""" + scale = (phys_max - phys_min) / (dig_max - dig_min) + offset = phys_min - dig_min * scale + scale, offset = scale * TO_UV.get(unit, 1.0), offset * TO_UV.get(unit, 1.0) + return (digital.astype(np.float64) * scale + offset).astype(np.float32) + + +def write_source_h5(path): + with h5py.File(path, "w") as h5: + h5.attrs.update(subject_id=SUBJECT, session_id=SESSION, sex="M", age=np.float64(93.0), + duration_sec=np.float32(20.0), meas_date="2001-02-03 22:15:00", + metadata_source="synthetic.csv") # fmt: skip + for name, (fs, unit, pmin, pmax, dmin, dmax, digital) in SIGNALS.items(): + data = h5.create_dataset(f"signals/{name}", data=digital.astype(np.int16)) + data.attrs.update(fs=fs, unit=unit, phys_min=pmin, phys_max=pmax, dig_min=dmin, + dig_max=dmax, prefilter="HP:0.3Hz", type="raw") # fmt: skip + for annotator, codes in (("expert_1", [5, 2, 2]), ("caisr", [5, 5, 2])): + table = h5.create_group(f"annotations/{annotator}/stage") + starts = np.array([0.0, 7.3333335, 13.1], dtype=np.float32) + durations = np.array([7.3333335, 5.7666664, 0.0], dtype=np.float32) + table["starts"], table["durations"] = starts, durations + table["ends"] = starts + durations + table["codes"] = np.array(codes, dtype=np.int16) + table.attrs["event_map"] = json.dumps({"5": "Wake", "2": "N2", "0": "Unscored"}) + table.attrs.update(format="event_table", rule="synthetic") + features = h5.create_group(ROOT) + features.attrs.update(namespace=ROOT, package_version="0.0.0", recording_id="x", + schema_version="sleep_feature_h5_v1") # fmt: skip + family = features.create_group("time_series/eeg.spectrum") + family.attrs.update(feature_id="eeg.spectrum", row_count=np.int64(3), unit="dB", + temporal_semantics="regular", value_json_storage="numeric_array") # fmt: skip + family["start_time_s"] = np.array([0.0, 4.0, 8.0]) + family["end_time_s"] = np.array([4.0, 8.0, 12.0]) + family["value_array"] = np.arange(12, dtype=np.float32).reshape(3, 4) / 3 + family["value_array_present"] = np.array([1, 0, 1], dtype=np.uint8) + family["status_code"] = np.array([0, 1, 0], dtype=np.int32) + family.create_dataset("status_labels", data=["ok", "qc_rejected"], + dtype=h5py.string_dtype()) # fmt: skip + axis = family.create_group("information/field_0000") + axis.attrs.update(name="frequency_hz", storage="constant_json") + axis.create_dataset("value_json", data="[1, 2, 3, 4]", dtype=h5py.string_dtype()) + features["time_series"].attrs.update(feature_count=np.int64(1), row_count=np.int64(3)) + summary = features.create_group("recording_summary") + rows = [ + ("sleep.tst", "number", "ok", 401.5, ""), + ("sleep.missing", "number", "missing_input", np.nan, ""), + ("brain_health.embedding", "array", "ok", np.nan, "arrays/brain_health.embedding"), + ] + text = h5py.string_dtype() + for column in ("short_name", "display_name", "display_scope", "unit", "source", + "result_kind", "value_shape", "message", "value_text"): # fmt: skip + summary.create_dataset(column, data=[column] * len(rows), dtype=text) + summary.create_dataset("feature_id", data=[r[0] for r in rows], dtype=text) + summary.create_dataset("storage_type", data=[r[1] for r in rows], dtype=text) + summary.create_dataset("status", data=[r[2] for r in rows], dtype=text) + summary.create_dataset("array_path", data=[r[4] for r in rows], dtype=text) + summary["value_number"] = np.array([r[3] for r in rows]) + summary["value_integer"] = np.zeros(len(rows), dtype=np.int64) + summary["value_boolean"] = np.zeros(len(rows), dtype=np.uint8) + summary["arrays/brain_health.embedding"] = np.array([0.25, -0.5, 0.1], dtype=np.float32) + summary["arrays/brain_health.embedding"].attrs["feature_id"] = "brain_health.embedding" + h5.create_group("features/research/spindles") + + +def recording_json(path, extra=None): + meta = {"subject": {"id": SUBJECT, "sex": "Male", "age_years": 90.0}, + "session": {"id": SESSION, "duration_s": 20.0}, + "source": {"file": "source.h5", "converter": "mimic", "skipped": {}, **(extra or {})}} + (path / "recording.json").write_text(json.dumps(meta)) # fmt: skip + + +def channel(root, key, attrs): + return root.create_group(str(key), attributes={"tsz": attrs}) + + +def copy_group(source, target): + target.attrs.update({k: v.item() if isinstance(v, np.generic) else v + for k, v in source.attrs.items()}) # fmt: skip + for name, node in source.items(): + if isinstance(node, h5py.Group): + copy_group(node, target.create_group(name)) + elif h5py.check_string_dtype(node.dtype): + data = np.asarray(node.asstr()[()], dtype=object) + target.create_array(name, shape=data.shape, dtype="str")[...] = data + else: + target.create_array(name, data=node[()]) + + +def convert(source, tmp_path): + """A minimal mimic of the converter's H5 -> split Zarr mapping.""" + paths = {"primary": tmp_path / "primary.zarr", "derivatives": tmp_path / "derivative.zarr", + "summary_json": tmp_path / "summary.json"} # fmt: skip + primary = zarr.open_group(str(paths["primary"]), mode="w", zarr_format=3, + attributes={"tsz": {"version": "1.0"}}) # fmt: skip + derivative = zarr.open_group(str(paths["derivatives"]), mode="w", zarr_format=3, + attributes={"tsz": {"version": "1.0"}}) # fmt: skip + recording_json(paths["primary"]) + recording_json(paths["derivatives"], {"feature_payload_schema": SCHEMA}) + keys = {"primary": 0, "derivatives": 0} + with h5py.File(source) as h5: + for name, node in h5["signals"].items(): + unit = node.attrs["unit"] + attrs = [float(node.attrs[k]) for k in ("phys_min", "phys_max", "dig_min", "dig_max")] + provenance = {"origin": "signal", "source_path": node.name} + if unit in TO_UV: + provenance["unit_converted_from"] = unit + group = channel(primary, keys["primary"], + {"kind": "continuous", "name": name, "id": node.name, + "unit": "uV" if unit in TO_UV else unit, + "rate_hz": float(node.attrs["fs"]), "offset_us": 0, + "provenance": provenance}) # fmt: skip + group.create_array("raw", data=physical(*attrs, node[()], unit)) + keys["primary"] += 1 + for annotator, tables in h5["annotations"].items(): + role = "primary" if annotator.startswith("expert") else "derivatives" + root = primary if role == "primary" else derivative + for kind, table in tables.items(): + event_map = {int(k): v for k, v in json.loads(table.attrs["event_map"]).items()} + codes = sorted(event_map) + group = channel(root, keys[role], { + "kind": "event", "name": f"{annotator}/{kind}", "id": table.name, + "label_names": [event_map[c] for c in codes], + "provenance": {"origin": "annotation", "annotator": annotator, + "label_codes": codes}}) # fmt: skip + us = lambda s: np.round(s[()].astype(np.float64) * 1e6).astype(np.int64) # noqa: E731 + group.create_array("events", data=us(table["starts"])) + group.create_array("durations", data=us(table["durations"])) + labels = [codes.index(int(c)) for c in table["codes"][()]] + group.create_array("labels", data=np.asarray(labels, dtype=np.uint16)) + keys[role] += 1 + for name, family in h5[f"{ROOT}/time_series"].items(): + key = keys["derivatives"] + group = channel(derivative, key, { + "kind": "event", "name": name, "id": name, + "provenance": {"origin": "feature", "feature_id": name, + "feature_payload": {"schema": SCHEMA, + "path": f"{key}/feature_payload"}}}) # fmt: skip + group.create_array("events", data=np.zeros(0, dtype=np.int64)) + group.create_array("durations", data=np.zeros(0, dtype=np.int64)) + payload = group.create_group("feature_payload", attributes={ + "schema": SCHEMA, "source_h5_path": family.name}) # fmt: skip + copy_group(family, payload.create_group("source")) + keys["derivatives"] += 1 + summary = h5[f"{ROOT}/recording_summary"] + columns = {name: summary[name] for name in summary if name != "arrays"} + features = {} + for i, feature_id in enumerate(columns["feature_id"].asstr()[()]): + row = {} + for name, data in columns.items(): + if name == "feature_id": + continue + value = data.asstr()[i] if h5py.check_string_dtype(data.dtype) else data[i].item() + row[name] = None if isinstance(value, float) and np.isnan(value) else value + row["value_boolean"] = bool(row["value_boolean"]) + features[feature_id] = row + embedding = summary["arrays/brain_health.embedding"][()].astype(float).tolist() + paths["summary_json"].write_text(json.dumps({ + "schema_version": "psg_features_sidecar_v0.5", "recording_id": f"{SUBJECT}_{SESSION}", + "subject": {"label": SUBJECT, "session": SESSION}, "recording": {"duration_s": 20.0}, + "provenance": {"meas_date": "2001-02-03 22:15:00"}, + "counts": {"summary_features": len(features)}, "features": features, + "vectors": {"brain_health.embedding": {"values": embedding, "length": 3}}})) # fmt: skip + return paths + + +@pytest.fixture +def split(tmp_path): + source = tmp_path / "source.h5" + write_source_h5(source) + return source, convert(source, tmp_path) + + +def test_round_trip_reproduces_the_source_h5(split, tmp_path): + source, paths = split + out = tmp_path / "rebuilt.h5" + report = write_h5(out, **paths) + assert (report.signals_int16, report.signals_float32) == (len(SIGNALS), 0) + assert (report.annotation_tracks, report.feature_families, report.summary_rows) == (2, 1, 3) + result = compare_h5(source, out) + assert result["verdict"] == "pass", result["failures"] + signals = result["signals"] + assert signals["digital_equal"] == signals["calibration_equal"] == len(SIGNALS) + assert signals["unit_equal"] == len(SIGNALS) + assert signals["attrs_not_exported"] == ["prefilter", "type"] + assert result["annotations"]["equal"] == 2 + assert result["annotations"]["attrs_not_exported"] == ["rule"] + assert result["features"]["time_series"]["equal"] == 1 + assert result["features"]["recording_summary"]["arrays_equal"] == 1 + assert result["not_exported"]["root_attrs"] == ["metadata_source"] + assert "/features/research" in result["not_exported"]["nodes"] + with h5py.File(out) as h5: + assert h5["signals/ecg"].attrs["unit"] == "mV" # restored from unit_converted_from + assert float(h5.attrs["age"]) == 90.0 # published cap, not the archived 93 + export = json.loads(h5.attrs["bdsp_h5_export"]) + assert export["inputs"]["primary"] == "primary.zarr" + + +def test_rebuilt_h5_reads_with_the_h5_reader(split, tmp_path): + source, paths = split + out = tmp_path / "rebuilt.h5" + write_h5(out, **paths) + original, rebuilt = bdsp.read_h5(source), bdsp.read_h5(out) + assert set(original.signals) == set(rebuilt.signals) + for name, values in original.signals.items(): + np.testing.assert_array_equal(values, rebuilt.signals[name]) + stage = rebuilt.annotations["expert_1"]["stage"] + np.testing.assert_array_equal(stage["codes"], [5, 2, 2]) + assert stage["event_map"] == {0: "Unscored", 2: "N2", 5: "Wake"} + + +def test_compare_detects_changed_samples_and_events(split, tmp_path): + source, paths = split + out = tmp_path / "rebuilt.h5" + write_h5(out, **paths) + with h5py.File(out, "r+") as h5: + h5["signals/abd"][3] += 1 + h5["annotations/caisr/stage/codes"][0] = 2 + h5[f"{ROOT}/time_series/eeg.spectrum/value_array"][0, 0] = 99 + failures = compare_h5(source, out)["failures"] + assert "signal samples differ: abd" in failures + assert "annotation table differs: caisr/stage" in failures + assert "feature family differs: eeg.spectrum" in failures + + +def test_unencodable_samples_stay_float32_and_partial_inputs(split, tmp_path): + _, paths = split + raw = zarr.open_group(str(paths["primary"]), mode="r+")["0/raw"] + values = raw[...] + values[2] = np.nan # an implicit-fill gap has no int16 representation + raw[...] = values + out = tmp_path / "primary_only.h5" + report = write_h5(out, paths["primary"]) + assert report.signals_float32 == 1 and report.feature_families == report.summary_rows == 0 + with h5py.File(out) as h5: + name = next(n for n in h5["signals"] if h5["signals"][n].dtype == np.float32) + np.testing.assert_array_equal(h5["signals"][name][()], values) + assert "features" not in h5 and "annotations/caisr" not in h5 + assert "meas_date" not in h5.attrs + + +def test_refuses_mismatched_artifacts_and_existing_output(split, tmp_path): + _, paths = split + other = json.loads(paths["summary_json"].read_text()) + other["subject"]["label"] = "sub-T0001999" + wrong = tmp_path / "other.json" + wrong.write_text(json.dumps(other)) + with pytest.raises(ValueError, match="different recording"): + write_h5(tmp_path / "x.h5", paths["primary"], paths["derivatives"], wrong) + out = tmp_path / "rebuilt.h5" + write_h5(out, **paths) + with pytest.raises(FileExistsError): + write_h5(out, **paths) + write_h5(out, **paths, overwrite=True) + assert not list(tmp_path.glob(".*.tmp")) + + +def test_command_line(split, tmp_path, capsys): + _, paths = split + out = tmp_path / "cli.h5" + assert main(["--primary", str(paths["primary"]), "--derivatives", str(paths["derivatives"]), + "--summary-json", str(paths["summary_json"]), "-o", str(out)]) == 0 # fmt: skip + assert out.exists() and "6 signals (6 int16, 0 float32)" in capsys.readouterr().out diff --git a/validation/README.md b/validation/README.md index f6a5be1..9cac6e3 100644 --- a/validation/README.md +++ b/validation/README.md @@ -95,6 +95,43 @@ scientific validity, speed improvements over H5, or Wolfgang/Qichen sign-off. Those are separate acceptance evidence. Source archives are never removed by these checks, regardless of older spreadsheet cleanup suggestions. +## H5 parity: Zarr to H5 + +`h5_parity.py` asks whether the published split artifacts suffice to rebuild +each recording's archived source H5. For a fixed-seed sample of subjects per +cohort (one seeded session each, among recordings with a primary store and an +archived source H5), it downloads the primary and derivative Zarr, summary JSON +and source H5 under their original names, writes an H5 with +`bdsp.zarr_to_h5.write_h5`, and compares it with the source using +`bdsp.h5_compare.compare_h5`. With `--converter-src`, the converter's own +source-to-export verifier is also run with the rebuilt H5 standing in as the +source of the published stores (channels appended after conversion are left +out of that copy, since the converter verifies them against their own file). + +```bash +python validation/h5_parity.py --per-cohort 5 --seed 20261127 --workers 6 \ + --converter-src ../bdsp-psg-conversion/src \ + --feature-h5 I0007=s3://bdsp-staging/arpa-h-rest/sleep-features/runs/aws-i0007-fullprofile-v3-20261003/derivatives/I0007 \ + --output validation/results/h5-parity-20261127 +``` + +I0007 session H5s never carried features; `--feature-h5` names the producer run +whose feature H5s the derivative stores were built from, so rebuilt features +are compared with those. The derivative check of the converter's verifier does +not apply there: its payload paths name that separate file. Downloads and +rebuilt H5s are deleted after each recording unless `--keep-files`. Repeat the +command to resume; selections are fixed by the saved manifest. + +A pass means every item the split export carries matched: identity and dates, +each signal's rate, length and physical float32 samples (by the converter's +calibration formula), annotation events and codes, every feature family and the +recording summary. Digital samples and calibration attributes are also counted; +another exact calibration can encode identical values. Content the split format +does not carry is reported under `not_exported` and is not a failure; the +[H5 export guide](../docs/bids-zarr/H5_EXPORT.md) lists it. + +Completed review: [H5 parity, six cohorts — 2026-11-27](reports/2026-11-27-h5-parity.md). + ## Evidence and privacy `results/` is Git-ignored. It contains `manifest.json`, `global.json`, append-only diff --git a/validation/h5_parity.py b/validation/h5_parity.py new file mode 100644 index 0000000..e5123eb --- /dev/null +++ b/validation/h5_parity.py @@ -0,0 +1,416 @@ +"""Rebuild sampled source H5s from published split Zarr; see validation/README.md. + +For each sampled recording this downloads the primary Zarr, derivative Zarr, +summary JSON and archived source H5 (plus a separate feature H5 where the +session H5 never carried features), writes an H5 with ``bdsp.zarr_to_h5``, +compares it with the source H5 using ``bdsp.h5_compare`` and, when the +converter source is supplied, also asks the converter's own source-to-export +verifier whether the rebuilt H5 is a valid source for the published stores. + +It only lists and reads S3. Downloads and rebuilt H5s live under the private +output directory and are deleted after each recording unless --keep-files. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +import importlib.metadata +import json +from pathlib import Path +import random +import shutil +import statistics +import sys +import time +import traceback +from urllib.parse import urlparse + +DEFAULT_ROOT = "s3://bdsp-opendata-repository/PSG/bids" +COHORTS = ("S0001", "I0002", "I0003", "I0004", "I0006", "I0007") +DERIV = "derivatives/bdsp_sleep_features" + + +def utcnow(): + return datetime.now(timezone.utc).isoformat() + + +def write_json(path, value): + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def client(profile=None): + import boto3 + from botocore.config import Config + + config = Config(connect_timeout=10, read_timeout=60, retries={"max_attempts": 5}, + max_pool_connections=32) # fmt: skip + return boto3.Session(profile_name=profile).client("s3", config=config) + + +def split(url): + parsed = urlparse(url) + return parsed.netloc, parsed.path.strip("/") + + +def children(s3, bucket, prefix): + out = [] + for page in s3.get_paginator("list_objects_v2").paginate( + Bucket=bucket, Prefix=prefix.rstrip("/") + "/", Delimiter="/" + ): + out += [p["Prefix"].rstrip("/").rsplit("/", 1)[-1] for p in page.get("CommonPrefixes", [])] + return sorted(out) + + +def exists(s3, bucket, key): + try: + s3.head_object(Bucket=bucket, Key=key) + return True + except s3.exceptions.ClientError: + return False + + +def read_json_object(s3, bucket, key): + return json.loads(s3.get_object(Bucket=bucket, Key=key)["Body"].read()) + + +def paths(cohort_prefix, subject, session, source_file): + stem = f"{subject}_{session}" + deriv = f"{cohort_prefix}/{DERIV}/{subject}/{stem}_task-psg_deriv-bdspsleepfeatures" + return { + "primary": f"{cohort_prefix}/primary/{subject}/{session}/psg/{stem}_task-psg_eeg.zarr", + "derivatives": deriv + ".zarr", + "summary_json": deriv + ".json", + "source_h5": f"{cohort_prefix}/sourcedata/{subject}/{session}/{source_file}", + } + + +def sample(args, s3): + """Seeded subjects per cohort, one seeded session each, with their artifact keys.""" + bucket, root = split(args.root) + selections, design = [], {} + for cohort in args.cohorts: + prefix = f"{root}/{cohort}" + subjects = children(s3, bucket, f"{prefix}/primary") + subjects = [s for s in subjects if s.startswith("sub-")] + order = list(subjects) + random.Random(f"{args.seed}:{cohort}").shuffle(order) + examined, excluded, chosen = 0, Counter(), [] + for subject in order: + if len(chosen) == args.per_cohort: + break + examined += 1 + sessions = [s for s in children(s3, bucket, f"{prefix}/primary/{subject}") + if s.startswith("ses-")] # fmt: skip + if not sessions: + excluded["no primary session"] += 1 + continue + session = random.Random(f"{args.seed}:{cohort}:{subject}").choice(sessions) + keys = paths(prefix, subject, session, "") + try: + meta = read_json_object(s3, bucket, keys["primary"] + "/recording.json") + except s3.exceptions.ClientError: + excluded["no primary recording.json"] += 1 + continue + source_file = (meta.get("source") or {}).get("file") + keys = paths(prefix, subject, session, source_file or "") + if not source_file or not exists(s3, bucket, keys["source_h5"]): + excluded["no archived source H5"] += 1 + continue + entry = {"cohort": cohort, "subject": subject, "session": session, + "keys": keys, "bucket": bucket} # fmt: skip + entry["has_derivatives"] = exists(s3, bucket, keys["derivatives"] + "/recording.json") + entry["has_summary_json"] = exists(s3, bucket, keys["summary_json"]) + feature_file = None + if entry["has_derivatives"]: + deriv = read_json_object(s3, bucket, keys["derivatives"] + "/recording.json") + feature_file = (deriv.get("source") or {}).get("feature_file") + entry["derivative_feature_file"] = bool(feature_file) + if cohort in args.feature_h5: # the producer's name when no derivative names it + feature_file = feature_file or f"{subject}_{session}_desc-sleepfeatures.h5" + fbucket, fprefix = split(args.feature_h5[cohort]) + entry["feature_h5"] = {"bucket": fbucket, + "key": f"{fprefix}/{subject}/{session}/{feature_file}"} + entry["appended_signals"] = list((meta.get("source") or {}).get("pap_channels", [])) + entry["id"] = f"{cohort}-{len(chosen) + 1}" + chosen.append(entry) + selections += chosen + design[cohort] = {"population_subjects": len(subjects), "examined": examined, + "selected": len(chosen), "excluded": dict(excluded)} # fmt: skip + print(f"{cohort}: {len(chosen)} selected from {examined} examined " + f"({len(subjects)} subjects)", flush=True) # fmt: skip + return selections, design + + +def download_prefix(s3, bucket, prefix, target): + keys = [] + for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix + "/"): + keys += [(o["Key"], o["Size"]) for o in page.get("Contents", [])] + if not keys: + raise FileNotFoundError("empty prefix") + + def fetch(key): + path = target / key[len(prefix) + 1 :] + path.parent.mkdir(parents=True, exist_ok=True) + s3.download_file(bucket, key, str(path)) + + with ThreadPoolExecutor(16) as pool: + for future in as_completed([pool.submit(fetch, key) for key, _ in keys]): + future.result() + return sum(size for _, size in keys) + + +def converter_checks(converter_src, files, entry, exported, exported_plain): + """The converter's own verifier, with the rebuilt H5 standing in as the source H5.""" + if str(converter_src) not in sys.path: + sys.path.insert(0, str(converter_src)) + import warnings + + import h5py + from bdsp_psg_conversion.common.h5_reader import read_identity, read_summary, summary_group + from bdsp_psg_conversion.zarr_json.recording_zarr import DERIVATIVE + from bdsp_psg_conversion.zarr_json.verify import verify_features_json, verify_recording_zarr + + out = {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + out["primary"] = verify_recording_zarr(files["primary"], exported_plain) + if "derivatives" in files: + if entry.get("derivative_feature_file"): + out["derivatives"] = "not run: payload paths name a separate feature H5" + else: + out["derivatives"] = verify_recording_zarr( + files["derivatives"], exported_plain, DERIVATIVE + ) + if "summary_json" in files: + with h5py.File(exported, "r") as h5: + identity = read_identity(h5) + summary = read_summary(h5) if summary_group(h5) else [] + out["summary_json"] = verify_features_json(files["summary_json"], identity, summary) + return out + + +def process(entry, options): + """Download, rebuild, compare and clean up one recording; returns a result row.""" + from bdsp.h5_compare import compare_h5 + from bdsp.zarr_to_h5 import write_h5 + + s3 = client(options["profile"]) + bucket = entry["bucket"] + work = Path(options["output"]) / "work" / entry["id"] + shutil.rmtree(work, ignore_errors=True) + work.mkdir(parents=True) + row = {"id": entry["id"], "cohort": entry["cohort"], "subject": entry["subject"], + "session": entry["session"], "started": utcnow()} # fmt: skip + timing, sizes, files = {}, {}, {} + try: + start = time.monotonic() + for role in ("primary", "derivatives"): + if role == "primary" or entry["has_derivatives"]: + files[role] = work / entry["keys"][role].rsplit("/", 1)[-1] + sizes[role] = download_prefix(s3, bucket, entry["keys"][role], files[role]) + singles = [("source_h5", bucket, entry["keys"]["source_h5"])] + if entry["has_summary_json"]: + singles.append(("summary_json", bucket, entry["keys"]["summary_json"])) + if entry.get("feature_h5"): + singles.append(("feature_h5", entry["feature_h5"]["bucket"], entry["feature_h5"]["key"])) + for role, source_bucket, key in singles: + files[role] = work / key.rsplit("/", 1)[-1] + try: + s3.download_file(source_bucket, key, str(files[role])) + except Exception as err: # a missing optional feature H5 is reported, not fatal + if role != "feature_h5": + raise + row["feature_h5_unavailable"] = type(err).__name__ + files.pop(role) + else: + sizes[role] = files[role].stat().st_size + timing["download_s"] = time.monotonic() - start + + start = time.monotonic() + exported = work / "rebuilt.h5" + report = write_h5(exported, files["primary"], files.get("derivatives"), + files.get("summary_json")) # fmt: skip + timing["export_s"] = time.monotonic() - start + sizes["rebuilt_h5"] = exported.stat().st_size + row["export"] = {"signals_int16": report.signals_int16, + "signals_float32": report.signals_float32, + "annotation_tracks": report.annotation_tracks, + "feature_families": report.feature_families, + "summary_rows": report.summary_rows, + "summary_arrays": report.summary_arrays, + "notes": list(report.notes)} # fmt: skip + + start = time.monotonic() + row["comparison"] = compare_h5(files["source_h5"], exported, + features=files.get("feature_h5")) # fmt: skip + timing["compare_s"] = time.monotonic() - start + + if options["converter_src"]: + start = time.monotonic() + plain = exported + if entry["appended_signals"]: # the converter checks appended channels elsewhere + plain = work / "rebuilt_without_appended.h5" + write_h5(plain, files["primary"], files.get("derivatives"), + files.get("summary_json"), include_appended_signals=False) # fmt: skip + row["converter_verify"] = converter_checks( + options["converter_src"], files, entry, exported, plain + ) + timing["converter_s"] = time.monotonic() - start + except Exception as err: + row["error"] = f"{type(err).__name__}: {err}" + row["traceback"] = traceback.format_exc(limit=8) + finally: + if not options["keep_files"]: + shutil.rmtree(work, ignore_errors=True) + row.update(timing=timing, sizes=sizes, finished=utcnow()) + return row + + +def converter_passed(row): + checks = row.get("converter_verify") + if not checks: + return None + return all(value == [] for value in checks.values() if isinstance(value, list)) + + +def summarize(rows, design, manifest): + by_cohort = defaultdict(list) + for row in rows: + by_cohort[row["cohort"]].append(row) + selected = {entry["id"]: entry for entry in manifest["selections"]} + + def aggregate(items): + done = [r for r in items if "comparison" in r] + out = {"recordings": len(items), "errors": sum("error" in r for r in items), + "pass": sum(r["comparison"]["verdict"] == "pass" for r in done), + "without_derivative_zarr": sum(not selected[r["id"]]["has_derivatives"] + for r in items), + "without_summary_json": sum(not selected[r["id"]]["has_summary_json"] + for r in items)} # fmt: skip + failures, not_exported = Counter(), Counter() + totals = Counter() + for r in done: + c = r["comparison"] + failures.update({f.split(":")[0] for f in c["failures"]}) + s, a = c["signals"], c["annotations"] + totals.update(signals=s["compared"], physical_equal=s["physical_equal"], + digital_equal=s["digital_equal"], int16=s["int16"], + calibration_equal=s["calibration_equal"], + appended_signals=len(s["appended_from_other_files"]), + annotation_tables=a["original"], annotation_equal=a["equal"]) # fmt: skip + f = c["features"] + if "time_series" in f: + totals.update(families=f["time_series"]["original"], + families_equal=f["time_series"]["equal"]) # fmt: skip + if "recording_summary" in f: + rs = f["recording_summary"] + totals.update(summary_rows=rs["rows"], summary_arrays=rs.get("arrays", 0), + summary_arrays_equal=rs.get("arrays_equal", 0)) # fmt: skip + items_seen = {f"signal attr {n}" for n in s["attrs_not_exported"]} + items_seen |= {f"annotation attr {n}" for n in a["attrs_not_exported"]} + items_seen |= {f"root attr {n}" for n in c["not_exported"]["root_attrs"]} + items_seen |= {f"feature root attr {n}" for n in f.get("root_attrs_not_exported", [])} + items_seen |= {"node " + "/".join(p.split("/")[:4]).replace( + f.get("original_root", "\0"), "") + for p in c["not_exported"]["nodes"]} # fmt: skip + not_exported.update(items_seen) + out["failure_kinds"] = dict(sorted(failures.items())) + out["totals"] = dict(totals) + out["not_exported_in_recordings"] = dict(sorted(not_exported.items())) + verdicts = [converter_passed(r) for r in done] + out["converter_verify_pass"] = sum(v is True for v in verdicts) + out["converter_verify_run"] = sum(v is not None for v in verdicts) + for key in ("download_s", "export_s", "compare_s"): + values = [r["timing"][key] for r in done if key in r.get("timing", {})] + if values: + out[f"median_{key}"] = round(statistics.median(values), 1) + ratios = [r["sizes"]["rebuilt_h5"] / r["sizes"]["source_h5"] + for r in done if "rebuilt_h5" in r.get("sizes", {})] # fmt: skip + if ratios: + out["median_size_ratio_rebuilt_to_source"] = round(statistics.median(ratios), 3) + return out + + return { + "created": utcnow(), + "options": manifest["options"], + "runtime": manifest["runtime"], + "design": design, + "overall": aggregate(rows), + "cohorts": {cohort: aggregate(items) for cohort, items in sorted(by_cohort.items())}, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", default=DEFAULT_ROOT, help="S3 prefix holding cohorts") + parser.add_argument("--cohorts", nargs="+", default=list(COHORTS)) + parser.add_argument("--per-cohort", type=int, default=5) + parser.add_argument("--seed", type=int, default=20261127) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--profile") + parser.add_argument("--converter-src", type=Path, + help="bdsp-psg-conversion src/ directory for its own verifier") # fmt: skip + parser.add_argument("--feature-h5", action="append", default=[], metavar="COHORT=S3_PREFIX", + help="separate feature-H5 run prefix for a cohort (e.g. I0007)") # fmt: skip + parser.add_argument("--keep-files", action="store_true") + args = parser.parse_args(argv) + args.feature_h5 = dict(item.split("=", 1) for item in args.feature_h5) + args.output.mkdir(parents=True, exist_ok=True) + args.output.chmod(0o700) + + options = {"root": args.root, "cohorts": args.cohorts, "per_cohort": args.per_cohort, + "seed": args.seed, "feature_h5": args.feature_h5, + "converter_src": str(args.converter_src.resolve()) if args.converter_src else None} # fmt: skip + manifest_path = args.output / "manifest.json" + if manifest_path.exists(): + manifest = json.loads(manifest_path.read_text()) + if manifest["options"] != options: + sys.exit("options differ from the saved manifest; use a new --output") + else: + import bdsp + + selections, design = sample(args, client(args.profile)) + manifest = {"created": utcnow(), "options": options, "design": design, + "selections": selections, + "runtime": {"python": sys.version.split()[0], "bdsp": bdsp.__version__, + "bdsp_path": str(Path(bdsp.__file__).parent), + **{p: importlib.metadata.version(p) + for p in ("zarr", "h5py", "numpy")}}} # fmt: skip + write_json(manifest_path, manifest) + + results_path = args.output / "recordings.jsonl" + rows = [json.loads(line) for line in results_path.open()] if results_path.exists() else [] + done = {row["id"] for row in rows if "error" not in row} + rows = [row for row in rows if row["id"] in done] + pending = [e for e in manifest["selections"] if e["id"] not in done] + run = {"output": str(args.output), "profile": args.profile, + "converter_src": options["converter_src"], "keep_files": args.keep_files} # fmt: skip + print(f"{len(done)} done, {len(pending)} pending", flush=True) + with ProcessPoolExecutor(max(1, args.workers)) as pool, results_path.open("a") as log: + futures = {pool.submit(process, entry, run): entry["id"] for entry in pending} + for future in as_completed(futures): + row = future.result() + log.write(json.dumps(row, allow_nan=False) + "\n") + log.flush() + rows.append(row) + verdict = "error" if "error" in row else row["comparison"]["verdict"] + converter = converter_passed(row) + print(f"[{len(rows)}/{len(manifest['selections'])}] {row['id']}: {verdict}" + + ("" if converter is None else f", converter verify {'pass' if converter else 'fail'}"), + flush=True) # fmt: skip + summary = summarize(rows, manifest["design"], manifest) + write_json(args.output / "summary.json", summary) + overall = summary["overall"] + print(json.dumps({k: overall[k] for k in ("recordings", "errors", "pass", + "converter_verify_pass", "converter_verify_run")})) # fmt: skip + return 0 if overall["pass"] == overall["recordings"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/validation/reports/2026-11-27-h5-parity.md b/validation/reports/2026-11-27-h5-parity.md new file mode 100644 index 0000000..36c1d4d --- /dev/null +++ b/validation/reports/2026-11-27-h5-parity.md @@ -0,0 +1,135 @@ +# Rebuilding source H5s from published split Zarr — 2026-11-27 + +**The published primary Zarr, derivative Zarr and summary JSON suffice to +rebuild the archived source H5 for every sampled recording in S0001, I0002, +I0003, I0004 and I0006 (25/25).** Every signal sample, annotation event, +feature time-series family and recording-summary row that the split format +carries matched the archived H5, and the converter's own source-to-export +verifier accepted every rebuilt H5 as the source of the published stores +(30/30). **I0007 cannot be rebuilt completely today: its derivative Zarr +stores are not published** (0 of 300 sampled subjects), so the rebuilt H5s +lack CAISR annotations and feature time series. Everything I0007 does publish +matched. + +## Scope and reproducibility + +- Read-only sources: `s3://bdsp-opendata-repository/PSG/bids//` for + S0001, I0002, I0003, I0004, I0006 and I0007; for I0007 features, the + producer run the derivative artifacts were built from + (`s3://bdsp-staging/arpa-h-rest/sleep-features/runs/aws-i0007-fullprofile-v3-20261003/`). +- Sample: **5 subjects per cohort**, seed **20261127**, one seeded session per + subject, 30 recordings. Every examined subject had a primary store and an + archived source H5, so none was replaced. Cohort sizes: S0001 21,263, + I0002 12,714, I0003 12,839, I0004 31,277, I0006 13,714 and I0007 22,033 + primary subjects. +- Code: `bdsp` 0.5.0 from this branch (`bdsp.zarr_to_h5`, `bdsp.h5_compare`), + [`validation/h5_parity.py`](../h5_parity.py); converter verifier from an + unmodified export of `bdsp-psg-conversion` `origin/main` at `c82da21`. + Runtime: Python 3.12.13, Zarr 3.3.0, h5py 3.16.0, NumPy 2.4.3. +- [Method and command](../README.md#h5-parity-zarr-to-h5). Selections, per-recording + results and object paths are kept privately in the ignored + `validation/results/h5-parity-20261127/`. Downloads and rebuilt H5s were + deleted after each recording. No cloud data were modified. + +## Results + +| Cohort | Pass | Signals: physical equal | int16 / digital equal / calibration equal | Annotation tables | Feature families | Summary rows | Converter verify | +| --- | --- | --- | --- | --- | --- | --- | --- | +| S0001 | 5/5 | 122/122 | 98 / 97 / 97 | 42/42 | 135/135 | 21,132 | 5/5 | +| I0002 | 5/5 | 123/123 | 118 / 110 / 110 | 50/50 | 179/179 | 26,415 | 5/5 | +| I0003 | 5/5 | 290/290 | 236 / 211 / 206 | 45/45 | 129/129 | 21,132 | 5/5 | +| I0004 | 5/5 | 158/158 | 148 / 135 / 125 | 28/28 | 31/31 | 5,283 | 5/5 | +| I0006 | 5/5 | 204/204 | 158 / 157 / 141 | 44/44 | 176/176 | 26,415 | 5/5 | +| I0007 | 0/5 | 127/127 | 92 / 78 / 53 | 12/12 | 0/121 (not published) | 26,415 | 5/5 | +| **All** | **25/30** | **1,024/1,024** | **850 / 788 / 732** | **221/221** | **650/650 published** | **126,792** | **30/30** | + +- **Signals.** All 1,024 source signals have identical rates, lengths and + physical float32 samples, computed with the converter's calibration formula. + 83% were rebuilt as int16, 77% with the archived digital samples and 71% with + the archived `phys_min/phys_max/dig_min/dig_max` attributes. The other int16 + signals use another calibration that reproduces the same values exactly. The + remaining 17% are stored as float32 with an identity calibration: sparsely + used or unusual ranges for which no short-decimal calibration reproduces + every sample. Twelve PAP channels appended after conversion were also + written, each naming its `*_desc-pap.h5`. +- **Annotations.** All 221 tables have identical codes and `event_map`s, and + onsets and durations are bit-identical. `ends`, rebuilt as + `starts + durations`, differs by up to 3.9 ms where a source table stored a + slightly different float32 end (the converter accepts up to 10 ms). +- **Features.** Every published feature family matched its source group + recursively: attributes, dtypes, shapes, masks, statuses and `information` + fields (650/650). Summary columns matched for all 126,792 rows in the 24 + recordings with features, and all 22 summary arrays (the 1,024-D embedding), + including their float32 dtype. Six sampled recordings (one S0001, one I0003, + four I0004) have no computed features; their source H5s have none either. +- **Dates and identity.** Subject, session, duration, published age and sex + matched for every recording. Root `meas_date` matched the source H5, using + `h5_meas_date` where an I0006 summary JSON carries a corrected date. +- **Converter verifier.** With the rebuilt H5 standing in as the source, + `verify_recording_zarr` reported no problems for every primary store (with + appended channels left out, as the converter verifies those against their own + file). It also reported no problems for each of the 25 published derivative stores, + and `verify_features_json` none for each of the 30 summary JSONs. +- **Reader compatibility.** For one I0002 recording, `bdsp.read_h5`, + `bdsp.open_h5` windows and `to_dataframe(resample_fs=100)` gave identical + results for the rebuilt and the source H5. The synthetic tests cover the same + calls. +- **Cost.** Median download 75 s, rebuild 43 s and comparison 15 s per + recording (I0003's larger recordings: median rebuild 228 s). Rebuilt H5s were + 0.97–1.41× the source size, median 1.05. + +## I0007: derivative Zarr not published + +All five sampled I0007 sessions have a primary store and a summary JSON +(written 2026-11-09/10), but no `*_deriv-bdspsleepfeatures.zarr`. A separate +read-only listing of 300 seeded I0007 subjects found **no derivative Zarr for +any of them**: 299 have only the JSON and one has neither. For comparison, the +same listing found derivative Zarr for 95/100 S0001 subjects (5 have neither +artifact) and 100/100 in I0002, I0003, I0004 and I0006. The cohort's `CHANGES` +says I0007's "feature JSON and derivative zarr bundles" were rebuilt from the +feature H5 on 2026-11-09/10. These listings show the JSONs but not the Zarr +stores. + +As a result, rebuilt I0007 H5s have expert annotations, signals and the full +recording summary (all rows and arrays matched the producer's feature H5), but +no CAISR annotations and none of the producer's temporal families (38 in three +sessions, 4 and 3 in the other two). This is missing input, not a writer failure. Publishing +I0007's derivative stores, e.g. with the converter's `--features-from` +reconversion, would close it. + +## Not carried by the split format + +These items occur in source H5s but are not stored in any split artifact, so +the rebuilt H5 lists them in `bdsp_h5_export` instead of inventing them. They +are not counted as failures: + +| Item | Recordings | +| --- | --- | +| signal `prefilter` and `type` attributes | 30/30 | +| root `age_in_days`, `metadata_source`, `hypopnea_rule_source` | 30/30 | +| annotation `rule`, `rule_description` (`resp_3`/`resp_4`) | 26/30 | +| producer `package_name`/`package_version`, `provenance/json`, `recording/identity_json`, `features/research` | 19/19 with merged features | +| I0007 root `annotation_patch*` attributes | 5/5 | + +## Limitations + +- Five recordings per cohort test the method across every cohort's variants: + PAP channels, corrected dates, separate feature H5s and recordings without + features. They do not bound prevalence tightly: zero failures in the 25 + complete recordings gives an approximate 95% upper bound of 12% for this + design. +- Parity covers what the split format carries. It does not restore the items + above, and it does not show that other H5 consumers (e.g. Sleep YODA desktop) + accept float32 signals or a missing `prefilter`. +- A different but exact int16 calibration changes the stored digital + integers, not the physical values. Comparisons and the converter's verifier + use physical values. + +## Next actions + +1. Decide on and publish the I0007 derivative Zarr stores, then rerun this + check for I0007. +2. If digital-sample identity matters more broadly, extend the calibration + search to the remaining sparse channels. Physical values are already exact. +3. Rerun this check with a larger sample before treating split-only storage as + the archival basis for local H5s.