Download code/compact_v1/build_system_index.py from liofoil/copuladock: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/datasets/liofoil/copuladock/resolve/main/code/compact_v1/build_system_index.py
- Command line
-
hf download hf://datasets/liofoil/copuladock/code/compact_v1/build_system_index.py
-
curl -L -o build_system_index.py https://huggingface.co/datasets/liofoil/copuladock/resolve/main/code/compact_v1/build_system_index.py
9.44 kB
| #!/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 os | |
| import json | |
| import time | |
| from collections import defaultdict | |
| import numpy as np | |
| import torch | |
| from 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 = 42 | |
| TRAIN_RATIO = 0.70 | |
| VAL_RATIO = 0.10 | |
| CALIB_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() | |