| |
| """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}" |
| ) |
|
|
| |
| |
| 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), |
| ) |
|
|
| |
| |
| |
| 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) |
|
|
| |
| |
| 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=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", |
| ] |
|
|