| |
| |
| """ |
| 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: 包含节点特征、边、标签的图数据 |
| """ |
| |
| 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]}") |
| |
| |
| |
| errors_prot = np.zeros(Np, dtype=np.float32) |
| |
| |
| errors_lig = np.linalg.norm(coords_lig_pred - coords_lig_native, axis=1).astype(np.float32) |
| |
| y_true = np.concatenate([errors_prot, errors_lig]) |
| |
| |
| coords_all_pred = np.vstack([coords_prot, coords_lig_pred]) |
| coords_all_native = np.vstack([coords_prot, coords_lig_native]) |
| |
| |
| |
| y_pred = coords_all_pred |
| y_grt = coords_all_native |
| |
| |
| all_atoms = list(prot_atoms) + list(lig_pred_atoms) |
| elements = [_get_element(atom) for atom in all_atoms] |
| |
| |
| |
| atom_type_oh = np.stack([ |
| _one_hot(ELEMENT2IDX.get(elem, ELEMENT2IDX["Other"]), len(ELEMENTS)) |
| for elem in elements |
| ]) |
| |
| |
| 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 = np.zeros((N, 1), dtype=np.float32) |
| is_protein[:Np] = 1.0 |
| is_ligand = 1.0 - is_protein |
| |
| |
| 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 |
| |
| |
| if use_enhanced_features: |
| |
| 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, |
| res_type_oh, |
| is_protein, |
| is_ligand, |
| d_prot_center_norm, |
| d_lig_center_norm, |
| d_min_prot_norm, |
| d_min_lig_norm, |
| local_geom_feat, |
| dist_stat_feat, |
| chem_feat, |
| prot_specific_feat, |
| topo_feat, |
| interface_feat, |
| local_env_feat, |
| ], axis=1).astype(np.float32) |
| else: |
| |
| 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) |
| |
| |
| mask = (dist_all <= cutoff) & (~np.eye(N, dtype=bool)) |
| src, dst = np.where(mask) |
| edge_index = np.vstack([src, dst]).astype(np.int64) |
| |
| |
| 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 |
| |
| |
| 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), |
| y_pred=torch.from_numpy(y_pred), |
| y_grt=torch.from_numpy(y_grt), |
| 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 |
| |
| |
| 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 |
| |
| |
| pose_files = [] |
| |
| if docking_type == "protenix": |
| |
| patterns = [ |
| os.path.join(subdir, f"*_pose*.pdb"), |
| os.path.join(subdir, f"{pdb_id}_pose_*.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, |
| ) |
| |
| 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() |
|
|
| |
| |
| |
| |
| |
| |
|
|