File size: 22,201 Bytes
0cb481f | 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 | #!/usr/bin/env python3
"""Lazy reader for the ``gnncp_compact_v1`` graph format.
The compact format stores data that are shared by all poses of a system only
once. A sample is reconstructed on demand with the same public PyG schema as
``build_graph_unified_enhanced.py``:
``x, edge_index, edge_attr, pos, is_protein, y_true, y_pred, y_grt``.
Nothing in this module changes the model-facing feature dimensions. Node
features are reconstructed as float32 [N, 82] and edge features as float32
[E, 4].
"""
from __future__ import annotations
import bisect
import json
from collections import OrderedDict
from pathlib import Path
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
import torch
from torch.utils.data import Dataset
from torch_geometric.data import Data
FORMAT_NAME = "gnncp_compact_v1"
SCHEMA_VERSION = 1
STATIC_WIDTH = 44
DYNAMIC_WIDTH = 38
NODE_WIDTH = 82
EDGE_WIDTH = 4
class CompactFormatError(RuntimeError):
"""Raised when a compact dataset does not satisfy the v1 contract."""
def _as_edge_matrix(value: torch.Tensor, name: str) -> torch.Tensor:
"""Return an edge tensor as [2, E] without materialising when possible."""
if value.ndim != 2:
raise CompactFormatError(f"{name} must be rank 2, got shape={tuple(value.shape)}")
if value.shape[0] == 2:
return value
if value.shape[1] == 2:
return value.t()
raise CompactFormatError(f"{name} must have shape [2,E] or [E,2], got {tuple(value.shape)}")
def _get_shard_path(entry: Mapping[str, Any]) -> str:
for key in ("path", "file", "filename"):
if key in entry:
return str(entry[key])
raise CompactFormatError("each manifest shard needs one of: path, file, filename")
def _get_shard_graph_count(entry: Mapping[str, Any]) -> int:
for key in ("num_graphs", "n_graphs"):
if key in entry:
return int(entry[key])
raise CompactFormatError("each manifest shard needs num_graphs (or n_graphs)")
class CompactGraphDataset(Dataset):
"""Map-style, mmap-backed dataset for compact GNNCP graphs.
Parameters
----------
root:
Compact dataset directory or its ``manifest.json`` path.
max_cached_shards:
Per-process LRU size. Each shard is loaded with ``mmap=True``; keeping
a shard in this cache does not eagerly read all tensor storage.
DataLoader workers each maintain their own cache.
strict:
Check inexpensive shape/range invariants while reconstructing samples.
"""
def __init__(
self,
root: Union[str, Path],
*,
max_cached_shards: int = 2,
strict: bool = True,
) -> None:
super().__init__()
root = Path(root).expanduser()
if root.is_dir():
self.root = root.resolve()
self.manifest_path = self.root / "manifest.json"
else:
self.manifest_path = root.resolve()
self.root = self.manifest_path.parent
if max_cached_shards < 1:
raise ValueError("max_cached_shards must be >= 1")
self.max_cached_shards = int(max_cached_shards)
self.strict = bool(strict)
self.manifest = self._read_manifest(self.manifest_path)
self.cutoff = float(self.manifest.get("cutoff", 6.0))
if self.cutoff <= 0:
raise CompactFormatError(f"cutoff must be positive, got {self.cutoff}")
raw_shards = self.manifest.get("shards")
if not isinstance(raw_shards, list) or not raw_shards:
raise CompactFormatError("manifest.shards must be a non-empty list")
self.shards: List[Mapping[str, Any]] = raw_shards
self._shard_counts = [_get_shard_graph_count(s) for s in self.shards]
self._shard_ends: List[int] = []
running = 0
for count in self._shard_counts:
if count < 0:
raise CompactFormatError(f"negative shard graph count: {count}")
running += count
self._shard_ends.append(running)
graph_map = self.manifest.get("graph_map")
if graph_map is None:
self._graph_map: Optional[Sequence[Any]] = None
self._length = running
else:
if not isinstance(graph_map, list):
raise CompactFormatError("manifest.graph_map must be a list")
self._graph_map = graph_map
self._length = len(graph_map)
declared = self.manifest.get("num_graphs", self.manifest.get("n_graphs"))
if declared is not None and int(declared) != self._length:
raise CompactFormatError(
f"manifest graph count mismatch: declared={declared}, mapped={self._length}"
)
# This cache must never be serialised into DataLoader workers. Each
# process reopens mmap-backed shards independently.
self._cache: MutableMapping[int, Mapping[str, Any]] = OrderedDict()
@staticmethod
def _read_manifest(path: Path) -> Dict[str, Any]:
if not path.is_file():
raise FileNotFoundError(f"compact manifest not found: {path}")
with path.open("r", encoding="utf-8") as handle:
manifest = json.load(handle)
if not isinstance(manifest, dict):
raise CompactFormatError("manifest root must be a JSON object")
format_name = manifest.get("format", manifest.get("format_name"))
if format_name != FORMAT_NAME:
raise CompactFormatError(
f"unsupported compact format {format_name!r}; expected {FORMAT_NAME!r}"
)
version = int(manifest.get("schema_version", manifest.get("version", -1)))
if version != SCHEMA_VERSION:
raise CompactFormatError(
f"unsupported schema version {version}; expected {SCHEMA_VERSION}"
)
static_columns = manifest.get("static_columns")
dynamic_columns = manifest.get("dynamic_columns")
expected_static = [[0, 34], [61, 71]]
expected_dynamic = [[34, 61], [71, 82]]
if static_columns is not None and static_columns != expected_static:
raise CompactFormatError(
f"unexpected static_columns={static_columns}; expected {expected_static}"
)
if dynamic_columns is not None and dynamic_columns != expected_dynamic:
raise CompactFormatError(
f"unexpected dynamic_columns={dynamic_columns}; expected {expected_dynamic}"
)
return manifest
def __len__(self) -> int:
return self._length
def __getstate__(self) -> Dict[str, Any]:
state = dict(self.__dict__)
state["_cache"] = OrderedDict()
return state
def _resolve_index(self, index: int) -> Tuple[int, int]:
if not isinstance(index, int):
try:
index = int(index)
except (TypeError, ValueError) as exc:
raise TypeError(f"graph index must be an integer, got {type(index)!r}") from exc
if index < 0:
index += self._length
if index < 0 or index >= self._length:
raise IndexError(f"graph index {index} outside [0, {self._length})")
if self._graph_map is None:
shard_index = bisect.bisect_right(self._shard_ends, index)
start = 0 if shard_index == 0 else self._shard_ends[shard_index - 1]
return shard_index, index - start
entry = self._graph_map[index]
if isinstance(entry, Mapping):
shard_index = entry.get("shard", entry.get("shard_index"))
local_index = entry.get(
"local_pose", entry.get("local_index", entry.get("graph_index"))
)
elif isinstance(entry, (list, tuple)) and len(entry) == 2:
shard_index, local_index = entry
else:
raise CompactFormatError(
f"graph_map[{index}] must be [shard,local_pose] or an object"
)
if shard_index is None or local_index is None:
raise CompactFormatError(f"incomplete graph_map entry at index {index}: {entry}")
shard_index = int(shard_index)
local_index = int(local_index)
if not 0 <= shard_index < len(self.shards):
raise CompactFormatError(
f"graph_map[{index}] has invalid shard index {shard_index}"
)
if not 0 <= local_index < self._shard_counts[shard_index]:
raise CompactFormatError(
f"graph_map[{index}] has invalid local pose {local_index} "
f"for shard {shard_index}"
)
return shard_index, local_index
def _load_shard(self, shard_index: int) -> Mapping[str, Any]:
if shard_index in self._cache:
shard = self._cache.pop(shard_index)
self._cache[shard_index] = shard
return shard
relative = Path(_get_shard_path(self.shards[shard_index]))
path = relative if relative.is_absolute() else self.root / relative
if not path.is_file():
raise FileNotFoundError(f"compact shard not found: {path}")
try:
shard = torch.load(
path,
map_location="cpu",
mmap=True,
weights_only=True,
)
except TypeError as exc:
raise RuntimeError(
"CompactGraphDataset requires a PyTorch version supporting "
"torch.load(..., mmap=True, weights_only=True)"
) from exc
if not isinstance(shard, Mapping):
raise CompactFormatError(f"shard {path} is not a tensor dictionary")
self._check_shard_header(shard, path, shard_index)
self._cache[shard_index] = shard
while len(self._cache) > self.max_cached_shards:
self._cache.popitem(last=False)
return shard
def _check_shard_header(
self,
shard: Mapping[str, Any],
path: Path,
shard_index: int,
) -> None:
required = {
"schema_version",
"system_graph_ptr",
"pose_system",
"source_graph_index",
"system_node_ptr",
"n_protein",
"x_static",
"protein_ptr",
"protein_pos",
"native_ligand_ptr",
"native_ligand_pos",
"pose_node_ptr",
"x_dynamic",
"pose_ligand_ptr",
"ligand_pos",
"pp_edge_ptr",
"pp_edge_upper",
"nonpp_edge_ptr",
"nonpp_edge_upper",
}
missing = sorted(required.difference(shard))
if missing:
raise CompactFormatError(f"shard {path} is missing keys: {missing}")
raw_version = shard["schema_version"]
if torch.is_tensor(raw_version):
if raw_version.numel() != 1:
raise CompactFormatError(f"{path}: schema_version must contain one value")
version = int(raw_version.reshape(-1)[0].item())
else:
version = int(raw_version)
if version != SCHEMA_VERSION:
raise CompactFormatError(f"{path}: schema_version={version}, expected 1")
expected_graphs = self._shard_counts[shard_index]
actual_graphs = int(shard["pose_system"].numel())
if expected_graphs != actual_graphs:
raise CompactFormatError(
f"{path}: pose count={actual_graphs}, manifest says {expected_graphs}"
)
if int(shard["source_graph_index"].numel()) != actual_graphs:
raise CompactFormatError(f"{path}: source_graph_index length mismatch")
num_systems = int(shard["n_protein"].numel())
pointer_lengths = {
"system_graph_ptr": num_systems + 1,
"system_node_ptr": num_systems + 1,
"protein_ptr": num_systems + 1,
"native_ligand_ptr": num_systems + 1,
"pp_edge_ptr": num_systems + 1,
"pose_node_ptr": actual_graphs + 1,
"pose_ligand_ptr": actual_graphs + 1,
"nonpp_edge_ptr": actual_graphs + 1,
}
for name, expected_length in pointer_lengths.items():
if int(shard[name].numel()) != expected_length:
raise CompactFormatError(
f"{path}: {name} length={shard[name].numel()}, "
f"expected {expected_length}"
)
if shard["x_static"].ndim != 2 or shard["x_static"].shape[1] != STATIC_WIDTH:
raise CompactFormatError(
f"{path}: x_static must be [sum_system_nodes,{STATIC_WIDTH}]"
)
if shard["x_dynamic"].ndim != 2 or shard["x_dynamic"].shape[1] != DYNAMIC_WIDTH:
raise CompactFormatError(
f"{path}: x_dynamic must be [sum_pose_nodes,{DYNAMIC_WIDTH}]"
)
@staticmethod
def _bounds(pointer: torch.Tensor, index: int, name: str) -> Tuple[int, int]:
start = int(pointer[index].item())
end = int(pointer[index + 1].item())
if start < 0 or end < start:
raise CompactFormatError(f"invalid {name} interval [{start}, {end})")
return start, end
def _reconstruct_edges(
self,
shard: Mapping[str, Any],
system_index: int,
pose_index: int,
pos: torch.Tensor,
n_protein: int,
) -> Tuple[torch.Tensor, torch.Tensor]:
pp_start, pp_end = self._bounds(shard["pp_edge_ptr"], system_index, "pp_edge_ptr")
np_start, np_end = self._bounds(
shard["nonpp_edge_ptr"], pose_index, "nonpp_edge_ptr"
)
pp_all = _as_edge_matrix(shard["pp_edge_upper"], "pp_edge_upper")
nonpp_all = _as_edge_matrix(shard["nonpp_edge_upper"], "nonpp_edge_upper")
pp = pp_all[:, pp_start:pp_end].to(torch.int64)
nonpp = nonpp_all[:, np_start:np_end].to(torch.int64)
upper = torch.cat((pp, nonpp), dim=1)
num_nodes = int(pos.shape[0])
if self.strict and upper.numel():
if int(upper.min().item()) < 0 or int(upper.max().item()) >= num_nodes:
raise CompactFormatError("edge endpoint outside graph node range")
if not bool(torch.all(upper[0] < upper[1]).item()):
raise CompactFormatError("compact edges must be upper triangular (src < dst)")
if pp.numel() and int(pp.max().item()) >= n_protein:
raise CompactFormatError("pp_edge_upper contains a ligand endpoint")
if nonpp.numel() and not bool(
torch.all(nonpp[1] >= n_protein).item()
):
raise CompactFormatError(
"nonpp_edge_upper must contain at least one ligand endpoint"
)
if upper.shape[1] == 0:
return (
torch.empty((2, 0), dtype=torch.int64),
torch.empty((0, EDGE_WIDTH), dtype=torch.float32),
)
# Compute the two geometric attributes once per undirected edge in
# float64. The legacy builder's scipy.cdist also computes distances
# from float32 coordinates in float64 before casting edge_attr to f32.
delta = pos[upper[0]].to(torch.float64) - pos[upper[1]].to(torch.float64)
distance = torch.sqrt(torch.sum(delta * delta, dim=1))
attr0 = (distance / self.cutoff).to(torch.float32)
attr1 = torch.exp(-distance / 3.0).to(torch.float32)
src = torch.cat((upper[0], upper[1]), dim=0)
dst = torch.cat((upper[1], upper[0]), dim=0)
attr0 = torch.cat((attr0, attr0), dim=0)
attr1 = torch.cat((attr1, attr1), dim=0)
# np.where in the legacy builder emits row-major (src,dst) order.
# Restoring this order makes edge_index parity deterministic.
order = torch.argsort(src * num_nodes + dst)
src = src[order]
dst = dst[order]
edge_index = torch.stack((src, dst), dim=0)
edge_attr = torch.stack(
(
attr0[order],
attr1[order],
(src < n_protein).to(torch.float32),
(dst < n_protein).to(torch.float32),
),
dim=1,
)
return edge_index, edge_attr
def __getitem__(self, index: int) -> Data:
shard_index, pose_index = self._resolve_index(index)
shard = self._load_shard(shard_index)
system_index = int(shard["pose_system"][pose_index].item())
num_systems = int(shard["n_protein"].numel())
if not 0 <= system_index < num_systems:
raise CompactFormatError(
f"pose {pose_index} references invalid system {system_index}"
)
n_protein = int(shard["n_protein"][system_index].item())
static_start, static_end = self._bounds(
shard["system_node_ptr"], system_index, "system_node_ptr"
)
dynamic_start, dynamic_end = self._bounds(
shard["pose_node_ptr"], pose_index, "pose_node_ptr"
)
static = shard["x_static"][static_start:static_end].to(torch.float32)
dynamic = shard["x_dynamic"][dynamic_start:dynamic_end].to(torch.float32)
num_nodes = static_end - static_start
if dynamic_end - dynamic_start != num_nodes:
raise CompactFormatError(
f"pose {pose_index}: static nodes={num_nodes}, "
f"dynamic nodes={dynamic_end - dynamic_start}"
)
protein_start, protein_end = self._bounds(
shard["protein_ptr"], system_index, "protein_ptr"
)
native_start, native_end = self._bounds(
shard["native_ligand_ptr"], system_index, "native_ligand_ptr"
)
ligand_start, ligand_end = self._bounds(
shard["pose_ligand_ptr"], pose_index, "pose_ligand_ptr"
)
protein_pos = shard["protein_pos"][protein_start:protein_end].to(torch.float32)
native_ligand_pos = shard["native_ligand_pos"][native_start:native_end].to(
torch.float32
)
ligand_pos = shard["ligand_pos"][ligand_start:ligand_end].to(torch.float32)
n_ligand = num_nodes - n_protein
if self.strict:
coordinate_counts = {
"protein": int(protein_pos.shape[0]),
"native_ligand": int(native_ligand_pos.shape[0]),
"pose_ligand": int(ligand_pos.shape[0]),
}
expected_counts = {
"protein": n_protein,
"native_ligand": n_ligand,
"pose_ligand": n_ligand,
}
if coordinate_counts != expected_counts:
raise CompactFormatError(
f"pose {pose_index}: coordinate counts {coordinate_counts}, "
f"expected {expected_counts}"
)
if protein_pos.ndim != 2 or protein_pos.shape[1] != 3:
raise CompactFormatError("protein_pos must have shape [Np,3]")
if ligand_pos.ndim != 2 or ligand_pos.shape[1] != 3:
raise CompactFormatError("ligand_pos must have shape [Nl,3]")
if native_ligand_pos.ndim != 2 or native_ligand_pos.shape[1] != 3:
raise CompactFormatError("native_ligand_pos must have shape [Nl,3]")
x = torch.empty((num_nodes, NODE_WIDTH), dtype=torch.float32)
x[:, :34] = static[:, :34]
x[:, 34:61] = dynamic[:, :27]
x[:, 61:71] = static[:, 34:44]
x[:, 71:82] = dynamic[:, 27:38]
pos = torch.cat((protein_pos, ligand_pos), dim=0)
y_grt = torch.cat((protein_pos, native_ligand_pos), dim=0)
is_protein = torch.zeros((num_nodes, 1), dtype=torch.float32)
is_protein[:n_protein] = 1.0
y_true = torch.zeros((num_nodes, 1), dtype=torch.float32)
ligand_error = ligand_pos - native_ligand_pos
y_true[n_protein:, 0] = torch.sqrt(
torch.sum(ligand_error * ligand_error, dim=1)
)
edge_index, edge_attr = self._reconstruct_edges(
shard, system_index, pose_index, pos, n_protein
)
return Data(
x=x,
edge_index=edge_index,
edge_attr=edge_attr,
pos=pos,
is_protein=is_protein,
y_true=y_true,
# y_pred intentionally aliases pos. It has the same value contract
# as the legacy data and avoids an unnecessary graph-local copy.
y_pred=pos,
y_grt=y_grt,
num_nodes=num_nodes,
)
def metadata(self, index: int) -> Dict[str, Any]:
"""Return stable source/system metadata without reconstructing a graph."""
shard_index, pose_index = self._resolve_index(index)
shard = self._load_shard(shard_index)
system_index = int(shard["pose_system"][pose_index].item())
source_index = int(shard["source_graph_index"][pose_index].item())
result: Dict[str, Any] = {
"dataset_index": int(index),
"source_graph_index": source_index,
"shard_index": shard_index,
"local_pose_index": pose_index,
"local_system_index": system_index,
}
shard_manifest = self.shards[shard_index]
system_ids = shard_manifest.get("system_ids")
if isinstance(system_ids, list) and 0 <= system_index < len(system_ids):
result["system_id"] = system_ids[system_index]
else:
systems = shard_manifest.get("systems")
if (
isinstance(systems, list)
and 0 <= system_index < len(systems)
and isinstance(systems[system_index], Mapping)
):
system_metadata = systems[system_index]
if "system_id" in system_metadata:
result["system_id"] = system_metadata["system_id"]
if "source_label" in system_metadata:
result["source_label"] = system_metadata["source_label"]
return result
__all__ = [
"CompactFormatError",
"CompactGraphDataset",
"FORMAT_NAME",
"SCHEMA_VERSION",
]
|