AlejandroGZ commited on
Commit
881cb3b
·
1 Parent(s): d218f6e

v2.6 dataset

Browse files
README.md CHANGED
@@ -37,8 +37,13 @@ All measurements are synthetic. DRMHB is not field data and is not a substitute
37
  for validation on real machinery.
38
 
39
  The current fixture was generated with VibSynth orchestration script 2.5.0,
40
- serialized as VibFrame 0.2.0, and validated with
41
- [`vibframe-anndata==0.2.2`](https://413hq.github.io/vibframe-anndata-docs/latest/).
 
 
 
 
 
42
 
43
  ## The challenge
44
 
@@ -167,97 +172,116 @@ thermal history and structural transfer.
167
 
168
  ## Ground truth and leakage prevention
169
 
170
- The source VibFrame keeps evaluation information in partitioned sidecars. During
171
- conversion, `vibframe-anndata` 0.2.2 can align snapshot truth one-to-one with
172
- observations and store it at:
173
-
174
- ```python
175
- adata.obsm["ground_truth"]
176
- ```
177
-
178
- The current aligned table has shape `(46907, 42)`. It includes regime,
179
- transition route and progress, acquisition kind, elapsed time, true process
180
- states, nuisance metadata, OOD status, fault types, severities and serialized
181
- physical states.
182
-
183
- Ground truth is colocated for reproducible evaluation, not for learning. Do not
184
- use `split`, `fault_*`, physical states, `ood_operational`, nuisance labels or
185
- other truth fields as unsupervised model inputs. The feature matrix `X` contains
186
- only explicitly materialized signal-derived features.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
  ## Distribution and local AnnData workflow
189
 
190
- The canonical public artifact is:
191
-
192
- ```text
193
- data/DRMHB.vibframe.zip
194
- ```
195
-
196
- AnnData files are derived locally so that the raw VibFrame remains the single
197
- canonical representation. Run from the repository root:
198
 
199
  ```bash
200
- python -m pip install "vibframe-anndata==0.2.2" "anndata>=0.10,<0.13"
201
 
202
  python examples/01_create_featureless_anndata.py \
203
- data/DRMHB.vibframe.zip \
204
- derived/DRMHB.float32.h5ad
205
 
206
  python examples/02_inspect_anndata.py \
207
- derived/DRMHB.float32.h5ad
208
 
209
  python examples/03_add_features.py \
210
- derived/DRMHB.float32.h5ad \
211
- derived/DRMHB.float32.eda-features.h5ad
 
212
  ```
213
 
214
- The base H5AD is intentionally featureless:
 
 
 
 
 
215
 
216
- ```text
217
- X.shape == (46907, 0)
218
- ```
 
219
 
220
- It retains raw spectra, ragged waveforms, tachometer arrays, provenance and
221
- aligned evaluation truth in `obsm`. The reference feature example produces:
222
 
223
- ```text
224
- X.shape == (46907, 468)
 
 
225
  ```
226
 
227
- Features are calculated exclusively from raw arrays in the base H5AD; the
228
- original VibFrame is not reopened. See [examples/README.md](examples/README.md)
229
- for detailed commands, validation output and storage notes.
 
 
230
 
231
- Validated local sizes with uncompressed raw arrays are approximately:
232
 
233
- | Artifact | Size |
234
- |---|---:|
235
- | Canonical VibFrame ZIP | 8.36 GiB |
236
- | Featureless float32 H5AD | 9.35 GiB |
237
- | Reference-feature float32 H5AD | 9.44 GiB |
 
 
 
 
 
 
238
 
239
  ## AnnData layout
240
 
241
  ```text
242
- obs
243
- |- snapshot identity, timestamp, machine, speed and availability flags
244
-
245
- X
246
- |- initially (46907, 0); signal-derived features after materialization
247
-
248
- var
249
- |- feature provenance and channel metadata
250
-
251
- obsm
252
- |- raw_spectra and lengths/positions/speed
253
- |- raw_waveforms and lengths/positions/speed
254
- |- raw_waveforms_tacho_rising / raw_waveforms_tacho_falling
255
- `- ground_truth (evaluation only)
256
-
257
- uns
258
- `- VibFrame, channel and conversion provenance
259
  ```
260
 
 
 
 
 
261
  ## Recommended evaluation protocol
262
 
263
  1. Fit preprocessing and models only on `calibration`.
@@ -277,6 +301,10 @@ hours; an observation gap longer than 4.5 hours breaks the run.
277
 
278
  ## Compact reference baseline
279
 
 
 
 
 
280
  The reference notebook fits four deliberately small unsupervised baselines.
281
  Thresholds are the 99th percentile of normal-holdout scores.
282
 
@@ -299,18 +327,29 @@ respectively, and the TwoNN intrinsic-dimension estimate is approximately 8.80.
299
 
300
  ```text
301
  DRMHB/
302
- |- data/ canonical VibFrame and local derived artifacts
303
- |- examples/ conversion, inspection and feature scripts
304
- |- notebooks/DRMHB_EDA.ipynb
305
- |- latexdocs/ LaTeX source, compiled PDF and EDA figures/tables
306
- |- generator.py reproducible scenario generator
307
- `- LICENSE.md
 
 
 
 
 
308
  ```
309
 
310
- The [explanatory PDF](latexdocs/DRMHB.pdf) describes the simulated plant,
311
- acquisition policy, physical fault mechanisms and evaluation challenge. The
312
- notebook is the executable EDA and exports reusable figures and baseline tables
313
- to `latexdocs/`.
 
 
 
 
 
 
314
 
315
  ## Limitations
316
 
 
37
  for validation on real machinery.
38
 
39
  The current fixture was generated with VibSynth orchestration script 2.5.0,
40
+ serialized as VibFrame 0.2.0. The conversion examples now use
41
+ [`vibframe-anndata==0.3.0`](https://413hq.github.io/vibframe-anndata-docs/0.3.0/)
42
+ with complete evaluation preservation. The raw ZIP is unchanged: this is the
43
+ published 2.5.0 fixture, not a newly generated compact-controls campaign.
44
+
45
+ **Start here:** [dataset report](docs/DRMHB.pdf), [conversion examples](examples/README.md)
46
+ and [complete ground-truth guide](docs/GROUND_TRUTH.md).
47
 
48
  ## The challenge
49
 
 
172
 
173
  ## Ground truth and leakage prevention
174
 
175
+ The source VibFrame keeps evaluation information in separate sidecars. The
176
+ 0.3.0 workflow preserves both supported observation-aligned views and the
177
+ original files, without automatically exposing targets to a model:
178
+
179
+ | AnnData location | Information |
180
+ |---|---|
181
+ | `obsm["ground_truth"]` | Snapshot truth, aligned with `obs_names` |
182
+ | `obsm["waveform_ground_truth"]` | Per-waveform annotations with explicit raw-channel bindings |
183
+ | `uns["vibframe_evaluation"]` | Byte-exact original annotation files and source/path/size/SHA-256 manifest |
184
+ | `uns["vibframe_anndata"]` | Conversion, raw-channel and feature provenance |
185
+ | `obsm["raw_*_capture_t"]` and `*_capture_t_known` | Actual capture times and explicit/fallback flags |
186
+
187
+ This includes construction labels, crop offsets and durations, quantization and
188
+ hashes, machine parameters, scenario configuration and DiagGT documents/tables.
189
+ All regular files under `evaluation/`, `ground-truth/` and `ground_truth/` are
190
+ preserved, plus root JSON/YAML and machine JSON context. Unknown annotation
191
+ fields are retained; the original Parquet schema can be recovered.
192
+
193
+ Snapshot joins use **source, machine and integer UTC-microsecond `snap_t`**, not
194
+ row order. Per-waveform joins also identify the raw channel. Capture `t` can be
195
+ later than `snap_t` because of cropping; it is not a different snapshot.
196
+
197
+ The reference snapshot view had 42 columns. Code must inspect actual fields
198
+ instead of hard-coding a fixed schema. Do not use `split`, `fault_*`, severity,
199
+ physical states, `ood_operational`, nuisance labels or DiagGT as unsupervised
200
+ model inputs. Operational-state knowledge must be an explicitly declared
201
+ experimental condition. The package never adds these fields to `X` implicitly.
202
+
203
+ **Preservation is not automatic labelling:** DiagGT intervals, consolidated
204
+ observations and findings retain their original semantics. No nearest-time
205
+ join is invented, and absence of a diagnosis does not mean healthy. The original
206
+ archive remains dataset-wide when AnnData observations are sliced.
207
 
208
  ## Distribution and local AnnData workflow
209
 
210
+ The single canonical public signal artifact is `data/DRMHB.vibframe.zip`.
211
+ H5ADs are local derivatives, not a second public source of truth.
 
 
 
 
 
 
212
 
213
  ```bash
214
+ python -m pip install -r examples/requirements.txt
215
 
216
  python examples/01_create_featureless_anndata.py \
217
+ data/DRMHB.vibframe.zip derived/DRMHB.v0.3.0.raw.h5ad
 
218
 
219
  python examples/02_inspect_anndata.py \
220
+ derived/DRMHB.v0.3.0.raw.h5ad --waveform-details
221
 
222
  python examples/03_add_features.py \
223
+ derived/DRMHB.v0.3.0.raw.h5ad derived/DRMHB.v0.3.0.features.h5ad
224
+
225
+ python examples/05_read_evaluation.py derived/DRMHB.v0.3.0.features.h5ad
226
  ```
227
 
228
+ Example 01 explicitly enables `ground_truth.scope="all"`, stores numerical
229
+ values as `float32`, and ingests in raw-data blocks of 8 MiB. The featureless base
230
+ has `X.shape == (46907, 0)` for the published fixture. The unchanged reference
231
+ feature requests materialized 468 machine/source-scoped columns in the reference
232
+ EDA, with structural missing values for other machines. They are not 468 dense
233
+ fleet-wide descriptors; the notebook explains the logical-column alignment.
234
 
235
+ Example 03 calculates features only from the raw H5AD and checks that original
236
+ annotations and raw coverage are preserved. Example 02 reads HDF5 metadata and
237
+ public annotation APIs selectively; it does not assume AnnData backed mode
238
+ keeps `obsm` or the evaluation archive out of RAM.
239
 
240
+ For an existing 0.2.x H5AD, preserve the original source identities and run:
 
241
 
242
+ ```bash
243
+ python examples/04_add_complete_ground_truth.py \
244
+ derived/DRMHB.float32.eda-features.h5ad data/DRMHB.vibframe.zip \
245
+ derived/DRMHB.v0.3.0.features.h5ad
246
  ```
247
 
248
+ This adds annotations without recalculating `X`, `var` or raw samples. A
249
+ transactional temporary copy needs roughly one additional H5AD of free disk.
250
+ Legacy capture-time companion arrays are not retroactively recovered by this
251
+ operation; new raw imports populate them. Crop information is still retained
252
+ in waveform truth.
253
 
254
+ ### Storage and memory
255
 
256
+ The canonical ZIP is **8,972,153,939 bytes (8.356 GiB)**. The reference 0.2.2
257
+ run measured about 9.35 GiB for its featureless H5AD and 9.44 GiB after reference
258
+ features. Those are historical snapshot-only sizes, **not measured 0.3.0 sizes**.
259
+ Full annotations add original sidecar bytes, aligned views and capture-time
260
+ matrices. Examples report their actual output size rather than extrapolating.
261
+
262
+ The default 512 MiB sidecar budget covers original encoded annotation files,
263
+ not decoded tables or total process RAM. Inspect exact archived sizes with
264
+ `list_evaluation_files()`. Raw-array compression remains `none`, as in the
265
+ existing examples; no compression benchmark is rerun. Ground-truth conversion
266
+ does not modify the VibFrame ZIP.
267
 
268
  ## AnnData layout
269
 
270
  ```text
271
+ obs : snapshot identity, snap_t, machine, source, speed and availability
272
+ X : n_snapshots × n_materialized_features (initially zero columns)
273
+ var : feature descriptors, units, channel identity and provenance
274
+ obsm : ragged raw spectra/waveforms + lengths/positions/speed
275
+ tachometer edges + capture_t/known companions
276
+ ground_truth + waveform_ground_truth (evaluation only)
277
+ uns : vibframe_anndata (package/raw/feature provenance)
278
+ vibframe_evaluation (original sidecar bytes and manifest)
 
 
 
 
 
 
 
 
 
279
  ```
280
 
281
+ See [examples/README.md](examples/README.md) for precise commands and
282
+ [docs/GROUND_TRUTH.md](docs/GROUND_TRUTH.md) for target selection, source identity,
283
+ original DiagGT access and missing-data semantics.
284
+
285
  ## Recommended evaluation protocol
286
 
287
  1. Fit preprocessing and models only on `calibration`.
 
301
 
302
  ## Compact reference baseline
303
 
304
+ The values below come from the immutable [published EDA run](notebooks/reference/DRMHB_EDA_published_2_5_0.ipynb)
305
+ for the 2.5.0 fixture with converter 0.2.2. Updating the annotation API does not
306
+ constitute rerunning those experiments.
307
+
308
  The reference notebook fits four deliberately small unsupervised baselines.
309
  Thresholds are the 99th percentile of normal-holdout scores.
310
 
 
327
 
328
  ```text
329
  DRMHB/
330
+ |- data/DRMHB.vibframe.zip canonical published 2.5.0 signal dataset
331
+ |- derived/ local H5ADs (not versioned)
332
+ |- examples/ import, inspect, features, retrofit, evaluation readers
333
+ |- notebooks/DRMHB_EDA.ipynb editable 0.3.0 EDA workflow, outputs cleared
334
+ |- notebooks/reference/ immutable executed source of published EDA results
335
+ |- docs/DRMHB.tex editable report source
336
+ |- docs/DRMHB.pdf compiled dataset report
337
+ |- docs/figures/ EDA images and editable vector diagrams
338
+ |- docs/provenance/ figure/table and source identities
339
+ |- tools/ report build and reference-asset recovery
340
+ `- tests/ small, synthetic example-integration checks
341
  ```
342
 
343
+ The [report](docs/DRMHB.pdf) explains the installation, daily/weekly state
344
+ schedule, acquisitions, degradation, evaluation and complete AnnData workflow.
345
+ Build it with `python tools/build_report.py` once a LaTeX distribution with
346
+ `latexmk` and TikZ is installed. The report's 37 EDA figures and two baseline
347
+ tables are recovered from the original executed notebook, not redrawn from
348
+ invented data. Their [manifest](docs/provenance/eda_assets.json) records source
349
+ cells and hashes. The updated notebook exports new plots/tables to
350
+ `derived/eda_v0.3.0/`, separately from the report reference assets. Review and
351
+ promote a complete new run together with its numerical narrative and provenance;
352
+ partial execution cannot silently replace published figures.
353
 
354
  ## Limitations
355
 
data/{DRMHB.vibframe.zip → DRMHB-compact-controls.vibframe.zip} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2f4ceef65242719134771a321199542ad794cb72c76c93b6c4b15da608a9affa
3
- size 8972153939
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b193177effafaf17089f753e57cd94b5ad969873d7cedfdceaab81171fdee128
3
+ size 185975818
data/DRMHB-compact.vibframe.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58d3fd1042cfac189ba9a464954fbcf3e6f990b75327ddaf1986d13e7583eb1b
3
+ size 7635324956
docs/DRMHB.pdf CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:a74abeab5b4b4e5673368b0ef826db5026b136c4963963b68a6e1e176c598761
3
- size 3716343
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7433c2b4c8baddb72cc7c4cc49291217edbd04d486b517ec5b419ac273de370
3
+ size 4506090
docs/GROUND_TRUTH.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ground truth for DRMHB researchers
2
+
3
+ ## Four different kinds of information
4
+
5
+ **Measured input** is raw acceleration/velocity information and measurement
6
+ context: units, sample rate/frequency grid, point, mode, speed and timing.
7
+ **Construction truth** records the simulator's process, health and nuisance
8
+ states. **Waveform truth** explains how a captured source became a stored crop.
9
+ **Diagnostic truth (DiagGT)** carries diagnostic documents, observations,
10
+ findings and materialization rules. These are complementary, not interchangeable.
11
+
12
+ | Where | Use |
13
+ |---|---|
14
+ | `obs` | Snapshot identity and measurement context |
15
+ | `X`, `var` | Explicit signal-derived feature values and definitions |
16
+ | `obsm['raw_waveforms']`, `raw_spectra` and companions | Reusable raw signals, real lengths, positions, speeds and tachometer edges |
17
+ | `obsm['ground_truth']` | Snapshot-aligned construction labels |
18
+ | `obsm['waveform_ground_truth']` | Per-snapshot `records_json` with zero or more channel-bound waveform labels |
19
+ | `uns['vibframe_evaluation']` | Original evaluation files, byte-exact, with source/path/size/SHA-256 |
20
+ | `uns['vibframe_anndata']` | Source, conversion, alignment, channel and feature provenance |
21
+
22
+ ## Import all the information
23
+
24
+ ```python
25
+ from vibframe_anndata import import_raw_to_h5ad
26
+ base = import_raw_to_h5ad(
27
+ "data/DRMHB.vibframe.zip", "derived/DRMHB.v0.3.0.raw.h5ad",
28
+ config={
29
+ "version": 1,
30
+ "raw_import": {"on_missing_signal": "nan"},
31
+ "ground_truth": {"enabled": True, "scope": "all",
32
+ "on_missing": "error", "max_sidecar_mib": 512},
33
+ "output": {"dtype": "float32", "raw_compression": "none"},
34
+ }, block_size_mib=8,
35
+ )
36
+ ```
37
+
38
+ Full scope retains regular files under `evaluation/`, `ground-truth/` and
39
+ `ground_truth/`, root JSON/YAML documents and machine JSON context. This includes
40
+ unknown future annotation fields and files. Files outside those locations are
41
+ not indiscriminately copied. The evaluation archive is not a duplicate waveform
42
+ archive. Raw `trends.parquet` is never a source of production feature values.
43
+
44
+ ## Identity and time
45
+
46
+ Use `(source, machine_id, snap_t)` for snapshot labels. Times are integer
47
+ microseconds since Unix epoch, UTC. Never infer the unit from the magnitude.
48
+ Waveform labels additionally bind point and available mode/definition/config
49
+ identifiers. Missing identity, duplicated bindings and ambiguous modes must not
50
+ be fixed by row-order or nearest-time guessing.
51
+
52
+ A source acquisition starts at `snap_t`; a stored crop starts at `t`:
53
+
54
+ ```text
55
+ t = snap_t + crop offset
56
+ ```
57
+
58
+ New imports retain `raw_waveforms_capture_t`, `raw_spectra_capture_t` and the
59
+ corresponding `*_known` matrices on the channel axis. Always check real lengths
60
+ and the known flags: an absent capture is not a date, and a legacy fallback is
61
+ not an explicitly measured time. Tachometer edges are relative to the stored crop.
62
+
63
+ ## Read labels without loading signals
64
+
65
+ ```python
66
+ from vibframe_anndata import (
67
+ get_snapshot_ground_truth, get_waveform_ground_truth, list_evaluation_files,
68
+ read_evaluation_table, read_evaluation_json,
69
+ )
70
+ path = "derived/DRMHB.v0.3.0.features.h5ad"
71
+ snapshot = get_snapshot_ground_truth(path)
72
+ waveform = get_waveform_ground_truth(path, point_id="pump_DE_H", proc_mode_id="ACC_10K")
73
+ files = list_evaluation_files(path)
74
+ # Pick an exact source/path from files before calling a reader.
75
+ rows = files.loc[files["path"].str.endswith("observations.parquet")]
76
+ if not rows.empty:
77
+ item = rows.iloc[0]
78
+ diagnostics = read_evaluation_table(path, item["path"], source=item["source"])
79
+ ```
80
+
81
+ Convenience views can stringify nested fields for HDF5 compatibility. The table
82
+ reader recovers the original Arrow schema; the byte reader verifies the original
83
+ hash by default. A selected table is materialized, but unrelated raw buffers are
84
+ not loaded. Avoid reading the entire `uns` group just to inspect metadata.
85
+
86
+ ## Protocol decisions remain explicit
87
+
88
+ Normality training must not automatically consume fault identity, severity,
89
+ physical state, nuisance/OOD flags, simulation seeds or future labels. A known
90
+ operating state is an oracle input only under an explicitly declared experiment.
91
+ Do not infer health from missing DiagGT. Consolidated diagnoses and intervals
92
+ must be interpreted using their original document/materialization semantics.
93
+
94
+ The aligned views follow observation slicing, but the original archive remains
95
+ dataset-wide. Features added/recalculated/removed by the package preserve both.
96
+ Keep independently generated paired controls out of the longitudinal training
97
+ and evaluation splits; use a separate H5AD/source and pair identities.
98
+
99
+ ## Existing H5ADs
100
+
101
+ Example 04 wraps `add_ground_truth_to_h5ad()`. It adds originals and aligned
102
+ annotations to an existing file without recomputing features or source raw
103
+ signals. Keep `obs.source`, `obs.machine`, `obs.snap_t` and the original source
104
+ set. The transactional copy requires additional disk space. It does not recreate
105
+ legacy capture-time companion arrays; new raw imports do. Original waveform
106
+ truth still provides offsets/durations for audit.
107
+
108
+ ## Resource accounting
109
+
110
+ The H5AD grows by original sidecar bytes, aligned labels, the manifest and timing
111
+ companions. `list_evaluation_files()` reports exact original sizes. The 512 MiB
112
+ budget refers to encoded sidecars, not total RAM. No raw compression is changed.
113
+ The published ZIP remains 8,972,153,939 bytes; full-annotation H5AD sizes must be
114
+ measured after conversion rather than reusing the older snapshot-only sizes.
115
+
116
+ Authoritative API and full coverage rules:
117
+ https://413hq.github.io/vibframe-anndata-docs/0.3.0/guides/ground-truth/
examples/01_create_featureless_anndata.py CHANGED
@@ -1,151 +1,51 @@
1
  #!/usr/bin/env python3
2
- """
3
- Create a featureless DRMHB AnnData from the distributed VibFrame archive.
4
-
5
- Validated with:
6
- vibframe-anndata==0.2.2
7
-
8
- DRMHB is distributed canonically as VibFrame. This script demonstrates the
9
- recommended out-of-core conversion into a reusable featureless H5AD.
10
-
11
- The 0.2.2 release can also ingest DRMHB snapshot-level evaluation truth from
12
- evaluation/snapshot_truth/ and store it in obsm["ground_truth"] without exposing
13
- those labels as model features.
14
-
15
- Install:
16
- python -m pip install "vibframe-anndata==0.2.2"
17
-
18
- Usage:
19
- python examples/01_create_featureless_anndata.py \
20
- data/DRMHB.vibframe.zip \
21
- derived/DRMHB.float32.h5ad
22
- """
23
 
24
  from __future__ import annotations
25
 
26
  import argparse
27
  from pathlib import Path
28
 
29
- from vibframe_anndata import (
30
- __version__ as vibframe_anndata_version,
31
- import_raw_to_h5ad,
32
- validate_streamed_h5ad,
33
- )
34
-
35
- EXPECTED_VERSION = "0.2.2"
36
 
37
 
38
  def parse_args() -> argparse.Namespace:
39
- parser = argparse.ArgumentParser(
40
- description="Convert DRMHB VibFrame into a featureless AnnData."
41
- )
42
- parser.add_argument(
43
- "vibframe",
44
- type=Path,
45
- help="Path to the DRMHB VibFrame ZIP archive.",
46
- )
47
- parser.add_argument(
48
- "output",
49
- type=Path,
50
- help="Destination .h5ad path.",
51
- )
52
  parser.add_argument(
53
- "--block-size-mib",
54
- type=int,
55
- default=32,
56
- help="Approximate raw-ingest block size in MiB (default: 32).",
57
  )
58
  parser.add_argument(
59
- "--dtype",
60
- choices=("float32", "float64"),
61
- default="float32",
62
- help="Numerical storage dtype (default: float32).",
63
- )
64
- parser.add_argument(
65
- "--without-ground-truth",
66
- action="store_true",
67
- help=(
68
- "Do not ingest evaluation/snapshot_truth into obsm['ground_truth']. "
69
- "By default DRMHB ground truth is imported explicitly for evaluation."
70
- ),
71
  )
 
 
72
  return parser.parse_args()
73
 
74
 
75
  def main() -> None:
76
  args = parse_args()
77
-
78
- if vibframe_anndata_version != EXPECTED_VERSION:
79
- raise RuntimeError(
80
- f"This example is validated for vibframe-anndata=={EXPECTED_VERSION}; "
81
- f"active version: {vibframe_anndata_version!r}"
82
- )
83
-
84
- if not args.vibframe.is_file():
85
- raise FileNotFoundError(args.vibframe)
86
-
87
- args.output.parent.mkdir(parents=True, exist_ok=True)
88
-
89
- config = {
90
- "version": 1,
91
- "raw_import": {
92
- "waveforms": True,
93
- "spectra": True,
94
- "on_missing_signal": "nan",
95
- },
96
- "ground_truth": {
97
- "enabled": not args.without_ground_truth,
98
- "on_missing": "error",
99
- },
100
- "output": {
101
- "dtype": args.dtype,
102
- # Explicitly use the 0.2.2 default. Compression is lossless but the
103
- # package benchmark shows that compressed raw payloads materially
104
- # slow later feature enrichment for this DRMHB-sized workload.
105
- "raw_compression": "none",
106
- },
107
- # Empty by design: the base AnnData contains raw reusable signals only.
108
- "features": [],
109
- "obs": {
110
- "include": [
111
- "snapshot_id",
112
- "timestamp",
113
- "snap_t",
114
- "source",
115
- "machine",
116
- "speed_hz",
117
- "has_waveform",
118
- "has_spectrum",
119
- ],
120
- },
121
- }
122
-
123
- output = import_raw_to_h5ad(
124
  args.vibframe,
125
  args.output,
126
- config=config,
 
127
  block_size_mib=args.block_size_mib,
 
 
128
  )
129
-
130
- validation = validate_streamed_h5ad(output)
131
-
132
- if int(validation["n_vars"]) != 0:
133
- raise RuntimeError("The base AnnData must remain featureless (n_vars = 0).")
134
- if not args.without_ground_truth and int(validation["ground_truth_rows"]) != int(
135
- validation["n_obs"]
136
- ):
137
- raise RuntimeError("Ground truth is not aligned one-to-one with observations.")
138
-
139
  print(f"Created: {output}")
140
- print(f"Observations: {validation['n_obs']:,}")
141
- print(f"Variables/features: {validation['n_vars']:,}")
142
- print("Expected featureless base: n_vars = 0")
143
  print(
144
- "Ground truth:",
145
- "disabled" if args.without_ground_truth else "stored in obsm['ground_truth']",
146
  )
147
- print(f"Waveform signals: {validation['waveform_signals']:,}")
148
- print(f"Spectrum signals: {validation['spectrum_signals']:,}")
149
 
150
 
151
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
+ """Import a DRMHB ZIP or directory with full ground truth (no features)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  from __future__ import annotations
5
 
6
  import argparse
7
  from pathlib import Path
8
 
9
+ from drmhb_workflow import create_base, positive_int
10
+ from vibframe_anndata import validate_streamed_h5ad
 
 
 
 
 
11
 
12
 
13
  def parse_args() -> argparse.Namespace:
14
+ parser = argparse.ArgumentParser(description=__doc__)
15
+ parser.add_argument("vibframe", type=Path)
16
+ parser.add_argument("output", type=Path)
17
+ parser.add_argument("--block-size-mib", type=positive_int, default=8)
18
+ parser.add_argument("--dtype", choices=("float32", "float64"), default="float32")
 
 
 
 
 
 
 
 
19
  parser.add_argument(
20
+ "--ground-truth-scope", choices=("all", "snapshot", "none"), default="all"
 
 
 
21
  )
22
  parser.add_argument(
23
+ "--without-ground-truth", action="store_true", help="Alias for scope=none"
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
+ parser.add_argument("--max-sidecar-mib", type=positive_int, default=512)
26
+ parser.add_argument("--overwrite", action="store_true")
27
  return parser.parse_args()
28
 
29
 
30
  def main() -> None:
31
  args = parse_args()
32
+ scope = "none" if args.without_ground_truth else args.ground_truth_scope
33
+ output = create_base(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  args.vibframe,
35
  args.output,
36
+ scope=scope,
37
+ dtype=args.dtype,
38
  block_size_mib=args.block_size_mib,
39
+ max_sidecar_mib=args.max_sidecar_mib,
40
+ overwrite=args.overwrite,
41
  )
 
 
 
 
 
 
 
 
 
 
42
  print(f"Created: {output}")
43
+ for key, value in validate_streamed_h5ad(output).items():
44
+ print(f"{key}: {value}")
 
45
  print(
46
+ f"File size: {output.stat().st_size / 1024**3:.3f} GiB; ground truth scope: {scope}"
 
47
  )
48
+ print("Evaluation is outside X/obs. block-size-mib is not a total RAM limit.")
 
49
 
50
 
51
  if __name__ == "__main__":
examples/02_inspect_anndata.py CHANGED
@@ -1,121 +1,85 @@
1
  #!/usr/bin/env python3
2
- """
3
- Inspect a DRMHB AnnData generated with vibframe-anndata 0.2.2.
4
-
5
- The H5AD is opened in backed read-only mode, so the multi-gigabyte raw signal
6
- payload is not loaded into RAM.
7
-
8
- Install:
9
- python -m pip install "vibframe-anndata==0.2.2" "anndata>=0.10,<0.13"
10
-
11
- Usage:
12
- python examples/02_inspect_anndata.py DRMHB.float32.h5ad
13
- """
14
 
15
  from __future__ import annotations
16
 
17
  import argparse
18
  from pathlib import Path
19
- import warnings
20
-
21
- import anndata as ad
22
 
 
23
  from vibframe_anndata import (
24
- __version__ as vibframe_anndata_version,
 
 
25
  validate_streamed_h5ad,
26
  )
27
 
28
- EXPECTED_VERSION = "0.2.2"
29
-
30
- warnings.filterwarnings(
31
- "ignore",
32
- message=r"Support for Awkward Arrays is currently experimental.*",
33
- )
34
-
35
-
36
- def parse_args() -> argparse.Namespace:
37
- parser = argparse.ArgumentParser(
38
- description="Inspect a locally generated DRMHB AnnData."
39
- )
40
- parser.add_argument("h5ad", type=Path, help="Path to a generated DRMHB .h5ad.")
41
- return parser.parse_args()
42
-
43
 
44
  def main() -> None:
45
- args = parse_args()
46
-
47
- if vibframe_anndata_version != EXPECTED_VERSION:
48
- raise RuntimeError(
49
- f"This example is validated for vibframe-anndata=={EXPECTED_VERSION}; "
50
- f"active version: {vibframe_anndata_version!r}"
51
- )
52
-
53
- if not args.h5ad.is_file():
54
- raise FileNotFoundError(args.h5ad)
55
-
56
- validation = validate_streamed_h5ad(args.h5ad)
57
- print("Streamed-H5AD validation:")
58
- for key in (
59
- "n_obs",
60
- "n_vars",
61
- "machines",
62
- "ground_truth_rows",
63
- "ground_truth_columns",
64
- "waveform_signals",
65
- "waveform_samples",
66
- "spectrum_signals",
67
- "spectrum_samples",
68
- ):
69
- print(f" - {key}: {validation.get(key):,}")
70
- print()
71
-
72
- adata = ad.read_h5ad(args.h5ad, backed="r")
73
-
74
- try:
75
- print(adata)
76
- print()
77
- print("X shape:", adata.shape)
78
-
79
- print("\nobs columns:")
80
- for column in adata.obs.columns:
81
- print(" -", column)
82
-
83
- print("\nobsm keys:")
84
- for key in adata.obsm.keys():
85
- print(" -", key)
86
-
87
- print("\nuns keys:")
88
- for key in adata.uns.keys():
89
- print(" -", key)
90
-
91
- print("\nFirst observations:")
92
- print(adata.obs.head())
93
-
94
- if "ground_truth" in adata.obsm:
95
- gt = adata.obsm["ground_truth"]
96
- print("\nGround truth:")
97
- print(" - location: obsm['ground_truth']")
98
- print(" - shape:", gt.shape)
99
- print(" - columns:", ", ".join(map(str, gt.columns)))
100
- print(
101
- " - note: evaluation-only metadata; do not include it "
102
- "automatically in unsupervised model inputs"
103
- )
104
- else:
105
- print(
106
- "\nGround truth was not imported. Recreate the H5AD without "
107
- "--without-ground-truth if evaluation labels are required."
108
- )
109
-
110
- if adata.n_vars == 0:
111
- print(
112
- "\nThis is a featureless base AnnData. "
113
- "Use examples/03_add_features.py to derive features from the "
114
- "raw signals already stored in the H5AD."
115
  )
116
- finally:
117
- if getattr(adata, "file", None) is not None:
118
- adata.file.close()
 
 
 
 
 
 
 
 
 
 
119
 
120
 
121
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
+ """Inspect HDF5 groups and evaluation metadata without loading raw obsm buffers."""
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  from __future__ import annotations
5
 
6
  import argparse
7
  from pathlib import Path
 
 
 
8
 
9
+ from drmhb_workflow import check_version, inventory_or_empty, read_metadata
10
  from vibframe_anndata import (
11
+ get_snapshot_ground_truth,
12
+ get_waveform_ground_truth,
13
+ read_evaluation_file,
14
  validate_streamed_h5ad,
15
  )
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def main() -> None:
19
+ parser = argparse.ArgumentParser(description=__doc__)
20
+ parser.add_argument("h5ad", type=Path)
21
+ parser.add_argument(
22
+ "--waveform-details",
23
+ action="store_true",
24
+ help="Decode aligned waveform metadata, not waveform samples",
25
+ )
26
+ parser.add_argument(
27
+ "--verify-hashes",
28
+ action="store_true",
29
+ help="Read and hash each annotation file one at a time",
30
+ )
31
+ args = parser.parse_args()
32
+ check_version()
33
+ report = validate_streamed_h5ad(args.h5ad)
34
+ for key, value in report.items():
35
+ print(f"{key}: {value}")
36
+ meta = read_metadata(args.h5ad)
37
+ print("\nX shape:", meta["shape"])
38
+ print("obs columns:", list(meta["obs"].columns))
39
+ print("obsm keys:", meta["obsm_keys"])
40
+ print("uns keys:", meta["uns_keys"])
41
+ print(meta["obs"].head().to_string())
42
+ if "ground_truth" in meta["obsm_keys"]:
43
+ truth = get_snapshot_ground_truth(args.h5ad)
44
+ print("\nSnapshot truth shape:", truth.shape)
45
+ print("Evaluation columns:", list(truth.columns))
46
+ if args.waveform_details and "waveform_ground_truth" in meta["obsm_keys"]:
47
+ wave = get_waveform_ground_truth(args.h5ad)
48
+ print("\nWaveform truth shape:", wave.shape)
49
+ if not wave.empty:
50
+ print(wave["vfta_alignment_status"].value_counts().to_string())
51
+ cols = [
52
+ c
53
+ for c in (
54
+ "vfta_snapshot_id",
55
+ "point_id",
56
+ "waveform_duration_s",
57
+ "waveform_start_offset_s",
58
+ "vfta_alignment_status",
59
+ )
60
+ if c in wave
61
+ ]
62
+ print(wave[cols].head().to_string(index=False))
63
+ inventory = inventory_or_empty(args.h5ad)
64
+ if not inventory.empty:
65
+ print("\nArchived original annotations:")
66
+ print(
67
+ inventory.groupby("kind").agg(
68
+ files=("path", "size"), bytes=("size_bytes", "sum")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  )
70
+ )
71
+ print(f"Original annotation bytes: {inventory.size_bytes.sum():,}")
72
+ if args.verify_hashes:
73
+ for row in inventory.itertuples():
74
+ read_evaluation_file(
75
+ args.h5ad, row.path, source=row.source, verify=True
76
+ )
77
+ print("All archived annotation SHA-256 checks passed.")
78
+ else:
79
+ print("\nNo complete archive. Use example 04 to enrich an existing H5AD.")
80
+ print(
81
+ "\nGround truth is evaluation-only. Archive scope remains dataset-wide after slicing."
82
+ )
83
 
84
 
85
  if __name__ == "__main__":
examples/03_add_features.py CHANGED
@@ -1,130 +1,37 @@
1
  #!/usr/bin/env python3
2
- """
3
- Materialize the compact feature set used by the DRMHB reference EDA.
4
-
5
- Validated with:
6
- vibframe-anndata==0.2.2
7
-
8
- This step works exclusively from raw signals already persisted in the H5AD and
9
- does not reopen the original VibFrame archive.
10
-
11
- Install:
12
- python -m pip install "vibframe-anndata==0.2.2"
13
-
14
- Usage:
15
- python examples/03_add_features.py \
16
- derived/DRMHB.float32.h5ad \
17
- derived/DRMHB.float32.eda-features.h5ad
18
-
19
- Documentation:
20
- https://413hq.github.io/vibframe-anndata-docs/latest/
21
- """
22
 
23
  from __future__ import annotations
24
 
25
  import argparse
26
  from pathlib import Path
27
 
28
- from vibframe_anndata import (
29
- __version__ as vibframe_anndata_version,
30
- add_features_to_h5ad,
31
- validate_streamed_h5ad,
32
- )
33
-
34
- EXPECTED_VERSION = "0.2.2"
35
 
36
 
37
- def parse_args() -> argparse.Namespace:
38
- parser = argparse.ArgumentParser(
39
- description="Add the compact DRMHB EDA feature set to a base AnnData."
40
- )
41
- parser.add_argument(
42
- "source",
43
- type=Path,
44
- help="Featureless DRMHB .h5ad generated from the VibFrame archive.",
45
- )
46
- parser.add_argument(
47
- "output",
48
- type=Path,
49
- help="Destination enriched .h5ad.",
50
- )
51
  parser.add_argument(
52
- "--block-rows",
53
- type=int,
54
- default=256,
55
- help="Observation block size (default: 256).",
56
  )
57
- return parser.parse_args()
58
-
59
-
60
- def main() -> None:
61
- args = parse_args()
62
-
63
- if vibframe_anndata_version != EXPECTED_VERSION:
64
- raise RuntimeError(
65
- f"This example is validated for vibframe-anndata=={EXPECTED_VERSION}; "
66
- f"active version: {vibframe_anndata_version!r}"
67
- )
68
-
69
- if not args.source.is_file():
70
- raise FileNotFoundError(args.source)
71
-
72
- if args.source.resolve() == args.output.resolve():
73
- raise ValueError("Source and output must be different files.")
74
-
75
- args.output.parent.mkdir(parents=True, exist_ok=True)
76
-
77
- source_validation = validate_streamed_h5ad(args.source)
78
- if int(source_validation["n_vars"]) != 0:
79
- raise RuntimeError(
80
- "This example expects the featureless H5AD created by example 01."
81
- )
82
-
83
- config = {
84
- "version": 1,
85
- "output": {"dtype": "float32"},
86
- "feature_policy": {
87
- "on_conflict": "error",
88
- "on_error": "nan",
89
- },
90
- "features": [
91
- {"name": "vel_overall_rms", "source": "spectrum"},
92
- {"name": "acc_overall_rms", "source": "spectrum"},
93
- {"name": "band_subsync_rms", "source": "spectrum"},
94
- {"name": "band_1X_rms", "source": "spectrum"},
95
- {"name": "band_harmonics_low_rms", "source": "spectrum"},
96
- {"name": "amp_1X", "source": "spectrum"},
97
- {"name": "amp_2X", "source": "spectrum"},
98
- {"name": "amp_BPFO", "source": "spectrum"},
99
- {"name": "amp_BPFI", "source": "spectrum"},
100
- {"name": "family_rms_VPF", "source": "spectrum"},
101
- {"name": "rms", "source": "waveform"},
102
- {"name": "crest_factor", "source": "waveform"},
103
- {"name": "kurtosis", "source": "waveform"},
104
- ],
105
- }
106
-
107
- output = add_features_to_h5ad(
108
  args.source,
109
- config,
110
- output=args.output,
111
  block_rows=args.block_rows,
 
 
112
  )
113
-
114
- validation = validate_streamed_h5ad(output)
115
-
116
- if int(validation["n_vars"]) == 0:
117
- raise RuntimeError("Feature materialization produced an empty X matrix.")
118
- if int(source_validation.get("ground_truth_rows", 0)):
119
- if int(validation["ground_truth_rows"]) != int(validation["n_obs"]):
120
- raise RuntimeError("Ground truth was not preserved in the enriched H5AD.")
121
-
122
- print(f"Created: {output}")
123
- print(f"Observations: {validation['n_obs']:,}")
124
- print(f"Variables/features: {validation['n_vars']:,}")
125
  print(
126
- "If ground truth was present in the source base H5AD, it remains "
127
- "evaluation metadata rather than an X feature."
128
  )
129
 
130
 
 
1
  #!/usr/bin/env python3
2
+ """Materialize the reference EDA features without reopening the VibFrame."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  from __future__ import annotations
5
 
6
  import argparse
7
  from pathlib import Path
8
 
9
+ from drmhb_workflow import add_reference_features, positive_int
10
+ from vibframe_anndata import validate_streamed_h5ad
 
 
 
 
 
11
 
12
 
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(description=__doc__)
15
+ parser.add_argument("source", type=Path)
16
+ parser.add_argument("output", type=Path)
17
+ parser.add_argument("--block-rows", type=positive_int, default=256)
 
 
 
 
 
 
 
 
 
18
  parser.add_argument(
19
+ "--features-config", type=Path, help="Optional package-format YAML"
 
 
 
20
  )
21
+ parser.add_argument("--overwrite", action="store_true")
22
+ args = parser.parse_args()
23
+ output = add_reference_features(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  args.source,
25
+ args.output,
 
26
  block_rows=args.block_rows,
27
+ config=args.features_config,
28
+ overwrite=args.overwrite,
29
  )
30
+ report = validate_streamed_h5ad(output)
31
+ print(f"Created: {output}\nX shape: ({report['n_obs']}, {report['n_vars']})")
32
+ print("Raw coverage and archived-annotation identities are unchanged.")
 
 
 
 
 
 
 
 
 
33
  print(
34
+ "Published reference: 468 source/machine-scoped columns, not 468 dense fleet-wide variables."
 
35
  )
36
 
37
 
examples/04_add_complete_ground_truth.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Enrich an existing H5AD with full annotations without recalculating X or raw arrays."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+ from drmhb_workflow import enrich_existing, positive_int
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(description=__doc__)
14
+ parser.add_argument("source", type=Path, help="Existing package-generated H5AD")
15
+ parser.add_argument(
16
+ "vibframe", type=Path, help="The original matching VibFrame ZIP/directory"
17
+ )
18
+ parser.add_argument("output", type=Path)
19
+ parser.add_argument("--max-sidecar-mib", type=positive_int, default=512)
20
+ parser.add_argument("--overwrite", action="store_true")
21
+ args = parser.parse_args()
22
+ print("A transactional copy needs about one additional H5AD of free disk space.")
23
+ result = enrich_existing(
24
+ args.source,
25
+ args.vibframe,
26
+ args.output,
27
+ max_sidecar_mib=args.max_sidecar_mib,
28
+ overwrite=args.overwrite,
29
+ )
30
+ print(f"Created: {result}")
31
+ print(
32
+ "Source identities must match. Legacy capture_t companions are not retroactively added."
33
+ )
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()
examples/05_read_evaluation.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """List/read/export original evaluation sidecars directly from H5AD, without raw arrays."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ from drmhb_workflow import check_version
11
+ from vibframe_anndata import (
12
+ export_evaluation_files,
13
+ list_evaluation_files,
14
+ read_evaluation_json,
15
+ read_evaluation_table,
16
+ )
17
+
18
+
19
+ def main() -> None:
20
+ parser = argparse.ArgumentParser(description=__doc__)
21
+ parser.add_argument("h5ad", type=Path)
22
+ parser.add_argument("--path", help="Exact relative path from the inventory")
23
+ parser.add_argument(
24
+ "--source", help="Exact source ID; required for ambiguous paths"
25
+ )
26
+ parser.add_argument(
27
+ "--export", type=Path, help="Recover all original sidecars (refuses overwrites)"
28
+ )
29
+ args = parser.parse_args()
30
+ check_version()
31
+ inventory = list_evaluation_files(args.h5ad)
32
+ print(inventory[["source", "path", "kind", "size_bytes"]].to_string(index=False))
33
+ if args.path:
34
+ if args.path.endswith(".parquet"):
35
+ table = read_evaluation_table(args.h5ad, args.path, source=args.source)
36
+ print("\nArrow schema:\n", table.schema)
37
+ print(table.slice(0, 5).to_pandas().to_string(index=False))
38
+ elif args.path.endswith(".json"):
39
+ print(
40
+ json.dumps(
41
+ read_evaluation_json(args.h5ad, args.path, source=args.source),
42
+ indent=2,
43
+ )
44
+ )
45
+ else:
46
+ parser.error(
47
+ "--path must be .parquet or .json; use export for other byte-exact formats"
48
+ )
49
+ if args.export:
50
+ paths = export_evaluation_files(args.h5ad, args.export, source=args.source)
51
+ print(
52
+ f"Exported {len(paths)} original files. Dataset-wide scope, not a relabelled subset."
53
+ )
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
examples/README.md CHANGED
@@ -1,125 +1,138 @@
1
- # DRMHB examples
2
 
3
- DRMHB is distributed canonically as a VibFrame archive. These scripts show the
4
- supported local conversion to AnnData, inspection of the result, and subsequent
5
- feature materialization without reopening the VibFrame.
6
 
7
- They are validated against:
8
-
9
- ```text
10
- vibframe-anndata==0.2.2
 
11
  ```
12
 
13
- Run all commands from the repository root. A small virtual environment is
14
- recommended:
15
 
16
- ```bash
17
- python -m venv .venv
18
- source .venv/bin/activate
19
- python -m pip install "vibframe-anndata==0.2.2" "anndata>=0.10,<0.13"
20
- ```
21
 
22
- The examples below write derived files to `derived/`, which is intentionally
23
- separate from the canonical archive under `data/`.
 
 
 
24
 
25
- ## 1. Create the featureless base AnnData
 
26
 
27
- ```bash
28
- python examples/01_create_featureless_anndata.py \
29
- data/DRMHB.vibframe.zip \
30
- derived/DRMHB.float32.h5ad
31
- ```
32
 
33
- The conversion is streamed and out of core. For the current fixture, validation
34
- should report:
 
 
 
35
 
36
- - 46,907 observations from 12 machines;
37
- - zero variables in `X`;
38
- - 281,442 spectral signals;
39
- - 140,721 waveform signals;
40
- - 46,907 rows and 42 columns in `obsm["ground_truth"]`.
41
 
42
- Snapshot-level evaluation truth is imported by default from
43
- `evaluation/snapshot_truth/` and aligned one-to-one with `obs`:
 
44
 
45
- ```python
46
- adata.obsm["ground_truth"]
47
- ```
 
 
48
 
49
- It remains separate from both `X` and `obs`; its presence does not make it a
50
- valid model input. To create a learning-only representation without evaluation
51
- truth, add `--without-ground-truth`.
 
52
 
53
- The example explicitly uses lossless uncompressed raw arrays:
54
 
55
- ```yaml
56
- output:
57
- dtype: float32
58
- raw_compression: none
59
  ```
60
 
61
- This is the package default and is recommended when the same base H5AD will be
62
- read repeatedly for feature experiments. The validated base occupies about
63
- 9.35 GiB, so allow ample space for both the base and enriched outputs.
 
 
 
 
64
 
65
- ## 2. Inspect an AnnData without loading raw arrays into RAM
66
 
67
  ```bash
68
- python examples/02_inspect_anndata.py \
69
- derived/DRMHB.float32.h5ad
 
 
 
70
  ```
71
 
72
- The file is opened in backed read-only mode. The script reports:
 
 
 
 
 
73
 
74
- - streamed-H5AD validation counts;
75
- - `obs`, `obsm` and `uns` structure;
76
- - feature geometry;
77
- - the location, shape and columns of aligned ground truth.
78
 
79
- The raw spectra and variable-length waveforms stay on disk during this
80
- inspection.
 
 
 
81
 
82
- ## 3. Materialize the reference EDA features
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  ```bash
85
- python examples/03_add_features.py \
86
- derived/DRMHB.float32.h5ad \
87
- derived/DRMHB.float32.eda-features.h5ad
88
  ```
89
 
90
- This second stage reads only the base H5AD. It does not reopen
91
- `DRMHB.vibframe.zip`.
92
-
93
- The example matches the compact feature catalogue used by the reference EDA:
94
-
95
- - spectral: overall velocity and acceleration RMS, subsynchronous, 1X and
96
- low-harmonic bands, 1X, 2X, BPFO, BPFI and VPF-family amplitudes;
97
- - waveform: RMS, crest factor and kurtosis.
98
-
99
- Metrics are expanded across applicable machines, channels and processing
100
- modes. On the current 12-machine fixture this produces `X.shape == (46907,
101
- 468)`. The enriched file retains the raw arrays, observation identity,
102
- provenance and `obsm["ground_truth"]` from the source.
103
-
104
- Choose a new output path or remove an earlier output before rerunning the
105
- feature example. Source and output must be different files.
106
-
107
- ## Execution order
108
-
109
- ```text
110
- data/DRMHB.vibframe.zip
111
- |
112
- | 01_create_featureless_anndata.py
113
- v
114
- derived/DRMHB.float32.h5ad X: (46907, 0)
115
- |
116
- | 02_inspect_anndata.py read-only inspection
117
- |
118
- | 03_add_features.py
119
- v
120
- derived/DRMHB.float32.eda-features.h5ad X: (46907, 468)
121
  ```
122
 
123
- For configuration semantics, supported metrics, compression trade-offs and the
124
- ground-truth contract, see the
125
- [`vibframe-anndata` documentation](https://413hq.github.io/vibframe-anndata-docs/latest/).
 
 
 
1
+ # DRMHB conversion and evaluation examples
2
 
3
+ Use Python 3.12 and `vibframe-anndata==0.3.0`. Run from the repository root.
4
+ These examples explicitly request complete annotations; the package itself
5
+ keeps ground-truth import disabled by default.
6
 
7
+ ```bash
8
+ python -m pip install -r examples/requirements.txt
9
+ python examples/01_create_featureless_anndata.py data/DRMHB.vibframe.zip derived/DRMHB.v0.3.0.raw.h5ad
10
+ python examples/02_inspect_anndata.py derived/DRMHB.v0.3.0.raw.h5ad --waveform-details
11
+ python examples/03_add_features.py derived/DRMHB.v0.3.0.raw.h5ad derived/DRMHB.v0.3.0.features.h5ad
12
  ```
13
 
14
+ ## 01 — Import once
 
15
 
16
+ Accepts a ZIP or extracted VibFrame. The base is featureless: `X` has zero
17
+ columns; raw waveforms, spectra, tachometers, identities and metadata remain
18
+ available for later features. The default is `float32`, 8 MiB raw blocks,
19
+ `scope=all`, strict missing truth and unchanged uncompressed raw HDF5 arrays.
 
20
 
21
+ `--ground-truth-scope snapshot` selects the legacy footprint; `none` (or
22
+ `--without-ground-truth`) excludes evaluation labels. `--max-sidecar-mib 512`
23
+ limits original encoded sidecars, not total memory. `--block-size-mib` and
24
+ `--dtype` are explicit. Existing destinations require `--overwrite`; inputs
25
+ cannot be used as outputs.
26
 
27
+ No feature is computed from `trends.parquet` or from construction/diagnostic
28
+ labels. The published dataset itself contains no scalar trends.
29
 
30
+ ## 02 — Inspect without loading multi-GiB raw signals
 
 
 
 
31
 
32
+ The inspector uses `h5py` group metadata, small `obs`/`var`/package metadata and
33
+ public ground-truth accessors. It never calls `anndata.read_h5ad(backed="r")`
34
+ as a blanket out-of-core solution: that mode does not make all `obsm`/`uns`
35
+ objects lazy. `--waveform-details` expands annotations only. `--verify-hashes`
36
+ reads one original annotation file at a time and checks its SHA-256.
37
 
38
+ ## 03 — Add the reference features
 
 
 
 
39
 
40
+ The thirteen feature requests remain the same as in the published EDA:
41
+ velocity/acceleration RMS, subsynchronous/1X/low-harmonic bands, 1X/2X/BPFO/BPFI
42
+ amplitudes, VPF-family RMS, and waveform RMS/crest factor/kurtosis.
43
 
44
+ For the reference fleet they materialized 468 machine/source-scoped columns.
45
+ Each machine populates its relevant descriptors; structural NaNs are not zeros.
46
+ The EDA constructs a common logical descriptor matrix without averaging different
47
+ machines. Preserve `var` units, processing mode, point and algorithm/options
48
+ when aligning columns. Do not match columns by short display name alone.
49
 
50
+ `--block-rows 256` controls feature block size. `--features-config FILE.yaml`
51
+ accepts an alternative package feature configuration. The original VibFrame
52
+ is not reopened. Dimension counts and original-annotation manifest identities
53
+ are compared before and after feature generation.
54
 
55
+ ## 04 — Upgrade existing H5ADs
56
 
57
+ ```bash
58
+ python examples/04_add_complete_ground_truth.py \
59
+ derived/DRMHB.float32.eda-features.h5ad data/DRMHB.vibframe.zip \
60
+ derived/DRMHB.v0.3.0.features.h5ad
61
  ```
62
 
63
+ Uses `add_ground_truth_to_h5ad`. It preserves signals and features and creates a
64
+ transactional disk copy. Supply the matching source set and retain `obs.source`,
65
+ `obs.machine` and integer `obs.snap_t`. Roughly one extra H5AD of free disk is
66
+ needed temporarily. Source-name/path collisions must not be repaired by guessing.
67
+ Legacy capture-time companions are not populated retrospectively: reimport raw
68
+ signals to obtain those arrays. Per-waveform crop offsets remain available from
69
+ original and aligned waveform truth.
70
 
71
+ ## 05 — Read originals and DiagGT
72
 
73
  ```bash
74
+ python examples/05_read_evaluation.py derived/DRMHB.v0.3.0.features.h5ad
75
+ python examples/05_read_evaluation.py derived/DRMHB.v0.3.0.features.h5ad \
76
+ --path ground-truth/observations.parquet
77
+ python examples/05_read_evaluation.py derived/DRMHB.v0.3.0.features.h5ad \
78
+ --export derived/recovered-evaluation
79
  ```
80
 
81
+ Use the exact path from the printed inventory; the layout is not assumed.
82
+ Use `--source SOURCE_ID` when a relative path occurs in several sources.
83
+ `read_evaluation_table()` returns Arrow types; `read_evaluation_json()` returns
84
+ parsed JSON; `read_evaluation_file()` returns the exact original bytes.
85
+ Export refuses overwrites and retains dataset-wide originals, even for a sliced
86
+ AnnData. No implicit DiagGT interval-to-snapshot labelling is performed.
87
 
88
+ ## Complete information and model input
 
 
 
89
 
90
+ `obsm['ground_truth']` and `obsm['waveform_ground_truth']` follow `obs_names`.
91
+ The byte archive in `uns['vibframe_evaluation']` is dataset-wide. `snap_t` is the
92
+ snapshot key in integer microseconds UTC; raw capture `t` may include a crop
93
+ offset. Waveform bindings include source/machine/point and supplied mode identity.
94
+ Unknown sidecars/fields are retained instead of silently discarded.
95
 
96
+ For normality learning, fit scaling, missing-value rules and models only on
97
+ calibration. Set thresholds on normal holdout. Evaluate on the future stream
98
+ using timestamps. Faults, severities, OOD, nuisance and latent physical state
99
+ are targets/audit fields, not automatic inputs. Declare explicitly any use of
100
+ regime or RPM. Keep a separately generated controls dataset in a separate H5AD;
101
+ controls are not part of the published 2.5.0 longitudinal ZIP.
102
+
103
+ ## Resources and verification
104
+
105
+ No raw compression settings or VibFrame bytes are changed. Historical 0.2.2
106
+ H5AD sizes are not estimates of the full-annotation 0.3.0 outputs: measure the
107
+ actual results. Metadata decoding also consumes RAM, so the raw block size and
108
+ 512 MiB encoded-sidecar budget are not process-memory caps.
109
+
110
+ Run the small synthetic integration suite with:
111
 
112
  ```bash
113
+ python -m pip install pytest
114
+ python -m pytest tests -q
 
115
  ```
116
 
117
+ The tests cover ZIP/directory import, complete/legacy/disabled truth, selective
118
+ metadata reads, preservation through feature engineering, retrofit, export and
119
+ CLI safety. They do not regenerate the 180-day campaign.
120
+
121
+ Package documentation: https://413hq.github.io/vibframe-anndata-docs/0.3.0/
122
+ Ground truth guide: https://413hq.github.io/vibframe-anndata-docs/0.3.0/guides/ground-truth/
123
+
124
+ ## Regression tests
125
+
126
+ The public scripts have a small deterministic fixture suite. It does not need
127
+ VibSynth or the 8.36 GiB campaign download:
128
+
129
+ ```bash
130
+ python -m pip install -r examples/requirements.txt 'pytest>=8,<10'
131
+ python -m pytest tests -q
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  ```
133
 
134
+ It checks ZIP/directory ingestion, all/snapshot/disabled ground truth, exact
135
+ source bytes and large integers, feature and metadata preservation, selective
136
+ inspection, legacy enrichment, CLI exports and the modified notebook's metadata
137
+ and waveform-audit cells. Published EDA image/table hashes are also checked.
138
+ It is not a substitute for executing the full EDA on the complete campaign.
examples/drmhb_workflow.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared, bounded-raw-memory DRMHB examples for vibframe-anndata 0.3.0.
2
+
3
+ Evaluation is explicitly requested, never copied into X or obs. Compressed
4
+ VibFrame inputs are not modified. No scalar ground-truth value becomes a feature.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import h5py
13
+ import pandas as pd
14
+ from vibframe_anndata import (
15
+ __version__,
16
+ add_features_to_h5ad,
17
+ add_ground_truth_to_h5ad,
18
+ get_snapshot_ground_truth,
19
+ get_waveform_ground_truth,
20
+ import_raw_to_h5ad,
21
+ list_evaluation_files,
22
+ validate_streamed_h5ad,
23
+ )
24
+
25
+ try:
26
+ from anndata.io import read_elem
27
+ except ImportError:
28
+ from anndata.experimental import read_elem
29
+
30
+ EXPECTED_VERSION = "0.3.0"
31
+ SPECTRAL_FEATURES = (
32
+ "vel_overall_rms",
33
+ "acc_overall_rms",
34
+ "band_subsync_rms",
35
+ "band_1X_rms",
36
+ "band_harmonics_low_rms",
37
+ "amp_1X",
38
+ "amp_2X",
39
+ "amp_BPFO",
40
+ "amp_BPFI",
41
+ "family_rms_VPF",
42
+ )
43
+ WAVEFORM_FEATURES = ("rms", "crest_factor", "kurtosis")
44
+ REFERENCE_FEATURE_CONFIG = {
45
+ "version": 1,
46
+ "output": {"dtype": "float32"},
47
+ "feature_policy": {"on_conflict": "error", "on_error": "nan"},
48
+ "features": (
49
+ [{"name": name, "source": "spectrum"} for name in SPECTRAL_FEATURES]
50
+ + [{"name": name, "source": "waveform"} for name in WAVEFORM_FEATURES]
51
+ ),
52
+ }
53
+
54
+
55
+ def check_version() -> None:
56
+ """Pin semantics rather than silently using an untested API version."""
57
+ if __version__ != EXPECTED_VERSION:
58
+ raise RuntimeError(
59
+ f"Install vibframe-anndata=={EXPECTED_VERSION}; found {__version__}"
60
+ )
61
+
62
+
63
+ def positive_int(value: str) -> int:
64
+ """Reject non-positive block sizes and metadata budgets before opening files."""
65
+ import argparse
66
+
67
+ try:
68
+ number = int(value)
69
+ except ValueError as exc:
70
+ raise argparse.ArgumentTypeError("Expected a positive integer") from exc
71
+ if number <= 0:
72
+ raise argparse.ArgumentTypeError("Expected a positive integer")
73
+ return number
74
+
75
+
76
+ def prepare_output(output: Path, *inputs: Path, overwrite: bool = False) -> Path:
77
+ """Prevent accidental clobbering and input/output aliases."""
78
+ result = output.expanduser().resolve()
79
+ if result.suffix.lower() != ".h5ad":
80
+ raise ValueError("Output must have the .h5ad extension")
81
+ if any(result == item.expanduser().resolve() for item in inputs):
82
+ raise ValueError("Input and output must be different files")
83
+ if result.exists() and not overwrite:
84
+ raise FileExistsError(
85
+ f"{result} exists; use a new output or --overwrite explicitly"
86
+ )
87
+ result.parent.mkdir(parents=True, exist_ok=True)
88
+ return result
89
+
90
+
91
+ def raw_config(
92
+ *, scope: str = "all", dtype: str = "float32", max_sidecar_mib: int = 512
93
+ ) -> dict[str, Any]:
94
+ """The full annotation contract is opt-in at package level, explicit here."""
95
+ if scope not in {"all", "snapshot", "none"}:
96
+ raise ValueError("scope must be all, snapshot or none")
97
+ if max_sidecar_mib <= 0:
98
+ raise ValueError("max_sidecar_mib must be positive")
99
+ return {
100
+ "version": 1,
101
+ "raw_import": {"waveforms": True, "spectra": True, "on_missing_signal": "nan"},
102
+ "ground_truth": {
103
+ "enabled": scope != "none",
104
+ "scope": "all" if scope == "none" else scope,
105
+ "on_missing": "error",
106
+ "max_sidecar_mib": max_sidecar_mib,
107
+ },
108
+ "output": {"dtype": dtype, "raw_compression": "none"},
109
+ "features": [],
110
+ "obs": {
111
+ "include": [
112
+ "snapshot_id",
113
+ "timestamp",
114
+ "snap_t",
115
+ "source",
116
+ "machine",
117
+ "speed_hz",
118
+ "has_waveform",
119
+ "has_spectrum",
120
+ ]
121
+ },
122
+ }
123
+
124
+
125
+ def read_metadata(path: Path) -> dict[str, Any]:
126
+ """Read only obs/var and package metadata; do not decode uns or raw obsm wholesale.
127
+
128
+ AnnData backed mode is not a promise that obsm/uns stay on disk. In 0.3.0,
129
+ uns also contains byte buffers for the complete evaluation archive.
130
+ """
131
+ with h5py.File(path, "r") as handle:
132
+ return {
133
+ "obs": read_elem(handle["obs"]),
134
+ "var": read_elem(handle["var"]),
135
+ "uns": {"vibframe_anndata": read_elem(handle["uns"]["vibframe_anndata"])},
136
+ "shape": tuple(handle["X"].shape),
137
+ "obsm_keys": list(handle["obsm"].keys()),
138
+ "uns_keys": list(handle["uns"].keys()),
139
+ }
140
+
141
+
142
+ def inventory_or_empty(path: Path) -> pd.DataFrame:
143
+ """Absence is explicit; errors in an existing archive must not be swallowed."""
144
+ with h5py.File(path, "r") as handle:
145
+ present = "vibframe_evaluation" in handle["uns"]
146
+ if not present:
147
+ return pd.DataFrame(columns=["source", "path", "kind", "size_bytes", "sha256"])
148
+ return list_evaluation_files(path)
149
+
150
+
151
+ def require_complete_drmhb(path: Path) -> dict[str, Any]:
152
+ """Require construction snapshot/waveform truth and originals for DRMHB EDA."""
153
+ result = validate_streamed_h5ad(path)
154
+ if result.get("ground_truth_rows", 0) != result["n_obs"]:
155
+ raise RuntimeError(
156
+ "No complete snapshot truth; run example 04 or recreate with scope=all"
157
+ )
158
+ if result.get("waveform_ground_truth_snapshots", 0) != result["n_obs"]:
159
+ raise RuntimeError(
160
+ "No waveform truth; run example 04 or recreate with scope=all"
161
+ )
162
+ if result.get("evaluation_files", 0) == 0:
163
+ raise RuntimeError(
164
+ "No archived originals; run example 04 or recreate with scope=all"
165
+ )
166
+ return result
167
+
168
+
169
+ def preservation_signature(path: Path) -> tuple[dict[str, Any], pd.DataFrame]:
170
+ """Small signature for numerical dimensions and original annotation identities."""
171
+ report = validate_streamed_h5ad(path)
172
+ keys = (
173
+ "n_obs",
174
+ "waveform_signals",
175
+ "waveform_samples",
176
+ "spectrum_signals",
177
+ "spectrum_samples",
178
+ "ground_truth_rows",
179
+ "waveform_ground_truth_snapshots",
180
+ )
181
+ counts = {key: report.get(key, 0) for key in keys}
182
+ files = inventory_or_empty(path)
183
+ cols = ["source", "path", "size_bytes", "sha256"]
184
+ return counts, files[cols].sort_values(["source", "path"]).reset_index(drop=True)
185
+
186
+
187
+ def assert_preserved(before: tuple, output: Path) -> None:
188
+ """Check dimensions and lossless archive identity after feature engineering."""
189
+ after = preservation_signature(output)
190
+ if before[0] != after[0] or not before[1].equals(after[1]):
191
+ raise RuntimeError("Signal/annotation coverage or archived originals changed")
192
+
193
+
194
+ def create_base(
195
+ source: Path,
196
+ output: Path,
197
+ *,
198
+ scope: str = "all",
199
+ dtype: str = "float32",
200
+ block_size_mib: int = 8,
201
+ max_sidecar_mib: int = 512,
202
+ overwrite: bool = False,
203
+ ) -> Path:
204
+ """Import a ZIP or extracted VibFrame with no calculated features."""
205
+ check_version()
206
+ if not source.exists():
207
+ raise FileNotFoundError(source)
208
+ if block_size_mib <= 0:
209
+ raise ValueError("block_size_mib must be positive")
210
+ output = prepare_output(output, source, overwrite=overwrite)
211
+ result = import_raw_to_h5ad(
212
+ source,
213
+ output,
214
+ config=raw_config(scope=scope, dtype=dtype, max_sidecar_mib=max_sidecar_mib),
215
+ block_size_mib=block_size_mib,
216
+ )
217
+ report = validate_streamed_h5ad(result)
218
+ if report["n_vars"] != 0:
219
+ raise RuntimeError("Featureless base must have zero features")
220
+ if scope == "all":
221
+ require_complete_drmhb(result)
222
+ elif scope == "snapshot" and report.get("ground_truth_rows", 0) != report["n_obs"]:
223
+ raise RuntimeError("Incomplete snapshot annotation coverage")
224
+ return result
225
+
226
+
227
+ def add_reference_features(
228
+ source: Path,
229
+ output: Path,
230
+ *,
231
+ block_rows: int = 256,
232
+ config: Any = None,
233
+ overwrite: bool = False,
234
+ ) -> Path:
235
+ """Compute unchanged reference features; keep raw signals and all annotations."""
236
+ check_version()
237
+ output = prepare_output(output, source, overwrite=overwrite)
238
+ if block_rows <= 0:
239
+ raise ValueError("block_rows must be positive")
240
+ if validate_streamed_h5ad(source)["n_vars"] != 0:
241
+ raise ValueError("This example expects a featureless base")
242
+ before = preservation_signature(source)
243
+ result = add_features_to_h5ad(
244
+ source, config or REFERENCE_FEATURE_CONFIG, output=output, block_rows=block_rows
245
+ )
246
+ assert_preserved(before, result)
247
+ if validate_streamed_h5ad(result)["n_vars"] == 0:
248
+ raise RuntimeError("Feature calculation returned zero variables")
249
+ return result
250
+
251
+
252
+ def enrich_existing(
253
+ source: Path,
254
+ vibframe: Path,
255
+ output: Path,
256
+ *,
257
+ max_sidecar_mib: int = 512,
258
+ overwrite: bool = False,
259
+ ) -> Path:
260
+ """Add original annotations to a legacy file, without numerical recomputation."""
261
+ check_version()
262
+ output = prepare_output(output, source, vibframe, overwrite=overwrite)
263
+ if not vibframe.exists():
264
+ raise FileNotFoundError(vibframe)
265
+ before = validate_streamed_h5ad(source)
266
+ result = add_ground_truth_to_h5ad(
267
+ source,
268
+ vibframe,
269
+ config=raw_config(max_sidecar_mib=max_sidecar_mib),
270
+ output=output,
271
+ )
272
+ after = require_complete_drmhb(result)
273
+ for key in (
274
+ "n_obs",
275
+ "n_vars",
276
+ "waveform_signals",
277
+ "waveform_samples",
278
+ "spectrum_signals",
279
+ "spectrum_samples",
280
+ ):
281
+ if before.get(key) != after.get(key):
282
+ raise RuntimeError(f"Existing numerical dimensions changed: {key}")
283
+ return result
284
+
285
+
286
+ def read_truth(path: Path) -> tuple[pd.DataFrame, pd.DataFrame]:
287
+ """Convenience labels are for evaluation; never place these frames in X."""
288
+ return get_snapshot_ground_truth(path), get_waveform_ground_truth(path)
examples/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ vibframe-anndata==0.3.0
2
+ h5py>=3.10,<4
notebooks/DRMHB_EDA.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
notebooks/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ version = "0.1.0"
4
  description = "EDA environment for the DRMHB dataset."
5
  requires-python = ">=3.12,<3.13"
6
  dependencies = [
7
- "vibframe-anndata==0.2.2",
8
  "anndata>=0.10,<0.13",
9
  "awkward>=2.5,<3",
10
  "h5py>=3.10,<4",
 
4
  description = "EDA environment for the DRMHB dataset."
5
  requires-python = ">=3.12,<3.13"
6
  dependencies = [
7
+ "vibframe-anndata==0.3.0",
8
  "anndata>=0.10,<0.13",
9
  "awkward>=2.5,<3",
10
  "h5py>=3.10,<4",
tests/conftest.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Expose standalone examples during regression testing."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "examples"))
tests/test_workflow.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline regression fixtures for the public DRMHB workflow, not a new campaign."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import runpy
8
+ import sys
9
+ import zipfile
10
+ from pathlib import Path
11
+
12
+ import h5py
13
+ import numpy as np
14
+ import pandas as pd
15
+ import pyarrow as pa
16
+ import pyarrow.parquet as pq
17
+ import pytest
18
+ from drmhb_workflow import (
19
+ REFERENCE_FEATURE_CONFIG,
20
+ add_reference_features,
21
+ create_base,
22
+ enrich_existing,
23
+ inventory_or_empty,
24
+ positive_int,
25
+ prepare_output,
26
+ read_metadata,
27
+ require_complete_drmhb,
28
+ )
29
+ from vibframe_anndata import (
30
+ get_snapshot_ground_truth,
31
+ get_waveform_ground_truth,
32
+ read_evaluation_file,
33
+ read_evaluation_table,
34
+ validate_streamed_h5ad,
35
+ )
36
+
37
+ ROOT = Path(__file__).resolve().parents[1]
38
+
39
+ POINTS = ("pump_DE_H", "pump_DE_V", "pump_DE_A")
40
+ TIMES = (1767225600000000, 1767232800000000)
41
+ CUSTOM_FEATURES = {
42
+ "version": 1,
43
+ "output": {"dtype": "float32"},
44
+ "feature_policy": {"on_error": "nan"},
45
+ "features": [{"name": "rms", "source": "waveform"}],
46
+ }
47
+
48
+
49
+ @pytest.fixture
50
+ def source(tmp_path: Path) -> Path:
51
+ root = tmp_path / "fixture.vibframe"
52
+ machine = root / "machine=M01"
53
+ machine.mkdir(parents=True)
54
+ (root / "dataset.json").write_text('{"name":"tiny-DRMHB-workflow-fixture"}')
55
+ (machine / "machine.json").write_text('{"machine":{"id":"M01"}}')
56
+ (root / "scenario_config.json").write_text(
57
+ '{"script_version":"test-fixture","not_a_campaign":true}'
58
+ )
59
+ waves, spectra, wtruth, truth = [], [], [], []
60
+ for i, t in enumerate(TIMES):
61
+ offset_us = (400000, 200000)[i]
62
+ truth.append(
63
+ {
64
+ "machine_id": "M01",
65
+ "timestamp": t,
66
+ "split": ("calibration", "future_stream")[i],
67
+ "regime_id": ("R1", "R2")[i],
68
+ "is_transition": False,
69
+ "fault_1_type": (None, "IMBALANCE")[i],
70
+ "fault_1_severity": i * 0.2,
71
+ "fault_1_physical_state_json": json.dumps({"damage": i * 0.2}),
72
+ }
73
+ )
74
+ for point in POINTS:
75
+ samples = np.asarray([i + 1.0, -i - 1.0], dtype=np.float32)
76
+ common = {
77
+ "snap_t": t,
78
+ "point_id": point,
79
+ "config_id": "cfg0",
80
+ "speed_hz": 25.0,
81
+ }
82
+ waves.append(
83
+ {
84
+ **common,
85
+ "t": t + offset_us,
86
+ "proc_mode_id": "ACC_10K",
87
+ "mode_definition_id": "wave-def",
88
+ "unit": "K40",
89
+ "signal_family": "acceleration",
90
+ "data": samples,
91
+ "sample_rate_hz": 1000.0,
92
+ "n_samples": 2,
93
+ "sync": True,
94
+ "tacho_rising": [0.0005],
95
+ "tacho_falling": [0.001],
96
+ }
97
+ )
98
+ wtruth.append(
99
+ {
100
+ "machine_id": "M01",
101
+ "snap_t": t,
102
+ "point_id": point,
103
+ "proc_mode_id": "ACC_10K",
104
+ "waveform_n_samples": 2,
105
+ "waveform_duration_s": 0.002,
106
+ "waveform_start_offset_s": offset_us / 1e6,
107
+ "stored_sample_rate_hz": 1000.0,
108
+ "is_anchor": False,
109
+ "waveform_storage_mode": "test_window",
110
+ "stored_waveform_sha256": hashlib.sha256(
111
+ samples.tobytes()
112
+ ).hexdigest(),
113
+ "future_nested": [{"value": i + 1}],
114
+ "nullable": None,
115
+ }
116
+ )
117
+ for mode, family, unit, fmax in [
118
+ ("ACC_10K", "acceleration", "K40", 10000.0),
119
+ ("VEL_1K", "velocity", "C16", 1000.0),
120
+ ]:
121
+ spectra.append(
122
+ {
123
+ **common,
124
+ "t": t,
125
+ "proc_mode_id": mode,
126
+ "mode_definition_id": "spec-" + mode,
127
+ "signal_family": family,
128
+ "unit": unit,
129
+ "data": np.asarray([0.0, 2.0, 1.0], np.float32),
130
+ "fmin_hz": 0.0,
131
+ "fmax_hz": fmax,
132
+ "lines": 3,
133
+ "window": "hann",
134
+ "averages": 1,
135
+ "spectrum_detector": "peak",
136
+ "power": False,
137
+ }
138
+ )
139
+ pd.DataFrame(waves[::-1]).to_parquet(machine / "waves.parquet", index=False)
140
+ pd.DataFrame(spectra[::-1]).to_parquet(machine / "spectra.parquet", index=False)
141
+ for family, rows in [("snapshot_truth", truth), ("waveform_truth", wtruth)]:
142
+ folder = root / "evaluation" / family / "machine=M01"
143
+ folder.mkdir(parents=True)
144
+ pd.DataFrame(rows[::-1]).to_parquet(folder / "part.parquet", index=False)
145
+ diag = root / "ground-truth"
146
+ diag.mkdir()
147
+ (diag / "tiny.diaggt.json").write_text(
148
+ '{"notice":"opaque fixture; not a diagnostic prediction","optional":null}'
149
+ )
150
+ (diag / "materialization.json").write_text(
151
+ '{"policy":"test-original-preservation"}'
152
+ )
153
+ table = pa.table(
154
+ {
155
+ "large_integer": pa.array([2**60 + 7, None], pa.int64()),
156
+ "nested": [[{"fault": "bearing"}], None],
157
+ }
158
+ )
159
+ pq.write_table(table, diag / "observations.parquet")
160
+ return root
161
+
162
+
163
+ @pytest.mark.parametrize("zipped", [False, True])
164
+ @pytest.mark.parametrize("scope", ["all", "snapshot", "none"])
165
+ def test_import_scopes_and_archive(tmp_path, source, zipped, scope):
166
+ incoming = source
167
+ if zipped:
168
+ incoming = tmp_path / "fixture.vibframe.zip"
169
+ with zipfile.ZipFile(incoming, "w") as archive:
170
+ for file in source.rglob("*"):
171
+ if file.is_file():
172
+ archive.write(
173
+ file, source.name + "/" + file.relative_to(source).as_posix()
174
+ )
175
+ output = create_base(
176
+ incoming, tmp_path / "base.h5ad", scope=scope, block_size_mib=1
177
+ )
178
+ meta = read_metadata(output)
179
+ assert meta["shape"] == (2, 0)
180
+ assert meta["obs"].snap_t.tolist() == list(TIMES)
181
+ assert not any(
182
+ "fault" in column or "severity" in column for column in meta["obs"].columns
183
+ )
184
+ inventory = inventory_or_empty(output)
185
+ assert bool(len(inventory)) == (scope == "all")
186
+ assert ("ground_truth" in meta["obsm_keys"]) == (scope != "none")
187
+ if scope == "all":
188
+ require_complete_drmhb(output)
189
+ gt = get_snapshot_ground_truth(output)
190
+ assert gt.index.equals(meta["obs"].index)
191
+ wave = get_waveform_ground_truth(output)
192
+ assert len(wave) == 6 and set(wave.vfta_alignment_status) == {"matched"}
193
+ for row in inventory.itertuples():
194
+ assert (
195
+ read_evaluation_file(output, row.path, source=row.source)
196
+ == (source / row.path).read_bytes()
197
+ )
198
+ table = read_evaluation_table(output, "ground-truth/observations.parquet")
199
+ assert table["large_integer"].to_pylist() == [2**60 + 7, None]
200
+ with h5py.File(output) as h:
201
+ actual = h["obsm/raw_waveforms_capture_t"][:]
202
+ assert np.array_equal(
203
+ actual,
204
+ np.array(TIMES)[:, None]
205
+ + np.array([400000, 200000])[:, None]
206
+ + np.zeros((2, 3), int),
207
+ )
208
+ assert h["obsm/raw_waveforms_capture_t_known"][:].all()
209
+
210
+
211
+ def test_features_and_enrichment_preserve_samples_and_labels(tmp_path, source):
212
+ base = create_base(source, tmp_path / "base.h5ad", scope="none", block_size_mib=1)
213
+ feature = add_reference_features(
214
+ base, tmp_path / "features.h5ad", config=CUSTOM_FEATURES, block_rows=1
215
+ )
216
+ complete = enrich_existing(feature, source, tmp_path / "complete.h5ad")
217
+ assert validate_streamed_h5ad(complete)["n_vars"] == 3
218
+ with h5py.File(feature) as old, h5py.File(complete) as new:
219
+ np.testing.assert_array_equal(old["X"][:], new["X"][:])
220
+ for family in ("raw_waveforms", "raw_spectra"):
221
+ np.testing.assert_array_equal(
222
+ old[f"obsm/{family}/node2-data"][:], new[f"obsm/{family}/node2-data"][:]
223
+ )
224
+ fullbase = create_base(source, tmp_path / "fullbase.h5ad", block_size_mib=1)
225
+ fullfeat = add_reference_features(
226
+ fullbase, tmp_path / "fullfeat.h5ad", config=CUSTOM_FEATURES, block_rows=1
227
+ )
228
+ pd.testing.assert_frame_equal(
229
+ get_snapshot_ground_truth(fullbase), get_snapshot_ground_truth(fullfeat)
230
+ )
231
+ pd.testing.assert_frame_equal(
232
+ inventory_or_empty(fullbase), inventory_or_empty(fullfeat)
233
+ )
234
+ with h5py.File(fullfeat) as h:
235
+ np.testing.assert_allclose(h["X"][:], [[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])
236
+
237
+
238
+ @pytest.mark.parametrize("scope", ["all", "snapshot", "none"])
239
+ def test_inspector_does_not_read_raw_buffers(
240
+ tmp_path, source, scope, monkeypatch, capsys
241
+ ):
242
+ path = create_base(source, tmp_path / "inspect.h5ad", scope=scope, block_size_mib=1)
243
+ original = h5py.Dataset.__getitem__
244
+
245
+ def guarded(self, key):
246
+ if "/raw_waveforms/" in self.name or "/raw_spectra/" in self.name:
247
+ if self.name.endswith("node2-data"):
248
+ raise AssertionError(f"Read of raw sample payload: {self.name}")
249
+ return original(self, key)
250
+
251
+ monkeypatch.setattr(h5py.Dataset, "__getitem__", guarded)
252
+ monkeypatch.setattr(
253
+ sys,
254
+ "argv",
255
+ ["02_inspect_anndata.py", str(path), "--waveform-details", "--verify-hashes"],
256
+ )
257
+ runpy.run_path(str(ROOT / "examples/02_inspect_anndata.py"), run_name="__main__")
258
+ assert "X shape: (2, 0)" in capsys.readouterr().out
259
+
260
+
261
+ @pytest.mark.parametrize(
262
+ "number",
263
+ [
264
+ "01_create_featureless_anndata.py",
265
+ "02_inspect_anndata.py",
266
+ "03_add_features.py",
267
+ "04_add_complete_ground_truth.py",
268
+ "05_read_evaluation.py",
269
+ ],
270
+ )
271
+ def test_help(number, monkeypatch):
272
+ monkeypatch.setattr(sys, "argv", [number, "--help"])
273
+ with pytest.raises(SystemExit) as exc:
274
+ runpy.run_path(str(ROOT / "examples" / number), run_name="__main__")
275
+ assert exc.value.code == 0
276
+
277
+
278
+ def test_safety_guards(tmp_path, source):
279
+ output = create_base(source, tmp_path / "base.h5ad", block_size_mib=1)
280
+ old_hash = hashlib.sha256(output.read_bytes()).hexdigest()
281
+ with pytest.raises(FileExistsError):
282
+ create_base(source, output)
283
+ with pytest.raises(ValueError, match="different"):
284
+ prepare_output(output, output, overwrite=True)
285
+ with pytest.raises(ValueError, match="positive"):
286
+ create_base(source, tmp_path / "other.h5ad", block_size_mib=0)
287
+ with pytest.raises(ValueError, match="positive"):
288
+ add_reference_features(output, tmp_path / "other.h5ad", block_rows=0)
289
+ assert old_hash == hashlib.sha256(output.read_bytes()).hexdigest()
290
+
291
+
292
+ @pytest.mark.parametrize("bad", ["0", "-1", "zero", "0.5"])
293
+ def test_positive_int(bad):
294
+ import argparse
295
+
296
+ with pytest.raises(argparse.ArgumentTypeError):
297
+ positive_int(bad)
298
+
299
+
300
+ def test_reference_requests_unchanged():
301
+ assert [x["name"] for x in REFERENCE_FEATURE_CONFIG["features"]] == [
302
+ "vel_overall_rms",
303
+ "acc_overall_rms",
304
+ "band_subsync_rms",
305
+ "band_1X_rms",
306
+ "band_harmonics_low_rms",
307
+ "amp_1X",
308
+ "amp_2X",
309
+ "amp_BPFO",
310
+ "amp_BPFI",
311
+ "family_rms_VPF",
312
+ "rms",
313
+ "crest_factor",
314
+ "kurtosis",
315
+ ]
316
+
317
+
318
+ def test_notebook_code_and_archived_evidence():
319
+ notebook = json.loads((ROOT / "notebooks/DRMHB_EDA.ipynb").read_text())
320
+ for i, cell in enumerate(notebook["cells"]):
321
+ if cell["cell_type"] == "code":
322
+ code = "".join(cell["source"])
323
+ compile(code, f"EDA-cell-{i}", "exec")
324
+ assert cell.get("outputs", []) == []
325
+ assert cell.get("execution_count") is None
326
+ archived = ROOT / "notebooks/reference/DRMHB_EDA_published_2_5_0.ipynb"
327
+ assert (
328
+ hashlib.sha256(archived.read_bytes()).hexdigest()
329
+ == "39b66eec8427fc1b6b8a5a48b09278a167dd976ea9acaec1122821853d237fad"
330
+ )
331
+ manifest = json.loads((ROOT / "docs/provenance/eda_assets.json").read_text())
332
+ assert len([a for a in manifest["assets"] if a["kind"] == "figure"]) == 37
333
+ for asset in manifest["assets"]:
334
+ path = ROOT / asset["path"]
335
+ assert hashlib.sha256(path.read_bytes()).hexdigest() == asset["sha256"]
336
+
337
+
338
+ def test_notebook_metadata_and_waveform_audit_cells(tmp_path, source):
339
+ """Execute the modified EDA joins/audit, independently of full-campaign models."""
340
+ path = source / "machine=M01/waves.parquet"
341
+ frame = pd.read_parquet(path)
342
+ frame["data"] = [
343
+ np.tile(np.asarray([1.0, -1.0], np.float32), 250) for _ in range(len(frame))
344
+ ]
345
+ frame["n_samples"] = 500
346
+ frame.to_parquet(path, index=False)
347
+ path = source / "evaluation/waveform_truth/machine=M01/part.parquet"
348
+ frame = pd.read_parquet(path)
349
+ frame["waveform_n_samples"] = 500
350
+ frame["waveform_duration_s"] = 0.5
351
+ frame.to_parquet(path, index=False)
352
+ path = source / "evaluation/snapshot_truth/machine=M01/part.parquet"
353
+ frame = pd.read_parquet(path)
354
+ frame["acquisition_kind"] = "steady"
355
+ frame["local_transient"] = False
356
+ frame["electromechanical_transient"] = False
357
+ frame.to_parquet(path, index=False)
358
+ output = create_base(source, tmp_path / "eda.h5ad", block_size_mib=1)
359
+ from vibframe_anndata import list_evaluation_files, read_evaluation_json
360
+
361
+ environment = dict(
362
+ Path=Path,
363
+ json=json,
364
+ np=np,
365
+ pd=pd,
366
+ h5py=h5py,
367
+ read_metadata=read_metadata,
368
+ get_snapshot_ground_truth=get_snapshot_ground_truth,
369
+ get_waveform_ground_truth=get_waveform_ground_truth,
370
+ list_evaluation_files=list_evaluation_files,
371
+ read_evaluation_json=read_evaluation_json,
372
+ display=lambda *_: None,
373
+ SOURCE_H5AD=output,
374
+ )
375
+ notebook = json.loads((ROOT / "notebooks/DRMHB_EDA.ipynb").read_text())
376
+ for i in (8, 11):
377
+ exec(
378
+ compile("".join(notebook["cells"][i]["source"]), f"EDA-cell-{i}", "exec"),
379
+ environment,
380
+ )
381
+ assert environment["waveform_audit"]["storage_mode"].tolist() == ["test_window"] * 2
382
+ np.testing.assert_allclose(environment["waveform_audit"]["duration_s"], 0.5)
383
+
384
+
385
+ def test_original_reader_and_safe_export_cli(tmp_path, source, monkeypatch, capsys):
386
+ output = create_base(source, tmp_path / "base.h5ad", block_size_mib=1)
387
+ script = ROOT / "examples/05_read_evaluation.py"
388
+ monkeypatch.setattr(
389
+ sys, "argv", [str(script), str(output), "--path", "scenario_config.json"]
390
+ )
391
+ runpy.run_path(str(script), run_name="__main__")
392
+ assert "test-fixture" in capsys.readouterr().out
393
+ monkeypatch.setattr(
394
+ sys, "argv", [str(script), str(output), "--export", str(tmp_path / "export")]
395
+ )
396
+ runpy.run_path(str(script), run_name="__main__")
397
+ files = list((tmp_path / "export").glob("*/scenario_config.json"))
398
+ assert (
399
+ len(files) == 1
400
+ and files[0].read_bytes() == (source / "scenario_config.json").read_bytes()
401
+ )
402
+ with pytest.raises(FileExistsError):
403
+ runpy.run_path(str(script), run_name="__main__")
404
+
405
+
406
+ def test_retrofit_preserves_legacy_absent_capture_companions(tmp_path, source):
407
+ legacy = create_base(
408
+ source, tmp_path / "legacy.h5ad", scope="snapshot", block_size_mib=1
409
+ )
410
+ with h5py.File(legacy, "r+") as h:
411
+ for family in ("waveforms", "spectra"):
412
+ del h[f"obsm/raw_{family}_capture_t"]
413
+ del h[f"obsm/raw_{family}_capture_t_known"]
414
+ result = enrich_existing(legacy, source, tmp_path / "enriched.h5ad")
415
+ require_complete_drmhb(result)
416
+ with h5py.File(result) as h:
417
+ assert "raw_waveforms_capture_t" not in h["obsm"]
418
+ assert "raw_spectra_capture_t" not in h["obsm"]
tools/build_report.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the self-contained English report, without executing the EDA notebook."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+
15
+ def check_assets(docs: Path) -> None:
16
+ """Fail before TeX if a referenced archived figure or diagram is absent."""
17
+ text = (docs / "DRMHB.tex").read_text(encoding="utf-8")
18
+ paths = [docs / "anndata_workflow.tex", docs / "figures/skeleton.png"]
19
+ for slug in re.findall(r"\\edaplot\{[^}]+\}\{([^}]+)\}", text):
20
+ base = docs / "figures/eda" / slug
21
+ if not any(base.with_suffix(ext).is_file() for ext in (".pdf", ".png")):
22
+ raise FileNotFoundError(f"EDA figure not found: {base}")
23
+ sources = text + (docs / "anndata_workflow.tex").read_text(encoding="utf-8")
24
+ paths += [docs / item for item in re.findall(r"\\input\{([^}]+)\}", sources)]
25
+ for path in paths:
26
+ if not path.is_file():
27
+ raise FileNotFoundError(path)
28
+
29
+
30
+ def main() -> None:
31
+ parser = argparse.ArgumentParser(description=__doc__)
32
+ parser.add_argument("--output", type=Path, help="Default: docs/DRMHB.pdf")
33
+ parser.add_argument(
34
+ "--build-dir", type=Path, help="Keep TeX logs/auxiliary files here"
35
+ )
36
+ args = parser.parse_args()
37
+ root = Path(__file__).resolve().parents[1]
38
+ docs = root / "docs"
39
+ output = (args.output or docs / "DRMHB.pdf").resolve()
40
+ if output.suffix.lower() != ".pdf":
41
+ parser.error("--output must be a PDF path")
42
+ if not shutil.which("latexmk") or not shutil.which("pdflatex"):
43
+ raise SystemExit(
44
+ "Install latexmk and a TeX distribution including TikZ and the packages in docs/DRMHB.tex"
45
+ )
46
+ check_assets(docs)
47
+ with tempfile.TemporaryDirectory(prefix="drmhb-report-") as temp:
48
+ build = args.build_dir.resolve() if args.build_dir else Path(temp)
49
+ build.mkdir(parents=True, exist_ok=True)
50
+ command = [
51
+ "latexmk",
52
+ "-pdf",
53
+ "-interaction=nonstopmode",
54
+ "-halt-on-error",
55
+ "-file-line-error",
56
+ f"-outdir={build}",
57
+ "DRMHB.tex",
58
+ ]
59
+ run = subprocess.run(
60
+ command,
61
+ cwd=docs,
62
+ text=True,
63
+ stdout=subprocess.PIPE,
64
+ stderr=subprocess.STDOUT,
65
+ check=False,
66
+ )
67
+ (build / "build.log").write_text(run.stdout, encoding="utf-8")
68
+ print(run.stdout[-4000:])
69
+ if run.returncode:
70
+ raise SystemExit(f"LaTeX failed ({run.returncode}); log directory: {build}")
71
+ log = (build / "DRMHB.log").read_text(encoding="utf-8", errors="replace")
72
+ summary = {
73
+ "engine": "pdflatex",
74
+ "eda_executed": False,
75
+ "overfull_boxes": re.findall(r"Overfull[^\n]+", log),
76
+ "unresolved_references": "There were undefined references" in log,
77
+ "source": "docs/DRMHB.tex",
78
+ }
79
+ (build / "build_summary.json").write_text(json.dumps(summary, indent=2) + "\n")
80
+ if summary["overfull_boxes"] or summary["unresolved_references"]:
81
+ raise SystemExit(
82
+ f"Layout/reference errors remain; see {build / 'build_summary.json'}"
83
+ )
84
+ output.parent.mkdir(parents=True, exist_ok=True)
85
+ staged = output.with_name(output.name + ".tmp")
86
+ shutil.copy2(build / "DRMHB.pdf", staged)
87
+ staged.replace(output)
88
+ print(f"Report: {output} ({output.stat().st_size:,} bytes)")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
tools/recover_reference_assets.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Recover document assets from the immutable executed EDA, without rerunning models.
3
+
4
+ The manifest binds every image/table to its cell/output and byte hash. Figures
5
+ are the original embedded PNG bytes, not recreated or statistically altered.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import base64
12
+ import hashlib
13
+ import json
14
+ import re
15
+ from pathlib import Path
16
+
17
+
18
+ def recover(root: Path) -> dict:
19
+ notebook = root / "notebooks/reference/DRMHB_EDA_published_2_5_0.ipynb"
20
+ nb = json.loads(notebook.read_text(encoding="utf-8"))
21
+ target = root / "docs/figures/eda"
22
+ target.mkdir(parents=True, exist_ok=True)
23
+ entries = []
24
+ for index, cell in enumerate(nb["cells"]):
25
+ source = "".join(cell.get("source", []))
26
+ if "publish_figure(" not in source or "def publish_figure" in source:
27
+ continue
28
+ names = re.findall(r'publish_figure\(fig,\s*"([^"]+)"', source)
29
+ if index == 29:
30
+ names = [
31
+ f"transition_portrait_off_r{regime}_{variable}"
32
+ for variable in ("flow", "load")
33
+ for regime in (1, 2, 3)
34
+ ]
35
+ elif index == 58:
36
+ names = [
37
+ f"fault_chronology_{fault}"
38
+ for fault in (
39
+ "bearing_inner",
40
+ "bearing_outer",
41
+ "imbalance",
42
+ "looseness",
43
+ "misalignment_angular",
44
+ "resonance",
45
+ )
46
+ ]
47
+ outputs = [
48
+ (i, item)
49
+ for i, item in enumerate(cell.get("outputs", []))
50
+ if "image/png" in item.get("data", {})
51
+ ]
52
+ if len(names) != len(outputs):
53
+ raise RuntimeError(
54
+ f"Cell {index}: {len(names)} names for {len(outputs)} plots"
55
+ )
56
+ for name, (output_index, output) in zip(names, outputs):
57
+ encoded = output["data"]["image/png"]
58
+ payload = base64.b64decode(
59
+ "".join(encoded) if isinstance(encoded, list) else encoded
60
+ )
61
+ path = target / f"{name}.png"
62
+ path.write_bytes(payload)
63
+ entries.append(
64
+ {
65
+ "slug": name,
66
+ "kind": "figure",
67
+ "path": str(path.relative_to(root)),
68
+ "cell_index": index,
69
+ "output_index": output_index,
70
+ "execution_count": cell.get("execution_count"),
71
+ "sha256": hashlib.sha256(payload).hexdigest(),
72
+ "format": "original embedded PNG",
73
+ }
74
+ )
75
+ for index, name in [(77, "baseline_ml_summary"), (78, "baseline_detection_delay")]:
76
+ cell = nb["cells"][index]
77
+ output = "".join(
78
+ "".join(item.get("text", [])) for item in cell.get("outputs", [])
79
+ )
80
+ match = re.search(r"\\begin\{table\}.*?\\end\{table\}", output, re.S)
81
+ if match is None:
82
+ raise RuntimeError(f"No original LaTeX table in cell {index}")
83
+ original = root / "docs/provenance" / f"{name}.original.tex"
84
+ original.parent.mkdir(parents=True, exist_ok=True)
85
+ original.write_text(match.group(0) + "\n", encoding="utf-8")
86
+ # Only presentation changes: sizes/centering/line breaks. Numeric tokens unchanged.
87
+ text = match.group(0).replace("[htbp]", "[H]")
88
+ text = text.replace(
89
+ r"\begin{table}[H]",
90
+ r"\begin{table}[H]" + "\n" + r"\centering\small\setlength{\tabcolsep}{4pt}",
91
+ )
92
+ if name == "baseline_ml_summary":
93
+ text = text.replace("Healthy FPR [\\%]", r"\shortstack{Healthy\\FPR [\%]}")
94
+ text = text.replace(
95
+ "Transition FPR [\\%]", r"\shortstack{Transition\\FPR [\%]}"
96
+ )
97
+ text = text.replace("OOD FPR [\\%]", r"\shortstack{OOD\\FPR [\%]}")
98
+ text = text.replace("Median delay [d]", r"\shortstack{Median\\delay [d]}")
99
+ path = root / "docs" / f"{name}.tex"
100
+ path.write_text(text + "\n", encoding="utf-8")
101
+ entries.append(
102
+ {
103
+ "slug": name,
104
+ "kind": "table",
105
+ "cell_index": index,
106
+ "execution_count": cell.get("execution_count"),
107
+ "path": str(path.relative_to(root)),
108
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
109
+ "original_sha256": hashlib.sha256(original.read_bytes()).hexdigest(),
110
+ "format": "original printed LaTeX table; layout-only formatting",
111
+ }
112
+ )
113
+ manifest = {
114
+ "repo_id": "AlejandroGZ/DRMHB",
115
+ "source_revision": "d218f6e1dc7505d7c92c0b23fc1d27808a26c107",
116
+ "dataset_generator_version": "2.5.0",
117
+ "executed_conversion_version": "0.2.2",
118
+ "notebook": str(notebook.relative_to(root)),
119
+ "notebook_sha256": hashlib.sha256(notebook.read_bytes()).hexdigest(),
120
+ "recomputed": False,
121
+ "assets": entries,
122
+ }
123
+ (root / "docs/provenance/eda_assets.json").write_text(
124
+ json.dumps(manifest, indent=2) + "\n"
125
+ )
126
+ return manifest
127
+
128
+
129
+ def main() -> None:
130
+ parser = argparse.ArgumentParser(description=__doc__)
131
+ parser.add_argument(
132
+ "--root", type=Path, default=Path(__file__).resolve().parents[1]
133
+ )
134
+ args = parser.parse_args()
135
+ print(json.dumps({"recovered_assets": len(recover(args.root)["assets"])}, indent=2))
136
+
137
+
138
+ if __name__ == "__main__":
139
+ main()