File size: 9,845 Bytes
881cb3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""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)