File size: 31,709 Bytes
0cb481f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
#!/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 os
import glob
import argparse
from typing import Sequence, List, Dict, Tuple, Optional
from collections import defaultdict

import numpy as np
import torch
from torch_geometric.data import Data
import MDAnalysis as mda
from io import StringIO
from scipy.spatial.distance import cdist
from 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=16