"""Shared, bounded-raw-memory DRMHB examples for vibframe-anndata 0.3.0. Evaluation is explicitly requested, never copied into X or obs. Compressed VibFrame inputs are not modified. No scalar ground-truth value becomes a feature. """ from __future__ import annotations from pathlib import Path from typing import Any import h5py import pandas as pd from vibframe_anndata import ( __version__, add_features_to_h5ad, add_ground_truth_to_h5ad, get_snapshot_ground_truth, get_waveform_ground_truth, import_raw_to_h5ad, list_evaluation_files, validate_streamed_h5ad, ) try: from anndata.io import read_elem except ImportError: from anndata.experimental import read_elem EXPECTED_VERSION = "0.3.0" SPECTRAL_FEATURES = ( "vel_overall_rms", "acc_overall_rms", "band_subsync_rms", "band_1X_rms", "band_harmonics_low_rms", "amp_1X", "amp_2X", "amp_BPFO", "amp_BPFI", "family_rms_VPF", ) WAVEFORM_FEATURES = ("rms", "crest_factor", "kurtosis") REFERENCE_FEATURE_CONFIG = { "version": 1, "output": {"dtype": "float32"}, "feature_policy": {"on_conflict": "error", "on_error": "nan"}, "features": ( [{"name": name, "source": "spectrum"} for name in SPECTRAL_FEATURES] + [{"name": name, "source": "waveform"} for name in WAVEFORM_FEATURES] ), } def check_version() -> None: """Pin semantics rather than silently using an untested API version.""" if __version__ != EXPECTED_VERSION: raise RuntimeError( f"Install vibframe-anndata=={EXPECTED_VERSION}; found {__version__}" ) def positive_int(value: str) -> int: """Reject non-positive block sizes and metadata budgets before opening files.""" import argparse try: number = int(value) except ValueError as exc: raise argparse.ArgumentTypeError("Expected a positive integer") from exc if number <= 0: raise argparse.ArgumentTypeError("Expected a positive integer") return number def prepare_output(output: Path, *inputs: Path, overwrite: bool = False) -> Path: """Prevent accidental clobbering and input/output aliases.""" result = output.expanduser().resolve() if result.suffix.lower() != ".h5ad": raise ValueError("Output must have the .h5ad extension") if any(result == item.expanduser().resolve() for item in inputs): raise ValueError("Input and output must be different files") if result.exists() and not overwrite: raise FileExistsError( f"{result} exists; use a new output or --overwrite explicitly" ) result.parent.mkdir(parents=True, exist_ok=True) return result def raw_config( *, scope: str = "all", dtype: str = "float32", max_sidecar_mib: int = 512 ) -> dict[str, Any]: """The full annotation contract is opt-in at package level, explicit here.""" if scope not in {"all", "snapshot", "none"}: raise ValueError("scope must be all, snapshot or none") if max_sidecar_mib <= 0: raise ValueError("max_sidecar_mib must be positive") return { "version": 1, "raw_import": {"waveforms": True, "spectra": True, "on_missing_signal": "nan"}, "ground_truth": { "enabled": scope != "none", "scope": "all" if scope == "none" else scope, "on_missing": "error", "max_sidecar_mib": max_sidecar_mib, }, "output": {"dtype": dtype, "raw_compression": "none"}, "features": [], "obs": { "include": [ "snapshot_id", "timestamp", "snap_t", "source", "machine", "speed_hz", "has_waveform", "has_spectrum", ] }, } def read_metadata(path: Path) -> dict[str, Any]: """Read only obs/var and package metadata; do not decode uns or raw obsm wholesale. AnnData backed mode is not a promise that obsm/uns stay on disk. In 0.3.0, uns also contains byte buffers for the complete evaluation archive. """ with h5py.File(path, "r") as handle: return { "obs": read_elem(handle["obs"]), "var": read_elem(handle["var"]), "uns": {"vibframe_anndata": read_elem(handle["uns"]["vibframe_anndata"])}, "shape": tuple(handle["X"].shape), "obsm_keys": list(handle["obsm"].keys()), "uns_keys": list(handle["uns"].keys()), } def inventory_or_empty(path: Path) -> pd.DataFrame: """Absence is explicit; errors in an existing archive must not be swallowed.""" with h5py.File(path, "r") as handle: present = "vibframe_evaluation" in handle["uns"] if not present: return pd.DataFrame(columns=["source", "path", "kind", "size_bytes", "sha256"]) return list_evaluation_files(path) def require_complete_drmhb(path: Path) -> dict[str, Any]: """Require construction snapshot/waveform truth and originals for DRMHB EDA.""" result = validate_streamed_h5ad(path) if result.get("ground_truth_rows", 0) != result["n_obs"]: raise RuntimeError( "No complete snapshot truth; run example 04 or recreate with scope=all" ) if result.get("waveform_ground_truth_snapshots", 0) != result["n_obs"]: raise RuntimeError( "No waveform truth; run example 04 or recreate with scope=all" ) if result.get("evaluation_files", 0) == 0: raise RuntimeError( "No archived originals; run example 04 or recreate with scope=all" ) return result def preservation_signature(path: Path) -> tuple[dict[str, Any], pd.DataFrame]: """Small signature for numerical dimensions and original annotation identities.""" report = validate_streamed_h5ad(path) keys = ( "n_obs", "waveform_signals", "waveform_samples", "spectrum_signals", "spectrum_samples", "ground_truth_rows", "waveform_ground_truth_snapshots", ) counts = {key: report.get(key, 0) for key in keys} files = inventory_or_empty(path) cols = ["source", "path", "size_bytes", "sha256"] return counts, files[cols].sort_values(["source", "path"]).reset_index(drop=True) def assert_preserved(before: tuple, output: Path) -> None: """Check dimensions and lossless archive identity after feature engineering.""" after = preservation_signature(output) if before[0] != after[0] or not before[1].equals(after[1]): raise RuntimeError("Signal/annotation coverage or archived originals changed") def create_base( source: Path, output: Path, *, scope: str = "all", dtype: str = "float32", block_size_mib: int = 8, max_sidecar_mib: int = 512, overwrite: bool = False, ) -> Path: """Import a ZIP or extracted VibFrame with no calculated features.""" check_version() if not source.exists(): raise FileNotFoundError(source) if block_size_mib <= 0: raise ValueError("block_size_mib must be positive") output = prepare_output(output, source, overwrite=overwrite) result = import_raw_to_h5ad( source, output, config=raw_config(scope=scope, dtype=dtype, max_sidecar_mib=max_sidecar_mib), block_size_mib=block_size_mib, ) report = validate_streamed_h5ad(result) if report["n_vars"] != 0: raise RuntimeError("Featureless base must have zero features") if scope == "all": require_complete_drmhb(result) elif scope == "snapshot" and report.get("ground_truth_rows", 0) != report["n_obs"]: raise RuntimeError("Incomplete snapshot annotation coverage") return result def add_reference_features( source: Path, output: Path, *, block_rows: int = 256, config: Any = None, overwrite: bool = False, ) -> Path: """Compute unchanged reference features; keep raw signals and all annotations.""" check_version() output = prepare_output(output, source, overwrite=overwrite) if block_rows <= 0: raise ValueError("block_rows must be positive") if validate_streamed_h5ad(source)["n_vars"] != 0: raise ValueError("This example expects a featureless base") before = preservation_signature(source) result = add_features_to_h5ad( source, config or REFERENCE_FEATURE_CONFIG, output=output, block_rows=block_rows ) assert_preserved(before, result) if validate_streamed_h5ad(result)["n_vars"] == 0: raise RuntimeError("Feature calculation returned zero variables") return result def enrich_existing( source: Path, vibframe: Path, output: Path, *, max_sidecar_mib: int = 512, overwrite: bool = False, ) -> Path: """Add original annotations to a legacy file, without numerical recomputation.""" check_version() output = prepare_output(output, source, vibframe, overwrite=overwrite) if not vibframe.exists(): raise FileNotFoundError(vibframe) before = validate_streamed_h5ad(source) result = add_ground_truth_to_h5ad( source, vibframe, config=raw_config(max_sidecar_mib=max_sidecar_mib), output=output, ) after = require_complete_drmhb(result) for key in ( "n_obs", "n_vars", "waveform_signals", "waveform_samples", "spectrum_signals", "spectrum_samples", ): if before.get(key) != after.get(key): raise RuntimeError(f"Existing numerical dimensions changed: {key}") return result def read_truth(path: Path) -> tuple[pd.DataFrame, pd.DataFrame]: """Convenience labels are for evaluation; never place these frames in X.""" return get_snapshot_ground_truth(path), get_waveform_ground_truth(path)