File size: 9,441 Bytes
0cb481f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/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()