Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- README.mdAdded+71
- code/compact_v1/README.mdAdded+28
- code/compact_v1/build_compact_v1_direct.pyAdded+1700
- code/compact_v1/build_compact_v1_direct.sbatchAdded+130
- code/compact_v1/build_graph_unified_enhanced.pyAdded+864
- code/compact_v1/build_system_index.pyAdded+295
- code/compact_v1/compact_graph_dataset.pyAdded+543
- code/compact_v1/convert_to_compact_v1.pyAdded+695
- code/compact_v1/materialize_hiqbind_gnncp.pyAdded+240
- code/compact_v1/requirements.txtAdded+9
- code/compact_v1/smoke_test_compact_dataset.pyAdded+636
- code/compact_v1/test_build_compact_v1_direct.pyAdded+403
- code/compact_v1/test_compact_graph_dataset.pyAdded+327
- code/compact_v1/validate_compact_dataset.pyAdded+401
- code/release/upload_copuladock.pyAdded+607
- code/release/upload_copuladock.sbatchAdded+44
- data/hiqbind_5k_v1/autodock_vina_full_v1/manifest.jsonAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00015.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00016.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00023.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00024.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00025.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00026.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00027.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00038.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00042.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00043.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00050.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00052.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00053.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00056.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00059.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00063.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00067.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00074.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00075.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00082.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00083.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00086.ptAdded+3
- data/hiqbind_5k_v1/autodock_vina_full_v1/source_index.jsonAdded
- data/hiqbind_5k_v1/autodock_vina_full_v1/system_index.jsonAdded
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00008.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00029.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00036.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00048.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00049.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00065.ptAdded+3
- data/hiqbind_5k_v1/diffdock_full_v1/system_index.jsonAdded
- docs/DATASET_USAGE_ZH.mdAdded+198
57 unmodified lines5859606157 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdata/hiqbind_5k_v1/autodock_vina_full_v1/manifest.json filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# HiQBind 5K Compact Docking Graphs
本仓库发布 HiQBind 5K 蛋白–配体体系的两套已完成 docking baseline 图数据:DiffDock 和 AutoDock Vina。数据采用 `gnncp_compact_v1` 格式,可通过附带的 PyTorch Geometric loader 按需重建单个 pose 图,适用于 CQR-GNN 及其他 pose-level 图模型。
## 本次发布内容
| baseline | protein–ligand system | pose graph | shard | 数据目录约占空间 || --- | ---: | ---: | ---: | ---: || DiffDock | 4,979 | 97,988 | 98 | 49 GiB || AutoDock Vina | 4,887 | 85,824 | 88 | 44 GiB |
这里的 **system** 就是一个 protein–ligand pair;一个 system 最多包含 20 个 docking pose,因此一个 pose 对应一张 graph。部分 system 的有效 pose 少于 20 个,故 graph 总数不必等于 system 数乘以 20。
两个目录都已经完成严格校验(`status: complete`、`strict_validation: true`),构图 cutoff 为 6.0 Å。两方法共同覆盖 4,868 个 system;做直接方法对比时请使用该共同 system 集合,而不要假定两个目录的 system 完全相同。
仓库布局如下:
```textdata/hiqbind_5k_v1/ diffdock_full_v1/ autodock_vina_full_v1/code/compact_v1/docs/DATASET_USAGE_ZH.md```
`data/` 中的 shard 是内部紧凑存储格式,不能把它直接当成 PyG `Data` 列表加载。请使用 `code/compact_v1/compact_graph_dataset.py` 提供的 `CompactGraphDataset`。
完整中文使用说明、system 级划分示例、图字段定义与重建流程见 [docs/DATASET_USAGE_ZH.md](docs/DATASET_USAGE_ZH.md)。原始结构与模型的上游条款说明见 [NOTICE.md](NOTICE.md)。
## 快速开始
下载所需的一个方法及 reader:
```pythonfrom huggingface_hub import snapshot_download
snapshot_download( repo_id="liofoil/copuladock", repo_type="dataset", local_dir="copuladock", allow_patterns=[ "code/compact_v1/compact_graph_dataset.py", "data/hiqbind_5k_v1/diffdock_full_v1/**", ],)```
然后:
```pythonimport sysfrom pathlib import Path
root = Path("copuladock")sys.path.insert(0, str(root / "code" / "compact_v1"))from compact_graph_dataset import CompactGraphDataset
dataset = CompactGraphDataset( root / "data" / "hiqbind_5k_v1" / "diffdock_full_v1")graph = dataset[0]print(len(dataset), graph.x.shape)```
## 重要使用约束
- 划分训练、验证和测试集时,必须以 `system` 为单位;同一个 protein–ligand pair 的所有 pose 不能跨 split,否则会发生 pose-level leakage。- 该发布不包含原始 HiQBind PDB/SDF、原始 docking 输出或模型权重。它足以直接加载和训练 compact 图,但不能仅凭这些 shard 重建 docking 流程。- 本批 5K 是一个 operational docking cohort,并非 PLINDER split。若用于 PLINDER 研究,请将它作为流程验证数据,另按 PLINDER 的规则建立最终划分。- AutoDock Vina 和 DiffDock 的覆盖数低于初始 5,000,是因为少量个例未能产生可用 pose;这些 pair 没有被伪造或补齐。12345678910111213141516171819202122232425262728# compact_v1 construction and reader code
This directory contains the minimum code needed to read the released compact shards and to rebuild the same format from PDB docking poses.
## Read an existing release
Only `compact_graph_dataset.py` is required for normal training. It provides `CompactGraphDataset`, which opens tensor-only shard files lazily with `torch.load(..., mmap=True)` and reconstructs standard PyTorch Geometric `Data` objects.
## Build compact shards from PDB poses
Keep these three files in the same directory because the builder imports the other two by filename:
- `build_compact_v1_direct.py`- `build_graph_unified_enhanced.py`- `convert_to_compact_v1.py`
The direct builder expects a flat directory with one subdirectory per system containing `protein.pdb`, `ligand.pdb`, and predicted pose `.pdb` files. `materialize_hiqbind_gnncp.py` converts Docking Base common outputs to that layout through hard links.
`build_compact_v1_direct.sbatch` is an example Slurm wrapper only. Review and adapt account, partition, Python environment, paths, CPU count, and memory for your own cluster before use.
Run the bundled unit tests after changing the format code:
```bashpython -m unittest -v test_compact_graph_dataset.py test_build_compact_v1_direct.py```
See `../../docs/DATASET_USAGE_ZH.md` for the Chinese user guide.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700#!/usr/bin/env python3"""Build GNNCP compact_v1 shards directly from docking pose files.
Unlike ``build_graph_unified_enhanced.py``, this program never accumulates adataset-wide ``list[Data]`` and never writes a monolithic legacy ``.pt`` file.It discovers poses deterministically; each worker builds one source system andimmediately converts it to compact records. A single parent commits completedsystems in source order, then packs bounded collections of records intotensor-only shards.
The output directory is published atomically only after every selected systemhas been processed. Before publication, progress lives in a stable hidden``.<name>.building`` directory. ``--resume`` reuses completed systemcheckpoints and any pose graphs already built for the current system.
Examples--------Single-system Slurm smoke test::
python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_smoke \ --method protenix \ --system-id tnks2_lig_20 \ --max-poses-per-system 2
Full resumable build::
python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_protenix \ --method protenix \ --num-workers 4 \ --resume
Memory-bounded high-CPU build::
python build_compact_v1_direct.py \ --data-dir /path/to/docking_results \ --output-dir /path/to/compact_protenix \ --method protenix \ --system-workers 28 \ --num-workers 1 \ --memory-budget-gib 150 \ --resume"""
from __future__ import annotations
import argparseimport concurrent.futuresimport fcntlimport gcimport hashlibimport jsonimport mathimport multiprocessingimport osimport reimport shutilimport sysimport timeimport tracebackfrom collections import Counter, OrderedDictfrom contextlib import contextmanagerfrom dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Sequence
import torch
from build_graph_unified_enhanced import build_graph_enhanced, find_docking_posesfrom convert_to_compact_v1 import ( DYNAMIC_COLUMNS, FORMAT_NAME, SCHEMA_VERSION, STATIC_COLUMNS, build_system_record, graph_content_hashes, pack_shard,)
DOCKING_METHODS = ("protenix", "diffdock", "autodock_vina", "medusagraph")PROGRESS_VERSION = 1READY_CHECKPOINT_VERSION = 1
# ``build_graph_enhanced`` deliberately computes several dense SciPy distance# matrices. A single float64 N-by-N matrix occupies 8 * N**2 bytes; the# estimate below reserves room for roughly eight such matrices plus a fixed# parser/tensor overhead. It is intentionally an admission-control estimate,# not a statement about the serialized compact-record size._WORKER_FIXED_MEMORY_MIB = 2048_WORKER_DENSE_MEMORY_MULTIPLIER = 8
@dataclass(frozen=True)class PoseSpec: """One discovered pose and its stable pre-filter discovery index."""
source_graph_index: int system_id: str protein: Path ligand_native: Path ligand_pred: Path
@dataclass(frozen=True)class SystemSpec: """All selected poses belonging to one source system."""
ordinal: int system_id: str protein: Path ligand_native: Path poses: tuple[PoseSpec, ...]
@dataclass(frozen=True)class BuildConfig: data_dir: Path output_dir: Path method: str cutoff: float = 6.0 target_shard_mib: int = 512 num_workers: int = 1 system_workers: int = 1 memory_budget_gib: float | None = None strict: bool = True resume: bool = False on_error: str = "abort" max_systems: int | None = None max_poses_per_system: int | None = None include_systems: tuple[str, ...] = ()
GraphBuilder = Callable[..., Any]
def _natural_key(value: str) -> tuple[Any, ...]: """Natural, case-insensitive ordering (pose2 before pose10).""" return tuple( int(part) if part.isdigit() else part.casefold() for part in re.split(r"(\d+)", value) )
def _atomic_json(path: Path, payload: Mapping[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") 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()) os.replace(temporary, path)
def _atomic_torch_save(payload: Any, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") torch.save(payload, temporary) os.replace(temporary, path)
@contextmanagerdef _exclusive_build_lock(output_dir: Path): """Hold a non-blocking advisory lock for the complete build/publication.
The lock is a stable sidecar next to the output/staging directories rather than a file inside staging. Consequently, two ``--resume`` jobs cannot both enter the same staging directory. The zero-byte-ish sidecar is kept after exit so every future opener locks the same inode; a crashed process automatically releases its kernel lock. """ output_dir.parent.mkdir(parents=True, exist_ok=True) lock_path = output_dir.with_name(f".{output_dir.name}.build.lock") handle = lock_path.open("a+", encoding="utf-8") try: try: fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: raise RuntimeError( f"another direct compact build is already using {output_dir}; " f"lock: {lock_path}" ) from exc handle.seek(0) handle.truncate() handle.write( json.dumps( { "pid": os.getpid(), "slurm_job_id": os.environ.get("SLURM_JOB_ID"), "output_dir": str(output_dir), "acquired_utc": datetime.now(timezone.utc).isoformat(), } ) + "\n" ) handle.flush() os.fsync(handle.fileno()) yield lock_path finally: try: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) finally: handle.close()
def _relative_or_absolute(path: Path, root: Path) -> str: try: return str(path.relative_to(root)) except ValueError: return str(path)
def parse_args(argv: Sequence[str] | None = None) -> BuildConfig: parser = argparse.ArgumentParser( description=( "Build enhanced GNNCP graphs one system at a time and write " "compact_v1 shards directly." ) ) parser.add_argument("--data-dir", required=True, type=Path) parser.add_argument("--output-dir", required=True, type=Path) parser.add_argument("--method", required=True, choices=DOCKING_METHODS) parser.add_argument("--cutoff", type=float, default=6.0) parser.add_argument("--target-shard-mib", type=int, default=512) parser.add_argument( "--num-workers", type=int, default=1, help=( "Pose builders within one system. This must be 1 when " "--system-workers is greater than 1, so graph builders are never " "nested." ), ) parser.add_argument( "--system-workers", type=int, default=1, help=( "Independent source systems to build concurrently. The default 1 " "keeps the original sequential-system implementation." ), ) parser.add_argument( "--memory-budget-gib", type=float, default=None, help=( "Usable aggregate memory budget for --system-workers > 1. " "Workers are admitted by a conservative protein-size O(N^2) " "estimate; reserve node/parent memory outside this value." ), ) parser.add_argument( "--resume", action="store_true", help="Resume the stable hidden build directory after interruption.", ) parser.add_argument( "--on-error", choices=("abort", "skip-system"), default="abort", help="Never drops individual poses: skip-system drops the whole source system.", ) parser.add_argument( "--skip-strict-validation", action="store_true", help="Skip expensive redundant-field and edge-symmetry validation.", ) parser.add_argument("--max-systems", type=int, default=None) parser.add_argument("--max-poses-per-system", type=int, default=None) parser.add_argument( "--system-id", "--include-system", dest="include_systems", action="append", default=[], metavar="ID", help="Only build this source system ID; repeat to select multiple systems.", ) args = parser.parse_args(argv) return BuildConfig( data_dir=args.data_dir.expanduser().resolve(), output_dir=args.output_dir.expanduser().resolve(), method=args.method, cutoff=args.cutoff, target_shard_mib=args.target_shard_mib, num_workers=args.num_workers, system_workers=args.system_workers, memory_budget_gib=args.memory_budget_gib, strict=not args.skip_strict_validation, resume=args.resume, on_error=args.on_error, max_systems=args.max_systems, max_poses_per_system=args.max_poses_per_system, include_systems=tuple(args.include_systems), )
def _validate_config(config: BuildConfig) -> None: if not config.data_dir.is_dir(): raise FileNotFoundError(f"data directory not found: {config.data_dir}") if config.method not in DOCKING_METHODS: raise ValueError(f"unsupported docking method: {config.method}") if config.cutoff <= 0: raise ValueError("--cutoff must be positive") if config.target_shard_mib <= 0: raise ValueError("--target-shard-mib must be positive") if config.num_workers <= 0: raise ValueError("--num-workers must be positive") if config.system_workers <= 0: raise ValueError("--system-workers must be positive") if config.system_workers > 1 and config.num_workers != 1: raise ValueError( "--system-workers > 1 requires --num-workers=1; nested " "system/pose process pools are intentionally forbidden" ) if config.memory_budget_gib is not None and config.memory_budget_gib <= 0: raise ValueError("--memory-budget-gib must be positive") if config.system_workers > 1 and config.memory_budget_gib is None: raise ValueError( "--system-workers > 1 requires --memory-budget-gib so concurrent " "dense graph builders remain memory bounded" ) if config.max_systems is not None and config.max_systems <= 0: raise ValueError("--max-systems must be positive") if ( config.max_poses_per_system is not None and config.max_poses_per_system <= 0 ): raise ValueError("--max-poses-per-system must be positive") if config.output_dir == config.data_dir: raise ValueError("output directory must differ from the docking data directory")
def discover_systems(config: BuildConfig) -> List[SystemSpec]: """Discover, filter, and deterministically order source systems and poses.""" raw_poses = find_docking_poses(str(config.data_dir), config.method) grouped: MutableMapping[str, List[Mapping[str, str]]] = OrderedDict() for pose in sorted( raw_poses, key=lambda item: ( _natural_key(str(item["pdb_id"])), _natural_key(str(Path(item["ligand_pred"]))), ), ): grouped.setdefault(str(pose["pdb_id"]), []).append(pose)
requested = set(config.include_systems) if requested: missing = requested.difference(grouped) if missing: available = ", ".join(list(grouped)[:10]) raise ValueError( f"requested system IDs were not discovered: {sorted(missing)}; " f"first available IDs: {available}" ) grouped = OrderedDict((key, grouped[key]) for key in grouped if key in requested)
selected_items = list(grouped.items()) if config.max_systems is not None: selected_items = selected_items[: config.max_systems] if not selected_items: raise ValueError("no docking systems matched the selection")
systems: List[SystemSpec] = [] source_graph_index = 0 for ordinal, (system_id, raw_system_poses) in enumerate(selected_items): unique_by_path: Dict[Path, Mapping[str, str]] = {} for pose in raw_system_poses: unique_by_path[Path(pose["ligand_pred"]).resolve()] = pose ordered = [ unique_by_path[path] for path in sorted(unique_by_path, key=lambda value: _natural_key(str(value))) ] if config.max_poses_per_system is not None: ordered = ordered[: config.max_poses_per_system] if not ordered: continue
proteins = {Path(pose["protein"]).resolve() for pose in ordered} natives = {Path(pose["ligand_native"]).resolve() for pose in ordered} if len(proteins) != 1 or len(natives) != 1: raise ValueError( f"{system_id}: discovered multiple protein/native files in one system" ) protein = next(iter(proteins)) ligand_native = next(iter(natives)) pose_specs: List[PoseSpec] = [] for pose in ordered: ligand_pred = Path(pose["ligand_pred"]).resolve() if ligand_pred.suffix.lower() != ".pdb": raise ValueError( f"{system_id}: unsupported pose format {ligand_pred.suffix!r}: " f"{ligand_pred}. build_graph_enhanced currently requires PDB poses." ) pose_specs.append( PoseSpec( source_graph_index=source_graph_index, system_id=system_id, protein=protein, ligand_native=ligand_native, ligand_pred=ligand_pred, ) ) source_graph_index += 1 systems.append( SystemSpec( ordinal=ordinal, system_id=system_id, protein=protein, ligand_native=ligand_native, poses=tuple(pose_specs), ) ) if not systems: raise ValueError("no PDB poses remained after filtering") return systems
def _discovery_fingerprint(config: BuildConfig, systems: Sequence[SystemSpec]) -> str: """Hash data/format inputs while allowing safe scheduler changes on resume.
``num_workers``, ``system_workers`` and ``memory_budget_gib`` deliberately do not participate: they change only execution scheduling, not discovery, tensor content, ordering, or shard boundaries. This is what permits an existing sequential staging directory to resume with the adaptive cross-system scheduler. """ digest = hashlib.sha256() config_payload = { "format": FORMAT_NAME, "schema_version": SCHEMA_VERSION, "data_dir": str(config.data_dir), "method": config.method, "cutoff": config.cutoff, "target_shard_mib": config.target_shard_mib, "strict": config.strict, "on_error": config.on_error, "max_systems": config.max_systems, "max_poses_per_system": config.max_poses_per_system, "include_systems": sorted(config.include_systems), } digest.update(json.dumps(config_payload, sort_keys=True).encode("utf-8")) unique_paths = { path for system in systems for path in ( system.protein, system.ligand_native, *(pose.ligand_pred for pose in system.poses), ) } for path in sorted(unique_paths, key=str): stat = path.stat() digest.update(str(path).encode("utf-8")) digest.update(stat.st_size.to_bytes(8, "little", signed=False)) digest.update(stat.st_mtime_ns.to_bytes(8, "little", signed=False)) return digest.hexdigest()
def _default_progress(fingerprint: str) -> Dict[str, Any]: return { "progress_version": PROGRESS_VERSION, "fingerprint": fingerprint, "next_system_index": 0, "next_shard_index": 0, "pending": [], "successful_source_systems": 0, "successful_graphs": 0, "compact_storage_groups": 0, "skipped_source_systems": 0, }
def _pose_graph_path(work_dir: Path, local_pose_index: int) -> Path: return work_dir / f"pose_{local_pose_index:04d}.pt"
def _count_nonhydrogen_pdb_atoms(path: Path) -> int: """Return a cheap, conservative node-count proxy without MDAnalysis.
The graph builder selects ``not name H*``. PDB columns are sufficient for scheduling: over-counting an unusual hydrogen name only makes admission more conservative, whereas under-counting a large protein could cause an avoidable OOM. """ count = 0 with path.open("r", encoding="utf-8", errors="replace") as handle: for line in handle: if not line.startswith(("ATOM ", "HETATM")): continue atom_name = line[12:16].strip().upper() element = line[76:78].strip().upper() if atom_name.startswith("H") or element == "H": continue count += 1 return count
def estimate_system_memory_mib(system: SystemSpec) -> int: """Estimate one system worker's peak working set for admission control.
This follows the actual graph-builder scaling, which is dominated by dense float64 ``cdist`` matrices over protein plus predicted-ligand atoms. The native ligand is parsed too, so use the larger of the native and predicted ligand atom counts as a small conservative adjustment. The estimate is deliberately independent of pose count: cross-system mode builds poses sequentially in each worker and never nests a pose process pool. """ protein_atoms = _count_nonhydrogen_pdb_atoms(system.protein) ligand_atoms = max( _count_nonhydrogen_pdb_atoms(system.ligand_native), _count_nonhydrogen_pdb_atoms(system.poses[0].ligand_pred), ) n_nodes = max(1, protein_atoms + ligand_atoms) one_dense_matrix_mib = (8.0 * n_nodes * n_nodes) / (1024.0 * 1024.0) estimate = ( _WORKER_FIXED_MEMORY_MIB + _WORKER_DENSE_MEMORY_MULTIPLIER * one_dense_matrix_mib ) return max(1, int(math.ceil(estimate)))
def _ready_checkpoint_path(stage_dir: Path, system_index: int) -> Path: return ( stage_dir / ".build_state" / "ready" / f"system_{system_index:08d}.pt" )
def _ready_error_path(stage_dir: Path, system_index: int) -> Path: return ( stage_dir / ".build_state" / "ready_errors" / f"system_{system_index:08d}.json" )
def _validate_ready_records( payload: Any, system_index: int, system: SystemSpec,) -> List[Dict[str, Any]]: """Validate a worker-produced durable record before the single writer uses it.""" if not isinstance(payload, Mapping): raise ValueError("ready payload is not a mapping") if payload.get("ready_checkpoint_version") != READY_CHECKPOINT_VERSION: raise ValueError("incompatible ready checkpoint version") if int(payload.get("source_system_index", -1)) != system_index: raise ValueError("ready checkpoint system index does not match its filename") if str(payload.get("source_system_id", "")) != system.system_id: raise ValueError("ready checkpoint system ID does not match discovery") records = payload.get("records") if not isinstance(records, list) or not records: raise ValueError("ready checkpoint has no compact records")
expected_indices = sorted(pose.source_graph_index for pose in system.poses) actual_indices: List[int] = [] for record in records: if not isinstance(record, Mapping): raise ValueError("ready checkpoint contains a non-mapping record") if str(record.get("_source_system_id", "")) != system.system_id: raise ValueError("ready checkpoint record has the wrong source system ID") source_graph_index = record.get("source_graph_index") if not isinstance(source_graph_index, torch.Tensor): raise ValueError("ready checkpoint record lacks source_graph_index") actual_indices.extend(int(value) for value in source_graph_index.tolist()) if sorted(actual_indices) != expected_indices: raise ValueError("ready checkpoint pose indices do not match discovery") return list(records)
def _load_ready_records( stage_dir: Path, system_index: int, system: SystemSpec, *, discard_invalid: bool = True,) -> List[Dict[str, Any]] | None: """Load a valid ready record, deleting only corrupt/stale local scratch.""" path = _ready_checkpoint_path(stage_dir, system_index) if not path.is_file(): return None try: payload = torch.load(path, map_location="cpu", weights_only=False) return _validate_ready_records(payload, system_index, system) except Exception as error: if discard_invalid: try: path.unlink() except FileNotFoundError: pass print( f"[ready-rebuild] {system.system_id}: discarded invalid ready " f"checkpoint ({type(error).__name__}: {error})", file=sys.stderr, flush=True, ) return None raise
def _load_ready_error( stage_dir: Path, system_index: int, system: SystemSpec,) -> Dict[str, Any] | None: """Load a durable skip-system outcome produced by a parallel worker.""" path = _ready_error_path(stage_dir, system_index) if not path.is_file(): return None try: with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) if ( int(payload.get("system_index", -1)) != system_index or str(payload.get("system_id", "")) != system.system_id ): raise ValueError("ready error does not match discovered system") return payload except Exception as error: try: path.unlink() except FileNotFoundError: pass print( f"[ready-rebuild] {system.system_id}: discarded invalid ready error " f"({type(error).__name__}: {error})", file=sys.stderr, flush=True, ) return None
def _build_pose_to_file( pose_payload: Mapping[str, Any], cutoff: float, output_path: str,) -> tuple[bool, str]: """Process-pool worker. Each result is committed by atomic rename.""" try: graph = build_graph_enhanced( protein_pdb=str(pose_payload["protein"]), ligand_pred_pdb=str(pose_payload["ligand_pred"]), ligand_native_pdb=str(pose_payload["ligand_native"]), cutoff=cutoff, use_enhanced_features=True, ) _atomic_torch_save(graph, Path(output_path)) return True, output_path except Exception: return False, traceback.format_exc()
def _validate_reusable_pose_file(path: Path) -> bool: try: graph = torch.load(path, map_location="cpu", weights_only=False) valid = ( hasattr(graph, "x") and isinstance(graph.x, torch.Tensor) and graph.x.ndim == 2 and graph.x.shape[1] == 82 ) del graph return bool(valid) except Exception: return False
def build_pose_graphs( system: SystemSpec, work_dir: Path, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced,) -> List[Any]: """Build/reuse every pose in one source system and return them in order.""" work_dir.mkdir(parents=True, exist_ok=True) missing: List[tuple[int, PoseSpec, Path]] = [] for local_index, pose in enumerate(system.poses): path = _pose_graph_path(work_dir, local_index) if path.is_file() and _validate_reusable_pose_file(path): continue if path.exists(): path.unlink() missing.append((local_index, pose, path))
if config.num_workers > 1 and graph_builder is not build_graph_enhanced: raise ValueError("a custom graph_builder is only supported with num_workers=1")
errors: List[str] = [] if config.num_workers == 1: for local_index, pose, path in missing: try: graph = graph_builder( protein_pdb=str(pose.protein), ligand_pred_pdb=str(pose.ligand_pred), ligand_native_pdb=str(pose.ligand_native), cutoff=config.cutoff, use_enhanced_features=True, ) _atomic_torch_save(graph, path) del graph except Exception: errors.append( f"pose {local_index} ({pose.ligand_pred}):\n" f"{traceback.format_exc()}" ) break elif missing: payloads = [ ( { "protein": str(pose.protein), "ligand_pred": str(pose.ligand_pred), "ligand_native": str(pose.ligand_native), }, config.cutoff, str(path), ) for _, pose, path in missing ] with concurrent.futures.ProcessPoolExecutor( max_workers=config.num_workers ) as executor: futures = [executor.submit(_build_pose_to_file, *payload) for payload in payloads] for (local_index, pose, _), future in zip(missing, futures): ok, detail = future.result() if not ok: errors.append( f"pose {local_index} ({pose.ligand_pred}):\n{detail}" )
if errors: raise RuntimeError( f"{system.system_id}: {len(errors)} pose build(s) failed; " "the source system was not partially committed.\n" + "\n".join(errors[:3]) )
graphs: List[Any] = [] for local_index in range(len(system.poses)): path = _pose_graph_path(work_dir, local_index) graphs.append(torch.load(path, map_location="cpu", weights_only=False)) return graphs
def compact_system_records( system: SystemSpec, graphs: Sequence[Any], strict: bool, data_root: Path,) -> List[Dict[str, Any]]: """Convert one source system, splitting only when exact static content differs.""" if len(graphs) != len(system.poses): raise ValueError( f"{system.system_id}: graph count {len(graphs)} != pose count {len(system.poses)}" ) grouped: MutableMapping[str, List[int]] = OrderedDict() native_hashes: Dict[str, str] = {} for local_index, graph in enumerate(graphs): native_hash, shared_hash = graph_content_hashes(graph) grouped.setdefault(shared_hash, []).append(local_index) previous = native_hashes.setdefault(shared_hash, native_hash) if previous != native_hash: raise RuntimeError("shared-content SHA-256 collision detected")
records: List[Dict[str, Any]] = [] multiple_groups = len(grouped) > 1 for shared_hash, local_indices in grouped.items(): storage_id = ( f"{system.system_id}__{shared_hash[:12]}" if multiple_groups else system.system_id ) descriptor = { "system_id": storage_id, "source_label": system.system_id, "source_label_counts": {system.system_id: len(local_indices)}, "native_hash": native_hashes[shared_hash], "shared_hash": shared_hash, "graph_indices": local_indices, } record = build_system_record(graphs, descriptor, strict=strict) global_indices = [ system.poses[local_index].source_graph_index for local_index in local_indices ] record["source_graph_index"] = torch.tensor(global_indices, dtype=torch.int64) record["_source_system_id"] = system.system_id record["_source_pose_paths"] = [ _relative_or_absolute( system.poses[local_index].ligand_pred, data_root, ) for local_index in local_indices ] records.append(record) return records
def _build_system_to_ready_checkpoint( system_index: int, system: SystemSpec, stage_dir: str, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced,) -> None: """Build one source system in a fresh process and atomically persist it.
This worker never writes global progress, shard files, or the final output. Its only durable success artifact is a per-system ready checkpoint; the parent is the sole process allowed to consume it in source order. A fresh process per source system is intentional: dense NumPy/SciPy allocations from a large protein are returned to the OS when that process exits. """ stage = Path(stage_dir) ready_path = _ready_checkpoint_path(stage, system_index) if _load_ready_records(stage, system_index, system) is not None: return
work_dir = stage / ".build_state" / "work" / f"system_{system_index:08d}" try: # Cross-system scheduling is validated to require one pose worker. A # replace makes that invariant explicit even if this helper is called # directly in a future test. worker_config = replace(config, num_workers=1, system_workers=1) graphs = build_pose_graphs( system, work_dir, worker_config, graph_builder=graph_builder, ) records = compact_system_records( system, graphs, strict=config.strict, data_root=config.data_dir, ) payload = { "ready_checkpoint_version": READY_CHECKPOINT_VERSION, "source_system_index": system_index, "source_system_id": system.system_id, "records": records, } _atomic_torch_save(payload, ready_path) del payload, records, graphs if work_dir.is_dir(): shutil.rmtree(work_dir) gc.collect() except Exception as error: if config.on_error != "skip-system": raise error_payload = { "system_index": system_index, "system_id": system.system_id, "num_poses": len(system.poses), "error_type": type(error).__name__, "error": str(error), "traceback": traceback.format_exc(), } _atomic_json(_ready_error_path(stage, system_index), error_payload)
def _parallel_system_worker_main( system_index: int, system: SystemSpec, stage_dir: str, config: BuildConfig, graph_builder: GraphBuilder = build_graph_enhanced,) -> None: """Top-level multiprocessing target; it must remain pickle/fork friendly.""" _build_system_to_ready_checkpoint( system_index, system, stage_dir, config, graph_builder=graph_builder, )
def _record_manifest_entry(record: Mapping[str, Any]) -> Dict[str, Any]: return { "system_id": record["_system_id"], "source_label": record["_source_label"], "source_system_id": record["_source_system_id"], "source_label_counts": record["_source_label_counts"], "native_hash": record["_native_hash"], "shared_hash": record["_shared_hash"], "num_graphs": record["_n_poses"], "num_nodes": record["_n_nodes"], "num_protein_nodes": record["_n_protein"], "num_ligand_nodes": record["_n_ligand"], "source_graph_indices": record["source_graph_index"].tolist(), "source_pose_paths": record["_source_pose_paths"], }
def _flush_pending( stage_dir: Path, progress_path: Path, progress: Dict[str, Any],) -> None: pending = list(progress["pending"]) if not pending: return records: List[Dict[str, Any]] = [] checkpoint_paths: List[Path] = [] for entry in pending: checkpoint_path = stage_dir / entry["path"] checkpoint_paths.append(checkpoint_path) payload = torch.load(checkpoint_path, map_location="cpu", weights_only=False) if not isinstance(payload, list) or not payload: raise ValueError(f"invalid system checkpoint: {checkpoint_path}") records.extend(payload)
shard_index = int(progress["next_shard_index"]) relative_path = f"shards/shard_{shard_index:05d}.pt" shard_path = stage_dir / relative_path packed = pack_shard(records) _atomic_torch_save(packed, shard_path) size_bytes = shard_path.stat().st_size metadata = { "path": relative_path, "num_graphs": int(packed["pose_system"].numel()), "num_systems": len(records), "num_source_systems": len( {str(record["_source_system_id"]) for record in records} ), "size_bytes": size_bytes, "systems": [_record_manifest_entry(record) for record in records], } meta_path = ( stage_dir / ".build_state" / "shard_metadata" / f"shard_{shard_index:05d}.json" ) _atomic_json(meta_path, metadata)
progress["pending"] = [] progress["next_shard_index"] = shard_index + 1 _atomic_json(progress_path, progress) for checkpoint_path in checkpoint_paths: if checkpoint_path.is_file(): checkpoint_path.unlink() del packed, records gc.collect() print( f"[shard] {relative_path}: {metadata['num_source_systems']} source systems, " f"{metadata['num_systems']} storage groups, {metadata['num_graphs']} poses, " f"{size_bytes / 2**20:.1f} MiB", flush=True, )
def _commit_system_records( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], system_index: int, system: SystemSpec, records: Sequence[Mapping[str, Any]], target_bytes: int, total_systems: int,) -> None: """Commit one fully-built source system in deterministic source order.
Only the parent process calls this function. The ordering and state transitions intentionally match the original sequential loop so existing staging directories retain their resume and shard semantics. """ if int(progress["next_system_index"]) != system_index: raise RuntimeError( f"out-of-order system commit: expected {progress['next_system_index']}, " f"got {system_index}" ) if not records: raise ValueError(f"{system.system_id}: refusing to commit no records") record_bytes = sum(int(record["_tensor_bytes"]) for record in records) pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"]) if progress["pending"] and pending_bytes + record_bytes > target_bytes: _flush_pending(stage_dir, progress_path, progress)
checkpoint_rel = f".build_state/checkpoints/system_{system_index:08d}.pt" checkpoint_path = stage_dir / checkpoint_rel _atomic_torch_save(list(records), checkpoint_path) progress["pending"].append( { "path": checkpoint_rel, "tensor_bytes": record_bytes, "source_system_index": system_index, "source_system_id": system.system_id, } ) progress["next_system_index"] = system_index + 1 progress["successful_source_systems"] += 1 progress["successful_graphs"] += len(system.poses) progress["compact_storage_groups"] += len(records) _atomic_json(progress_path, progress) print( f"[system] {system_index + 1}/{total_systems} " f"{system.system_id}: {len(system.poses)} poses, {len(records)} storage " f"group(s), {record_bytes / 2**20:.1f} MiB", flush=True, )
def _flush_pending_if_full( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], target_bytes: int,) -> None: pending_bytes = sum(int(item["tensor_bytes"]) for item in progress["pending"]) if pending_bytes >= target_bytes: _flush_pending(stage_dir, progress_path, progress)
def _commit_skipped_system( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], system_index: int, system: SystemSpec, error_payload: Mapping[str, Any],) -> None: """Record a whole-system failure without disturbing deterministic order.""" if int(progress["next_system_index"]) != system_index: raise RuntimeError( f"out-of-order skipped-system commit: expected " f"{progress['next_system_index']}, got {system_index}" ) error_path = ( stage_dir / ".build_state" / "errors" / f"system_{system_index:08d}.json" ) _atomic_json(error_path, dict(error_payload)) progress["next_system_index"] = system_index + 1 progress["skipped_source_systems"] += 1 _atomic_json(progress_path, progress) print( f"[skip-system] {system.system_id}: " f"{error_payload.get('error_type', 'Error')}: {error_payload.get('error', '')}", file=sys.stderr, flush=True, )
def _load_shard_metadata(stage_dir: Path, count: int) -> List[Dict[str, Any]]: result = [] for shard_index in range(count): path = ( stage_dir / ".build_state" / "shard_metadata" / f"shard_{shard_index:05d}.json" ) with path.open("r", encoding="utf-8") as handle: result.append(json.load(handle)) return result
def _load_errors(stage_dir: Path) -> List[Dict[str, Any]]: error_dir = stage_dir / ".build_state" / "errors" if not error_dir.is_dir(): return [] result = [] for path in sorted(error_dir.glob("system_*.json")): with path.open("r", encoding="utf-8") as handle: result.append(json.load(handle)) return result
def _source_index_payload( config: BuildConfig, systems: Sequence[SystemSpec], successful_source_indices: set[int], errors: Sequence[Mapping[str, Any]],) -> Dict[str, Any]: error_by_id = {str(item["system_id"]): item for item in errors} source_systems = [] for system in systems: successful = all( pose.source_graph_index in successful_source_indices for pose in system.poses ) source_systems.append( { "system_id": system.system_id, "status": "complete" if successful else "skipped", "protein": _relative_or_absolute(system.protein, config.data_dir), "ligand_native": _relative_or_absolute( system.ligand_native, config.data_dir ), "source_graph_indices": [ pose.source_graph_index for pose in system.poses ], "poses": [ _relative_or_absolute(pose.ligand_pred, config.data_dir) for pose in system.poses ], "error": error_by_id.get(system.system_id), } ) return { "data_dir": str(config.data_dir), "method": config.method, "systems": source_systems, }
def _finish_dataset( config: BuildConfig, stage_dir: Path, progress: Mapping[str, Any], systems: Sequence[SystemSpec],) -> Dict[str, Any]: shard_count = int(progress["next_shard_index"]) if shard_count == 0: raise RuntimeError("no systems were built successfully; refusing empty dataset") shards = _load_shard_metadata(stage_dir, shard_count)
placements: List[tuple[int, int, int]] = [] compact_bytes = 0 for shard_index, shard_meta in enumerate(shards): shard_path = stage_dir / str(shard_meta["path"]) shard = torch.load( shard_path, map_location="cpu", mmap=True, weights_only=True, ) source_indices = shard["source_graph_index"].tolist() placements.extend( (int(source_index), shard_index, local_pose) for local_pose, source_index in enumerate(source_indices) ) compact_bytes += int(shard_meta["size_bytes"]) del shard placements.sort(key=lambda item: item[0]) successful_source_indices = [item[0] for item in placements] if len(successful_source_indices) != len(set(successful_source_indices)): raise RuntimeError("duplicate source_graph_index detected across shards") graph_map = [[item[1], item[2]] for item in placements]
system_by_source_index = { pose.source_graph_index: system.system_id for system in systems for pose in system.poses } graph_to_system = [ system_by_source_index[source_index] for source_index in successful_source_indices ] counts = Counter(graph_to_system) system_index = { "graph_to_system": graph_to_system, "n_graphs": len(graph_to_system), "n_systems": len(counts), "systems": sorted(counts, key=_natural_key), "system_counts": dict(sorted(counts.items(), key=lambda item: _natural_key(item[0]))), "source_graph_indices": successful_source_indices, "note": ( "Labels are original source system IDs. Exact-content storage-group " "splits do not change graph_to_system." ), } _atomic_json(stage_dir / "system_index.json", system_index)
errors = _load_errors(stage_dir) source_index = _source_index_payload( config, systems, set(successful_source_indices), errors, ) _atomic_json(stage_dir / "source_index.json", source_index)
compact_systems = sum(int(shard["num_systems"]) for shard in shards) manifest: Dict[str, Any] = { "format": FORMAT_NAME, "schema_version": SCHEMA_VERSION, "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), "method": config.method, "cutoff": config.cutoff, "source": { "data_dir": str(config.data_dir), "mode": "direct_from_docking_poses", "source_index": "source_index.json", "system_index": "system_index.json", "discovered_source_systems": len(systems), "discovered_poses": sum(len(system.poses) for system in systems), "skipped_source_systems": int(progress["skipped_source_systems"]), }, "grouping": { "split_label": "original_source_system_id", "storage_mode": "exact_shared_content_hash_within_source_system", "authoritative_storage_key": ( "sha256(exact float32 y_grt + node partition + " "x[:,0:34] + x[:,61:71])" ), "storage_splits_do_not_change_system_index": True, }, "features": { "full_dimension": 82, "dtype": "float32", "static_dimension": len(STATIC_COLUMNS), "static_columns": list(STATIC_COLUMNS), "dynamic_dimension": len(DYNAMIC_COLUMNS), "dynamic_columns": list(DYNAMIC_COLUMNS), }, "edges": { "index_dtype_on_disk": "int32", "stored_direction": "upper_triangle_src_lt_dst", "protein_protein_scope": "once_per_storage_group", "non_protein_protein_scope": "once_per_pose", "edge_attr": "derived_from_float32_coordinates_and_endpoint_types", }, "derived_fields": [ "pos", "is_protein", "y_true", "y_pred", "y_grt", "edge_index_reverse_direction", "edge_attr", "num_nodes", ], "n_graphs": len(graph_map), "n_systems": compact_systems, "n_source_systems": int(progress["successful_source_systems"]), "n_shards": len(shards), "graph_map": graph_map, "shards": shards, "size": {"compact_shard_bytes": compact_bytes}, "strict_validation": config.strict, "direct_builder": { "target_shard_mib": config.target_shard_mib, "resume_fingerprint": progress["fingerprint"], "on_error": config.on_error, }, } _atomic_json(stage_dir / "manifest.json", manifest) return manifest
@dataclassclass _RunningSystemWorker: process: Any estimated_memory_mib: int
def _ready_outcome_kind( stage_dir: Path, system_index: int, system: SystemSpec,) -> str | None: """Return a validated durable worker outcome without retaining tensors.""" records = _load_ready_records(stage_dir, system_index, system) if records is not None: del records return "success" error = _load_ready_error(stage_dir, system_index, system) if error is not None: return "skipped" return None
def _unlink_if_exists(path: Path) -> None: try: path.unlink() except FileNotFoundError: pass
def _commit_ready_systems_in_order( stage_dir: Path, progress_path: Path, progress: Dict[str, Any], systems: Sequence[SystemSpec], target_bytes: int, submitted: set[int],) -> int: """Consume only the next contiguous ready outcomes into the global writer.""" committed = 0 while int(progress["next_system_index"]) < len(systems): system_index = int(progress["next_system_index"]) system = systems[system_index] records = _load_ready_records(stage_dir, system_index, system) if records is not None: _commit_system_records( stage_dir, progress_path, progress, system_index, system, records, target_bytes, len(systems), ) _flush_pending_if_full(stage_dir, progress_path, progress, target_bytes) del records _unlink_if_exists(_ready_checkpoint_path(stage_dir, system_index)) # A prior interrupted retry can leave an obsolete skip artifact. _unlink_if_exists(_ready_error_path(stage_dir, system_index)) submitted.discard(system_index) committed += 1 continue
error_payload = _load_ready_error(stage_dir, system_index, system) if error_payload is not None: _commit_skipped_system( stage_dir, progress_path, progress, system_index, system, error_payload, ) _unlink_if_exists(_ready_error_path(stage_dir, system_index)) submitted.discard(system_index) committed += 1 continue break if committed: gc.collect() return committed
def _next_unscheduled_system_index( stage_dir: Path, progress: Mapping[str, Any], systems: Sequence[SystemSpec], submitted: set[int],) -> int | None: """Find the earliest source system not already running or durably ready.""" start = int(progress["next_system_index"]) for system_index in range(start, len(systems)): if system_index in submitted: continue outcome = _ready_outcome_kind(stage_dir, system_index, systems[system_index]) if outcome is not None: submitted.add(system_index) continue return system_index return None
def _terminate_running_workers(running: Mapping[int, _RunningSystemWorker]) -> None: """Best-effort cleanup when the parent aborts before workers finish.""" for worker in running.values(): if worker.process.is_alive(): worker.process.terminate() for worker in running.values(): worker.process.join()
def _run_parallel_system_build( config: BuildConfig, stage_dir: Path, progress_path: Path, progress: Dict[str, Any], systems: Sequence[SystemSpec], *, graph_builder: GraphBuilder,) -> None: """Build systems in memory-bounded fresh processes, then commit in order.
Workers write only their own ready files. The parent alone updates progress/checkpoints/shards, so a completion-order race cannot change source_graph_index, graph_map, or shard membership. Fresh processes also prevent a large system's NumPy allocator high-water mark from becoming a hidden baseline for later small systems. """ if config.system_workers <= 1: raise ValueError("parallel system build requires --system-workers > 1") if config.num_workers != 1: raise ValueError("parallel system build requires --num-workers=1") if config.memory_budget_gib is None: raise ValueError("parallel system build requires --memory-budget-gib")
ready_dir = stage_dir / ".build_state" / "ready" ready_error_dir = stage_dir / ".build_state" / "ready_errors" ready_dir.mkdir(parents=True, exist_ok=True) ready_error_dir.mkdir(parents=True, exist_ok=True)
target_bytes = config.target_shard_mib * 1024 * 1024 budget_mib = int(math.floor(config.memory_budget_gib * 1024.0)) estimates = [estimate_system_memory_mib(system) for system in systems] too_large = [ (system.system_id, estimate) for system, estimate in zip(systems, estimates) if estimate > budget_mib ] if too_large: first_id, first_mib = too_large[0] raise ValueError( f"{len(too_large)} system(s) exceed the usable memory budget; first " f"{first_id} is estimated at {first_mib / 1024.0:.1f} GiB versus " f"{budget_mib / 1024.0:.1f} GiB. Increase --memory-budget-gib or " "build those systems in a larger-memory allocation." )
print( f"system workers: {config.system_workers} (one pose builder each)", flush=True, ) print( f"memory budget: {budget_mib / 1024.0:.1f} GiB usable; estimates " f"{min(estimates) / 1024.0:.1f}-{max(estimates) / 1024.0:.1f} GiB/system", flush=True, )
context = multiprocessing.get_context() running: Dict[int, _RunningSystemWorker] = {} submitted: set[int] = set() in_flight_mib = 0
try: while int(progress["next_system_index"]) < len(systems): _commit_ready_systems_in_order( stage_dir, progress_path, progress, systems, target_bytes, submitted, )
made_submission = False while len(running) < config.system_workers: system_index = _next_unscheduled_system_index( stage_dir, progress, systems, submitted, ) if system_index is None: break estimate_mib = estimates[system_index] if in_flight_mib + estimate_mib > budget_mib: break system = systems[system_index] process = context.Process( target=_parallel_system_worker_main, args=( system_index, system, str(stage_dir), config, graph_builder, ), name=f"compact-system-{system_index:05d}", ) process.start() running[system_index] = _RunningSystemWorker(process, estimate_mib) submitted.add(system_index) in_flight_mib += estimate_mib made_submission = True print( f"[schedule] {system_index + 1}/{len(systems)} " f"{system.system_id}: estimate {estimate_mib / 1024.0:.1f} GiB; " f"in flight {len(running)}/{config.system_workers}, " f"{in_flight_mib / 1024.0:.1f}/{budget_mib / 1024.0:.1f} GiB", flush=True, )
reaped = False for system_index, worker in list(running.items()): if worker.process.is_alive(): continue worker.process.join() exit_code = worker.process.exitcode del running[system_index] in_flight_mib -= worker.estimated_memory_mib reaped = True if system_index < int(progress["next_system_index"]): # The parent already consumed this worker's atomically # written ready artifact while it was doing final cleanup. # The artifact is intentionally gone by the time the child # exits, so do not require it a second time. continue outcome = _ready_outcome_kind( stage_dir, system_index, systems[system_index] ) if exit_code != 0: raise RuntimeError( f"parallel worker for {systems[system_index].system_id} " f"exited with status {exit_code}; no global progress was " "committed for that system" ) if outcome is None: raise RuntimeError( f"parallel worker for {systems[system_index].system_id} " "exited successfully without a ready checkpoint or error" )
if int(progress["next_system_index"]) >= len(systems): # A child may have written its ready file before completing # scratch cleanup. Join every such child before publishing or # removing .build_state so it cannot race the final rename. if not running: break if not reaped: time.sleep(0.1) continue if not made_submission and not reaped: # Never spin on a full memory budget while a worker is active. # A short polling interval also lets Slurm SIGTERM interrupt # promptly, leaving only atomically committed ready artifacts. time.sleep(0.1) except BaseException: _terminate_running_workers(running) raise
def _run_locked( config: BuildConfig, *, graph_builder: GraphBuilder = build_graph_enhanced,) -> Dict[str, Any]: """Implementation entered only while the output sidecar lock is held.""" _validate_config(config) if config.output_dir.exists(): raise FileExistsError( f"refusing to overwrite existing output directory: {config.output_dir}" ) stage_dir = config.output_dir.with_name(f".{config.output_dir.name}.building") if stage_dir.exists() and not config.resume: raise FileExistsError( f"incomplete build exists: {stage_dir}; pass --resume or move it aside" )
systems = discover_systems(config) fingerprint = _discovery_fingerprint(config, systems) progress_path = stage_dir / ".build_state" / "progress.json" if stage_dir.exists() and (stage_dir / "manifest.json").is_file(): os.replace(stage_dir, config.output_dir) print(f"published previously completed build: {config.output_dir}", flush=True) with (config.output_dir / "manifest.json").open("r", encoding="utf-8") as handle: return json.load(handle)
if progress_path.is_file(): with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) if progress.get("progress_version") != PROGRESS_VERSION: raise ValueError("incompatible direct-builder progress version") if progress.get("fingerprint") != fingerprint: raise ValueError( "resume fingerprint changed: inputs or storage-affecting options differ" ) else: if stage_dir.exists() and any(stage_dir.iterdir()): raise ValueError( f"{stage_dir} exists without a valid progress file; move it aside" ) (stage_dir / "shards").mkdir(parents=True, exist_ok=True) (stage_dir / ".build_state" / "checkpoints").mkdir(parents=True, exist_ok=True) (stage_dir / ".build_state" / "work").mkdir(parents=True, exist_ok=True) progress = _default_progress(fingerprint) _atomic_json(progress_path, progress)
print(f"data: {config.data_dir}", flush=True) print(f"output: {config.output_dir}", flush=True) print(f"staging: {stage_dir}", flush=True) print(f"systems: {len(systems)}", flush=True) print(f"poses: {sum(len(system.poses) for system in systems)}", flush=True) print(f"resume at: {progress['next_system_index']}", flush=True) print(f"pose workers/system: {config.num_workers}", flush=True) print(f"system workers: {config.system_workers}", flush=True) if config.memory_budget_gib is not None: print(f"memory budget: {config.memory_budget_gib:.1f} GiB usable", flush=True) print(f"strict: {config.strict}", flush=True)
target_bytes = config.target_shard_mib * 1024 * 1024 if config.system_workers > 1: _run_parallel_system_build( config, stage_dir, progress_path, progress, systems, graph_builder=graph_builder, ) else: for system_index in range(int(progress["next_system_index"]), len(systems)): system = systems[system_index] work_dir = ( stage_dir / ".build_state" / "work" / f"system_{system_index:08d}" ) committed = False try: graphs = build_pose_graphs( system, work_dir, config, graph_builder=graph_builder, ) records = compact_system_records( system, graphs, strict=config.strict, data_root=config.data_dir, ) _commit_system_records( stage_dir, progress_path, progress, system_index, system, records, target_bytes, len(systems), ) committed = True _flush_pending_if_full( stage_dir, progress_path, progress, target_bytes ) del graphs, records if work_dir.is_dir(): shutil.rmtree(work_dir) gc.collect() except Exception as error: if committed: # The durable checkpoint/progress update succeeded. Do not # reinterpret a later scratch-cleanup failure as a skipped # source system. raise if config.on_error == "abort": raise error_payload = { "system_index": system_index, "system_id": system.system_id, "num_poses": len(system.poses), "error_type": type(error).__name__, "error": str(error), "traceback": traceback.format_exc(), } _commit_skipped_system( stage_dir, progress_path, progress, system_index, system, error_payload, )
_flush_pending(stage_dir, progress_path, progress) manifest = _finish_dataset(config, stage_dir, progress, systems) os.replace(stage_dir, config.output_dir) state_dir = config.output_dir / ".build_state" if state_dir.is_dir(): shutil.rmtree(state_dir) print( f"complete: {config.output_dir / 'manifest.json'} " f"({manifest['n_graphs']} graphs, {manifest['n_source_systems']} source " f"systems, {manifest['n_shards']} shards)", flush=True, ) return manifest
def run( config: BuildConfig, *, graph_builder: GraphBuilder = build_graph_enhanced,) -> Dict[str, Any]: """Run a direct compact build under an output-directory exclusive lock.
The injectable graph builder is intentionally only for small CPU tests. Production CLI calls always use ``build_graph_enhanced``. """ with _exclusive_build_lock(config.output_dir): return _run_locked(config, graph_builder=graph_builder)
def main(argv: Sequence[str] | None = None) -> int: config = parse_args(argv) run(config) return 0
if __name__ == "__main__": try: raise SystemExit(main()) except Exception as error: print(f"ERROR: {error}", file=sys.stderr, flush=True) raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130#!/bin/bash# Build compact_v1 directly from docking PDB poses.## Full build:# sbatch --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/compact,METHOD=protenix \# build_compact_v1_direct.sbatch## High-CPU adaptive build (one fresh process per source system; no nested pose# pools):# sbatch --cpus-per-task=32 --mem=192G --time=24:00:00 \# --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/compact,METHOD=protenix,SYSTEM_WORKERS=28,NUM_WORKERS=1,MEMORY_BUDGET_GIB=150 \# build_compact_v1_direct.sbatch## One-system smoke test:# sbatch --export=ALL,DATA_DIR=/path/to/poses,OUTPUT_DIR=/path/to/smoke,METHOD=protenix,SYSTEM_ID=tnks2_lig_20,MAX_POSES=2 \# build_compact_v1_direct.sbatch
#SBATCH --account=bghp-delta-cpu#SBATCH --partition=cpu#SBATCH --nodes=1#SBATCH --ntasks-per-node=1#SBATCH --cpus-per-task=8#SBATCH --mem=96G#SBATCH --time=24:00:00#SBATCH --job-name=build_compact#SBATCH --output=/work/nvme/bghp/hhao/gnncp/system_split_code/build_compact_%j.out#SBATCH --error=/work/nvme/bghp/hhao/gnncp/system_split_code/build_compact_%j.err#SBATCH --open-mode=append#SBATCH --requeue#SBATCH --mail-type=FAIL
set -Eeuo pipefailumask 007
: "${DATA_DIR:?Export DATA_DIR=/path/to/docking_results}": "${OUTPUT_DIR:?Export OUTPUT_DIR=/path/to/new_compact_dataset}": "${METHOD:?Export METHOD=protenix|diffdock|autodock_vina|medusagraph}"
readonly PROJECT_ROOT=/work/nvme/bghp/hhao/gnncpreadonly BUILDER="${PROJECT_ROOT}/system_split_code/build_compact_v1_direct.py"readonly PYTHON=/u/hhao/anaconda3/envs/gcp/bin/pythonreadonly SYSTEM_WORKERS="${SYSTEM_WORKERS:-1}"if (( SYSTEM_WORKERS > 1 )); then # Cross-system mode deliberately has one in-process pose builder per child. # This avoids multiplying dense N-by-N distance matrices in nested pools. readonly NUM_WORKERS="${NUM_WORKERS:-1}"else readonly NUM_WORKERS="${NUM_WORKERS:-4}"fireadonly MEMORY_BUDGET_GIB="${MEMORY_BUDGET_GIB:-}"readonly TARGET_SHARD_MIB="${TARGET_SHARD_MIB:-512}"readonly ON_ERROR="${ON_ERROR:-abort}"
finish(){ local rc=$? echo "[$(date --iso-8601=seconds)] job=${SLURM_JOB_ID} exit=${rc}"}trap finish EXIT
echo "[$(date --iso-8601=seconds)] host=$(hostname)"echo "data=${DATA_DIR}"echo "output=${OUTPUT_DIR}"echo "method=${METHOD} pose_workers=${NUM_WORKERS} system_workers=${SYSTEM_WORKERS} memory_budget_gib=${MEMORY_BUDGET_GIB:-unset}"
test -x "${PYTHON}"test -r "${BUILDER}"test -d "${DATA_DIR}"mkdir -p "$(dirname "${OUTPUT_DIR}")"
if [[ -s "${OUTPUT_DIR}/manifest.json" ]]; then echo "Output already has a manifest; skipping completed build." exit 0fiif [[ -e "${OUTPUT_DIR}" ]]; then echo "Output exists without a manifest; refusing to overwrite: ${OUTPUT_DIR}" >&2 exit 3fi
if (( SYSTEM_WORKERS > 1 )); then if [[ "${NUM_WORKERS}" != "1" ]]; then echo "SYSTEM_WORKERS>1 requires NUM_WORKERS=1; nested process pools are unsafe." >&2 exit 2 fi : "${MEMORY_BUDGET_GIB:?Set MEMORY_BUDGET_GIB to a usable aggregate worker-memory budget for SYSTEM_WORKERS>1}"fiif [[ -n "${SLURM_CPUS_PER_TASK:-}" ]] && (( SYSTEM_WORKERS > SLURM_CPUS_PER_TASK )); then echo "SYSTEM_WORKERS=${SYSTEM_WORKERS} exceeds SLURM_CPUS_PER_TASK=${SLURM_CPUS_PER_TASK}" >&2 exit 2fi
# Each pose worker performs dense scipy distance calculations. Keep numerical# libraries single-threaded and parallelise at the pose-process level.export PYTHONUNBUFFERED=1export OMP_NUM_THREADS=1export MKL_NUM_THREADS=1export OPENBLAS_NUM_THREADS=1export NUMEXPR_NUM_THREADS=1export MALLOC_ARENA_MAX=2
ARGS=( --data-dir "${DATA_DIR}" --output-dir "${OUTPUT_DIR}" --method "${METHOD}" --num-workers "${NUM_WORKERS}" --system-workers "${SYSTEM_WORKERS}" --target-shard-mib "${TARGET_SHARD_MIB}" --on-error "${ON_ERROR}" --resume)if [[ -n "${MEMORY_BUDGET_GIB}" ]]; then ARGS+=(--memory-budget-gib "${MEMORY_BUDGET_GIB}")fiif [[ -n "${SYSTEM_ID:-}" ]]; then ARGS+=(--system-id "${SYSTEM_ID}")fiif [[ -n "${MAX_SYSTEMS:-}" ]]; then ARGS+=(--max-systems "${MAX_SYSTEMS}")fiif [[ -n "${MAX_POSES:-}" ]]; then ARGS+=(--max-poses-per-system "${MAX_POSES}")fi
df -h "$(dirname "${OUTPUT_DIR}")"/usr/bin/time -v "${PYTHON}" "${BUILDER}" "${ARGS[@]}"
test -s "${OUTPUT_DIR}/manifest.json"test -s "${OUTPUT_DIR}/system_index.json"du -sh "${OUTPUT_DIR}"echo "[$(date --iso-8601=seconds)] compact dataset committed successfully"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Build Graph Unified Enhanced=============================
整合版构图脚本,用于批量处理蛋白-配体数据并构建增强版图数据集
功能:1. 批量处理多个 docking 结果2. 构建增强版图特征 (82维节点特征 + 4维边特征)3. 计算预测误差标签 (y_true, y_pred, y_grt)4. 保存为 PyTorch Geometric 格式
使用方法: python build_graph_unified_enhanced.py \\ --data_dir ./docking_results \\ --output ./datasets_x/protenix_enhanced_graphs.pt \\ --docking_type protenix
数据目录结构 (示例): data_dir/ ├── 1a30/ │ ├── protein.pdb # 蛋白结构 │ ├── ligand_native.pdb # 配体真实结构 (ground truth) │ ├── 1a30_pose_01.pdb # Docking 预测 pose 1 │ ├── 1a30_pose_02.pdb # Docking 预测 pose 2 │ └── ... ├── 1b38/ │ └── ... └── ..."""
import osimport globimport argparsefrom typing import Sequence, List, Dict, Tuple, Optionalfrom collections import defaultdict
import numpy as npimport torchfrom torch_geometric.data import Dataimport MDAnalysis as mdafrom io import StringIOfrom scipy.spatial.distance import cdistfrom tqdm import tqdm
# =============================================================================# 基础字典# =============================================================================
ELEMENTS = ["C", "N", "O", "S", "P", "F", "Cl", "Br", "I", "H", "Other"]ELEMENT2IDX = {e: i for i, e in enumerate(ELEMENTS)}
AA3 = [ "ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL"]AA3_2IDX = {aa: i for i, aa in enumerate(AA3)}AA_DIM = len(AA3) + 1
# 化学属性ELECTRONEGATIVITY = { "C": 2.55, "N": 3.04, "O": 3.44, "S": 2.58, "P": 2.19, "F": 3.98, "Cl": 3.16, "Br": 2.96, "I": 2.66, "H": 2.20, "Other": 2.5}
VDW_RADIUS = { "C": 1.70, "N": 1.55, "O": 1.52, "S": 1.80, "P": 1.80, "F": 1.47, "Cl": 1.75, "Br": 1.85, "I": 1.98, "H": 1.20, "Other": 1.70}
ATOMIC_MASS = { "C": 12.0, "N": 14.0, "O": 16.0, "S": 32.0, "P": 31.0, "F": 19.0, "Cl": 35.5, "Br": 80.0, "I": 127.0, "H": 1.0, "Other": 12.0}
HYDROPHOBICITY = { "ALA": 0.70, "ARG": 0.00, "ASN": 0.11, "ASP": 0.11, "CYS": 0.78, "GLN": 0.11, "GLU": 0.11, "GLY": 0.46, "HIS": 0.14, "ILE": 1.00, "LEU": 0.92, "LYS": 0.07, "MET": 0.71, "PHE": 0.81, "PRO": 0.32, "SER": 0.41, "THR": 0.42, "TRP": 0.40, "TYR": 0.36, "VAL": 0.97,}
AROMATIC_RESIDUES = {"PHE", "TYR", "TRP", "HIS"}CHARGED_RESIDUES = {"ARG": 1, "LYS": 1, "ASP": -1, "GLU": -1, "HIS": 0.5}POLAR_RESIDUES = {"SER", "THR", "ASN", "GLN", "TYR", "CYS"}BACKBONE_ATOMS = {"N", "CA", "C", "O"}
# =============================================================================# 工具函数# =============================================================================
def _one_hot(idx: int, dim: int) -> np.ndarray: v = np.zeros(dim, dtype=np.float32) if 0 <= idx < dim: v[idx] = 1.0 return v
def _get_element(atom) -> str: elem = getattr(atom, "element", None) if elem: e = elem.strip().capitalize() if e.upper() in ["CL", "BR"]: return e.upper().title() return e[0].upper() name = atom.name.strip() if not name: return "Other" if name[0].isdigit(): name = name[1:] if name[:2].upper() in ["CL", "BR"]: return name[:2].upper().title() return name[0].upper()
def load_pdb_clean_models(pdb_path: str) -> mda.Universe: """读取 PDB,忽略 MODEL/ENDMDL""" with open(pdb_path, "r") as f: lines = f.readlines() cleaned = [] for line in lines: rec = line[:6].strip().upper() if rec in ("MODEL", "ENDMDL"): continue cleaned.append(line) text = "".join(cleaned) return mda.Universe(StringIO(text), format="PDB")
# =============================================================================# 增强版特征计算# =============================================================================
def compute_local_geometry_features( coords: np.ndarray, radii: Sequence[float] = (3.0, 5.0, 8.0),) -> np.ndarray: """局部几何特征: 邻居数量、各向异性、重心偏移""" N = coords.shape[0] dist_matrix = cdist(coords, coords) features_list = [] for r in radii: mask = (dist_matrix <= r) & (dist_matrix > 0) n_neighbors = mask.sum(axis=1).astype(np.float32) anisotropy = np.zeros(N, dtype=np.float32) centroid_dist = np.zeros(N, dtype=np.float32) for i in range(N): neighbor_idx = np.where(mask[i])[0] if len(neighbor_idx) < 3: continue neighbor_coords = coords[neighbor_idx] - coords[i] centroid = neighbor_coords.mean(axis=0) centroid_dist[i] = np.linalg.norm(centroid) if len(neighbor_idx) >= 3: cov = np.cov(neighbor_coords.T) try: eigenvalues = np.linalg.eigvalsh(cov) eigenvalues = np.sort(eigenvalues)[::-1] total = eigenvalues.sum() + 1e-8 anisotropy[i] = (eigenvalues[0] - eigenvalues[-1]) / total except: pass features_list.extend([ n_neighbors.reshape(-1, 1), anisotropy.reshape(-1, 1), centroid_dist.reshape(-1, 1), ]) return np.concatenate(features_list, axis=1)
def compute_distance_statistics( coords: np.ndarray, coords_prot: np.ndarray, coords_lig: np.ndarray,) -> np.ndarray: """距离统计特征""" N = coords.shape[0] dist_to_prot = cdist(coords, coords_prot) prot_min = dist_to_prot.min(axis=1, keepdims=True) prot_mean = dist_to_prot.mean(axis=1, keepdims=True) prot_std = dist_to_prot.std(axis=1, keepdims=True) prot_q25 = np.percentile(dist_to_prot, 25, axis=1, keepdims=True) prot_q75 = np.percentile(dist_to_prot, 75, axis=1, keepdims=True) dist_to_lig = cdist(coords, coords_lig) lig_min = dist_to_lig.min(axis=1, keepdims=True) lig_mean = dist_to_lig.mean(axis=1, keepdims=True) lig_std = dist_to_lig.std(axis=1, keepdims=True) lig_q25 = np.percentile(dist_to_lig, 25, axis=1, keepdims=True) lig_q75 = np.percentile(dist_to_lig, 75, axis=1, keepdims=True) dist_all = cdist(coords, coords) shells = [(0, 3), (3, 5), (5, 8), (8, 12)] shell_counts = [] for r_min, r_max in shells: mask = (dist_all > r_min) & (dist_all <= r_max) count = mask.sum(axis=1, keepdims=True).astype(np.float32) shell_counts.append(count) return np.concatenate([ prot_min, prot_mean, prot_std, prot_q25, prot_q75, lig_min, lig_mean, lig_std, lig_q25, lig_q75, *shell_counts, ], axis=1)
def compute_chemical_features(atoms, elements: List[str]) -> np.ndarray: """化学特征""" N = len(atoms) electroneg = np.zeros((N, 1), dtype=np.float32) vdw = np.zeros((N, 1), dtype=np.float32) mass = np.zeros((N, 1), dtype=np.float32) hbond_donor = np.zeros((N, 1), dtype=np.float32) hbond_acceptor = np.zeros((N, 1), dtype=np.float32) for i, (atom, elem) in enumerate(zip(atoms, elements)): electroneg[i] = ELECTRONEGATIVITY.get(elem, 2.5) vdw[i] = VDW_RADIUS.get(elem, 1.7) mass[i] = ATOMIC_MASS.get(elem, 12.0) if elem in ["N", "O"]: hbond_donor[i] = 1.0 hbond_acceptor[i] = 1.0 elif elem == "S": hbond_acceptor[i] = 0.5 electroneg = (electroneg - 2.0) / 2.0 vdw = (vdw - 1.2) / 0.8 mass = np.log1p(mass) / 5.0 return np.concatenate([electroneg, vdw, mass, hbond_donor, hbond_acceptor], axis=1)
def compute_protein_specific_features(atoms, is_protein: np.ndarray) -> np.ndarray: """蛋白质特定特征""" N = len(atoms) is_backbone = np.zeros((N, 1), dtype=np.float32) hydrophobicity = np.zeros((N, 1), dtype=np.float32) aromaticity = np.zeros((N, 1), dtype=np.float32) charge = np.zeros((N, 1), dtype=np.float32) polarity = np.zeros((N, 1), dtype=np.float32) for i, atom in enumerate(atoms): if is_protein[i, 0] < 0.5: hydrophobicity[i] = 0.5 continue resname = atom.resname.strip().upper() atomname = atom.name.strip().upper() if atomname in BACKBONE_ATOMS: is_backbone[i] = 1.0 hydrophobicity[i] = HYDROPHOBICITY.get(resname, 0.5) aromaticity[i] = 1.0 if resname in AROMATIC_RESIDUES else 0.0 charge[i] = CHARGED_RESIDUES.get(resname, 0.0) polarity[i] = 1.0 if resname in POLAR_RESIDUES else 0.0 return np.concatenate([is_backbone, hydrophobicity, aromaticity, charge, polarity], axis=1)
def compute_topology_features(dist_matrix: np.ndarray, cutoff: float = 6.0) -> np.ndarray: """拓扑特征""" N = dist_matrix.shape[0] adj = (dist_matrix <= cutoff) & (dist_matrix > 0) degree = adj.sum(axis=1).astype(np.float32) clustering = np.zeros(N, dtype=np.float32) for i in range(N): neighbors = np.where(adj[i])[0] k = len(neighbors) if k < 2: continue subgraph = adj[np.ix_(neighbors, neighbors)] edges = subgraph.sum() / 2 max_edges = k * (k - 1) / 2 clustering[i] = edges / max_edges if max_edges > 0 else 0 adj2 = adj @ adj np.fill_diagonal(adj2, 0) second_degree = (adj2 > 0).sum(axis=1).astype(np.float32) degree_norm = degree / (degree.max() + 1e-8) second_degree_norm = second_degree / (second_degree.max() + 1e-8) return np.stack([degree_norm, clustering, second_degree_norm], axis=1)
def compute_interface_features(coords: np.ndarray, is_protein: np.ndarray, cutoff: float = 5.0) -> np.ndarray: """界面特征""" N = coords.shape[0] prot_mask = is_protein.flatten() > 0.5 coords_prot = coords[prot_mask] coords_lig = coords[~prot_mask] dist_prot_to_lig = cdist(coords_prot, coords_lig) prot_min_dist = dist_prot_to_lig.min(axis=1) dist_lig_to_prot = cdist(coords_lig, coords_prot) lig_min_dist = dist_lig_to_prot.min(axis=1) is_interface = np.zeros((N, 1), dtype=np.float32) interface_distance = np.zeros((N, 1), dtype=np.float32) prot_idx = np.where(prot_mask)[0] lig_idx = np.where(~prot_mask)[0] for i, idx in enumerate(prot_idx): is_interface[idx] = 1.0 if prot_min_dist[i] <= cutoff else 0.0 interface_distance[idx] = prot_min_dist[i] for i, idx in enumerate(lig_idx): is_interface[idx] = 1.0 if lig_min_dist[i] <= cutoff else 0.0 interface_distance[idx] = lig_min_dist[i] interface_distance = np.clip(interface_distance / 10.0, 0, 1) return np.concatenate([is_interface, interface_distance], axis=1)
def compute_local_environment_features(coords: np.ndarray, elements: List[str], cutoff: float = 5.0) -> np.ndarray: """局部环境特征""" N = coords.shape[0] dist_matrix = cdist(coords, coords) mask = (dist_matrix <= cutoff) & (dist_matrix > 0) elem_to_idx = {"C": 0, "N": 1, "O": 2, "S": 3} neighbor_composition = np.zeros((N, 4), dtype=np.float32) neighbor_electroneg = np.zeros((N, 1), dtype=np.float32) neighbor_mass = np.zeros((N, 1), dtype=np.float32) for i in range(N): neighbor_idx = np.where(mask[i])[0] if len(neighbor_idx) == 0: continue for j in neighbor_idx: elem = elements[j] if elem in elem_to_idx: neighbor_composition[i, elem_to_idx[elem]] += 1 neighbor_electroneg[i] += ELECTRONEGATIVITY.get(elem, 2.5) neighbor_mass[i] += ATOMIC_MASS.get(elem, 12.0) n = len(neighbor_idx) neighbor_composition[i] /= n neighbor_electroneg[i] /= n neighbor_mass[i] /= n neighbor_electroneg = (neighbor_electroneg - 2.5) / 1.5 neighbor_mass = np.log1p(neighbor_mass) / 5.0 return np.concatenate([neighbor_composition, neighbor_electroneg, neighbor_mass], axis=1)
# =============================================================================# 核心构图函数# =============================================================================
def build_graph_enhanced( protein_pdb: str, ligand_pred_pdb: str, ligand_native_pdb: str, cutoff: float = 6.0, neighbor_radii: Sequence[float] = (3.0, 5.0, 8.0), use_enhanced_features: bool = True,) -> Data: """ 构建增强版蛋白-配体图 Args: protein_pdb: 蛋白结构文件 ligand_pred_pdb: 配体预测结构 (docking pose) ligand_native_pdb: 配体真实结构 (ground truth) cutoff: 构图距离阈值 neighbor_radii: 邻居统计的距离半径 use_enhanced_features: 是否使用增强特征 (82维),否则使用基础特征 (~40维) Returns: Data: 包含节点特征、边、标签的图数据 """ # ---- 1. 读取文件 ---- u_p = load_pdb_clean_models(protein_pdb) u_l_pred = load_pdb_clean_models(ligand_pred_pdb) u_l_native = load_pdb_clean_models(ligand_native_pdb) prot_atoms = u_p.select_atoms("not name H*") lig_pred_atoms = u_l_pred.select_atoms("not name H*") lig_native_atoms = u_l_native.select_atoms("not name H*") coords_prot = prot_atoms.positions.astype(np.float32) coords_lig_pred = lig_pred_atoms.positions.astype(np.float32) coords_lig_native = lig_native_atoms.positions.astype(np.float32) Np = coords_prot.shape[0] Nl = coords_lig_pred.shape[0] N = Np + Nl # 检查配体原子数是否匹配 if coords_lig_pred.shape[0] != coords_lig_native.shape[0]: raise ValueError(f"配体原子数不匹配: pred={coords_lig_pred.shape[0]}, native={coords_lig_native.shape[0]}") # ---- 2. 计算误差标签 ---- # 蛋白原子误差 = 0 (蛋白位置固定) errors_prot = np.zeros(Np, dtype=np.float32) # 配体原子误差 = |pred - native| errors_lig = np.linalg.norm(coords_lig_pred - coords_lig_native, axis=1).astype(np.float32) y_true = np.concatenate([errors_prot, errors_lig]) # [N] # 预测坐标和真实坐标 (用于评估时计算区间) coords_all_pred = np.vstack([coords_prot, coords_lig_pred]) # [N, 3] coords_all_native = np.vstack([coords_prot, coords_lig_native]) # [N, 3] # y_pred 和 y_grt 存储完整的三维坐标 # 评估时用 |y_pred - y_grt| 计算实际误差,检查是否 <= radius y_pred = coords_all_pred # [N, 3] y_grt = coords_all_native # [N, 3] # ---- 3. 合并原子列表 ---- all_atoms = list(prot_atoms) + list(lig_pred_atoms) elements = [_get_element(atom) for atom in all_atoms] # ---- 4. 基础特征 ---- # 元素 one-hot atom_type_oh = np.stack([ _one_hot(ELEMENT2IDX.get(elem, ELEMENT2IDX["Other"]), len(ELEMENTS)) for elem in elements ]) # 残基类型 one-hot res_type_oh = [] for i, atom in enumerate(all_atoms): if i < Np: resname = atom.resname.strip().upper() idx = AA3_2IDX.get(resname, len(AA3)) else: idx = len(AA3) res_type_oh.append(_one_hot(idx, AA_DIM)) res_type_oh = np.stack(res_type_oh) # is_protein / is_ligand is_protein = np.zeros((N, 1), dtype=np.float32) is_protein[:Np] = 1.0 is_ligand = 1.0 - is_protein # ---- 5. 距离特征 ---- prot_center = coords_prot.mean(axis=0, keepdims=True) lig_center = coords_lig_pred.mean(axis=0, keepdims=True) d_prot_center = np.linalg.norm(coords_all_pred - prot_center, axis=1, keepdims=True) d_lig_center = np.linalg.norm(coords_all_pred - lig_center, axis=1, keepdims=True) dist_all = cdist(coords_all_pred, coords_all_pred) d_min_prot = cdist(coords_all_pred, coords_prot).min(axis=1, keepdims=True) d_min_lig = cdist(coords_all_pred, coords_lig_pred).min(axis=1, keepdims=True) # 归一化 d_prot_center_norm = d_prot_center / 50.0 d_lig_center_norm = d_lig_center / 30.0 d_min_prot_norm = d_min_prot / 20.0 d_min_lig_norm = d_min_lig / 20.0 # ---- 6. 构建特征 ---- if use_enhanced_features: # 增强特征 (82维) local_geom_feat = compute_local_geometry_features(coords_all_pred, radii=neighbor_radii) dist_stat_feat = compute_distance_statistics(coords_all_pred, coords_prot, coords_lig_pred) / 20.0 chem_feat = compute_chemical_features(all_atoms, elements) prot_specific_feat = compute_protein_specific_features(all_atoms, is_protein) topo_feat = compute_topology_features(dist_all, cutoff=cutoff) interface_feat = compute_interface_features(coords_all_pred, is_protein) local_env_feat = compute_local_environment_features(coords_all_pred, elements, cutoff=5.0) data_x = np.concatenate([ atom_type_oh, # 11 res_type_oh, # 21 is_protein, # 1 is_ligand, # 1 d_prot_center_norm, # 1 d_lig_center_norm, # 1 d_min_prot_norm, # 1 d_min_lig_norm, # 1 local_geom_feat, # 9 dist_stat_feat, # 14 chem_feat, # 5 prot_specific_feat, # 5 topo_feat, # 3 interface_feat, # 2 local_env_feat, # 6 ], axis=1).astype(np.float32) else: # 基础特征 (~40维) neighbor_feats = [] for r in neighbor_radii[:2]: # 只用前两个半径 mask = (dist_all <= r) & (~np.eye(N, dtype=bool)) n_nb = mask.sum(axis=1, keepdims=True) neighbor_feats.append(n_nb.astype(np.float32)) neighbor_feats = np.concatenate(neighbor_feats, axis=1) data_x = np.concatenate([ atom_type_oh, res_type_oh, is_protein, is_ligand, d_prot_center_norm, d_lig_center_norm, d_min_prot_norm, d_min_lig_norm, neighbor_feats, ], axis=1).astype(np.float32) # ---- 7. 构建边 ---- mask = (dist_all <= cutoff) & (~np.eye(N, dtype=bool)) src, dst = np.where(mask) edge_index = np.vstack([src, dst]).astype(np.int64) # ---- 8. 边特征 ---- if use_enhanced_features: edge_dist = dist_all[src, dst] edge_attr = np.stack([ edge_dist / cutoff, np.exp(-edge_dist / 3.0), (src < Np).astype(np.float32), (dst < Np).astype(np.float32), ], axis=1).astype(np.float32) else: edge_attr = None # ---- 9. 构建 Data ---- data = Data( x=torch.from_numpy(data_x), edge_index=torch.from_numpy(edge_index), pos=torch.from_numpy(coords_all_pred), is_protein=torch.from_numpy(is_protein), y_true=torch.from_numpy(y_true).unsqueeze(-1), # [N, 1] 误差 y_pred=torch.from_numpy(y_pred), # [N, 3] 预测坐标 y_grt=torch.from_numpy(y_grt), # [N, 3] 真实坐标 num_nodes=N, ) if edge_attr is not None: data.edge_attr = torch.from_numpy(edge_attr) return data
# =============================================================================# 批量处理函数# =============================================================================
def find_docking_poses( pdb_dir: str, docking_type: str = "protenix",) -> List[Dict[str, str]]: """ 自动发现目录中的 docking poses 支持的目录结构: - protenix: {target}_{lig_id}/lig_{id}_pose*.pdb 或 {pdb_id}_pose_*.pdb - diffdock: {pdb_id}/rank*_confidence*.sdf 或 *pose*.pdb - autodock_vina: {pdb_id}/vina_pose_*.pdb 或 *pose*.pdb - medusagraph: {pdb_id}/medusa_pose_*.pdb 或 *pose*.pdb Returns: List of dicts with keys: pdb_id, protein, ligand_pred, ligand_native """ poses = [] for pdb_id in os.listdir(pdb_dir): subdir = os.path.join(pdb_dir, pdb_id) if not os.path.isdir(subdir): continue # 找蛋白文件 protein_file = None for name in ["protein.pdb", f"{pdb_id}_protein.pdb", "receptor.pdb"]: path = os.path.join(subdir, name) if os.path.exists(path): protein_file = path break if protein_file is None: continue # 找原生配体 (增加 ligands.pdb) native_file = None for name in ["ligands.pdb", "ligand.pdb", "ligand_native.pdb", f"{pdb_id}_ligand.pdb", "native.pdb"]: path = os.path.join(subdir, name) if os.path.exists(path): native_file = path break if native_file is None: continue # 找 docking poses (更灵活的匹配) pose_files = [] if docking_type == "protenix": # 尝试多种模式 patterns = [ os.path.join(subdir, f"*_pose*.pdb"), # lig_1_pose1.pdb, xxx_pose_01.pdb os.path.join(subdir, f"{pdb_id}_pose_*.pdb"), # cdk2_lig_1_pose_01.pdb ] elif docking_type == "diffdock": patterns = [ os.path.join(subdir, f"*_pose*.pdb"), os.path.join(subdir, f"rank*.pdb"), os.path.join(subdir, f"rank*_confidence*.sdf"), ] elif docking_type == "autodock_vina": patterns = [ os.path.join(subdir, f"*_pose*.pdb"), os.path.join(subdir, "vina_pose_*.pdb"), os.path.join(subdir, "vina_out*.pdb"), ] elif docking_type == "medusagraph": patterns = [ os.path.join(subdir, f"*_pose*.pdb"), os.path.join(subdir, "medusa_pose_*.pdb"), ] else: patterns = [os.path.join(subdir, f"*pose*.pdb")] for pattern in patterns: pose_files.extend(glob.glob(pattern)) # 去重并排除原生配体文件 pose_files = list(set(pose_files)) pose_files = [f for f in pose_files if os.path.basename(f) not in ["ligands.pdb", "ligand.pdb", "native.pdb"]] for pose_file in pose_files: poses.append({ 'pdb_id': pdb_id, 'protein': protein_file, 'ligand_pred': pose_file, 'ligand_native': native_file, }) return poses
def _build_single_graph(args): """单个图构建函数 (用于多进程)""" pose, cutoff, use_enhanced_features, temp_dir = args try: data = build_graph_enhanced( protein_pdb=pose['protein'], ligand_pred_pdb=pose['ligand_pred'], ligand_native_pdb=pose['ligand_native'], cutoff=cutoff, use_enhanced_features=use_enhanced_features, ) # 保存到临时文件,避免跨进程传输 PyTorch tensor temp_file = os.path.join(temp_dir, f"{pose['pdb_id']}_{os.path.basename(pose['ligand_pred'])}.pt") torch.save(data, temp_file) return ('success', temp_file) except Exception as e: return ('error', (pose['pdb_id'], str(e)))
def build_dataset( data_dir: str, output_path: str, docking_type: str = "protenix", cutoff: float = 6.0, use_enhanced_features: bool = True, max_samples: int = None, num_workers: int = 1,) -> None: """ 批量构建数据集 Args: data_dir: 数据目录 output_path: 输出文件路径 docking_type: docking 类型 cutoff: 构图阈值 use_enhanced_features: 是否使用增强特征 max_samples: 最大样本数 (用于测试) num_workers: 并行进程数 (默认 1,设为 -1 使用所有 CPU) """ import multiprocessing as mp import tempfile import shutil print(f"扫描目录: {data_dir}") poses = find_docking_poses(data_dir, docking_type) print(f"发现 {len(poses)} 个 docking poses") if max_samples is not None: poses = poses[:max_samples] print(f"限制为 {max_samples} 个样本") # 确定进程数 if num_workers == -1: num_workers = mp.cpu_count() elif num_workers <= 0: num_workers = 1 graphs = [] errors = [] if num_workers == 1: # 单进程模式 for pose in tqdm(poses, desc="构建图"): try: data = build_graph_enhanced( protein_pdb=pose['protein'], ligand_pred_pdb=pose['ligand_pred'], ligand_native_pdb=pose['ligand_native'], cutoff=cutoff, use_enhanced_features=use_enhanced_features, ) graphs.append(data) except Exception as e: errors.append((pose['pdb_id'], str(e))) else: # 多进程模式 - 使用临时目录存储中间结果 print(f"使用 {num_workers} 个进程并行构建") # 创建临时目录 temp_dir = tempfile.mkdtemp(prefix="graph_build_") print(f"临时目录: {temp_dir}") try: # 准备参数 args_list = [(pose, cutoff, use_enhanced_features, temp_dir) for pose in poses] # 使用进程池 with mp.Pool(processes=num_workers) as pool: results = list(tqdm( pool.imap(_build_single_graph, args_list), total=len(args_list), desc=f"构建图 ({num_workers} workers)" )) # 收集结果 print("正在收集结果...") temp_files = [] for result in results: if result[0] == 'success': temp_files.append(result[1]) else: errors.append(result[1]) # 从临时文件加载数据 for temp_file in tqdm(temp_files, desc="加载图数据"): try: data = torch.load(temp_file, weights_only=False) graphs.append(data) except Exception as e: errors.append(("load_error", str(e))) finally: # 清理临时目录 print(f"清理临时目录...") shutil.rmtree(temp_dir, ignore_errors=True) print(f"\n成功: {len(graphs)} | 失败: {len(errors)}") if errors and len(errors) <= 10: print("失败样本:") for pdb_id, err in errors: print(f" {pdb_id}: {err}") # 保存 os.makedirs(os.path.dirname(output_path), exist_ok=True) torch.save(graphs, output_path) print(f"\n数据集已保存到: {output_path}") # 统计 if graphs: n_nodes = sum(g.num_nodes for g in graphs) n_edges = sum(g.edge_index.shape[1] for g in graphs) feature_dim = graphs[0].x.shape[1] has_edge_attr = hasattr(graphs[0], 'edge_attr') and graphs[0].edge_attr is not None print(f"\n数据集统计:") print(f" 图数量: {len(graphs)}") print(f" 总节点数: {n_nodes}") print(f" 总边数: {n_edges}") print(f" 节点特征维度: {feature_dim}") print(f" 边特征: {'有' if has_edge_attr else '无'}") # 误差统计 all_errors = [] for g in graphs: is_prot = g.is_protein.squeeze(-1) y_true = g.y_true.squeeze(-1) lig_mask = (is_prot == 0) all_errors.append(y_true[lig_mask]) all_errors = torch.cat(all_errors) print(f"\n误差统计 (配体原子):") print(f" 样本数: {len(all_errors)}") print(f" 均值: {all_errors.mean():.4f} Å") print(f" 中位数: {all_errors.median():.4f} Å") print(f" 标准差: {all_errors.std():.4f} Å") print(f" 范围: [{all_errors.min():.4f}, {all_errors.max():.4f}] Å") print(f" 90% 分位: {torch.quantile(all_errors, 0.9):.4f} Å")
# =============================================================================# 命令行接口# =============================================================================
def main(): parser = argparse.ArgumentParser(description="构建增强版蛋白-配体图数据集") parser.add_argument("--data_dir", type=str, required=True, help="数据目录") parser.add_argument("--output", type=str, required=True, help="输出文件路径") parser.add_argument("--docking_type", type=str, default="protenix", choices=["protenix", "diffdock", "autodock_vina", "medusagraph"], help="Docking 类型") parser.add_argument("--cutoff", type=float, default=6.0, help="构图距离阈值") parser.add_argument("--no_enhanced", action="store_true", help="不使用增强特征") parser.add_argument("--max_samples", type=int, default=None, help="最大样本数") parser.add_argument("--num_workers", type=int, default=1, help="并行进程数 (默认 1,设为 -1 使用所有 CPU)") args = parser.parse_args() build_dataset( data_dir=args.data_dir, output_path=args.output, docking_type=args.docking_type, cutoff=args.cutoff, use_enhanced_features=not args.no_enhanced, max_samples=args.max_samples, num_workers=args.num_workers, )
if __name__ == "__main__": main()
# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/protenix --output /work/nvme/bghp/hhao/gnncp/datasets_all/protenix_enhanced_graphs.pt --docking_type protenix --num_workers -1# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/diffdock --output /work/nvme/bghp/hhao/gnncp/datasets_all/diffdock_enhanced_graphs.pt --docking_type diffdock --num_workers -1# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/medusagraph --output /work/nvme/bghp/hhao/gnncp/datasets_all/medusagraph_enhanced_graphs.pt --docking_type medusagraph --num_workers -1# python build_graph_unified_enhanced.py --data_dir /work/nvme/bghp/hhao/gnncp/filtered_output/autodock_vina --output /work/nvme/bghp/hhao/gnncp/datasets_all/autodock_vina_enhanced_graphs.pt --docking_type autodock_vina --num_workers -1# salloc -t 06:00:00 --mem=128g --account=beyd-delta-cpu --partition=cpu --nodes=1 --tasks=1 --tasks-per-node=1 --cpus-per-task=24# salloc -t 03:00:00 --mem=64g --account=beyd-delta-cpu --partition=cpu --nodes=1 --tasks=1 --tasks-per-node=1 --cpus-per-task=16123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295#!/usr/bin/env python3"""Build graph→system index for each enhanced dataset + global split assignment.
Two outputs:
1. Per-method graph→system mapping (needed to know which graph belongs to which system): datasets_all/{method}_system_index.json { "graph_to_system": ["cdk2_lig_1", ...], "systems": [...], ... }
2. Global split assignment (shared across ALL methods, generated once): datasets_all/system_split_assignment.json { "train": ["cdk2_lig_1", ...], "val": ["mcl1_lig_5", ...], "calib": ["syk_lig_10", ...], "test": ["cdk8_lig_3", ...], "seed": 42, "ratios": {"train": 0.70, "val": 0.10, "calib": 0.10, "test": 0.10} }
The split assignment uses the FULL system list from autodock_vina (as reference)to ensure all 4 methods use the exact same split.
Usage: python build_system_index.py"""
import osimport jsonimport timefrom collections import defaultdict
import numpy as npimport torchfrom torch_geometric.data import Data
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
from build_graph_unified_enhanced import load_pdb_clean_models
torch.serialization.add_safe_globals([Data])
# Data directories: siblings of system_split/# Structure: parent_dir/system_split/ (this), parent_dir/filtered_output/, parent_dir/datasets_all/PARENT_DIR = os.path.dirname(SCRIPT_DIR)DATA_DIR = os.path.join(PARENT_DIR, "filtered_output")DATASETS_DIR = os.path.join(PARENT_DIR, "datasets_all")
METHODS = { "autodock_vina": "autodock_vina_enhanced_graphs.pt", "diffdock": "diffdock_enhanced_graphs.pt", "medusagraph": "medusagraph_enhanced_graphs.pt", "protenix": "protenix_enhanced_graphs.pt",}
def compute_fingerprint(graph): """(n_lig_atoms, (cx, cy, cz)) from ligand ground truth centroid.""" is_prot = graph.is_protein.squeeze(-1) lig_mask = is_prot == 0 n_lig = int(lig_mask.sum().item()) if n_lig == 0: return (0, (0.0, 0.0, 0.0)) lig_grt = graph.y_grt[lig_mask] centroid = lig_grt.mean(dim=0) return (n_lig, (round(centroid[0].item(), 2), round(centroid[1].item(), 2), round(centroid[2].item(), 2)))
def read_native_centroid(pdb_path): """Read native ligand PDB → (n_heavy_atoms, (cx, cy, cz)).""" u = load_pdb_clean_models(pdb_path) atoms = u.select_atoms("not name H*") coords = atoms.positions.astype(np.float32) n = coords.shape[0] c = coords.mean(axis=0) return (n, (round(float(c[0]), 2), round(float(c[1]), 2), round(float(c[2]), 2)))
def build_fp_to_system(method_subdir): """Build fingerprint → system name mapping from PDB files.""" method_dir = os.path.join(DATA_DIR, method_subdir) systems = sorted([d for d in os.listdir(method_dir) if os.path.isdir(os.path.join(method_dir, d))])
fp_to_system = {} for system in systems: native_path = os.path.join(method_dir, system, "ligands.pdb") if not os.path.exists(native_path): continue try: fp = read_native_centroid(native_path) fp_to_system[fp] = system except Exception: continue
return fp_to_system
def match_graph_to_system(graph_fp, fp_to_system): """Exact match, then fuzzy match (same n_atoms, closest centroid < 0.5 Å).""" if graph_fp in fp_to_system: return fp_to_system[graph_fp]
n_lig, (cx, cy, cz) = graph_fp best_dist = 999.0 best_sys = None for fp, sys_name in fp_to_system.items(): fn, (fx, fy, fz) = fp if fn != n_lig: continue dist = ((cx - fx)**2 + (cy - fy)**2 + (cz - fz)**2) ** 0.5 if dist < best_dist: best_dist = dist best_sys = sys_name if best_dist < 0.5: return best_sys return None
def process_method(method_name, dataset_filename): """Build system index for one method.""" dataset_path = os.path.join(DATASETS_DIR, dataset_filename) if not os.path.exists(dataset_path): print(f" [SKIP] {dataset_path} not found") return
print(f"\n{'='*60}") print(f" {method_name}") print(f"{'='*60}")
# Load dataset print(f" Loading {dataset_path} ...") t0 = time.time() graphs = torch.load(dataset_path, weights_only=False) n = len(graphs) print(f" Loaded {n} graphs in {time.time()-t0:.1f}s")
# Build fingerprint → system mapping print(f" Building fingerprint map from PDB files...") fp_to_system = build_fp_to_system(method_name) print(f" {len(fp_to_system)} systems from PDB files")
# Match each graph print(f" Matching graphs to systems...") graph_to_system = [] matched = 0 unmatched = 0
for i, g in enumerate(graphs): fp = compute_fingerprint(g) system = match_graph_to_system(fp, fp_to_system) if system: graph_to_system.append(system) matched += 1 else: graph_to_system.append("UNKNOWN") unmatched += 1
print(f" Matched: {matched}/{n}, Unmatched: {unmatched}")
# Verify: count per system system_counts = defaultdict(int) for s in graph_to_system: system_counts[s] += 1
systems = sorted([s for s in system_counts.keys() if s != "UNKNOWN"]) print(f" Unique systems: {len(systems)}")
counts = [system_counts[s] for s in systems] print(f" Poses per system: min={min(counts)}, max={max(counts)}, " f"median={sorted(counts)[len(counts)//2]}")
# Save index_filename = dataset_filename.replace("_enhanced_graphs.pt", "_system_index.json") index_path = os.path.join(DATASETS_DIR, index_filename)
index_data = { "graph_to_system": graph_to_system, "systems": systems, "n_graphs": n, "n_systems": len(systems), "system_counts": dict(sorted(system_counts.items())), }
with open(index_path, 'w') as f: json.dump(index_data, f, indent=2) print(f" Saved: {index_path}")
del graphs return index_data
SPLIT_SEED = 42TRAIN_RATIO = 0.70VAL_RATIO = 0.10CALIB_RATIO = 0.10
def generate_split_assignment(all_systems, seed=SPLIT_SEED): """ Generate a global system-level split assignment. Uses a canonical sorted list of all systems, shuffles with fixed seed, then splits 70/10/10/10.
Returns dict with train/val/calib/test system lists. """ import random as _random
systems = sorted(all_systems) n = len(systems)
rng = _random.Random(seed) rng.shuffle(systems)
train_end = int(n * TRAIN_RATIO) val_end = train_end + int(n * VAL_RATIO) calib_end = val_end + int(n * CALIB_RATIO)
assignment = { "train": sorted(systems[:train_end]), "val": sorted(systems[train_end:val_end]), "calib": sorted(systems[val_end:calib_end]), "test": sorted(systems[calib_end:]), "seed": seed, "ratios": { "train": TRAIN_RATIO, "val": VAL_RATIO, "calib": CALIB_RATIO, "test": round(1.0 - TRAIN_RATIO - VAL_RATIO - CALIB_RATIO, 2), }, "n_systems": n, "n_train": train_end, "n_val": val_end - train_end, "n_calib": calib_end - val_end, "n_test": n - calib_end, }
return assignment
def main(): print("Building system indices for all datasets") print(f"Data dir: {DATA_DIR}") print(f"Datasets dir: {DATASETS_DIR}")
all_method_systems = {} for method_name, dataset_filename in METHODS.items(): result = process_method(method_name, dataset_filename) if result: all_method_systems[method_name] = result["systems"]
# ---- Generate global split assignment ---- # Use the full system list (intersection of all methods to be safe) if all_method_systems: common_systems = set(all_method_systems[list(all_method_systems.keys())[0]]) for systems in all_method_systems.values(): common_systems &= set(systems) common_systems = sorted(common_systems)
print(f"\n{'='*60}") print(f" Global Split Assignment") print(f"{'='*60}") print(f" Common systems across all methods: {len(common_systems)}")
# Check if all methods have the same systems for method, systems in all_method_systems.items(): diff = set(systems) - set(common_systems) if diff: print(f" [WARN] {method} has extra systems: {diff}")
assignment = generate_split_assignment(common_systems)
print(f" Train: {assignment['n_train']} systems") print(f" Val: {assignment['n_val']} systems") print(f" Calib: {assignment['n_calib']} systems") print(f" Test: {assignment['n_test']} systems")
# Show per-target distribution in test set target_counts = defaultdict(int) for s in assignment["test"]: target = s.rsplit("_lig_", 1)[0] target_counts[target] += 1 print(f"\n Test set targets: {dict(sorted(target_counts.items()))}")
assignment_path = os.path.join(DATASETS_DIR, "system_split_assignment.json") with open(assignment_path, 'w') as f: json.dump(assignment, f, indent=2) print(f" Saved: {assignment_path}")
print("\nDone!")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543#!/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 onlyonce. 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. Nodefeatures are reconstructed as float32 [N, 82] and edge features as float32[E, 4]."""
from __future__ import annotations
import bisectimport jsonfrom collections import OrderedDictfrom pathlib import Pathfrom typing import Any, Dict, List, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
import torchfrom torch.utils.data import Datasetfrom torch_geometric.data import Data
FORMAT_NAME = "gnncp_compact_v1"SCHEMA_VERSION = 1STATIC_WIDTH = 44DYNAMIC_WIDTH = 38NODE_WIDTH = 82EDGE_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",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695#!/usr/bin/env python3"""Convert a legacy ``torch.save(list[torch_geometric.data.Data])`` dataset toGNNCP compact_v1 shards.
This program is intentionally meant to run in a Slurm compute job. The legacyfile is a single pickle, so it must be opened as a whole; ``mmap=True`` keepsits tensor storages file-backed while the converter processes one system at atime.
The compact format is lossless for the stored float32 node features andcoordinates. It does not reduce the 82-dimensional model input:
* 44 pose-invariant x columns are stored once per system.* 38 pose-dependent x columns are stored once per pose.* protein-protein undirected edges are stored once per system.* all other undirected edges are stored once per pose.* pos, is_protein, y_true, y_pred, y_grt, edge_attr and reverse edges are derived by the loader.
All systems remain wholly within one shard. ``manifest.json`` maps everylegacy graph index to ``[shard_index, local_pose_index]``."""
from __future__ import annotations
import argparseimport gcimport hashlibimport jsonimport osimport sysfrom collections import Counter, defaultdictfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Sequence, Tuple
import torch
FORMAT_NAME = "gnncp_compact_v1"SCHEMA_VERSION = 1
# build_graph_unified_enhanced.py column layout:# static: atom OH (11), residue OH (21), protein/ligand flags (2),# chemistry (5), protein-specific (5)# dynamic: all geometry/topology/interface/environment columns.STATIC_COLUMNS: Tuple[int, ...] = tuple(range(0, 34)) + tuple(range(61, 71))DYNAMIC_COLUMNS: Tuple[int, ...] = tuple(range(34, 61)) + tuple(range(71, 82))
UNKNOWN_LABELS = {"", "UNKNOWN", "NONE", "NULL", "N/A"}
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Convert a legacy GNNCP PyG list to compact_v1 tensor shards." ) parser.add_argument("--input", required=True, type=Path, help="Legacy *_enhanced_graphs.pt") parser.add_argument("--output-dir", required=True, type=Path, help="New method output directory") parser.add_argument("--method", required=True, help="Docking method name stored in manifest") parser.add_argument( "--system-index", type=Path, default=None, help=( "Optional JSON containing graph_to_system labels. Exact tensor " "content remains the authoritative grouping key." ), ) parser.add_argument( "--target-shard-mib", type=int, default=512, help="Approximate uncompressed tensor bytes per shard; systems never cross shards.", ) parser.add_argument( "--cutoff", type=float, default=6.0, help="Original graph cutoff, needed to reconstruct edge_attr (default: 6.0 A).", ) parser.add_argument( "--no-mmap", action="store_true", help="Eagerly load tensor storage. Only use in a sufficiently large-memory compute job.", ) parser.add_argument( "--skip-strict-validation", action="store_true", help="Skip expensive edge symmetry and redundant-field consistency checks.", ) return parser.parse_args()
def tensor_bytes(tensor: torch.Tensor) -> int: return tensor.numel() * tensor.element_size()
def require_tensor(graph: Any, name: str) -> torch.Tensor: value = getattr(graph, name, None) if not isinstance(value, torch.Tensor): raise ValueError(f"graph is missing tensor field {name!r}") if value.device.type != "cpu": value = value.cpu() return value
def infer_partition(graph: Any) -> Tuple[int, int, int]: x = require_tensor(graph, "x") if x.ndim != 2 or x.shape[1] != 82: raise ValueError(f"expected x=[N,82], got {tuple(x.shape)}") if x.dtype != torch.float32: raise ValueError(f"expected float32 x, got {x.dtype}")
mask = require_tensor(graph, "is_protein").reshape(-1) n_nodes = x.shape[0] if mask.numel() != n_nodes: raise ValueError("is_protein length does not match x") is_protein = mask > 0.5 n_protein = int(is_protein.sum().item()) if n_protein <= 0 or n_protein >= n_nodes: raise ValueError(f"invalid protein/ligand partition: N={n_nodes}, Np={n_protein}") expected = torch.arange(n_nodes) < n_protein if not torch.equal(is_protein, expected): raise ValueError("compact_v1 requires protein nodes first and ligand nodes last") return n_nodes, n_protein, n_nodes - n_protein
def graph_content_hashes(graph: Any) -> Tuple[str, str]: """Return exact native-structure and pose-shared-content hashes.
The legacy per-method indices are useful labels, but some of them are not aligned perfectly with the graph list. The shared-content hash is therefore the authoritative grouping key. It also includes all 44 nominally static x columns: a few legacy poses use different ligand atom annotations despite sharing the same native coordinates, and those poses must not silently share an incompatible x_static tensor. """ n_nodes, n_protein, n_ligand = infer_partition(graph) y_grt = require_tensor(graph, "y_grt") if y_grt.dtype != torch.float32 or tuple(y_grt.shape) != (n_nodes, 3): raise ValueError(f"expected y_grt float32 [{n_nodes},3], got {y_grt.dtype} {tuple(y_grt.shape)}") x = require_tensor(graph, "x") static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64) x_static = x.index_select(1, static_index).contiguous()
prefix = bytearray(b"gnncp-native-v1\0") prefix.extend(n_nodes.to_bytes(8, "little", signed=False)) prefix.extend(n_protein.to_bytes(8, "little", signed=False)) prefix.extend(n_ligand.to_bytes(8, "little", signed=False))
native_digest = hashlib.sha256() native_digest.update(prefix) native_digest.update(memoryview(y_grt.detach().contiguous().numpy())) native_hash = native_digest.hexdigest()
shared_digest = hashlib.sha256() shared_digest.update(b"gnncp-shared-v1\0") shared_digest.update(bytes.fromhex(native_hash)) shared_digest.update(memoryview(x_static.detach().numpy())) return native_hash, shared_digest.hexdigest()
def read_system_labels(path: Path | None, n_graphs: int) -> Tuple[List[str | None], str]: if path is None: return [None] * n_graphs, "y_grt_sha256" with path.open("r", encoding="utf-8") as handle: payload = json.load(handle) labels = payload.get("graph_to_system") if not isinstance(labels, list): raise ValueError(f"{path}: graph_to_system is not a list") if len(labels) != n_graphs: raise ValueError( f"{path}: graph_to_system has {len(labels)} entries, legacy dataset has {n_graphs}" ) normalized: List[str | None] = [] for value in labels: label = str(value).strip() if value is not None else "" normalized.append(None if label.upper() in UNKNOWN_LABELS else label) return normalized, "graph_to_system_plus_y_grt_sha256"
def group_graphs( graphs: Sequence[Any], labels: Sequence[str | None]) -> List[Dict[str, Any]]: """ Group solely by exact pose-shared tensor content.
External system labels are deliberately not part of the grouping key. They are attached only when every labelled member agrees. This prevents a stale/misaligned index from either merging unrelated graphs or splitting poses that have identical shared tensors. """ grouped: MutableMapping[str, List[int]] = defaultdict(list) native_hash_by_shared: Dict[str, str] = {} n_graphs = len(graphs) for graph_index, graph in enumerate(graphs): native_hash, shared_hash = graph_content_hashes(graph) grouped[shared_hash].append(graph_index) previous_native_hash = native_hash_by_shared.setdefault(shared_hash, native_hash) if previous_native_hash != native_hash: raise RuntimeError("shared-content SHA-256 collision detected") if (graph_index + 1) % 500 == 0 or graph_index + 1 == n_graphs: print(f"[group] hashed {graph_index + 1}/{n_graphs} graphs", flush=True)
systems: List[Dict[str, Any]] = [] for shared_hash, graph_indices in grouped.items(): label_counts = Counter( labels[index] for index in graph_indices if labels[index] is not None ) agreed_label = next(iter(label_counts)) if len(label_counts) == 1 else None systems.append( { "system_id": agreed_label or f"hash_{shared_hash[:20]}", "source_label": agreed_label, "source_label_counts": dict(sorted(label_counts.items())), "native_hash": native_hash_by_shared[shared_hash], "shared_hash": shared_hash, "graph_indices": sorted(graph_indices), } )
# A legacy label can legitimately cover more than one exact shared tensor # signature. Keep those records distinct and make their IDs unambiguous. label_occurrences = Counter( item["source_label"] for item in systems if item["source_label"] is not None ) for item in systems: label = item["source_label"] if label is not None and label_occurrences[label] > 1: item["system_id"] = f"{label}__{item['shared_hash'][:12]}"
# Deterministic output independent of dict insertion details. systems.sort(key=lambda item: (item["system_id"], item["graph_indices"][0])) return systems
def canonical_upper_edges( edge_index: torch.Tensor, n_nodes: int, strict: bool) -> torch.Tensor: """Return each symmetric directed edge pair once, with local src < dst.""" if edge_index.ndim != 2 or edge_index.shape[0] != 2: raise ValueError(f"expected edge_index=[2,E], got {tuple(edge_index.shape)}") edge = edge_index.to(dtype=torch.int64) src, dst = edge[0], edge[1] if edge.numel() and ( int(edge.min().item()) < 0 or int(edge.max().item()) >= n_nodes ): raise ValueError("edge_index contains an out-of-range node index") if torch.any(src == dst): raise ValueError("legacy graph unexpectedly contains self edges")
upper_mask = src < dst upper = edge[:, upper_mask] if strict: lower_mask = src > dst if int(upper_mask.sum()) != int(lower_mask.sum()): raise ValueError("edge_index is not a symmetric directed edge list") upper_key = upper[0] * n_nodes + upper[1] reverse_lower_key = dst[lower_mask] * n_nodes + src[lower_mask] upper_key = torch.sort(upper_key).values reverse_lower_key = torch.sort(reverse_lower_key).values if not torch.equal(upper_key, reverse_lower_key): raise ValueError("edge_index is missing one or more reverse edges") if upper_key.numel() > 1 and torch.any(upper_key[1:] == upper_key[:-1]): raise ValueError("edge_index contains duplicate edges") return upper.to(dtype=torch.int32).contiguous()
def assert_equal(name: str, actual: torch.Tensor, expected: torch.Tensor) -> None: if actual.dtype != expected.dtype or actual.shape != expected.shape: raise ValueError( f"{name} differs: {actual.dtype}{tuple(actual.shape)} vs " f"{expected.dtype}{tuple(expected.shape)}" ) if not torch.equal(actual, expected): raise ValueError(f"{name} is not identical within a system")
def build_system_record( graphs: Sequence[Any], system: Mapping[str, Any], strict: bool,) -> Dict[str, Any]: graph_indices: List[int] = list(system["graph_indices"]) reference = graphs[graph_indices[0]] n_nodes, n_protein, n_ligand = infer_partition(reference) n_poses = len(graph_indices)
static_index = torch.tensor(STATIC_COLUMNS, dtype=torch.int64) dynamic_index = torch.tensor(DYNAMIC_COLUMNS, dtype=torch.int64)
ref_x = require_tensor(reference, "x") x_static = ref_x.index_select(1, static_index).contiguous().clone() ref_pos = require_tensor(reference, "pos") ref_y_pred = require_tensor(reference, "y_pred") ref_y_grt = require_tensor(reference, "y_grt") for field_name, value in ( ("pos", ref_pos), ("y_pred", ref_y_pred), ("y_grt", ref_y_grt), ): if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3): raise ValueError( f"{system['system_id']}: expected {field_name} float32 [{n_nodes},3]" ) if strict: assert_equal("reference pos/y_pred", ref_pos, ref_y_pred)
protein_pos = ref_pos[:n_protein].contiguous().clone() native_ligand_pos = ref_y_grt[n_protein:].contiguous().clone() x_dynamic = torch.empty((n_poses * n_nodes, len(DYNAMIC_COLUMNS)), dtype=torch.float32) ligand_pos = torch.empty((n_poses * n_ligand, 3), dtype=torch.float32)
ref_upper = canonical_upper_edges( require_tensor(reference, "edge_index"), n_nodes, strict ) ref_pp_mask = (ref_upper[0] < n_protein) & (ref_upper[1] < n_protein) pp_edge_upper = ref_upper[:, ref_pp_mask].contiguous().clone()
nonpp_edges: List[torch.Tensor] = [] nonpp_counts: List[int] = []
for pose_index, graph_index in enumerate(graph_indices): graph = graphs[graph_index] shape = infer_partition(graph) if shape != (n_nodes, n_protein, n_ligand): raise ValueError( f"{system['system_id']}: graph {graph_index} changed node partition " f"from {(n_nodes, n_protein, n_ligand)} to {shape}" )
x = require_tensor(graph, "x") current_static = x.index_select(1, static_index) assert_equal("x static columns", current_static, x_static) dynamic_start = pose_index * n_nodes x_dynamic[dynamic_start : dynamic_start + n_nodes].copy_( x.index_select(1, dynamic_index) )
pos = require_tensor(graph, "pos") y_pred = require_tensor(graph, "y_pred") y_grt = require_tensor(graph, "y_grt") for field_name, value in (("pos", pos), ("y_pred", y_pred), ("y_grt", y_grt)): if value.dtype != torch.float32 or tuple(value.shape) != (n_nodes, 3): raise ValueError( f"{system['system_id']}: graph {graph_index} has invalid {field_name}" ) assert_equal("protein coordinates", pos[:n_protein], protein_pos) assert_equal("native ligand coordinates", y_grt[n_protein:], native_ligand_pos) if strict: assert_equal("pos/y_pred", pos, y_pred) assert_equal("ground-truth protein coordinates", y_grt[:n_protein], protein_pos) y_true = require_tensor(graph, "y_true").reshape(-1) if y_true.dtype != torch.float32 or y_true.numel() != n_nodes: raise ValueError("invalid y_true") expected_error = torch.linalg.vector_norm(pos - y_grt, dim=1) if not torch.allclose(y_true, expected_error, rtol=1e-5, atol=1e-5): raise ValueError("y_true cannot be reconstructed from pos and y_grt")
ligand_start = pose_index * n_ligand ligand_pos[ligand_start : ligand_start + n_ligand].copy_(pos[n_protein:])
upper = canonical_upper_edges(require_tensor(graph, "edge_index"), n_nodes, strict) pp_mask = (upper[0] < n_protein) & (upper[1] < n_protein) assert_equal("protein-protein edges", upper[:, pp_mask], pp_edge_upper) nonpp = upper[:, ~pp_mask].contiguous().clone() nonpp_edges.append(nonpp) nonpp_counts.append(nonpp.shape[1])
if strict: edge_attr = require_tensor(graph, "edge_attr") if edge_attr.dtype != torch.float32 or tuple(edge_attr.shape) != ( require_tensor(graph, "edge_index").shape[1], 4, ): raise ValueError("invalid edge_attr")
if nonpp_edges: nonpp_edge_upper = torch.cat(nonpp_edges, dim=1) else: nonpp_edge_upper = torch.empty((2, 0), dtype=torch.int32)
record: Dict[str, Any] = { # Metadata used for packing/manifest; not serialized into the tensor shard. "_system_id": system["system_id"], "_source_label": system["source_label"], "_source_label_counts": system["source_label_counts"], "_native_hash": system["native_hash"], "_shared_hash": system["shared_hash"], "_n_nodes": n_nodes, "_n_protein": n_protein, "_n_ligand": n_ligand, "_n_poses": n_poses, # Serialized tensors. "x_static": x_static, "protein_pos": protein_pos, "native_ligand_pos": native_ligand_pos, "x_dynamic": x_dynamic, "ligand_pos": ligand_pos, "pp_edge_upper": pp_edge_upper, "nonpp_edge_upper": nonpp_edge_upper, "nonpp_edge_counts": torch.tensor(nonpp_counts, dtype=torch.int64), "source_graph_index": torch.tensor(graph_indices, dtype=torch.int64), } record["_tensor_bytes"] = sum( tensor_bytes(value) for value in record.values() if isinstance(value, torch.Tensor) ) return record
def cumulative_ptr(lengths: Iterable[int]) -> torch.Tensor: values = [0] for length in lengths: values.append(values[-1] + int(length)) return torch.tensor(values, dtype=torch.int64)
def concatenate(records: Sequence[Mapping[str, Any]], key: str, dim: int = 0) -> torch.Tensor: tensors = [record[key] for record in records] return torch.cat(tensors, dim=dim)
def pack_shard(records: Sequence[Mapping[str, Any]]) -> Dict[str, torch.Tensor]: n_poses = [record["_n_poses"] for record in records] n_nodes = [record["_n_nodes"] for record in records] n_protein = [record["_n_protein"] for record in records] n_ligand = [record["_n_ligand"] for record in records]
pose_system = torch.repeat_interleave( torch.arange(len(records), dtype=torch.int32), torch.tensor(n_poses, dtype=torch.int64), ) pose_node_lengths: List[int] = [] pose_ligand_lengths: List[int] = [] for p, n, nl in zip(n_poses, n_nodes, n_ligand): pose_node_lengths.extend([n] * p) pose_ligand_lengths.extend([nl] * p)
return { "schema_version": torch.tensor([SCHEMA_VERSION], dtype=torch.int32), "system_graph_ptr": cumulative_ptr(n_poses), "pose_system": pose_system, "source_graph_index": concatenate(records, "source_graph_index"), "system_node_ptr": cumulative_ptr(n_nodes), "n_protein": torch.tensor(n_protein, dtype=torch.int32), "x_static": concatenate(records, "x_static"), "protein_ptr": cumulative_ptr(n_protein), "protein_pos": concatenate(records, "protein_pos"), "native_ligand_ptr": cumulative_ptr(n_ligand), "native_ligand_pos": concatenate(records, "native_ligand_pos"), "pose_node_ptr": cumulative_ptr(pose_node_lengths), "x_dynamic": concatenate(records, "x_dynamic"), "pose_ligand_ptr": cumulative_ptr(pose_ligand_lengths), "ligand_pos": concatenate(records, "ligand_pos"), "pp_edge_ptr": cumulative_ptr( record["pp_edge_upper"].shape[1] for record in records ), "pp_edge_upper": concatenate(records, "pp_edge_upper", dim=1), "nonpp_edge_ptr": cumulative_ptr( int(count) for record in records for count in record["nonpp_edge_counts"].tolist() ), "nonpp_edge_upper": concatenate(records, "nonpp_edge_upper", dim=1), }
def main() -> int: args = parse_args() input_path = args.input.resolve() output_dir = args.output_dir.resolve() system_index = args.system_index.resolve() if args.system_index else None
if not input_path.is_file(): raise FileNotFoundError(input_path) if system_index is not None and not system_index.is_file(): raise FileNotFoundError(system_index) if output_dir.exists(): raise FileExistsError( f"refusing to overwrite existing output directory: {output_dir}" ) if args.target_shard_mib <= 0: raise ValueError("--target-shard-mib must be positive")
output_dir.parent.mkdir(parents=True, exist_ok=True) run_id = os.environ.get("SLURM_JOB_ID") or str(os.getpid()) staging_dir = output_dir.with_name(f".{output_dir.name}.building.{run_id}") if staging_dir.exists(): raise FileExistsError(f"staging directory already exists: {staging_dir}") shard_dir = staging_dir / "shards" shard_dir.mkdir(parents=True)
print(f"input: {input_path}", flush=True) print(f"output: {output_dir}", flush=True) print(f"staging: {staging_dir}", flush=True) print(f"method: {args.method}", flush=True) print(f"mmap: {not args.no_mmap}", flush=True) print(f"strict: {not args.skip_strict_validation}", flush=True)
try: graphs = torch.load( input_path, map_location="cpu", weights_only=False, mmap=not args.no_mmap, ) except RuntimeError as exc: if not args.no_mmap: raise RuntimeError( "mmap loading failed. Re-submit a sufficiently large-memory Slurm job " "with --no-mmap if this file uses legacy torch serialization." ) from exc raise if not isinstance(graphs, (list, tuple)): raise TypeError(f"expected legacy list/tuple, got {type(graphs).__name__}") n_graphs = len(graphs) if n_graphs == 0: raise ValueError("legacy dataset is empty") print(f"opened {n_graphs} legacy graphs", flush=True)
labels, grouping_mode = read_system_labels(system_index, n_graphs) systems = group_graphs(graphs, labels) print( f"grouped into {len(systems)} systems via exact shared-content hash " f"(labels: {grouping_mode})", flush=True, )
target_bytes = args.target_shard_mib * 1024 * 1024 strict = not args.skip_strict_validation graph_map: List[List[int] | None] = [None] * n_graphs shard_manifest: List[Dict[str, Any]] = [] pending: List[Dict[str, Any]] = [] pending_bytes = 0 compact_bytes = 0
def flush_pending() -> None: nonlocal pending, pending_bytes, compact_bytes if not pending: return shard_index = len(shard_manifest) relative_path = f"shards/shard_{shard_index:05d}.pt" final_path = staging_dir / relative_path temp_path = final_path.with_suffix(".pt.tmp") packed = pack_shard(pending) torch.save(packed, temp_path) os.replace(temp_path, final_path) size_bytes = final_path.stat().st_size compact_bytes += size_bytes
local_pose = 0 system_entries: List[Dict[str, Any]] = [] for record in pending: source_indices = record["source_graph_index"].tolist() for offset, source_index in enumerate(source_indices): graph_map[source_index] = [shard_index, local_pose + offset] system_entries.append( { "system_id": record["_system_id"], "source_label": record["_source_label"], "source_label_counts": record["_source_label_counts"], "native_hash": record["_native_hash"], "shared_hash": record["_shared_hash"], "num_graphs": record["_n_poses"], "num_nodes": record["_n_nodes"], "num_protein_nodes": record["_n_protein"], "num_ligand_nodes": record["_n_ligand"], } ) local_pose += record["_n_poses"]
shard_manifest.append( { "path": relative_path, "num_graphs": local_pose, "num_systems": len(pending), "size_bytes": size_bytes, "systems": system_entries, } ) print( f"[write] {relative_path}: {len(pending)} systems, {local_pose} graphs, " f"{size_bytes / 2**20:.1f} MiB", flush=True, ) del packed pending = [] pending_bytes = 0 gc.collect()
for system_number, system in enumerate(systems, start=1): record = build_system_record(graphs, system, strict=strict) record_bytes = int(record["_tensor_bytes"]) if pending and pending_bytes + record_bytes > target_bytes: flush_pending() pending.append(record) pending_bytes += record_bytes print( f"[system] {system_number}/{len(systems)} {system['system_id']}: " f"{record['_n_poses']} poses, {record_bytes / 2**20:.1f} MiB raw compact", flush=True, ) flush_pending()
if any(item is None for item in graph_map): raise RuntimeError("internal error: graph_map is incomplete")
source_stat = input_path.stat() manifest: Dict[str, Any] = { "format": FORMAT_NAME, "schema_version": SCHEMA_VERSION, "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), "method": args.method, "cutoff": args.cutoff, "source": { "path": str(input_path), "size_bytes": source_stat.st_size, "mtime_ns": source_stat.st_mtime_ns, "system_index": str(system_index) if system_index else None, }, "grouping": { "mode": "exact_shared_content_hash", "label_source": grouping_mode, "authoritative_key": ( "sha256(exact float32 y_grt + node partition + " "x[:,0:34] + x[:,61:71])" ), "external_labels_are_metadata_only": True, }, "features": { "full_dimension": 82, "dtype": "float32", "static_dimension": len(STATIC_COLUMNS), "static_columns": list(STATIC_COLUMNS), "dynamic_dimension": len(DYNAMIC_COLUMNS), "dynamic_columns": list(DYNAMIC_COLUMNS), }, "edges": { "index_dtype_on_disk": "int32", "stored_direction": "upper_triangle_src_lt_dst", "protein_protein_scope": "once_per_system", "non_protein_protein_scope": "once_per_pose", "edge_attr": "derived_from_float32_coordinates_and_endpoint_types", }, "derived_fields": [ "pos", "is_protein", "y_true", "y_pred", "y_grt", "edge_index_reverse_direction", "edge_attr", "num_nodes", ], "n_graphs": n_graphs, "n_systems": len(systems), "n_shards": len(shard_manifest), "graph_map": graph_map, "shards": shard_manifest, "size": { "legacy_bytes": source_stat.st_size, "compact_shard_bytes": compact_bytes, "legacy_to_compact_ratio": ( source_stat.st_size / compact_bytes if compact_bytes else None ), }, "strict_validation": strict, } manifest_path = staging_dir / "manifest.json" temp_manifest = staging_dir / "manifest.json.tmp" with temp_manifest.open("w", encoding="utf-8") as handle: json.dump(manifest, handle, indent=2, ensure_ascii=False) handle.write("\n") os.replace(temp_manifest, manifest_path)
# Atomic publication: manifest.json is the stable completion marker. os.replace(staging_dir, output_dir) print(f"complete: {output_dir / 'manifest.json'}", flush=True) print( f"legacy={source_stat.st_size / 2**30:.2f} GiB, " f"compact_shards={compact_bytes / 2**30:.2f} GiB, " f"ratio={source_stat.st_size / compact_bytes:.2f}x", flush=True, ) return 0
if __name__ == "__main__": try: raise SystemExit(main()) except Exception as error: print(f"ERROR: {error}", file=sys.stderr, flush=True) raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240#!/usr/bin/env python3"""Materialize Docking Base PDB outputs into GNNCP's flat pose layout.
The operation is intentionally non-destructive: it reads canonical commonoutputs and creates hard links in a new directory. It neither rewrites normoves a docking result. The resulting layout is accepted by``gnncp/system_split_code/build_compact_v1_direct.py``."""
from __future__ import annotations
import argparseimport csvimport jsonimport osimport reimport shutilimport tempfilefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable
METHODS = ("diffdock", "autodock_vina", "medusagraph", "protenix")TARGET_RE = re.compile(r"[A-Za-z0-9_.-]+\Z")
class MaterializeError(RuntimeError): pass
def _utc_now() -> str: return datetime.now(timezone.utc).isoformat()
def _write_json(path: Path, value: dict[str, Any]) -> None: path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def _read_manifest(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise MaterializeError(f"cannot read manifest {path}: {exc}") from exc if not isinstance(value, dict): raise MaterializeError(f"manifest is not an object: {path}") return value
def _inside(path: Path, root: Path) -> Path: resolved = path.resolve() try: resolved.relative_to(root.resolve()) except ValueError as exc: raise MaterializeError(f"path escapes native output directory: {path}") from exc return resolved
def _pose_paths(native: Path) -> list[Path]: csv_path = native / "poses.csv" try: with csv_path.open("r", newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) except OSError as exc: raise MaterializeError(f"cannot read {csv_path}: {exc}") from exc if not rows: raise MaterializeError(f"no emitted poses in {csv_path}") poses: list[tuple[int, str, Path]] = [] for ordinal, row in enumerate(rows, start=1): raw_path = row.get("pose_file") if not raw_path: raise MaterializeError(f"{csv_path}: pose row {ordinal} has no pose_file") candidate = Path(raw_path) source = candidate if candidate.is_absolute() else native / candidate source = _inside(source, native) if source.suffix.lower() != ".pdb" or not source.is_file(): raise MaterializeError(f"{csv_path}: unsupported or missing PDB pose {source}") rank_text = row.get("rank", "") try: rank = int(rank_text) except ValueError: rank = ordinal poses.append((rank, source.name, source)) poses.sort(key=lambda item: (item[0], item[1])) return [item[2] for item in poses]
def _discover(source_roots: Iterable[Path], method: str) -> dict[str, dict[str, Any]]: """Discover eligible outputs; later source roots deliberately take precedence.""" selected: dict[str, dict[str, Any]] = {} for source_root in source_roots: if not source_root.is_dir(): raise MaterializeError(f"source root is not a directory: {source_root}") # Do not use a recursive glob here: a bulk run's work tree includes # multi-gigabyte raw model artifacts. These are the only published # Docking Base layouts produced by the normal/sharded/bulk launchers. patterns = ( f"output/{method}/*/native/manifest.json", f"shards/*/{method}/output/{method}/*/native/manifest.json", f"workers/*/units/*/{method}/output/{method}/*/native/manifest.json", f"*/{method}/output/{method}/*/native/manifest.json", ) manifest_paths = { path for pattern in patterns for path in source_root.glob(pattern) } for manifest_path in sorted(manifest_paths, key=lambda value: str(value)): native = manifest_path.parent target = native.parent.name if not TARGET_RE.fullmatch(target): raise MaterializeError(f"unsafe target name {target!r} in {native}") manifest = _read_manifest(manifest_path) if manifest.get("status") not in {"success", "partial"}: continue selected[target] = { "native": native.resolve(), "manifest": manifest_path.resolve(), "source_root": source_root.resolve(), } return selected
def _link(source: Path, destination: Path) -> None: if destination.exists() or destination.is_symlink(): raise MaterializeError(f"unexpected existing materialized file: {destination}") try: os.link(source, destination) except OSError as exc: raise MaterializeError( f"hard-link failed ({source} -> {destination}); source and output must share a filesystem: {exc}" ) from exc
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--method", choices=METHODS, required=True) parser.add_argument( "--source-root", action="append", type=Path, required=True, help="run root to scan; repeatable, later roots take target precedence", ) parser.add_argument("--output-root", type=Path, required=True) parser.add_argument("--max-systems", type=int, help="materialize this many ordered systems") parser.add_argument("--max-poses-per-system", type=int, default=20) return parser
def main() -> int: args = build_parser().parse_args() if args.max_systems is not None and args.max_systems <= 0: raise MaterializeError("--max-systems must be positive") if args.max_poses_per_system <= 0: raise MaterializeError("--max-poses-per-system must be positive") output_root = args.output_root.expanduser().resolve() if output_root.exists(): raise MaterializeError(f"output root already exists; refusing to replace it: {output_root}") source_roots = [path.expanduser().resolve() for path in args.source_root] selected = _discover(source_roots, args.method) ordered_targets = sorted(selected, key=str.casefold) if args.max_systems is not None: ordered_targets = ordered_targets[: args.max_systems] if not ordered_targets: raise MaterializeError("no success/partial common outputs discovered")
output_root.parent.mkdir(parents=True, exist_ok=True) staging = Path(tempfile.mkdtemp(prefix=f".{output_root.name}.building-", dir=output_root.parent)) records: dict[str, Any] = {} skipped: dict[str, str] = {} try: for target in ordered_targets: source = selected[target] native = Path(source["native"]) try: protein = _inside(native / "protein.pdb", native) ligand = _inside(native / "ligand.pdb", native) if not protein.is_file() or not ligand.is_file(): raise MaterializeError("missing protein.pdb or ligand.pdb") poses = _pose_paths(native)[: args.max_poses_per_system] if not poses: raise MaterializeError("no usable PDB poses") destination = staging / target destination.mkdir() _link(protein, destination / "protein.pdb") _link(ligand, destination / "ligand.pdb") names: list[str] = [] for ordinal, pose in enumerate(poses, start=1): name = f"{target}_pose_{ordinal:03d}.pdb" _link(pose, destination / name) names.append(name) records[target] = { "source_root": str(source["source_root"]), "source_native": str(native), "source_manifest": str(source["manifest"]), "pose_count": len(names), "materialized_poses": names, } except MaterializeError as exc: shutil.rmtree(staging / target, ignore_errors=True) skipped[target] = str(exc) if not records: raise MaterializeError("all selected systems were unusable") source_index = { "kind": "docking_base_common_output_to_gnncp_flat_index", "method": args.method, "records": records, "skipped": skipped, } _write_json(staging / "source_index.json", source_index) _write_json( staging / "materialization_manifest.json", { "kind": "docking_base_gnncp_materialization", "created_utc": _utc_now(), "method": args.method, "link_mode": "hardlink", "source_roots": [str(path) for path in source_roots], "requested_system_count": len(ordered_targets), "materialized_system_count": len(records), "materialized_pose_count": sum(item["pose_count"] for item in records.values()), "skipped_system_count": len(skipped), "max_poses_per_system": args.max_poses_per_system, }, ) os.replace(staging, output_root) except Exception: shutil.rmtree(staging, ignore_errors=True) raise print(json.dumps({"output_root": str(output_root), **json.loads((output_root / "materialization_manifest.json").read_text())}, sort_keys=True)) return 0
if __name__ == "__main__": try: raise SystemExit(main()) except MaterializeError as exc: print(f"error: {exc}") raise SystemExit(2)123456789# Reader dependenciestorch>=2.3torch-geometric>=2.4
# Additional dependencies required only to rebuild compact shards from PDB posesnumpy>=1.24scipy>=1.10MDAnalysis>=2.5tqdm>=4.65123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636#!/usr/bin/env python3"""Compute-node smoke test for :class:`CompactGraphDataset`.
The test intentionally samples rather than scans the complete dataset. Itexercises:
* deterministic random graph reconstruction;* at least one graph from every selected shard and cross-shard batches;* the per-process mmap shard cache through repeated access;* PyG DataLoader collation with zero and multiple worker processes; and* model-facing tensor shapes, dtypes, index ranges, and finite values.
Timing, process RSS/high-water marks, page faults, and filesystem I/O countersare written to an atomic JSON report. GNU ``time -v`` and Slurm accounting inthe companion sbatch file provide job-wide measurements including workers."""
from __future__ import annotations
import argparseimport gcimport jsonimport mathimport osimport randomimport resourceimport socketimport statisticsimport sysimport timeimport tracebackfrom pathlib import Pathfrom typing import Any, Dict, List, Mapping, Sequence
import torchimport torch_geometricfrom torch.utils.data import Subsetfrom torch_geometric.data import Batch, Datafrom torch_geometric.loader import DataLoader
from compact_graph_dataset import CompactGraphDataset
MIB = 1024 * 1024
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Sample, batch, and profile a compact GNNCP dataset." ) parser.add_argument("--compact", required=True, help="Compact dataset directory") parser.add_argument("--report", help="Atomic JSON report path") parser.add_argument("--num-random", type=int, default=16) parser.add_argument( "--max-shards", type=int, default=0, help="Maximum shards to probe; 0 tests every shard", ) parser.add_argument("--batch-size", type=int, default=4) parser.add_argument("--num-workers", type=int, default=2) parser.add_argument( "--worker-timeout-s", type=float, default=180.0, help="Multi-worker DataLoader timeout; zero disables it", ) parser.add_argument("--max-batches", type=int, default=8) parser.add_argument("--max-cached-shards", type=int, default=2) parser.add_argument("--repeat-count", type=int, default=3) parser.add_argument("--seed", type=int, default=0) parser.add_argument( "--torch-threads", type=int, default=min(4, int(os.environ.get("SLURM_CPUS_PER_TASK", "4"))), ) parser.add_argument( "--no-strict", action="store_true", help="Disable loader invariant checks (not recommended for smoke tests)", ) args = parser.parse_args() positive = { "num_random": args.num_random, "batch_size": args.batch_size, "max_batches": args.max_batches, "max_cached_shards": args.max_cached_shards, "repeat_count": args.repeat_count, "torch_threads": args.torch_threads, } for name, value in positive.items(): if value < 1: parser.error(f"--{name.replace('_', '-')} must be >= 1") if args.num_workers < 0: parser.error("--num-workers must be >= 0") if args.worker_timeout_s < 0: parser.error("--worker-timeout-s must be >= 0") if args.max_shards < 0: parser.error("--max-shards must be >= 0") return args
def _proc_status_mib(field: str) -> float | None: try: with Path("/proc/self/status").open("r", encoding="utf-8") as handle: for line in handle: if line.startswith(f"{field}:"): return float(line.split()[1]) / 1024.0 except OSError: return None return None
def _proc_io_bytes() -> Dict[str, int]: result = {"read_bytes": 0, "write_bytes": 0} try: with Path("/proc/self/io").open("r", encoding="utf-8") as handle: for line in handle: key, raw_value = line.split(":", 1) if key in result: result[key] = int(raw_value.strip()) except OSError: pass return result
def resource_snapshot() -> Dict[str, float | int | None]: usage = resource.getrusage(resource.RUSAGE_SELF) children = resource.getrusage(resource.RUSAGE_CHILDREN) io_bytes = _proc_io_bytes() # ru_maxrss is KiB on Linux, which is the target Slurm platform. return { "monotonic_s": time.perf_counter(), "rss_mib": _proc_status_mib("VmRSS"), "hwm_mib": _proc_status_mib("VmHWM"), "ru_maxrss_mib": float(usage.ru_maxrss) / 1024.0, "minor_faults": int(usage.ru_minflt), "major_faults": int(usage.ru_majflt), "self_user_cpu_s": float(usage.ru_utime), "self_system_cpu_s": float(usage.ru_stime), "children_ru_maxrss_mib": float(children.ru_maxrss) / 1024.0, "children_minor_faults": int(children.ru_minflt), "children_major_faults": int(children.ru_majflt), "children_user_cpu_s": float(children.ru_utime), "children_system_cpu_s": float(children.ru_stime), "read_bytes": io_bytes["read_bytes"], "write_bytes": io_bytes["write_bytes"], }
def resource_delta( before: Mapping[str, float | int | None], after: Mapping[str, float | int | None],) -> Dict[str, float | int | None]: def subtract(key: str) -> float | int | None: left = after.get(key) right = before.get(key) if left is None or right is None: return None return left - right
return { "elapsed_s": subtract("monotonic_s"), "rss_mib_after": after.get("rss_mib"), "rss_mib_delta": subtract("rss_mib"), "hwm_mib_after": after.get("hwm_mib"), "ru_maxrss_mib_after": after.get("ru_maxrss_mib"), "minor_faults_delta": subtract("minor_faults"), "major_faults_delta": subtract("major_faults"), "self_user_cpu_s_delta": subtract("self_user_cpu_s"), "self_system_cpu_s_delta": subtract("self_system_cpu_s"), "children_ru_maxrss_mib_after": after.get("children_ru_maxrss_mib"), "children_minor_faults_delta": subtract("children_minor_faults"), "children_major_faults_delta": subtract("children_major_faults"), "children_user_cpu_s_delta": subtract("children_user_cpu_s"), "children_system_cpu_s_delta": subtract("children_system_cpu_s"), "read_mib_delta": ( None if subtract("read_bytes") is None else float(subtract("read_bytes")) / MIB ), "write_mib_delta": ( None if subtract("write_bytes") is None else float(subtract("write_bytes")) / MIB ), }
def latency_summary(values: Sequence[float]) -> Dict[str, float | int]: if not values: return {"count": 0} ordered = sorted(values) p95_index = max(0, math.ceil(0.95 * len(ordered)) - 1) return { "count": len(ordered), "total_s": float(sum(ordered)), "mean_ms": float(statistics.fmean(ordered) * 1000.0), "median_ms": float(statistics.median(ordered) * 1000.0), "p95_ms": float(ordered[p95_index] * 1000.0), "min_ms": float(ordered[0] * 1000.0), "max_ms": float(ordered[-1] * 1000.0), }
def ensure_finite(name: str, tensor: torch.Tensor) -> None: if not bool(torch.isfinite(tensor).all().item()): raise RuntimeError(f"{name} contains NaN or infinity")
def check_graph(data: Data, dataset_index: int) -> Dict[str, Any]: required = ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt", ) missing = [name for name in required if not hasattr(data, name)] if missing: raise RuntimeError(f"graph {dataset_index} is missing fields: {missing}")
num_nodes = int(data.num_nodes) if data.x.shape != (num_nodes, 82) or data.x.dtype != torch.float32: raise RuntimeError( f"graph {dataset_index}: x={tuple(data.x.shape)} {data.x.dtype}" ) if data.edge_index.ndim != 2 or data.edge_index.shape[0] != 2: raise RuntimeError( f"graph {dataset_index}: edge_index={tuple(data.edge_index.shape)}" ) if data.edge_index.dtype != torch.int64: raise RuntimeError( f"graph {dataset_index}: edge_index dtype={data.edge_index.dtype}" ) num_edges = int(data.edge_index.shape[1]) if data.edge_attr.shape != (num_edges, 4): raise RuntimeError( f"graph {dataset_index}: edge_attr={tuple(data.edge_attr.shape)}" ) if data.edge_attr.dtype != torch.float32: raise RuntimeError( f"graph {dataset_index}: edge_attr dtype={data.edge_attr.dtype}" )
node_shapes = { "pos": (num_nodes, 3), "is_protein": (num_nodes, 1), "y_true": (num_nodes, 1), "y_pred": (num_nodes, 3), "y_grt": (num_nodes, 3), } for name, expected in node_shapes.items(): tensor = getattr(data, name) if tuple(tensor.shape) != expected or tensor.dtype != torch.float32: raise RuntimeError( f"graph {dataset_index}: {name}={tuple(tensor.shape)} {tensor.dtype}" ) ensure_finite(f"graph {dataset_index} {name}", tensor)
ensure_finite(f"graph {dataset_index} x", data.x) ensure_finite(f"graph {dataset_index} edge_attr", data.edge_attr) if not torch.equal(data.pos, data.y_pred): raise RuntimeError(f"graph {dataset_index}: pos and y_pred differ") if num_edges: edge_min = int(data.edge_index.min().item()) edge_max = int(data.edge_index.max().item()) if edge_min < 0 or edge_max >= num_nodes: raise RuntimeError( f"graph {dataset_index}: edge endpoints [{edge_min},{edge_max}] " f"outside [0,{num_nodes})" ) protein_values = torch.unique(data.is_protein) if not bool(torch.all((protein_values == 0) | (protein_values == 1)).item()): raise RuntimeError(f"graph {dataset_index}: is_protein is not binary")
return { "dataset_index": dataset_index, "num_nodes": num_nodes, "num_edges": num_edges, "num_protein_nodes": int(data.is_protein.sum().item()), "max_y_true": float(data.y_true.max().item()) if num_nodes else 0.0, }
def check_batch(batch: Batch, expected_graphs: int) -> Dict[str, Any]: actual_graphs = int(batch.num_graphs) if actual_graphs != expected_graphs: raise RuntimeError( f"batch reports {actual_graphs} graphs, expected {expected_graphs}" ) num_nodes = int(batch.x.shape[0]) if batch.x.ndim != 2 or batch.x.shape[1] != 82: raise RuntimeError(f"batched x has shape {tuple(batch.x.shape)}") if batch.edge_attr.ndim != 2 or batch.edge_attr.shape[1] != 4: raise RuntimeError( f"batched edge_attr has shape {tuple(batch.edge_attr.shape)}" ) if batch.batch.numel() != num_nodes: raise RuntimeError("PyG batch assignment length does not match node count") if batch.ptr.numel() != actual_graphs + 1: raise RuntimeError("PyG batch ptr length is invalid") if not torch.equal(batch.pos, batch.y_pred): raise RuntimeError("batched pos and y_pred differ") ensure_finite("batch x", batch.x) ensure_finite("batch edge_attr", batch.edge_attr) ensure_finite("batch pos", batch.pos) return { "num_graphs": actual_graphs, "num_nodes": num_nodes, "num_edges": int(batch.edge_index.shape[1]), }
def evenly_spaced(values: Sequence[int], limit: int) -> List[int]: if limit <= 0 or len(values) <= limit: return list(values) if limit == 1: return [values[0]] positions = { round(index * (len(values) - 1) / (limit - 1)) for index in range(limit) } return [values[position] for position in sorted(positions)]
def global_indices_by_shard(dataset: CompactGraphDataset) -> List[List[int]]: result: List[List[int]] = [[] for _ in dataset.shards] graph_map = dataset.manifest.get("graph_map") if graph_map is not None: for global_index, entry in enumerate(graph_map): if isinstance(entry, Mapping): shard_index = entry.get("shard", entry.get("shard_index")) else: shard_index = entry[0] result[int(shard_index)].append(global_index) else: global_index = 0 for shard_index, count in enumerate(dataset._shard_counts): result[shard_index].extend(range(global_index, global_index + count)) global_index += count empty = [index for index, indices in enumerate(result) if not indices] if empty: raise RuntimeError(f"manifest contains empty shards: {empty}") return result
def load_direct( dataset: CompactGraphDataset, indices: Sequence[int],) -> Dict[str, Any]: before = resource_snapshot() latencies: List[float] = [] samples: List[Dict[str, Any]] = [] total_nodes = 0 total_edges = 0 for dataset_index in indices: started = time.perf_counter() graph = dataset[dataset_index] latency = time.perf_counter() - started metrics = check_graph(graph, dataset_index) metadata = dataset.metadata(dataset_index) metrics.update( { "shard_index": int(metadata["shard_index"]), "source_graph_index": int(metadata["source_graph_index"]), "latency_ms": latency * 1000.0, } ) if "system_id" in metadata: metrics["system_id"] = metadata["system_id"] samples.append(metrics) latencies.append(latency) total_nodes += metrics["num_nodes"] total_edges += metrics["num_edges"] del graph gc.collect() after = resource_snapshot() resources = resource_delta(before, after) elapsed = float(resources["elapsed_s"] or 0.0) return { "indices": list(indices), "latency": latency_summary(latencies), "total_nodes": total_nodes, "total_edges": total_edges, "graphs_per_s": len(indices) / elapsed if elapsed > 0 else None, "nodes_per_s": total_nodes / elapsed if elapsed > 0 else None, "samples": samples, "resources": resources, }
def run_loader( dataset: CompactGraphDataset, indices: Sequence[int], *, batch_size: int, num_workers: int, max_batches: int, worker_timeout_s: float,) -> Dict[str, Any]: before = resource_snapshot() subset = Subset(dataset, list(indices)) loader = DataLoader( subset, batch_size=batch_size, shuffle=False, num_workers=num_workers, persistent_workers=False, pin_memory=False, timeout=worker_timeout_s if num_workers else 0, ) latencies: List[float] = [] batch_metrics: List[Dict[str, Any]] = [] iterator = iter(loader) prior = time.perf_counter() try: for batch_number, batch in enumerate(iterator): now = time.perf_counter() latency = now - prior latencies.append(latency) metrics = check_batch(batch, min(batch_size, len(indices) - batch_number * batch_size)) metrics["batch_number"] = batch_number metrics["latency_ms"] = latency * 1000.0 batch_metrics.append(metrics) del batch if batch_number + 1 >= max_batches: break prior = time.perf_counter() finally: del iterator del loader del subset gc.collect() after = resource_snapshot() resources = resource_delta(before, after) elapsed = float(resources["elapsed_s"] or 0.0) total_graphs = sum(item["num_graphs"] for item in batch_metrics) total_nodes = sum(item["num_nodes"] for item in batch_metrics) total_edges = sum(item["num_edges"] for item in batch_metrics) return { "num_workers": num_workers, "worker_timeout_s": worker_timeout_s if num_workers else 0, "batch_size": batch_size, "input_indices": list(indices), "batches_tested": len(batch_metrics), "graphs_tested": total_graphs, "total_nodes": total_nodes, "total_edges": total_edges, "graphs_per_s": total_graphs / elapsed if elapsed > 0 else None, "nodes_per_s": total_nodes / elapsed if elapsed > 0 else None, "latency": latency_summary(latencies), "batches": batch_metrics, "resources": resources, }
def write_report(path: Path, report: Mapping[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp.{os.getpid()}") with temporary.open("w", encoding="utf-8") as handle: json.dump(report, handle, indent=2, sort_keys=True, ensure_ascii=False) handle.write("\n") os.replace(temporary, path)
def run(args: argparse.Namespace) -> Dict[str, Any]: compact = Path(args.compact).expanduser().resolve() default_report = compact / ( f"smoke_report_{os.environ.get('SLURM_JOB_ID', str(os.getpid()))}.json" ) report_path = ( Path(args.report).expanduser().resolve() if args.report else default_report ) report: Dict[str, Any] = { "status": "running", "compact": str(compact), "report": str(report_path), "started_utc_epoch_s": time.time(), "environment": { "hostname": socket.gethostname(), "pid": os.getpid(), "python": sys.version, "torch": torch.__version__, "torch_geometric": torch_geometric.__version__, "slurm_job_id": os.environ.get("SLURM_JOB_ID"), "slurm_array_job_id": os.environ.get("SLURM_ARRAY_JOB_ID"), "slurm_array_task_id": os.environ.get("SLURM_ARRAY_TASK_ID"), "slurm_cpus_per_task": os.environ.get("SLURM_CPUS_PER_TASK"), }, "config": vars(args), "resources_at_start": resource_snapshot(), } try: torch.set_num_threads(args.torch_threads) initialization_before = resource_snapshot() dataset = CompactGraphDataset( compact, max_cached_shards=args.max_cached_shards, strict=not args.no_strict, ) initialization_after = resource_snapshot() if len(dataset) < 1: raise RuntimeError("compact dataset is empty")
report["dataset"] = { "num_graphs": len(dataset), "num_shards": len(dataset.shards), "n_systems": dataset.manifest.get("n_systems"), "method": dataset.manifest.get("method"), "size": dataset.manifest.get("size"), "initialization": resource_delta( initialization_before, initialization_after ), }
shard_indices = global_indices_by_shard(dataset) selected_shards = evenly_spaced( list(range(len(shard_indices))), args.max_shards ) boundary_indices: List[int] = [] first_per_shard: List[int] = [] for shard_index in selected_shards: indices = shard_indices[shard_index] first_per_shard.append(indices[0]) boundary_indices.append(indices[0]) if indices[-1] != indices[0]: boundary_indices.append(indices[-1]) report["shard_probe"] = { "selected_shards": selected_shards, "boundary_indices": boundary_indices, "all_shards_selected": len(selected_shards) == len(dataset.shards), } report["direct_cross_shard"] = load_direct(dataset, boundary_indices)
rng = random.Random(args.seed) random_count = min(args.num_random, len(dataset)) random_indices = rng.sample(range(len(dataset)), random_count) report["direct_random"] = load_direct(dataset, random_indices)
repeat_index = random_indices[0] repeat_latencies: List[float] = [] repeat_before = resource_snapshot() for _ in range(args.repeat_count): started = time.perf_counter() graph = dataset[repeat_index] repeat_latencies.append(time.perf_counter() - started) check_graph(graph, repeat_index) del graph gc.collect() repeat_after = resource_snapshot() report["repeated_access"] = { "index": repeat_index, "latency": latency_summary(repeat_latencies), "resources": resource_delta(repeat_before, repeat_after), }
cross_loader_indices = first_per_shard[ : args.batch_size * args.max_batches ] report["cross_shard_dataloader"] = run_loader( dataset, cross_loader_indices, batch_size=min(args.batch_size, len(cross_loader_indices)), num_workers=0, max_batches=args.max_batches, worker_timeout_s=args.worker_timeout_s, )
worker_indices = list(dict.fromkeys(random_indices + boundary_indices)) worker_indices = worker_indices[: args.batch_size * args.max_batches] # Forked workers should start with an empty mmap cache. Constructing a # fresh dataset here also catches errors in opening the same manifest # independently from more than one process. worker_dataset = CompactGraphDataset( compact, max_cached_shards=args.max_cached_shards, strict=not args.no_strict, ) report["multiworker_dataloader"] = run_loader( worker_dataset, worker_indices, batch_size=min(args.batch_size, len(worker_indices)), num_workers=args.num_workers, max_batches=args.max_batches, worker_timeout_s=args.worker_timeout_s, ) del worker_dataset
report["resources_at_end"] = resource_snapshot() report["completed_utc_epoch_s"] = time.time() report["elapsed_s"] = ( report["completed_utc_epoch_s"] - report["started_utc_epoch_s"] ) report["status"] = "passed" except Exception as error: report["status"] = "failed" report["completed_utc_epoch_s"] = time.time() report["elapsed_s"] = ( report["completed_utc_epoch_s"] - report["started_utc_epoch_s"] ) report["error"] = f"{type(error).__name__}: {error}" report["traceback"] = traceback.format_exc() write_report(report_path, report) raise
write_report(report_path, report) print( json.dumps( { "status": report["status"], "report": str(report_path), "num_graphs": report["dataset"]["num_graphs"], "num_shards": report["dataset"]["num_shards"], "elapsed_s": report["elapsed_s"], "rss_mib": report["resources_at_end"]["rss_mib"], "hwm_mib": report["resources_at_end"]["hwm_mib"], }, indent=2, sort_keys=True, ), flush=True, ) return report
def main() -> int: args = parse_args() report = run(args) return 0 if report["status"] == "passed" else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403#!/usr/bin/env python3"""Small, CPU-only tests for the resumable direct compact_v1 builder."""
from __future__ import annotations
import jsonimport tempfileimport timeimport unittestfrom pathlib import Pathfrom unittest import mock
import torchfrom torch_geometric.data import Data
import build_compact_v1_direct as directfrom compact_graph_dataset import CompactGraphDataset
def _synthetic_graph( system_id: str, pose_number: int, *, split_static: bool = False,) -> Data: n_protein = 2 n_nodes = 4 x = torch.zeros((n_nodes, 82), dtype=torch.float32) x[:, 0] = 1.0 x[:n_protein, 11] = 1.0 x[n_protein:, 31] = 1.0 x[:n_protein, 32] = 1.0 x[n_protein:, 33] = 1.0 x[:, 61:71] = 0.25 x[:, 34:61] = float(pose_number) x[:, 71:82] = float(pose_number) / 10.0 if split_static and pose_number == 2: x[2, 0] = 0.0 x[2, 1] = 1.0
system_offset = 5.0 if system_id == "sys_b" else 0.0 protein_pos = torch.tensor( [[system_offset, 0.0, 0.0], [system_offset + 1.0, 0.0, 0.0]], dtype=torch.float32, ) ligand_pos = torch.tensor( [ [system_offset + 1.5, 0.1 * pose_number, 0.0], [system_offset + 2.0, 0.2 * pose_number, 0.0], ], dtype=torch.float32, ) native_ligand = torch.tensor( [ [system_offset + 1.5, 0.0, 0.0], [system_offset + 2.0, 0.0, 0.0], ], dtype=torch.float32, ) pos = torch.cat((protein_pos, ligand_pos), dim=0) y_grt = torch.cat((protein_pos, native_ligand), dim=0) y_true = torch.linalg.vector_norm(pos - y_grt, dim=1, keepdim=True) edge_index = torch.tensor( [[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]], dtype=torch.int64, ) src, dst = edge_index distance = torch.linalg.vector_norm( pos[src].to(torch.float64) - pos[dst].to(torch.float64), dim=1, ) edge_attr = torch.stack( ( (distance / 6.0).to(torch.float32), torch.exp(-distance / 3.0).to(torch.float32), (src < n_protein).to(torch.float32), (dst < n_protein).to(torch.float32), ), dim=1, ) is_protein = torch.zeros((n_nodes, 1), dtype=torch.float32) is_protein[:n_protein] = 1.0 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.clone(), y_grt=y_grt, num_nodes=n_nodes, )
class DirectCompactBuilderTest(unittest.TestCase): def test_exclusive_output_lock_rejects_concurrent_resume(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_lock_") as temp: output = Path(temp) / "compact" with direct._exclusive_build_lock(output): with self.assertRaisesRegex( RuntimeError, "another direct compact build" ): with direct._exclusive_build_lock(output): self.fail("the second lock must not be acquired")
def test_corrupt_pose_checkpoint_is_rebuilt(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_corrupt_") as temp: root = Path(temp) for name in ("protein.pdb", "native.pdb", "pose_1.pdb"): (root / name).write_text("test\n", encoding="utf-8") pose = direct.PoseSpec( source_graph_index=0, system_id="sys_a", protein=(root / "protein.pdb"), ligand_native=(root / "native.pdb"), ligand_pred=(root / "pose_1.pdb"), ) system = direct.SystemSpec( ordinal=0, system_id="sys_a", protein=pose.protein, ligand_native=pose.ligand_native, poses=(pose,), ) work_dir = root / "work" work_dir.mkdir() corrupt = direct._pose_graph_path(work_dir, 0) corrupt.write_bytes(b"not a torch checkpoint") calls = []
def graph_builder(**kwargs): calls.append(kwargs["ligand_pred_pdb"]) return _synthetic_graph("sys_a", 1)
config = direct.BuildConfig( data_dir=root, output_dir=root / "output", method="protenix", ) graphs = direct.build_pose_graphs( system, work_dir, config, graph_builder=graph_builder, ) self.assertEqual(len(calls), 1) self.assertEqual(len(graphs), 1) rebuilt = torch.load(corrupt, map_location="cpu", weights_only=False) self.assertTrue(torch.equal(rebuilt.x, graphs[0].x))
def test_resume_atomic_publish_and_original_system_index(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_test_") as temp: root = Path(temp) data_dir = root / "docking" output_dir = root / "compact" raw_poses = [] for system_id in ("sys_a", "sys_b"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } )
def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph( system_id, pose_number, split_static=system_id == "sys_b", )
def first_attempt_builder(**kwargs): if Path(kwargs["ligand_pred_pdb"]).parent.name == "sys_b": raise RuntimeError("intentional interruption") return graph_builder(**kwargs)
config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=output_dir.resolve(), method="protenix", target_shard_mib=1, num_workers=1, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): with self.assertRaisesRegex(RuntimeError, "intentional interruption"): direct.run(config, graph_builder=first_attempt_builder)
progress_path = ( output_dir.with_name(".compact.building") / ".build_state" / "progress.json" ) with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) self.assertEqual(progress["next_system_index"], 1) self.assertEqual(progress["successful_source_systems"], 1)
resumed = direct.BuildConfig( **{**config.__dict__, "resume": True} ) manifest = direct.run(resumed, graph_builder=graph_builder)
self.assertTrue((output_dir / "manifest.json").is_file()) self.assertFalse(output_dir.with_name(".compact.building").exists()) self.assertFalse((output_dir / ".build_state").exists()) self.assertEqual(manifest["n_graphs"], 4) self.assertEqual(manifest["n_source_systems"], 2) # sys_b is intentionally split into two exact-content storage groups. self.assertEqual(manifest["n_systems"], 3)
with (output_dir / "system_index.json").open( "r", encoding="utf-8" ) as handle: system_index = json.load(handle) self.assertEqual( system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"], ) self.assertEqual(system_index["n_systems"], 2)
dataset = CompactGraphDataset(output_dir) self.assertEqual(len(dataset), 4) expected = [ _synthetic_graph("sys_a", 1), _synthetic_graph("sys_a", 2), _synthetic_graph("sys_b", 1, split_static=True), _synthetic_graph("sys_b", 2, split_static=True), ] for actual, reference in zip(dataset, expected): for name in ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt", ): self.assertTrue( torch.allclose( getattr(actual, name), getattr(reference, name), rtol=1e-6, atol=1e-6, ), msg=name, )
def test_parallel_system_build_matches_serial_order(self) -> None: """Out-of-order worker completion must not change source graph order.""" with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_") as temp: root = Path(temp) data_dir = root / "docking" raw_poses = [] for system_id in ("sys_a", "sys_b", "sys_c"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } )
def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name # sys_a is deliberately slower so workers complete out of order. if system_id == "sys_a": time.sleep(0.15) pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph(system_id, pose_number)
serial_output = root / "serial" parallel_output = root / "parallel" serial_config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=serial_output.resolve(), method="protenix", target_shard_mib=1, num_workers=1, ) parallel_config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=parallel_output.resolve(), method="protenix", target_shard_mib=1, num_workers=1, system_workers=2, memory_budget_gib=8.0, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): serial_manifest = direct.run(serial_config, graph_builder=graph_builder) parallel_manifest = direct.run(parallel_config, graph_builder=graph_builder)
self.assertEqual(serial_manifest["n_graphs"], parallel_manifest["n_graphs"]) self.assertEqual(serial_manifest["graph_map"], parallel_manifest["graph_map"]) self.assertEqual(serial_manifest["shards"], parallel_manifest["shards"]) with (serial_output / "system_index.json").open("r", encoding="utf-8") as handle: serial_index = json.load(handle) with (parallel_output / "system_index.json").open("r", encoding="utf-8") as handle: parallel_index = json.load(handle) self.assertEqual(serial_index, parallel_index)
def test_parallel_ready_checkpoint_resumes_in_source_order(self) -> None: """A later ready system survives interruption before the earlier system.""" with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_resume_") as temp: root = Path(temp) data_dir = root / "docking" output_dir = root / "compact" raw_poses = [] for system_id in ("sys_a", "sys_b"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } )
def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph(system_id, pose_number)
def interrupted_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) if pose_path.parent.name == "sys_a": time.sleep(0.35) raise RuntimeError("intentional parallel interruption") return graph_builder(**kwargs)
config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=output_dir.resolve(), method="protenix", target_shard_mib=1, num_workers=1, system_workers=2, memory_budget_gib=8.0, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): with self.assertRaisesRegex(RuntimeError, "parallel worker.*sys_a"): direct.run(config, graph_builder=interrupted_builder)
stage_dir = output_dir.with_name(".compact.building") progress_path = stage_dir / ".build_state" / "progress.json" with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) self.assertEqual(progress["next_system_index"], 0) self.assertTrue( (stage_dir / ".build_state" / "ready" / "system_00000001.pt").is_file() )
resumed = direct.BuildConfig(**{**config.__dict__, "resume": True}) manifest = direct.run(resumed, graph_builder=graph_builder)
self.assertEqual(manifest["n_graphs"], 4) with (output_dir / "system_index.json").open("r", encoding="utf-8") as handle: system_index = json.load(handle) self.assertEqual( system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"] )
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327#!/usr/bin/env python3"""Tiny synthetic round-trip test for CompactGraphDataset.
The test creates only a few dozen tensor values in a temporary directory. Itdoes not read any production dataset."""
from __future__ import annotations
import jsonimport pickleimport subprocessimport sysimport tempfileimport unittestfrom pathlib import Pathfrom typing import Dict, List, Sequence, Tuple
import torchfrom torch_geometric.data import Datafrom torch_geometric.loader import DataLoader
from compact_graph_dataset import CompactGraphDataset
CUTOFF = 2.5
def _upper_edges(pos: torch.Tensor, n_protein: int) -> Tuple[torch.Tensor, torch.Tensor]: pairs: List[Tuple[int, int]] = [] nonpp: List[Tuple[int, int]] = [] for src in range(pos.shape[0]): for dst in range(src + 1, pos.shape[0]): distance = torch.sqrt( torch.sum( (pos[src].to(torch.float64) - pos[dst].to(torch.float64)) ** 2 ) ) if float(distance) <= CUTOFF: if dst < n_protein: pairs.append((src, dst)) else: nonpp.append((src, dst)) pp_tensor = ( torch.tensor(pairs, dtype=torch.int32).t().contiguous() if pairs else torch.empty((2, 0), dtype=torch.int32) ) nonpp_tensor = ( torch.tensor(nonpp, dtype=torch.int32).t().contiguous() if nonpp else torch.empty((2, 0), dtype=torch.int32) ) return pp_tensor, nonpp_tensor
def _legacy_graph( static: torch.Tensor, dynamic: torch.Tensor, protein: torch.Tensor, ligand: torch.Tensor, native: torch.Tensor, pp_upper: torch.Tensor, nonpp_upper: torch.Tensor,) -> Data: n_protein = protein.shape[0] n = static.shape[0] x = torch.empty((n, 82), 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, ligand), dim=0) y_grt = torch.cat((protein, native), dim=0) is_protein = torch.zeros((n, 1), dtype=torch.float32) is_protein[:n_protein] = 1 y_true = torch.zeros((n, 1), dtype=torch.float32) y_true[n_protein:, 0] = torch.sqrt( torch.sum((ligand - native) ** 2, dim=1) )
upper = torch.cat((pp_upper.to(torch.int64), nonpp_upper.to(torch.int64)), dim=1) src = torch.cat((upper[0], upper[1])) dst = torch.cat((upper[1], upper[0])) distance = torch.sqrt( torch.sum( ( pos[upper[0]].to(torch.float64) - pos[upper[1]].to(torch.float64) ) ** 2, dim=1, ) ) attr0 = torch.cat(((distance / CUTOFF).float(), (distance / CUTOFF).float())) attr1 = torch.cat((torch.exp(-distance / 3).float(), torch.exp(-distance / 3).float())) order = torch.argsort(src * n + dst) src, dst = src[order], dst[order] edge_index = torch.stack((src, dst)) edge_attr = torch.stack( ( attr0[order], attr1[order], (src < n_protein).float(), (dst < n_protein).float(), ), dim=1, ) 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=n, )
def _make_dataset(root: Path) -> Sequence[Data]: generator = torch.Generator().manual_seed(17)
protein_a = torch.tensor( [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=torch.float32, ) native_a = torch.tensor([[1.4, 1.1, 0.0], [2.0, 1.0, 0.0]], dtype=torch.float32) ligands_a = [ native_a + torch.tensor([[0.1, 0.0, 0.0], [0.0, -0.2, 0.1]]), native_a + torch.tensor([[-0.2, 0.1, 0.0], [0.2, 0.0, -0.1]]), ] protein_b = torch.tensor([[10.0, 0.0, 0.0], [11.0, 0.0, 0.0]], dtype=torch.float32) native_b = torch.tensor([[10.5, 1.0, 0.0]], dtype=torch.float32) ligands_b = [native_b + torch.tensor([[0.0, 0.2, -0.1]])]
systems = [ (protein_a, native_a, ligands_a), (protein_b, native_b, ligands_b), ] static_parts = [ torch.randn((protein.shape[0] + native.shape[0], 44), generator=generator) for protein, native, _ in systems ] pp_parts: List[torch.Tensor] = [] for protein, native, _ in systems: pp, _ = _upper_edges(torch.cat((protein, native), dim=0), protein.shape[0]) pp_parts.append(pp)
# Local pose order: A0, A1, B0. Original/source order: B0, A0, A1. pose_system = torch.tensor([0, 0, 1], dtype=torch.int32) source_graph_index = torch.tensor([1, 2, 0], dtype=torch.int64) dynamic_parts: List[torch.Tensor] = [] ligand_parts: List[torch.Tensor] = [] nonpp_parts: List[torch.Tensor] = [] local_graphs: List[Data] = [] for system_index, (_, _, ligands) in enumerate(systems): protein, native, _ = systems[system_index] for ligand in ligands: n = protein.shape[0] + ligand.shape[0] dynamic = torch.randn((n, 38), generator=generator) _, nonpp = _upper_edges(torch.cat((protein, ligand), dim=0), protein.shape[0]) dynamic_parts.append(dynamic) ligand_parts.append(ligand) nonpp_parts.append(nonpp) local_graphs.append( _legacy_graph( static_parts[system_index], dynamic, protein, ligand, native, pp_parts[system_index], nonpp, ) )
def pointer(lengths: Sequence[int]) -> torch.Tensor: result = [0] for length in lengths: result.append(result[-1] + int(length)) return torch.tensor(result, dtype=torch.int64)
shard: Dict[str, torch.Tensor] = { "schema_version": torch.tensor([1], dtype=torch.int32), "system_graph_ptr": torch.tensor([0, 2, 3], dtype=torch.int64), "pose_system": pose_system, "source_graph_index": source_graph_index, "system_node_ptr": pointer([part.shape[0] for part in static_parts]), "n_protein": torch.tensor( [protein.shape[0] for protein, _, _ in systems], dtype=torch.int32 ), "x_static": torch.cat(static_parts, dim=0), "protein_ptr": pointer([protein.shape[0] for protein, _, _ in systems]), "protein_pos": torch.cat([protein for protein, _, _ in systems], dim=0), "native_ligand_ptr": pointer([native.shape[0] for _, native, _ in systems]), "native_ligand_pos": torch.cat([native for _, native, _ in systems], dim=0), "pose_node_ptr": pointer([part.shape[0] for part in dynamic_parts]), "x_dynamic": torch.cat(dynamic_parts, dim=0), "pose_ligand_ptr": pointer([part.shape[0] for part in ligand_parts]), "ligand_pos": torch.cat(ligand_parts, dim=0), "pp_edge_ptr": pointer([part.shape[1] for part in pp_parts]), "pp_edge_upper": torch.cat(pp_parts, dim=1), "nonpp_edge_ptr": pointer([part.shape[1] for part in nonpp_parts]), "nonpp_edge_upper": torch.cat(nonpp_parts, dim=1), } (root / "shards").mkdir() torch.save(shard, root / "shards" / "shard_00000.pt") manifest = { "format": "gnncp_compact_v1", "schema_version": 1, "cutoff": CUTOFF, "num_graphs": 3, "static_columns": [[0, 34], [61, 71]], "dynamic_columns": [[34, 61], [71, 82]], "shards": [ { "path": "shards/shard_00000.pt", "num_graphs": 3, "system_ids": ["system_a", "system_b"], } ], "graph_map": [[0, 2], [0, 0], [0, 1]], } (root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") return [local_graphs[2], local_graphs[0], local_graphs[1]]
class CompactGraphDatasetTest(unittest.TestCase): def test_round_trip_and_batch(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) references = _make_dataset(root) dataset = CompactGraphDataset(root) self.assertEqual(len(dataset), 3) for index, reference in enumerate(references): actual = dataset[index] for field in ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt", ): self.assertTrue( torch.equal(getattr(actual, field), getattr(reference, field)), msg=f"mismatch at graph={index}, field={field}", ) self.assertEqual(dataset.metadata(index)["source_graph_index"], index)
batch = next(iter(DataLoader(dataset, batch_size=2, shuffle=False))) self.assertEqual(batch.x.shape[1], 82) self.assertEqual(batch.edge_attr.shape[1], 4) self.assertEqual(batch.num_graphs, 2)
# DataLoader spawn/fork must not serialise mmap shard objects. restored = pickle.loads(pickle.dumps(dataset)) self.assertEqual(len(restored._cache), 0) self.assertTrue(torch.equal(restored[-1].x, references[-1].x))
def test_converter_cli_round_trip(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) seed_root = root / "seed" seed_root.mkdir() references = _make_dataset(seed_root) legacy = root / "legacy.pt" system_index = root / "system_index.json" output = root / "converted" torch.save(list(references), legacy) system_index.write_text( json.dumps( {"graph_to_system": ["system_b", "system_a", "system_a"]} ), encoding="utf-8", ) script = Path(__file__).with_name("convert_to_compact_v1.py") subprocess.run( [ sys.executable, str(script), "--input", str(legacy), "--output-dir", str(output), "--method", "synthetic", "--system-index", str(system_index), "--target-shard-mib", "1", "--cutoff", str(CUTOFF), ], check=True, cwd=script.parent, capture_output=True, text=True, )
dataset = CompactGraphDataset(output) self.assertEqual(len(dataset), len(references)) for index, reference in enumerate(references): actual = dataset[index] for field in ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt", ): self.assertTrue( torch.equal(getattr(actual, field), getattr(reference, field)), msg=f"writer round-trip mismatch graph={index}, field={field}", ) self.assertEqual(dataset.metadata(index)["source_graph_index"], index)
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401#!/usr/bin/env python3"""Sample-level validation for a GNNCP compact graph dataset.
This program never iterates the full legacy dataset. When ``--legacy`` isprovided it opens the old monolithic .pt with ``torch.load(..., mmap=True)``and touches only the requested sample tensors."""
from __future__ import annotations
import argparseimport jsonimport randomimport resourceimport sysfrom pathlib import Pathfrom typing import Any, Dict, Iterable, List, Optional, Sequence
import torch
from compact_graph_dataset import CompactGraphDataset
CORE_FIELDS = ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt",)FLOAT_FIELDS = { "x", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt",}
def _rss_mib() -> float: value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # Linux reports KiB; macOS reports bytes. if sys.platform == "darwin": return value / (1024.0 * 1024.0) return value / 1024.0
def _parse_indices(text: Optional[str], length: int) -> Optional[List[int]]: if text is None: return None values: List[int] = [] for token in text.split(","): token = token.strip() if not token: continue if ":" in token: parts = token.split(":") if len(parts) not in (2, 3): raise ValueError(f"bad index range: {token!r}") start = int(parts[0]) if parts[0] else 0 stop = int(parts[1]) if parts[1] else length step = int(parts[2]) if len(parts) == 3 and parts[2] else 1 values.extend(range(start, stop, step)) else: values.append(int(token)) normalised = [] for index in values: if index < 0: index += length if not 0 <= index < length: raise IndexError(f"sample index {index} outside [0,{length})") normalised.append(index) return list(dict.fromkeys(normalised))
def _choose_indices(length: int, count: int, seed: int) -> List[int]: if length <= 0: return [] count = min(max(int(count), 1), length) selected = {0, length - 1} rng = random.Random(seed) while len(selected) < count: selected.add(rng.randrange(length)) return sorted(selected)[:count]
def _tensor_stats( actual: torch.Tensor, expected: torch.Tensor, *, atol: float, rtol: float,) -> Dict[str, Any]: result: Dict[str, Any] = { "actual_shape": list(actual.shape), "expected_shape": list(expected.shape), "actual_dtype": str(actual.dtype), "expected_dtype": str(expected.dtype), } if tuple(actual.shape) != tuple(expected.shape): result.update({"passed": False, "reason": "shape_mismatch"}) return result if actual.dtype != expected.dtype: result["dtype_match"] = False else: result["dtype_match"] = True
if actual.numel() == 0: result.update( { "passed": bool(result["dtype_match"]), "exact": True, "max_abs": 0.0, "mean_abs": 0.0, } ) return result
if actual.is_floating_point() or expected.is_floating_point(): actual_f64 = actual.to(torch.float64) expected_f64 = expected.to(torch.float64) finite_match = torch.equal(torch.isfinite(actual_f64), torch.isfinite(expected_f64)) diff = torch.abs(actual_f64 - expected_f64) finite_diff = diff[torch.isfinite(diff)] max_abs = float(finite_diff.max().item()) if finite_diff.numel() else float("inf") mean_abs = float(finite_diff.mean().item()) if finite_diff.numel() else float("inf") close = bool( torch.allclose(actual_f64, expected_f64, atol=atol, rtol=rtol, equal_nan=True) ) result.update( { "passed": bool(close and result["dtype_match"] and finite_match), "exact": bool(torch.equal(actual, expected)), "finite_pattern_match": finite_match, "max_abs": max_abs, "mean_abs": mean_abs, } ) else: exact = bool(torch.equal(actual, expected)) result.update( { "passed": bool(exact and result["dtype_match"]), "exact": exact, } ) return result
def _invariants(graph: Any, cutoff: float, atol: float) -> Dict[str, Any]: checks: Dict[str, bool] = {} n = int(graph.num_nodes) checks["x_Nx82"] = tuple(graph.x.shape) == (n, 82) checks["edge_index_2xE"] = graph.edge_index.ndim == 2 and graph.edge_index.shape[0] == 2 edge_count = int(graph.edge_index.shape[1]) if checks["edge_index_2xE"] else -1 checks["edge_attr_Ex4"] = tuple(graph.edge_attr.shape) == (edge_count, 4) checks["pos_Nx3"] = tuple(graph.pos.shape) == (n, 3) checks["is_protein_Nx1"] = tuple(graph.is_protein.shape) == (n, 1) checks["y_true_Nx1"] = tuple(graph.y_true.shape) == (n, 1) checks["y_pred_Nx3"] = tuple(graph.y_pred.shape) == (n, 3) checks["y_grt_Nx3"] = tuple(graph.y_grt.shape) == (n, 3) checks["x_float32"] = graph.x.dtype == torch.float32 checks["edge_index_int64"] = graph.edge_index.dtype == torch.int64 checks["edge_attr_float32"] = graph.edge_attr.dtype == torch.float32 checks["coordinates_float32"] = ( graph.pos.dtype == graph.y_pred.dtype == graph.y_grt.dtype == torch.float32 ) checks["pos_equals_y_pred"] = bool(torch.equal(graph.pos, graph.y_pred))
if edge_count >= 0 and graph.edge_index.numel(): src, dst = graph.edge_index checks["edge_bounds"] = bool( (src.min() >= 0) and (dst.min() >= 0) and (src.max() < n) and (dst.max() < n) ) checks["no_self_edges"] = bool(torch.all(src != dst).item()) key = src * n + dst checks["legacy_edge_order"] = bool(torch.all(key[1:] > key[:-1]).item()) reversed_key = dst * n + src checks["edges_are_bidirectional"] = bool( torch.equal(torch.sort(key).values, torch.sort(reversed_key).values) ) distance = torch.sqrt( torch.sum( ( graph.pos[src].to(torch.float64) - graph.pos[dst].to(torch.float64) ) ** 2, dim=1, ) ) checks["edges_within_cutoff"] = bool( torch.all(distance <= cutoff + atol).item() ) checks["edge_attr_distance"] = bool( torch.allclose( graph.edge_attr[:, 0].to(torch.float64), distance / cutoff, atol=atol, rtol=0.0, ) ) is_protein = graph.is_protein[:, 0] checks["edge_attr_endpoint_types"] = bool( torch.equal(graph.edge_attr[:, 2], is_protein[src]) and torch.equal(graph.edge_attr[:, 3], is_protein[dst]) ) else: checks["edge_bounds"] = True checks["no_self_edges"] = True checks["legacy_edge_order"] = True checks["edges_are_bidirectional"] = True checks["edges_within_cutoff"] = True checks["edge_attr_distance"] = True checks["edge_attr_endpoint_types"] = True
protein = graph.is_protein[:, 0] > 0.5 checks["protein_first"] = bool( not protein.numel() or not bool((~protein).any().item()) or not bool(protein[torch.nonzero(~protein, as_tuple=False)[0, 0] :].any().item()) ) checks["protein_y_true_zero"] = bool( torch.all(graph.y_true[protein] == 0).item() ) ligand_error = torch.sqrt( torch.sum((graph.y_pred[~protein] - graph.y_grt[~protein]) ** 2, dim=1) ) checks["ligand_y_true_matches_coordinates"] = bool( torch.allclose( graph.y_true[~protein, 0], ligand_error, atol=atol, rtol=0.0, ) ) return {"passed": all(checks.values()), "checks": checks}
def _load_legacy(path: Path, allow_eager: bool) -> Sequence[Any]: try: return torch.load( path, map_location="cpu", mmap=True, weights_only=False, ) except (TypeError, RuntimeError, ValueError) as exc: if not allow_eager: raise RuntimeError( f"could not mmap legacy dataset {path}: {exc}. " "Refusing an eager multi-GB load; pass --allow-eager-legacy " "only inside a suitably sized Slurm job." ) from exc return torch.load(path, map_location="cpu", weights_only=False)
def validate(args: argparse.Namespace) -> Dict[str, Any]: dataset = CompactGraphDataset( args.compact, max_cached_shards=args.max_cached_shards, strict=True, ) indices = _parse_indices(args.indices, len(dataset)) if indices is None: indices = _choose_indices(len(dataset), args.num_samples, args.seed)
report: Dict[str, Any] = { "compact": str(Path(args.compact).resolve()), "num_graphs": len(dataset), "indices": indices, "atol": args.atol, "rtol": args.rtol, "rss_mib_before_samples": _rss_mib(), "samples": [], }
legacy: Optional[Sequence[Any]] = None if args.legacy is not None: legacy = _load_legacy(Path(args.legacy), args.allow_eager_legacy) report["legacy"] = str(Path(args.legacy).resolve()) report["legacy_num_graphs"] = len(legacy) if len(legacy) != len(dataset): report["length_match"] = False else: report["length_match"] = True
all_passed = report.get("length_match", True) for index in indices: graph = dataset[index] sample_report: Dict[str, Any] = { "index": index, "metadata": dataset.metadata(index), "invariants": _invariants(graph, dataset.cutoff, args.atol), } sample_passed = bool(sample_report["invariants"]["passed"])
if legacy is not None and index < len(legacy): reference = legacy[index] parity: Dict[str, Any] = {} for field in CORE_FIELDS: if not hasattr(reference, field): parity[field] = { "passed": False, "reason": "missing_in_legacy_graph", } continue actual = getattr(graph, field) expected = getattr(reference, field) if not torch.is_tensor(actual) or not torch.is_tensor(expected): parity[field] = { "passed": False, "reason": "field_is_not_tensor", } continue parity[field] = _tensor_stats( actual, expected, atol=args.atol if field in FLOAT_FIELDS else 0.0, rtol=args.rtol if field in FLOAT_FIELDS else 0.0, ) sample_report["parity"] = parity sample_passed = sample_passed and all( bool(result["passed"]) for result in parity.values() )
sample_report["passed"] = sample_passed all_passed = all_passed and sample_passed report["samples"].append(sample_report)
report["rss_mib_after_samples"] = _rss_mib() report["passed"] = bool(all_passed) return report
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Validate compact GNNCP graphs and optionally compare with legacy tensors." ) parser.add_argument( "--compact", required=True, help="Compact dataset directory or manifest.json", ) parser.add_argument( "--legacy", help="Legacy list[torch_geometric.data.Data] .pt for mmap parity checks", ) parser.add_argument( "--num-samples", type=int, default=8, help="Number of deterministic samples when --indices is omitted (default: 8)", ) parser.add_argument( "--indices", help="Comma-separated indices/ranges, e.g. '0,10,20:24,-1'", ) parser.add_argument("--seed", type=int, default=0) parser.add_argument( "--atol", type=float, default=1e-6, help="Absolute tolerance for reconstructed floating tensors", ) parser.add_argument("--rtol", type=float, default=1e-6) parser.add_argument("--max-cached-shards", type=int, default=2) parser.add_argument( "--allow-eager-legacy", action="store_true", help="Allow fallback to an eager legacy torch.load if mmap is unavailable", ) parser.add_argument( "--report", help="Optional JSON report path (written atomically by the caller/job filesystem)", ) return parser
def main() -> int: args = build_parser().parse_args() report = validate(args) rendered = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) print(rendered) if args.report: output = Path(args.report) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(rendered + "\n", encoding="utf-8") return 0 if report["passed"] else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607#!/usr/bin/env python3"""Prepare and publish the completed HiQBind compact datasets to Hugging Face.
The published repository layout is intentionally simple and stable::
README.md docs/ code/compact_v1/ data/hiqbind_5k_v1/ autodock_vina_full_v1/ diffdock_full_v1/
``--prepare`` makes a persistent local staging tree. Tensor shards are*hard-linked* from the completed local datasets, so the staging tree does notduplicate the roughly 93 GB payload. The two JSON files which could exposelocal source paths (``manifest.json`` and ``source_index.json``) are copiedafter recursively replacing absolute paths with a non-path marker.
``--upload`` accepts ``HF_TOKEN``, ``--token``, or a token saved by``huggingface_hub.login()``. It authenticates with ``whoami`` and checks thetarget dataset repository before invoking ``HfApi.upload_large_folder``. Thelatter keeps its resume metadata below the staging tree, therefore retain thesame ``--stage-root`` if an upload is interrupted.
Examples--------Inspect without writing or contacting Hugging Face::
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --dry-run
Build and inspect the reusable staging tree::
/u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --verify
Upload after review (the token is intentionally not printed)::
HF_TOKEN=... /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py \ --prepare --verify --upload --num-workers 8"""
from __future__ import annotations
import argparseimport jsonimport osimport shutilimport sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable, Mapping, Sequence
RELEASE_ROOT = Path(__file__).resolve().parentPROJECT_ROOT = RELEASE_ROOT.parentWORKSPACE_ROOT = PROJECT_ROOT.parentDEFAULT_DATASET_ROOT = PROJECT_ROOT / "datasets_compact_hiqbind_v1"DEFAULT_STAGE_ROOT = RELEASE_ROOT / "hf_stage_copuladock"DEFAULT_REPO_ID = "liofoil/copuladock"
@dataclass(frozen=True)class DatasetSpec: """A completed compact dataset and its release-relative destination."""
source_name: str release_name: str
DATASETS: tuple[DatasetSpec, ...] = ( DatasetSpec("autodock_vina_full_v1", "autodock_vina_full_v1"), DatasetSpec("diffdock_full_v1", "diffdock_full_v1"),)
# These are the minimal reproducible construction/reader components. They# intentionally exclude raw docking outputs and cluster logs.CODE_SOURCES: tuple[tuple[Path, Path], ...] = ( ( WORKSPACE_ROOT / "docking_base/scripts/materialize_hiqbind_gnncp.py", Path("code/compact_v1/materialize_hiqbind_gnncp.py"), ), ( PROJECT_ROOT / "system_split_code/build_compact_v1_direct.py", Path("code/compact_v1/build_compact_v1_direct.py"), ), ( PROJECT_ROOT / "system_split_code/build_compact_v1_direct.sbatch", Path("code/compact_v1/build_compact_v1_direct.sbatch"), ), ( PROJECT_ROOT / "system_split_code/build_graph_unified_enhanced.py", Path("code/compact_v1/build_graph_unified_enhanced.py"), ), ( PROJECT_ROOT / "system_split_code/convert_to_compact_v1.py", Path("code/compact_v1/convert_to_compact_v1.py"), ), ( PROJECT_ROOT / "system_split_code/compact_graph_dataset.py", Path("code/compact_v1/compact_graph_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/build_system_index.py", Path("code/compact_v1/build_system_index.py"), ), ( PROJECT_ROOT / "system_split_code/validate_compact_dataset.py", Path("code/compact_v1/validate_compact_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/smoke_test_compact_dataset.py", Path("code/compact_v1/smoke_test_compact_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/test_build_compact_v1_direct.py", # Keep tests alongside the modules they import. The upstream tests # intentionally resolve convert_to_compact_v1.py by sibling path. Path("code/compact_v1/test_build_compact_v1_direct.py"), ), ( PROJECT_ROOT / "system_split_code/test_compact_graph_dataset.py", Path("code/compact_v1/test_compact_graph_dataset.py"), ),)
# Previous staging revisions placed the two tests under ``tests/``. Prune# only these exact, generated staging copies during --prepare so an old stage# cannot publish duplicate stale tests. No dataset data are ever removed.OBSOLETE_STAGE_FILES: tuple[Path, ...] = ( Path("code/compact_v1/tests/test_build_compact_v1_direct.py"), Path("code/compact_v1/tests/test_compact_graph_dataset.py"),)
class ReleaseError(RuntimeError): """A release-preparation or release-verification failure."""
def _relative_to(path: Path, root: Path) -> Path: """Return ``path`` relative to ``root`` or raise a contextual error."""
try: return path.relative_to(root) except ValueError as exc: raise ReleaseError(f"path escapes its expected root: {path} (root={root})") from exc
def _is_absolute_path_text(value: str) -> bool: """Detect POSIX/Windows-looking absolute paths without interpreting IDs."""
return value.startswith("/") or (len(value) >= 3 and value[1:3] in (":\\", ":/"))
def _sanitize_value(value: Any) -> Any: """Copy JSON-like values while removing every absolute-path string."""
if isinstance(value, dict): return {str(key): _sanitize_value(item) for key, item in value.items()} if isinstance(value, list): return [_sanitize_value(item) for item in value] if isinstance(value, str) and _is_absolute_path_text(value): return "<local-path-removed>" return value
def _find_absolute_path_values(value: Any, prefix: str = "$") -> list[str]: """Return JSON locations that still contain an absolute path string."""
found: list[str] = [] if isinstance(value, Mapping): for key, item in value.items(): found.extend(_find_absolute_path_values(item, f"{prefix}.{key}")) elif isinstance(value, list): for index, item in enumerate(value): found.extend(_find_absolute_path_values(item, f"{prefix}[{index}]")) elif isinstance(value, str) and _is_absolute_path_text(value): found.append(prefix) return found
def _read_json(path: Path) -> Any: try: with path.open("r", encoding="utf-8") as handle: return json.load(handle) except (OSError, json.JSONDecodeError) as exc: raise ReleaseError(f"cannot read JSON {path}: {exc}") from exc
def _write_json(path: Path, payload: Any) -> None: """Write a small JSON file atomically inside the staging tree."""
path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") try: with temporary.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: # If json.dump failed before os.replace, only remove the known temp file. if temporary.exists(): temporary.unlink()
def _copy_file(source: Path, destination: Path) -> None: """Snapshot a small code/document file without following unsafe parents."""
if not source.is_file(): raise ReleaseError(f"required release file is missing: {source}") destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_name(destination.name + ".tmp") try: shutil.copy2(source, temporary) os.replace(temporary, destination) finally: if temporary.exists(): temporary.unlink()
def _hardlink_file(source: Path, destination: Path) -> None: """Make one idempotent hard link; never silently copy a tensor shard."""
if not source.is_file(): raise ReleaseError(f"source file is missing: {source}") destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists(): source_stat = source.stat() destination_stat = destination.stat() if (source_stat.st_dev, source_stat.st_ino) == (destination_stat.st_dev, destination_stat.st_ino): return raise ReleaseError( "staging file already exists but is not the expected hard link; " f"refusing to replace it: {destination}" ) try: os.link(source, destination) except OSError as exc: raise ReleaseError( "hard-link failed; staging and source must share a filesystem. " f"source={source}, destination={destination}: {exc}" ) from exc
def _dataset_source(dataset_root: Path, spec: DatasetSpec) -> Path: source = (dataset_root / spec.source_name).resolve() if not source.is_dir(): raise ReleaseError(f"completed compact dataset is missing: {source}") manifest = source / "manifest.json" if not manifest.is_file(): raise ReleaseError(f"completed compact dataset has no manifest: {manifest}") value = _read_json(manifest) if not isinstance(value, dict) or value.get("status") != "complete": raise ReleaseError(f"dataset is not a complete compact release: {source}") return source
def _release_dataset_root(stage_root: Path, spec: DatasetSpec) -> Path: return stage_root / "data" / "hiqbind_5k_v1" / spec.release_name
def _sanitized_json_payload(source: Path) -> Any: payload = _sanitize_value(_read_json(source)) leftovers = _find_absolute_path_values(payload) if leftovers: raise ReleaseError(f"path sanitizer left absolute paths in {source}: {leftovers[:5]}") return payload
def _stage_dataset(source: Path, destination: Path) -> None: """Stage a compact dataset, hard-linking all immutable source artifacts."""
for source_file in sorted(source.rglob("*")): if not source_file.is_file(): continue relative = _relative_to(source_file, source) target = destination / relative # These two records contain source provenance. Their release versions # preserve logical relative fields but never disclose local paths. if source_file.name in {"manifest.json", "source_index.json"}: _write_json(target, _sanitized_json_payload(source_file)) else: _hardlink_file(source_file, target)
def _release_assets() -> list[tuple[Path, Path]]: """Discover authored release documents plus the static code mapping."""
assets = list(CODE_SOURCES)
# README is the Hugging Face dataset card. Other authored Markdown files # are companion documents, keeping the remote root uncluttered. for source in sorted(RELEASE_ROOT.glob("*.md"), key=lambda item: item.name.casefold()): remote = Path("README.md") if source.name == "README.md" else Path("docs") / source.name assets.append((source, remote))
# Release-authored companion docs and the small hand-written package notes # live in the release tree itself. Include them recursively while # deliberately excluding generated __pycache__ / staging content. authored_docs = RELEASE_ROOT / "docs" if authored_docs.is_dir(): for source in sorted(authored_docs.rglob("*"), key=lambda item: str(item).casefold()): if source.is_file() and "__pycache__" not in source.parts: assets.append((source, Path("docs") / _relative_to(source, authored_docs)))
authored_code = RELEASE_ROOT / "code" / "compact_v1" if authored_code.is_dir(): for source in sorted(authored_code.rglob("*"), key=lambda item: str(item).casefold()): if source.is_file() and "__pycache__" not in source.parts: assets.append((source, Path("code/compact_v1") / _relative_to(source, authored_code)))
# A dependency file placed at the release root is also supported for # convenience; a code/compact_v1 version takes precedence by causing an # explicit duplicate-destination error rather than silent replacement. for name in ("requirements.txt", "environment.yml", "environment.yaml"): source = RELEASE_ROOT / name if source.is_file(): assets.append((source, Path("code/compact_v1") / name))
# Include the reproducible release entry points themselves, but not this # staging directory or arbitrary local files. for name in ("upload_copuladock.py", "upload_copuladock.sbatch"): source = RELEASE_ROOT / name if source.is_file(): assets.append((source, Path("code/release") / name))
return assets
def _stage_assets(stage_root: Path) -> list[Path]: staged: list[Path] = [] seen_destinations: set[Path] = set() for source, remote in _release_assets(): if remote in seen_destinations: raise ReleaseError(f"duplicate release destination: {remote}") seen_destinations.add(remote) if not source.is_file(): raise ReleaseError(f"required construction code is missing: {source}") target = stage_root / remote _copy_file(source, target) staged.append(target) return staged
def _prune_obsolete_stage_files(stage_root: Path) -> None: """Remove only known stale generated code copies from an older layout."""
for relative in OBSOLETE_STAGE_FILES: target = stage_root / relative if target.is_file(): target.unlink() # Leave a directory untouched when it contains anything unexpected; # upload_large_folder ignores empty directories in any event. parent = target.parent if parent.is_dir() and not any(parent.iterdir()): parent.rmdir()
def _validate_stage_location(stage_root: Path, dataset_root: Path) -> None: """Prevent accidental recursive staging into either source dataset root."""
stage_root = stage_root.resolve() dataset_root = dataset_root.resolve() if stage_root == dataset_root: raise ReleaseError("--stage-root must not equal --dataset-root") try: stage_root.relative_to(dataset_root) except ValueError: return raise ReleaseError("--stage-root must not be inside --dataset-root")
def _expected_tensor_files(source: Path) -> list[Path]: return sorted(path for path in source.rglob("*.pt") if path.is_file())
def _human_bytes(number: int) -> str: value = float(number) for suffix in ("B", "KiB", "MiB", "GiB", "TiB"): if value < 1024.0 or suffix == "TiB": return f"{value:.1f} {suffix}" value /= 1024.0 return f"{number} B"
def _source_summary(dataset_root: Path) -> list[dict[str, Any]]: summary: list[dict[str, Any]] = [] for spec in DATASETS: source = _dataset_source(dataset_root, spec) manifest = _read_json(source / "manifest.json") tensors = _expected_tensor_files(source) summary.append( { "name": spec.release_name, "source": str(source), "systems": int(manifest.get("n_systems", 0)), "graphs": int(manifest.get("n_graphs", 0)), "shards": len(tensors), "tensor_bytes": sum(path.stat().st_size for path in tensors), } ) return summary
def prepare_stage(stage_root: Path, dataset_root: Path, *, dry_run: bool) -> None: """Create/update the reusable stage. ``dry_run`` performs no writes."""
_validate_stage_location(stage_root, dataset_root) summaries = _source_summary(dataset_root) assets = _release_assets() print(f"stage root: {stage_root}") for item in summaries: print( f" {item['name']}: {item['systems']} systems, {item['graphs']} graphs, " f"{item['shards']} .pt shards, {_human_bytes(item['tensor_bytes'])}" ) print(f" construction/release files: {len(assets)}") if dry_run: print("dry-run: source checks passed; no staging files were created or changed.") return
stage_root.mkdir(parents=True, exist_ok=True) for spec in DATASETS: _stage_dataset(_dataset_source(dataset_root, spec), _release_dataset_root(stage_root, spec)) _stage_assets(stage_root) _prune_obsolete_stage_files(stage_root) print("staging preparation completed (tensor shards are hard links).")
def verify_stage(stage_root: Path, dataset_root: Path, *, require_readme: bool) -> None: """Check staging layout, sanitization, and every tensor hard link."""
if not stage_root.is_dir(): raise ReleaseError(f"staging root does not exist: {stage_root}")
errors: list[str] = [] checked_tensors = 0 for spec in DATASETS: source = _dataset_source(dataset_root, spec) staged = _release_dataset_root(stage_root, spec) if not staged.is_dir(): errors.append(f"missing staged dataset directory: {staged}") continue for name in ("manifest.json", "source_index.json", "system_index.json"): candidate = staged / name if not candidate.is_file(): errors.append(f"missing staged metadata: {candidate}")
for name in ("manifest.json", "source_index.json"): candidate = staged / name if candidate.is_file(): try: leftovers = _find_absolute_path_values(_read_json(candidate)) except ReleaseError as exc: errors.append(str(exc)) else: if leftovers: errors.append(f"absolute paths remain in {candidate}: {leftovers[:5]}")
for source_tensor in _expected_tensor_files(source): staged_tensor = staged / _relative_to(source_tensor, source) if not staged_tensor.is_file(): errors.append(f"missing staged tensor: {staged_tensor}") continue source_stat = source_tensor.stat() staged_stat = staged_tensor.stat() if (source_stat.st_dev, source_stat.st_ino) != (staged_stat.st_dev, staged_stat.st_ino): errors.append(f"tensor is not a hard link: {staged_tensor}") if source_stat.st_size != staged_stat.st_size: errors.append(f"tensor size differs: {staged_tensor}") checked_tensors += 1
for source, remote in _release_assets(): staged_file = stage_root / remote if not staged_file.is_file(): errors.append(f"missing staged release asset: {staged_file}") elif staged_file.stat().st_size != source.stat().st_size: errors.append(f"staged release asset size differs: {staged_file}")
readme = stage_root / "README.md" if require_readme and not readme.is_file(): errors.append("README.md is required before upload; add it under release_copuladock/") if errors: raise ReleaseError("staging verification failed:\n - " + "\n - ".join(errors)) print(f"staging verification passed: {checked_tensors} tensor hard links checked; no local absolute paths in release metadata.")
def _get_token(args: argparse.Namespace) -> str: token = args.token or os.environ.get("HF_TOKEN") if token: return token try: from huggingface_hub import get_token except ImportError as exc: raise ReleaseError( "--upload requires --token/HF_TOKEN or a saved Hugging Face login; " "huggingface_hub is unavailable." ) from exc token = get_token() if not token: raise ReleaseError( "--upload requires --token, HF_TOKEN, or a saved Hugging Face login. " "Run `python -c 'from huggingface_hub import login; login()'` first." ) return token
def upload_stage(args: argparse.Namespace) -> None: """Authenticate safely and perform the one resumable folder upload."""
if args.dry_run: print( "dry-run: would verify credentials and call HfApi.upload_large_folder " f"for dataset repo {args.repo_id!r} from {args.stage_root}." ) return token = _get_token(args) try: from huggingface_hub import HfApi except ImportError as exc: raise ReleaseError( "huggingface_hub is unavailable. Run with " "/u/hhao/anaconda3/envs/hgf/bin/python." ) from exc
api = HfApi(token=token) try: account = api.whoami(token=token) api.repo_info(args.repo_id, repo_type="dataset", revision=args.revision, token=token) except Exception as exc: # The Hub library exposes several transport/auth exception types. raise ReleaseError( f"cannot authenticate to or access dataset repository {args.repo_id!r}: {exc}" ) from exc # The user identity is useful operational evidence but contains no secret. account_name = account.get("name") if isinstance(account, Mapping) else None print(f"Hugging Face authentication verified for account: {account_name or '<unknown>'}") print( "starting resumable upload_large_folder: " f"repo={args.repo_id}, revision={args.revision}, workers={args.num_workers}" ) try: api.upload_large_folder( repo_id=args.repo_id, folder_path=args.stage_root, repo_type="dataset", revision=args.revision, num_workers=args.num_workers, # upload_large_folder writes resumable state below .cache; it is # operational metadata, not part of the scientific release. ignore_patterns=[".cache/**", "**/__pycache__/**", "*.pyc", "*.tmp"], print_report=True, ) except Exception as exc: raise ReleaseError( "Hugging Face upload did not complete. Keep the staging root unchanged and rerun " "the same command to resume: " f"{exc}" ) from exc print("upload_large_folder completed successfully.")
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--prepare", action="store_true", help="create/update the persistent staging tree") parser.add_argument("--verify", action="store_true", help="verify an existing staging tree") parser.add_argument("--upload", action="store_true", help="upload a verified staging tree to Hugging Face") parser.add_argument( "--dry-run", action="store_true", help="show prepare/upload actions without staging writes or network access", ) parser.add_argument("--repo-id", default=DEFAULT_REPO_ID, help=f"target dataset repo (default: {DEFAULT_REPO_ID})") parser.add_argument("--revision", default="main", help="target revision (default: main)") parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT) parser.add_argument("--stage-root", type=Path, default=DEFAULT_STAGE_ROOT) parser.add_argument("--num-workers", type=int, default=8, help="upload_large_folder worker count (default: 8)") parser.add_argument("--token", help="Hugging Face token; prefer HF_TOKEN in a job environment") return parser
def main(argv: Sequence[str] | None = None) -> int: args = build_parser().parse_args(argv) if not (args.prepare or args.verify or args.upload): raise ReleaseError("select at least one action: --prepare, --verify, and/or --upload") if args.num_workers < 1: raise ReleaseError("--num-workers must be at least 1") args.dataset_root = args.dataset_root.expanduser().resolve() args.stage_root = args.stage_root.expanduser().resolve()
if args.prepare: prepare_stage(args.stage_root, args.dataset_root, dry_run=args.dry_run) if args.verify or args.upload: # A dry-run upload has no staging side effects, but validates a real # stage when one is already present. This catches layout mistakes # before credentials/network access are involved. verify_stage(args.stage_root, args.dataset_root, require_readme=args.upload and not args.dry_run) if args.upload: upload_stage(args) return 0
if __name__ == "__main__": try: raise SystemExit(main()) except ReleaseError as exc: print(f"ERROR: {exc}", file=sys.stderr) raise SystemExit(2)1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/bin/bash# Reusable, resumable Hugging Face release upload for liofoil/copuladock.## Submit only after reviewing the staging tree. Authentication may come from# HF_TOKEN in the submission environment or a token saved by# `huggingface_hub.login()`; never put a token in this file.# sbatch upload_copuladock.sbatch## If a network transfer is interrupted, submit the same script again. Do not# remove hf_stage_copuladock/: huggingface_hub retains its upload state there.
#SBATCH --account=bghp-delta-cpu#SBATCH --partition=cpu#SBATCH --nodes=1#SBATCH --ntasks-per-node=1#SBATCH --cpus-per-task=8#SBATCH --mem=32G#SBATCH --time=2-00:00:00#SBATCH --job-name=copuladock_hf_upload#SBATCH --output=/work/nvme/bghp/hhao/gnncp/release_copuladock/copuladock_hf_upload_%j.out#SBATCH --error=/work/nvme/bghp/hhao/gnncp/release_copuladock/copuladock_hf_upload_%j.err#SBATCH --open-mode=append#SBATCH --mail-type=FAIL,END
set -Eeuo pipefailumask 007
readonly RELEASE_ROOT=/work/nvme/bghp/hhao/gnncp/release_copuladockreadonly PYTHON=/u/hhao/anaconda3/envs/hgf/bin/pythonreadonly UPLOAD_WORKERS="${UPLOAD_WORKERS:-8}"
finish(){ local rc=$? echo "[$(date --iso-8601=seconds)] job=${SLURM_JOB_ID:-unknown} exit=${rc}"}trap finish EXIT
test -x "${PYTHON}"test -r "${RELEASE_ROOT}/upload_copuladock.py"echo "[$(date --iso-8601=seconds)] host=$(hostname) workers=${UPLOAD_WORKERS}"
"${PYTHON}" "${RELEASE_ROOT}/upload_copuladock.py" \ --prepare --verify --upload --num-workers "${UPLOAD_WORKERS}"123version https://git-lfs.github.com/spec/v1oid sha256:841527641a6035c77a0446b515a6eaae7c1e8fe604f240375b02bed5397dd8ddsize 14884303123version https://git-lfs.github.com/spec/v1oid sha256:3f6c5e126c2bef0e0c9c7a64285b42ee9cc7d9032cf58cacf199d1f36600b2desize 534092249123version https://git-lfs.github.com/spec/v1oid sha256:393f5d1a3be510750ae0accd7c698d4295dbc61d81e5cb8f135b6f2cc1b621dasize 535229273123version https://git-lfs.github.com/spec/v1oid sha256:6e6c6453428bef1c27930537b12686dbdc8a91e3baa473162ae11fb1b3eac753size 529267865123version https://git-lfs.github.com/spec/v1oid sha256:e600f4a0910fb99f716b681aabccbc22283faa302db92b106cb500db08addb76size 530521753123version https://git-lfs.github.com/spec/v1oid sha256:ac05897b319e04175b5939decd3e0cfc57adab0ed9b2e4077e90e262a5596e55size 528331609123version https://git-lfs.github.com/spec/v1oid sha256:da426b81143436dc79d2fa0207e0b90a721c24b59c24e70e11b3de3a043d9b80size 534128345123version https://git-lfs.github.com/spec/v1oid sha256:9423f17b5e0e1989acd92b73c3b5b5f6918b48ad9eb9fd0176e4b008dd0f2a70size 535495961123version https://git-lfs.github.com/spec/v1oid sha256:b08a73cf2ffff0f4ba3334b720a38b21cfd2db12b9a53495b5062366041cd823size 525024473123version https://git-lfs.github.com/spec/v1oid sha256:4ee42f9b3ffe1fca4e47523d610b1ffea938a5ff789b3b256d653205135bc557size 529624857123version https://git-lfs.github.com/spec/v1oid sha256:8169ec37de9a23df15f978706818c4c78ac6ac6c7e9bab370ebf7c72c04fe4d1size 536233881123version https://git-lfs.github.com/spec/v1oid sha256:0a6757f24419fbc66f6b617524be753725e0085725072531cb138dd6a0c4683asize 535844569123version https://git-lfs.github.com/spec/v1oid sha256:c3ee0f4eadda859b71bcbc305434c56cb8393cf9027cd42bc2f7420975edd185size 527677081123version https://git-lfs.github.com/spec/v1oid sha256:a5d03e0067d28e1f7458c3e7fad63f0100618c0f4fd2eea70029d3e1eb77532fsize 536549849123version https://git-lfs.github.com/spec/v1oid sha256:d5f533a35ca2c973cee8a8cbcc8c3844874bad39271f0034c9af9626302f60c2size 519235801123version https://git-lfs.github.com/spec/v1oid sha256:e7aa44ac4d0008281dd3ce21516a9538cb90194c23bc7f0880b83ee5f2d9cf8esize 534088793123version https://git-lfs.github.com/spec/v1oid sha256:caf1f91fbb3915bb2f8b3a3e6fa8169d1bb01678e32f2e7e3534f042d888a89fsize 535543385123version https://git-lfs.github.com/spec/v1oid sha256:c120eebd2ee4656bd448991c77ecc5c9094942baebf41e7c10706a94bb3bcc33size 529791833123version https://git-lfs.github.com/spec/v1oid sha256:c140b2c3076bf3300c968a433d5bfbca3b61ea7e018388ba9e2f1a61cda8f6e1size 524637849123version https://git-lfs.github.com/spec/v1oid sha256:7eed91d4c944606de9211f2c9dd45be8c0f5cfb1ee0386c180041d290b03c310size 533015065123version https://git-lfs.github.com/spec/v1oid sha256:df57012302574ac27379e16cb348d12718b79e2111fea4debbc3d8f8ac31dcf2size 530900377123version https://git-lfs.github.com/spec/v1oid sha256:7e47a8ff6dbe4a742e6bb019ce99571b7409dedc3722678320bb1a00dcf26c34size 522335129123version https://git-lfs.github.com/spec/v1oid sha256:500dc13556cc42fda7b2101f6c600ae384690d548abc66a2647df92423f0e79esize 535780761123version https://git-lfs.github.com/spec/v1oid sha256:365759c19d43e31d44487b7320947ee87f75e873d7111ad680fc016578499e63size 528301785123version https://git-lfs.github.com/spec/v1oid sha256:de26f8ee0a0dff7d85edab50217198742a7cc4c1f9ec70e4c3f03d9f5316ee79size 533930713123version https://git-lfs.github.com/spec/v1oid sha256:c9a63663b4a8dadc09c3441c7ef37948a17b26622367648af5a5cd98c8412ff2size 524476377123version https://git-lfs.github.com/spec/v1oid sha256:50a0939dfddd0162b462ac3ac22f1600081e72a3d47af55af2056e4df99f2817size 534420377123version https://git-lfs.github.com/spec/v1oid sha256:f7d9af1c108359ad37a7ce82dcc90dc6d6ade3c483a26036022399647dfd8506size 536033305123version https://git-lfs.github.com/spec/v1oid sha256:8dde60a8d5a936372665daec9d92adc337241fdc77b571d4be7d74901e01a866size 535040537123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198# CopulaDock HiQBind 5K compact 数据集使用说明
## 1. 数据集的单位与规模
本发布包含 HiQBind 5K cohort 的两个 docking baseline 输出,经统一构图后保存为 `gnncp_compact_v1`。
| 方法 | system(protein–ligand pair) | graph(docking pose) | 完成状态 || --- | ---: | ---: | --- || DiffDock | 4,979 | 97,988 | complete / strict validation passed || AutoDock Vina | 4,887 | 85,824 | complete / strict validation passed |
定义如下:
- **system**:一个 protein–ligand pair,也是数据划分的最小单位。- **graph**:该 system 的一个预测 docking pose 构成的一张原子图。- 每个 system 最多请求 20 个 pose;实际 graph 数量可能少于 20,因为个别 pose 被方法或几何检查拒绝。
因此,例如构图阶段的“158 个 system 产生 2,849 个 graph”是正常的:它说明这些 pair 的有效 pose 总数为 2,849,并不表示出现了 2,849 个不同的 protein–ligand pair。
两个方法的共同 system 为 4,868 个。若做 DiffDock 与 Vina 的逐 system 对照,请先取 `system_index.json` 中 `systems` 字段的交集。
## 2. 下载
完整下载约需 93 GiB 可用空间。通常只需下载一个方法以及 reader 代码:
```pythonfrom huggingface_hub import snapshot_download
snapshot_download( repo_id="liofoil/copuladock", repo_type="dataset", local_dir="copuladock", allow_patterns=[ "code/compact_v1/compact_graph_dataset.py", "data/hiqbind_5k_v1/diffdock_full_v1/**", ],)```
若使用命令行客户端,也可执行:
```bashhf download liofoil/copuladock \ --repo-type dataset \ --local-dir copuladock \ --include 'code/compact_v1/compact_graph_dataset.py' \ --include 'data/hiqbind_5k_v1/diffdock_full_v1/**'```
将 `diffdock_full_v1` 替换为 `autodock_vina_full_v1` 即可下载 Vina 数据。
## 3. 环境
读取 compact 数据至少需要支持 `torch.load(..., mmap=True, weights_only=True)` 的 PyTorch 和 PyTorch Geometric:
```bashpip install 'torch>=2.3' torch-geometric```
若需要从 PDB pose 重新构图,再安装发布目录 `code/compact_v1/requirements.txt` 中的完整依赖:
```bashpip install -r code/compact_v1/requirements.txt```
## 4. 正确加载数据
不要直接把 `shards/shard_*.pt` 当作 `list[torch_geometric.data.Data]` 来读取。它们是压缩后的内部张量存储;请通过 `CompactGraphDataset` 进行按需重建。
```pythonimport sysfrom pathlib import Path
from torch_geometric.loader import DataLoader
repo_root = Path("copuladock")sys.path.insert(0, str(repo_root / "code" / "compact_v1"))from compact_graph_dataset import CompactGraphDataset
data_root = ( repo_root / "data" / "hiqbind_5k_v1" / "diffdock_full_v1")dataset = CompactGraphDataset( data_root, max_cached_shards=2, strict=True,)
print(len(dataset)) # 97,988 for DiffDockgraph = dataset[0] # torch_geometric.data.Datametadata = dataset.metadata(0) # 包含 system_id、shard 与 source graph 索引
loader = DataLoader( dataset, batch_size=4, shuffle=True, num_workers=4, persistent_workers=True,)batch = next(iter(loader))```
该 reader 以 mmap 方式打开 shard,并在取样时重建一张 PyG 图;避免先执行 `[dataset[i] for i in range(len(dataset))]`,否则会失去紧凑格式的内存优势。
## 5. 返回图的字段
| 字段 | 形状 / dtype | 含义 || --- | --- | --- || `x` | `[N, 82]`, `float32` | 节点特征 || `edge_index` | `[2, E]`, `int64` | 双向图边 || `edge_attr` | `[E, 4]`, `float32` | 距离 / 距离衰减 / 边两端蛋白标记 || `pos` | `[N, 3]`, `float32` | 当前 docking pose 坐标 || `y_pred` | `[N, 3]`, `float32` | 预测 pose 坐标;数值上与 `pos` 相同 || `y_grt` | `[N, 3]`, `float32` | native/reference 坐标 || `is_protein` | `[N, 1]`, `float32` | 蛋白节点为 1,配体节点为 0 || `y_true` | `[N, 1]`, `float32` | 配体原子的 `||y_pred - y_grt||_2`;蛋白节点为 0 |
计算配体 pose 误差或训练 CQR-GNN 时,应以 `is_protein == 0` 选择配体节点。蛋白节点的 `y_true=0` 并不代表预测误差为零,而是本构图定义中蛋白坐标固定。
## 6. 必须按 system 划分数据
同一 system 的多个 pose 共享蛋白、配体和 native reference。若把 pose 随机切分到 train/validation/test,会造成严重的信息泄漏。
`system_index.json` 提供 `systems`、`graph_to_system`、`system_counts` 和 `source_graph_indices`。推荐先在 system ID 层级使用 PLINDER 或其他规则完成划分,再展开为 graph index:
```pythonimport jsonfrom collections import defaultdictfrom torch.utils.data import Subset
with (data_root / "system_index.json").open() as handle: system_index = json.load(handle)
indices_by_system = defaultdict(list)for graph_index, system_id in enumerate(system_index["graph_to_system"]): indices_by_system[system_id].append(graph_index)
# 这里应由 PLINDER / 时间切分 / 家族切分等外部规则提供 system ID 集合。train_systems = set(...)train_indices = [ graph_index for system_id in train_systems for graph_index in indices_by_system[system_id]]train_dataset = Subset(dataset, train_indices)```
这批 HiQBind 数据没有自带 PLINDER split,也不应被解释为最终泛化评估集。它的主要用途是验证从 baseline pose 到 CQR-GNN 训练样本的端到端流程。
## 7. compact 格式为何更小
同一个 system 的蛋白静态节点特征、native 配体坐标和 protein–protein 边仅存储一次;每个 pose 只保存必要的动态特征、配体坐标和含配体边。`CompactGraphDataset` 会无损重建模型使用的标准 PyG `Data` 字段。
因此,虽然图数接近每个 system 20 个 pose,磁盘中不会为每个 pose 重复保存整份蛋白图。
## 8. 从 Docking Base 输出重新构建
本仓库发布的内容足以加载和训练,不包含原始 HiQBind PDB/SDF 或原始 docking 输出。若希望重建 compact 数据,过程为:
1. 准备符合 Docking Base common-output contract 的已发布 docking 结果;2. 使用 `materialize_hiqbind_gnncp.py` 将嵌套输出硬链接为扁平 PDB pose 目录;3. 使用 `build_compact_v1_direct.py` 构建可断点续跑的 compact shard;4. 使用 `validate_compact_dataset.py` 或 `smoke_test_compact_dataset.py` 抽样验证。
扁平输入中的每个 system 至少需要:
```text<system_id>/├── protein.pdb├── ligand.pdb└── <system_id>_pose_001.pdb ...```
构图入口只接受 PDB pose。典型命令:
```bashpython materialize_hiqbind_gnncp.py \ --method diffdock \ --source-root /path/to/docking_run \ --output-root /path/to/materialized_diffdock
python build_compact_v1_direct.py \ --data-dir /path/to/materialized_diffdock \ --output-dir /path/to/diffdock_compact_v1 \ --method diffdock \ --target-shard-mib 512 \ --system-workers 28 \ --num-workers 1 \ --memory-budget-gib 150 \ --on-error skip-system \ --resume```
`--system-workers > 1` 时必须令 `--num-workers=1`,避免跨 system 并行和 pose 并行嵌套造成不可控内存峰值。上例是适用于 32 CPU / 192 GiB 节点的保守配置;请根据蛋白规模和节点内存调低 `--system-workers` 或 `--memory-budget-gib`。
## 9. 溯源字段
`manifest.json`、`source_index.json` 中的 source 字段只描述构图来源;它们不是下载后必须存在的本地路径。训练和 system-level split 仅需要 compact 根目录、`manifest.json`、`system_index.json` 和 `shards/`。.gitattributes+1
README.mdAdded+71
code/compact_v1/README.mdAdded+28
code/compact_v1/build_compact_v1_direct.pyAdded+1700
code/compact_v1/build_compact_v1_direct.sbatchAdded+130
code/compact_v1/build_graph_unified_enhanced.pyAdded+864
code/compact_v1/build_system_index.pyAdded+295
code/compact_v1/compact_graph_dataset.pyAdded+543
code/compact_v1/convert_to_compact_v1.pyAdded+695
code/compact_v1/materialize_hiqbind_gnncp.pyAdded+240
code/compact_v1/requirements.txtAdded+9
code/compact_v1/smoke_test_compact_dataset.pyAdded+636
code/compact_v1/test_build_compact_v1_direct.pyAdded+403
code/compact_v1/test_compact_graph_dataset.pyAdded+327
code/compact_v1/validate_compact_dataset.pyAdded+401
code/release/upload_copuladock.pyAdded+607
code/release/upload_copuladock.sbatchAdded+44
data/hiqbind_5k_v1/autodock_vina_full_v1/manifest.jsonAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00015.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00016.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00023.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00024.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00025.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00026.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00027.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00038.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00042.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00043.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00050.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00052.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00053.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00056.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00059.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00063.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00067.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00074.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00075.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00082.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00083.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/shards/shard_00086.ptAdded+3
data/hiqbind_5k_v1/autodock_vina_full_v1/source_index.jsonAdded
data/hiqbind_5k_v1/autodock_vina_full_v1/system_index.jsonAdded
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00008.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00029.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00036.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00048.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00049.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/shards/shard_00065.ptAdded+3
data/hiqbind_5k_v1/diffdock_full_v1/system_index.jsonAdded
docs/DATASET_USAGE_ZH.mdAdded+198