Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 29 additions & 2 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
133 changes: 133 additions & 0 deletions docs/bids-zarr/H5_EXPORT.md
Original file line number Diff line number Diff line change
@@ -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/<name>` | primary continuous channels with origin `signal` | int16 digital samples with `fs`, `unit`, `phys_min`, `phys_max`, `dig_min`, `dig_max` (below) |
| `/annotations/<scorer>/<kind>/` | event channels with origin `annotation`, primary and derivative | `starts`, `ends`, `durations` (float32 seconds), `codes` (int16 original codes), `event_map`, `format="event_table"` |
| `<root>/time_series/<family>/` | `bdsp.sleep-feature-payload.v1` payload groups | copied as stored: attributes, dtypes, shapes, masks, statuses, `information` |
| `<root>/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 |

`<root>` 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.
6 changes: 4 additions & 2 deletions docs/bids-zarr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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 |
Expand Down Expand Up @@ -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) |

Expand Down
7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion src/bdsp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
"read_h5",
]

__version__ = "0.4.0"
__version__ = "0.5.0"
Loading
Loading