Merge branch 'main' of https://huggingface.co/datasets/AlejandroGZ/DRMHB
Browse files- tests/conftest.py +0 -6
- tests/test_workflow.py +0 -418
- tools/build_report.py +0 -92
- tools/recover_reference_assets.py +0 -139
tests/conftest.py
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,418 +0,0 @@
|
|
| 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"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 @@
|
|
| 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
DELETED
|
@@ -1,139 +0,0 @@
|
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|