File size: 29,673 Bytes
8c74f19 | 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 | #!/usr/bin/env python3
"""Read-only integrity audit for a pooled-v2 compact dataset.
The audit is intentionally stricter than a reader smoke test. For every
graph selected in a v2 dataset it proves four links:
1. the manifest/source index maps the dataset index to one unique discovered
raw pose path;
2. the reconstructed graph node rows, atom-static columns, coordinates and
coordinate-error labels match that raw protein/native/predicted pose;
3. PP edges and pose-specific non-PP edges are exactly the cutoff graph of
those raw coordinates; and
4. when a matching v1 compact staging shard is supplied, all serialized graph
tensors are bitwise equal for every common source graph index.
It only reads input datasets. A JSON report is optional and is written only
to a path that does not already exist.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from collections import Counter
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple
import numpy as np
import torch
from scipy.spatial.distance import cdist
THIS_DIR = Path(__file__).resolve().parent
SYSTEM_SPLIT = THIS_DIR.parent / "system_split_code"
for directory in (THIS_DIR, SYSTEM_SPLIT):
if str(directory) not in sys.path:
sys.path.insert(0, str(directory))
import build_pooled_v2 as v2 # noqa: E402
from compact_graph_dataset import CompactGraphDataset # noqa: E402
@dataclass(frozen=True)
class Arguments:
data_dir: Path
v2_root: Path
v1_shard: Path | None
report: Path | None
cutoff: float
def parse_args(argv: Sequence[str] | None = None) -> Arguments:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data-dir", required=True, type=Path)
parser.add_argument("--v2-root", required=True, type=Path)
parser.add_argument(
"--v1-shard",
type=Path,
default=None,
help="Optional old gnncp_compact_v1 shard containing the same source indices.",
)
parser.add_argument(
"--report",
type=Path,
default=None,
help="Optional new JSON report path; existing files are never overwritten.",
)
parser.add_argument("--cutoff", type=float, default=6.0)
raw = parser.parse_args(argv)
return Arguments(
data_dir=raw.data_dir.expanduser().resolve(),
v2_root=raw.v2_root.expanduser().resolve(),
v1_shard=raw.v1_shard.expanduser().resolve() if raw.v1_shard else None,
report=raw.report.expanduser().resolve() if raw.report else None,
cutoff=float(raw.cutoff),
)
def _atomic_json_new(path: Path, payload: Mapping[str, Any]) -> None:
if path.exists():
raise FileExistsError(f"refusing to overwrite audit report: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + f".tmp.{os.getpid()}")
with temporary.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2, ensure_ascii=False)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
if path.exists():
temporary.unlink(missing_ok=True)
raise FileExistsError(f"audit report appeared concurrently: {path}")
os.replace(temporary, path)
def _load_json(path: Path) -> Dict[str, Any]:
with path.open("r", encoding="utf-8") as handle:
value = json.load(handle)
if not isinstance(value, dict):
raise TypeError(f"expected object in {path}")
return value
def _bounds(pointer: torch.Tensor, index: int, name: str) -> tuple[int, int]:
begin = int(pointer[index].item())
end = int(pointer[index + 1].item())
if begin < 0 or end < begin:
raise AssertionError(f"invalid {name}[{index}] = [{begin}, {end})")
return begin, end
def _slice_system(shard: Mapping[str, torch.Tensor], system_index: int) -> Dict[str, torch.Tensor]:
static_start, static_end = _bounds(shard["system_node_ptr"], system_index, "system_node_ptr")
protein_start, protein_end = _bounds(shard["protein_ptr"], system_index, "protein_ptr")
native_start, native_end = _bounds(
shard["native_ligand_ptr"], system_index, "native_ligand_ptr"
)
pp_start, pp_end = _bounds(shard["pp_edge_ptr"], system_index, "pp_edge_ptr")
return {
"n_protein": shard["n_protein"][system_index : system_index + 1],
"x_static": shard["x_static"][static_start:static_end],
"protein_pos": shard["protein_pos"][protein_start:protein_end],
"native_ligand_pos": shard["native_ligand_pos"][native_start:native_end],
"pp_edge_upper": shard["pp_edge_upper"][:, pp_start:pp_end],
}
def _slice_pose(
shard: Mapping[str, torch.Tensor], pose_index: int
) -> Dict[str, torch.Tensor]:
dynamic_start, dynamic_end = _bounds(shard["pose_node_ptr"], pose_index, "pose_node_ptr")
ligand_start, ligand_end = _bounds(shard["pose_ligand_ptr"], pose_index, "pose_ligand_ptr")
nonpp_start, nonpp_end = _bounds(shard["nonpp_edge_ptr"], pose_index, "nonpp_edge_ptr")
return {
"x_dynamic": shard["x_dynamic"][dynamic_start:dynamic_end],
"ligand_pos": shard["ligand_pos"][ligand_start:ligand_end],
"nonpp_edge_upper": shard["nonpp_edge_upper"][:, nonpp_start:nonpp_end],
}
def _equal(name: str, actual: torch.Tensor, expected: torch.Tensor, context: str) -> None:
if actual.dtype != expected.dtype or tuple(actual.shape) != tuple(expected.shape):
raise AssertionError(
f"{context}: {name} shape/dtype differs: "
f"{actual.dtype}{tuple(actual.shape)} vs {expected.dtype}{tuple(expected.shape)}"
)
if not torch.equal(actual, expected):
difference = (
float((actual.to(torch.float64) - expected.to(torch.float64)).abs().max().item())
if actual.numel() and actual.is_floating_point()
else None
)
raise AssertionError(f"{context}: {name} differs; max_abs={difference}")
def _allclose(
name: str,
actual: torch.Tensor,
expected: torch.Tensor,
context: str,
*,
rtol: float = 1e-6,
atol: float = 1e-6,
) -> float:
"""Return max absolute difference after a deliberately stated tolerance."""
if actual.dtype != expected.dtype or tuple(actual.shape) != tuple(expected.shape):
raise AssertionError(
f"{context}: {name} shape/dtype differs: "
f"{actual.dtype}{tuple(actual.shape)} vs {expected.dtype}{tuple(expected.shape)}"
)
difference = (
float((actual.to(torch.float64) - expected.to(torch.float64)).abs().max().item())
if actual.numel()
else 0.0
)
if not torch.allclose(actual, expected, rtol=rtol, atol=atol):
raise AssertionError(
f"{context}: {name} differs beyond rtol={rtol}, atol={atol}; max_abs={difference}"
)
return difference
def _as_tensor(array: np.ndarray) -> torch.Tensor:
return torch.from_numpy(np.ascontiguousarray(array))
def _expected_pp_upper(coords_protein: np.ndarray, cutoff: float) -> torch.Tensor:
distance = cdist(coords_protein, coords_protein)
mask = (distance <= cutoff) & (~np.eye(coords_protein.shape[0], dtype=bool))
src, dst = np.where(mask)
keep = src < dst
return _as_tensor(np.vstack([src[keep], dst[keep]]).astype(np.int32))
def _expected_nonpp_upper(
coords_protein: np.ndarray,
coords_ligand: np.ndarray,
cutoff: float,
) -> torch.Tensor:
"""Recreate the row-major upper-edge order used by the original builder."""
n_protein = coords_protein.shape[0]
protein_ligand = cdist(coords_protein, coords_ligand)
protein_src, ligand_local = np.where(protein_ligand <= cutoff)
protein_ligand_edges = np.vstack(
[protein_src, n_protein + ligand_local]
).astype(np.int32)
ligand_ligand = cdist(coords_ligand, coords_ligand)
ligand_mask = (ligand_ligand <= cutoff) & (~np.eye(coords_ligand.shape[0], dtype=bool))
ligand_src, ligand_dst = np.where(ligand_mask)
keep = ligand_src < ligand_dst
ligand_ligand_edges = np.vstack(
[n_protein + ligand_src[keep], n_protein + ligand_dst[keep]]
).astype(np.int32)
return _as_tensor(np.concatenate([protein_ligand_edges, ligand_ligand_edges], axis=1))
def _full_static(protein_atoms: Any, ligand_atoms: Any) -> np.ndarray:
protein_static, _ = v2._static_features(protein_atoms, protein=True)
ligand_static, _ = v2._static_features(ligand_atoms, protein=False)
return np.concatenate([protein_static, ligand_static], axis=0)
def _discover_expected(data_dir: Path, method: str, n_source_systems: int) -> List[v2.SystemSpec]:
config = v2.BuildConfig(
data_dir=data_dir,
output_dir=Path("/tmp/unused_audit_output"),
method=method,
cutoff=6.0,
target_shard_mib=1,
system_workers=1,
max_systems=n_source_systems,
max_poses_per_system=None,
include_systems=(),
on_error="abort",
verify_reference=False,
verify_reference_systems=1,
verify_reference_poses=1,
reader_smoke_graphs=0,
)
return v2.discover_systems(config)
def _tensor_storage_bytes(shard: Mapping[str, torch.Tensor]) -> int:
return sum(value.numel() * value.element_size() for value in shard.values() if torch.is_tensor(value))
def _v2_shards(root: Path, manifest: Mapping[str, Any]) -> List[Mapping[str, torch.Tensor]]:
result = []
for entry in manifest["shards"]:
path = root / str(entry["path"])
result.append(torch.load(path, map_location="cpu", mmap=True, weights_only=True))
return result
def _check_v2_index_and_manifest(
root: Path,
manifest: Mapping[str, Any],
source_index: Mapping[str, Any],
expected_by_source: Mapping[int, v2.PoseSpec],
) -> tuple[Dict[int, tuple[int, int, int]], Dict[str, int]]:
"""Return source -> (shard, local pose, local storage system)."""
shards = _v2_shards(root, manifest)
source_locations: Dict[int, tuple[int, int, int]] = {}
pointer_systems_checked = 0
records_checked = 0
for shard_index, (entry, shard) in enumerate(zip(manifest["shards"], shards)):
n_poses = int(shard["pose_system"].numel())
if n_poses != int(entry["num_graphs"]):
raise AssertionError(f"shard {shard_index}: manifest pose count differs")
if int(shard["source_graph_index"].numel()) != n_poses:
raise AssertionError(f"shard {shard_index}: source_graph_index length differs")
if int(shard["n_protein"].numel()) != int(entry["num_systems"]):
raise AssertionError(f"shard {shard_index}: manifest storage-system count differs")
for local_pose, source_value in enumerate(shard["source_graph_index"].tolist()):
source = int(source_value)
if source in source_locations:
raise AssertionError(f"source graph index appears twice: {source}")
if source not in expected_by_source:
raise AssertionError(f"unexpected source graph index in v2: {source}")
storage_system = int(shard["pose_system"][local_pose].item())
source_locations[source] = (shard_index, local_pose, storage_system)
for storage_system, record in enumerate(entry["systems"]):
pose_start, pose_end = _bounds(
shard["system_graph_ptr"], storage_system, "system_graph_ptr"
)
actual_sources = [
int(value)
for value in shard["source_graph_index"][pose_start:pose_end].tolist()
]
declared_sources = [int(value) for value in record["source_graph_indices"]]
if actual_sources != declared_sources:
raise AssertionError(
f"shard {shard_index} storage system {storage_system}: "
"manifest source indices differ from tensor pointers"
)
if int(record["num_graphs"]) != pose_end - pose_start:
raise AssertionError(f"storage group graph count mismatch for {record['system_id']}")
expected_poses = [expected_by_source[source] for source in actual_sources]
expected_systems = {pose.system_id for pose in expected_poses}
if expected_systems != {str(record["source_system_id"])}:
raise AssertionError(f"storage group source system mismatch for {record['system_id']}")
expected_paths = [
str(pose.ligand_pred.relative_to(next(iter(expected_poses)).ligand_pred.parents[1]))
for pose in expected_poses
]
# Dataset paths are relative to the data root, rather than their
# immediate system directory. Recompute below with a stable root.
del expected_paths
pointer_systems_checked += 1
records_checked += 1
declared_sources = [int(value) for value in source_index["source_graph_indices"]]
if len(declared_sources) != len(set(declared_sources)):
raise AssertionError("source_index has duplicate source graph indices")
if set(declared_sources) != set(source_locations):
missing = sorted(set(declared_sources).symmetric_difference(source_locations))[:10]
raise AssertionError(f"source_index/tensor source set mismatch: {missing}")
graph_map = manifest["graph_map"]
if len(graph_map) != len(declared_sources):
raise AssertionError("manifest graph_map length differs from source_index")
for dataset_index, source in enumerate(declared_sources):
location = [int(value) for value in graph_map[dataset_index]]
actual = source_locations[source]
if location != list(actual[:2]):
raise AssertionError(
f"dataset index {dataset_index}: graph_map {location} != source location {actual[:2]}"
)
expected = expected_by_source[source]
if str(source_index["graph_to_system"][dataset_index]) != expected.system_id:
raise AssertionError(f"dataset index {dataset_index}: graph_to_system mismatch")
return source_locations, {"storage_systems": pointer_systems_checked, "records": records_checked}
def _check_declared_pose_paths(
data_dir: Path,
manifest: Mapping[str, Any],
expected_by_source: Mapping[int, v2.PoseSpec],
) -> int:
checked = 0
for shard_entry in manifest["shards"]:
for record in shard_entry["systems"]:
declared_sources = [int(value) for value in record["source_graph_indices"]]
declared_paths = [str(value) for value in record["source_pose_paths"]]
expected_paths = [
str(expected_by_source[source].ligand_pred.relative_to(data_dir))
for source in declared_sources
]
if declared_paths != expected_paths:
raise AssertionError(
f"{record['system_id']}: declared pose paths do not match source graph indices"
)
checked += len(declared_sources)
return checked
def _check_raw_and_edges(
arguments: Arguments,
manifest: Mapping[str, Any],
source_index: Mapping[str, Any],
expected_by_source: Mapping[int, v2.PoseSpec],
source_locations: Mapping[int, tuple[int, int, int]],
) -> Dict[str, int]:
"""Verify every row/label against the raw pose and every stored upper edge."""
dataset = CompactGraphDataset(arguments.v2_root, strict=True)
shards = _v2_shards(arguments.v2_root, manifest)
protein_cache: Dict[str, tuple[np.ndarray, np.ndarray, Any, Any]] = {}
checked_pp_systems: set[tuple[int, int]] = set()
counts = Counter()
static_index = torch.tensor(v2.STATIC_COLUMNS, dtype=torch.int64)
for dataset_index, source_value in enumerate(source_index["source_graph_indices"]):
source = int(source_value)
pose = expected_by_source[source]
shard_index, local_pose, storage_system = source_locations[source]
shard = shards[shard_index]
graph = dataset[dataset_index]
if int(shard["source_graph_index"][local_pose].item()) != source:
raise AssertionError(f"dataset index {dataset_index}: source graph index changed")
if int(shard["pose_system"][local_pose].item()) != storage_system:
raise AssertionError(f"dataset index {dataset_index}: storage system pointer changed")
if pose.system_id not in protein_cache:
protein_universe = v2.load_pdb_clean_models(str(pose.protein))
native_universe = v2.load_pdb_clean_models(str(pose.ligand_native))
protein_atoms = protein_universe.select_atoms("not name H*")
native_atoms = native_universe.select_atoms("not name H*")
protein_cache[pose.system_id] = (
protein_atoms.positions.astype(np.float32),
native_atoms.positions.astype(np.float32),
protein_atoms,
native_atoms,
)
coords_protein, coords_native, protein_atoms, _ = protein_cache[pose.system_id]
ligand_universe = v2.load_pdb_clean_models(str(pose.ligand_pred))
ligand_atoms = ligand_universe.select_atoms("not name H*")
coords_ligand = ligand_atoms.positions.astype(np.float32)
if coords_ligand.shape[0] != coords_native.shape[0]:
raise AssertionError(f"{pose.ligand_pred}: raw pred/native ligand atom count differs")
expected_pos = _as_tensor(np.vstack([coords_protein, coords_ligand]))
expected_y_grt = _as_tensor(np.vstack([coords_protein, coords_native]))
expected_static = _as_tensor(_full_static(protein_atoms, ligand_atoms))
# The original graph builder uses NumPy norm, whereas
# CompactGraphDataset deliberately reconstructs y_true with Torch from
# stored float32 coordinates. These are mathematically identical but
# can differ by one float32 ULP. Verify the reader formula bitwise and
# independently verify legacy/raw semantics within one ULP tolerance.
expected_error_legacy = _as_tensor(
np.concatenate(
[
np.zeros(coords_protein.shape[0], dtype=np.float32),
np.linalg.norm(coords_ligand - coords_native, axis=1).astype(np.float32),
]
)
).unsqueeze(-1)
context = f"source={source} dataset={dataset_index} pose={pose.ligand_pred.name}"
_equal("raw pos", graph.pos, expected_pos, context)
_equal("raw y_pred", graph.y_pred, expected_pos, context)
_equal("raw y_grt", graph.y_grt, expected_y_grt, context)
expected_error_reader = torch.zeros_like(graph.y_true)
ligand_delta = expected_pos[coords_protein.shape[0] :] - expected_y_grt[
coords_protein.shape[0] :
]
expected_error_reader[coords_protein.shape[0] :, 0] = torch.sqrt(
torch.sum(ligand_delta * ligand_delta, dim=1)
)
_equal("reader-reconstructed y_true", graph.y_true, expected_error_reader, context)
raw_y_true_difference = _allclose(
"raw legacy y_true",
graph.y_true,
expected_error_legacy,
context,
rtol=1e-6,
atol=1e-6,
)
counts["max_raw_y_true_abs"] = max(
raw_y_true_difference,
float(counts.get("max_raw_y_true_abs", 0.0)),
)
_equal("raw static atom features", graph.x.index_select(1, static_index), expected_static, context)
expected_is_protein = torch.zeros((expected_pos.shape[0], 1), dtype=torch.float32)
expected_is_protein[: coords_protein.shape[0]] = 1.0
_equal("protein/ligand node partition", graph.is_protein, expected_is_protein, context)
# The reader emits exactly one reverse edge per stored upper edge.
stored_pose = _slice_pose(shard, local_pose)
stored_system = _slice_system(shard, storage_system)
expected_edge_count = 2 * (
stored_system["pp_edge_upper"].shape[1]
+ stored_pose["nonpp_edge_upper"].shape[1]
)
if int(graph.edge_index.shape[1]) != expected_edge_count:
raise AssertionError(f"{context}: reconstructed edge count differs from compact storage")
system_key = (shard_index, storage_system)
if system_key not in checked_pp_systems:
_equal(
"raw PP upper edges",
stored_system["pp_edge_upper"],
_expected_pp_upper(coords_protein, arguments.cutoff),
context,
)
checked_pp_systems.add(system_key)
counts["pp_systems"] += 1
_equal(
"raw non-PP upper edges",
stored_pose["nonpp_edge_upper"],
_expected_nonpp_upper(coords_protein, coords_ligand, arguments.cutoff),
context,
)
# Independently verify every reconstructed edge attribute from the raw
# coordinate rows, including both directed orientations.
src, dst = graph.edge_index
distance = torch.sqrt(
torch.sum(
(expected_pos[src].to(torch.float64) - expected_pos[dst].to(torch.float64)) ** 2,
dim=1,
)
)
expected_attr = torch.stack(
[
(distance / arguments.cutoff).to(torch.float32),
torch.exp(-distance / 3.0).to(torch.float32),
(src < coords_protein.shape[0]).to(torch.float32),
(dst < coords_protein.shape[0]).to(torch.float32),
],
dim=1,
)
_equal("reconstructed edge attributes", graph.edge_attr, expected_attr, context)
counts["raw_poses"] += 1
if counts["raw_poses"] % 50 == 0:
print(f"[raw] checked {counts['raw_poses']}/{len(dataset)} poses", flush=True)
return dict(counts)
def _check_v1_tensor_parity(
v1_shard_path: Path,
v2_root: Path,
manifest: Mapping[str, Any],
source_locations: Mapping[int, tuple[int, int, int]],
) -> Dict[str, int]:
"""Bitwise-compare every v2 source pose against its same-source v1 record."""
v1 = torch.load(v1_shard_path, map_location="cpu", mmap=True, weights_only=True)
v2_shards = _v2_shards(v2_root, manifest)
v1_locations: Dict[int, tuple[int, int]] = {}
for local_pose, source_value in enumerate(v1["source_graph_index"].tolist()):
source = int(source_value)
if source in v1_locations:
raise AssertionError(f"v1 shard has duplicate source graph index {source}")
v1_locations[source] = (local_pose, int(v1["pose_system"][local_pose].item()))
missing = sorted(set(source_locations).difference(v1_locations))
if missing:
raise AssertionError(f"v1 shard lacks v2 source graph indices; first: {missing[:10]}")
compared_system_pairs: set[tuple[int, int]] = set()
compared_poses = 0
for source in sorted(source_locations):
shard_index, v2_pose_index, v2_system_index = source_locations[source]
v1_pose_index, v1_system_index = v1_locations[source]
pair = (v1_system_index, v2_system_index)
if pair not in compared_system_pairs:
left = _slice_system(v1, v1_system_index)
right = _slice_system(v2_shards[shard_index], v2_system_index)
context = f"source={source} v1system={v1_system_index} v2system={v2_system_index}"
for name in ("n_protein", "x_static", "protein_pos", "native_ligand_pos", "pp_edge_upper"):
_equal(f"v1/v2 {name}", right[name], left[name], context)
compared_system_pairs.add(pair)
left_pose = _slice_pose(v1, v1_pose_index)
right_pose = _slice_pose(v2_shards[shard_index], v2_pose_index)
context = f"source={source} v1pose={v1_pose_index} v2pose={v2_pose_index}"
for name in ("x_dynamic", "ligand_pos", "nonpp_edge_upper"):
_equal(f"v1/v2 {name}", right_pose[name], left_pose[name], context)
compared_poses += 1
return {
"v1_v2_storage_system_pairs": len(compared_system_pairs),
"v1_v2_poses_bitwise_compared": compared_poses,
"v1_v2_v1_shard_source_graphs": len(v1_locations),
}
def run(arguments: Arguments) -> Dict[str, Any]:
if not arguments.data_dir.is_dir():
raise FileNotFoundError(arguments.data_dir)
if not arguments.v2_root.is_dir():
raise FileNotFoundError(arguments.v2_root)
if arguments.v1_shard is not None and not arguments.v1_shard.is_file():
raise FileNotFoundError(arguments.v1_shard)
if arguments.report is not None and arguments.report.exists():
raise FileExistsError(arguments.report)
started = time.perf_counter()
manifest = _load_json(arguments.v2_root / "manifest.json")
source_index = _load_json(arguments.v2_root / "source_index.json")
if manifest.get("format") != "gnncp_compact_v1" or int(manifest.get("schema_version", -1)) != 1:
raise AssertionError("v2 output is not compact_v1-reader compatible")
if manifest.get("status") != "complete":
raise AssertionError("v2 manifest is not complete")
expected_systems = _discover_expected(
arguments.data_dir,
str(manifest["method"]),
int(manifest["source"]["discovered_source_systems"]),
)
expected_poses = [pose for system in expected_systems for pose in system.poses]
expected_by_source = {pose.source_graph_index: pose for pose in expected_poses}
if len(expected_by_source) != len(expected_poses):
raise AssertionError("source discovery unexpectedly assigned duplicate indices")
if int(manifest["n_graphs"]) != len(expected_poses):
raise AssertionError(
f"manifest graphs={manifest['n_graphs']} vs raw discovery={len(expected_poses)}"
)
if int(source_index["n_graphs"]) != len(expected_poses):
raise AssertionError("source_index graph count differs from raw discovery")
if list(source_index["graph_to_system"]) != [pose.system_id for pose in expected_poses]:
raise AssertionError("source_index graph_to_system differs from raw discovery ordering")
print(f"[index] auditing {len(expected_systems)} systems / {len(expected_poses)} poses", flush=True)
source_locations, index_counts = _check_v2_index_and_manifest(
arguments.v2_root, manifest, source_index, expected_by_source
)
declared_paths_checked = _check_declared_pose_paths(
arguments.data_dir, manifest, expected_by_source
)
print("[raw] verifying raw node rows, labels, static atoms, and cutoff edges", flush=True)
raw_counts = _check_raw_and_edges(
arguments, manifest, source_index, expected_by_source, source_locations
)
parity_counts: Dict[str, int] = {}
if arguments.v1_shard is not None:
print("[v1] bitwise-comparing all common compact tensors", flush=True)
parity_counts = _check_v1_tensor_parity(
arguments.v1_shard, arguments.v2_root, manifest, source_locations
)
v2_shards = _v2_shards(arguments.v2_root, manifest)
tensor_bytes = sum(_tensor_storage_bytes(shard) for shard in v2_shards)
report: Dict[str, Any] = {
"status": "passed",
"created_utc": datetime.now(timezone.utc).isoformat(),
"elapsed_seconds": time.perf_counter() - started,
"inputs": {
"data_dir": str(arguments.data_dir),
"v2_root": str(arguments.v2_root),
"v1_shard": str(arguments.v1_shard) if arguments.v1_shard else None,
"cutoff": arguments.cutoff,
},
"counts": {
"raw_discovered_systems": len(expected_systems),
"raw_discovered_poses": len(expected_poses),
"manifest_graphs": int(manifest["n_graphs"]),
"manifest_storage_groups": int(manifest["n_systems"]),
"declared_pose_paths_checked": declared_paths_checked,
"v2_tensor_storage_bytes": tensor_bytes,
**index_counts,
**raw_counts,
**parity_counts,
},
"guarantees_checked": [
"unique source_graph_index and graph_map placement",
"source-index order and source-system labels against deterministic raw discovery",
"manifest pose paths against raw discovered pose paths",
(
"all raw heavy-atom node coordinates, atom-static features, partition flags, "
"and y_pred/y_grt; y_true exact under the reader's float32 formula and "
"within 1e-6 of the legacy NumPy formula"
),
"all PP and all pose-specific non-PP cutoff upper edges against raw coordinates",
"all reconstructed edge attributes against raw coordinate rows",
"all common v1/v2 serialized static, dynamic, coordinate, and edge tensors bitwise equal",
],
}
if arguments.report is not None:
_atomic_json_new(arguments.report, report)
print(f"[report] wrote {arguments.report}", flush=True)
print(
f"PASS: {len(expected_poses)} poses, {raw_counts['pp_systems']} storage systems, "
f"{raw_counts['raw_poses']} raw node/edge checks in {report['elapsed_seconds']:.1f}s",
flush=True,
)
return report
def main(argv: Sequence[str] | None = None) -> int:
run(parse_args(argv))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|