dualmapref 0.2.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- args_parse.py +593 -0
- candidate_corrector.py +161 -0
- candidate_scorer.py +359 -0
- conformend/__init__.py +36 -0
- conformend/refiner.py +25 -0
- dataset/__init__.py +1 -0
- dataset/drugdataset.py +644 -0
- dataset/manifold.py +237 -0
- dataset/sharded_drugdataset.py +124 -0
- dataset/smiles2graph.py +217 -0
- dualmapref/__init__.py +24 -0
- dualmapref/refiner.py +16 -0
- dualmapref-0.2.8.dist-info/LICENSE +21 -0
- dualmapref-0.2.8.dist-info/METADATA +167 -0
- dualmapref-0.2.8.dist-info/RECORD +186 -0
- dualmapref-0.2.8.dist-info/WHEEL +5 -0
- dualmapref-0.2.8.dist-info/entry_points.txt +10 -0
- dualmapref-0.2.8.dist-info/top_level.txt +29 -0
- exputils.py +289 -0
- infer.py +23 -0
- infer_base_conformers.py +5589 -0
- infer_mean_dispersion_torsion.py +1117 -0
- infer_torsion.py +752 -0
- infer_torsional_denoiser.py +1021 -0
- manimol/__init__.py +30 -0
- manimol/__main__.py +6 -0
- manimol/cli.py +36 -0
- manimol/full_cli.py +41 -0
- manimol/legacy_imports.py +43 -0
- manimol/manifest.py +56 -0
- manimol/postprocess.py +148 -0
- manimol/priors.py +60 -0
- manimol/protocols.py +119 -0
- manimol/refiner.py +645 -0
- manimol/runtime.py +194 -0
- manimol/selection.py +85 -0
- manimol/torsion.py +22 -0
- manimol/train_cli.py +14 -0
- mixture_flow/src/__init__.py +1 -0
- mixture_flow/src/_path.py +7 -0
- mixture_flow/src/infer28_mixture_torsion_flow.py +1093 -0
- mixture_flow/src/mixture_torsion_flow.py +291 -0
- mixture_flow/src/summarize_mixture_debug.py +80 -0
- mixture_flow/src/train28_mixture_torsion_flow.py +583 -0
- mixture_torsion_flow.py +7 -0
- models/ manifold_learning.py +86 -0
- models/__init__.py +8 -0
- models/dist.py +273 -0
- models/dist2coords.py +23 -0
- models/egnn.py +107 -0
- models/experimental_backbones.py +364 -0
- models/gnnconv.py +512 -0
- models/kernel_inversion.py +141 -0
- models/kernels.py +427 -0
- models/losses.py +154 -0
- models/mean_dispersion_bridge.py +119 -0
- models/mean_dispersion_torsion_context.py +155 -0
- models/model.py +73 -0
- models/model0.py +2375 -0
- models/vis.py +128 -0
- pgraph_controls.py +107 -0
- scripts/__init__.py +2 -0
- scripts/analyze_basin_alignment.py +63 -0
- scripts/analyze_hif2a_conformer_aggregation.py +267 -0
- scripts/analyze_hif2a_contact_pharmacophore.py +1111 -0
- scripts/analyze_hif2a_fixed_budget.py +202 -0
- scripts/analyze_hif2a_pharmacophore.py +405 -0
- scripts/analyze_hif2a_pharmacophore_match_metric.py +386 -0
- scripts/analyze_p_control_candidate_flow.py +154 -0
- scripts/analyze_scaffold_basin.py +83 -0
- scripts/audit_dispersion_proposals.py +208 -0
- scripts/audit_etflow_protocol.py +258 -0
- scripts/audit_external_overlap.py +150 -0
- scripts/audit_oldbest_fulltrainval_split.py +82 -0
- scripts/audit_pdbbind_contact_pharmacophores.py +146 -0
- scripts/audit_qm9_geomol_test_split.py +94 -0
- scripts/audit_stage1_stage2_cross.py +131 -0
- scripts/build_geom_drugs_lowref_diagnostic.py +84 -0
- scripts/build_qm9_backfill_manifest.py +99 -0
- scripts/check_etflow_runtime.py +56 -0
- scripts/compare_prior_sources.py +122 -0
- scripts/compose_binding_mode_figure.py +87 -0
- scripts/compose_hif2a_contact_pharmacophore_suppfig.py +255 -0
- scripts/compose_hif2a_functional_geometry_pipeline.py +266 -0
- scripts/compose_manimol_internal_architecture.py +291 -0
- scripts/diagnose_flow_basin_intervention.py +54 -0
- scripts/diagnose_hif2a_pharmacophore_budget.py +185 -0
- scripts/diagnose_route2_p_ranking.py +123 -0
- scripts/discover_binding_mode_inputs.py +30 -0
- scripts/evaluate_functional_prior_stage1.py +230 -0
- scripts/evaluate_geomanimol.py +74 -0
- scripts/evaluate_geomanimol_flow.py +23 -0
- scripts/evaluate_geomanimol_multiscaffold.py +46 -0
- scripts/evaluate_geomanimol_residual.py +45 -0
- scripts/evaluate_geomanimol_torsion.py +40 -0
- scripts/evaluate_hif2a_bioactive_enrichment.py +91 -0
- scripts/evaluate_hif2a_pms_suite.py +440 -0
- scripts/evaluate_pdbbind_contact_pms.py +155 -0
- scripts/evaluate_platinum_external.py +114 -0
- scripts/evaluate_platinum_pool.py +82 -0
- scripts/evaluate_route2_calibrated_p.py +104 -0
- scripts/evaluate_route2_library_components.py +596 -0
- scripts/evaluate_route2_p_basin_budget.py +288 -0
- scripts/evaluate_stage1_checkpoint_only.py +30 -0
- scripts/export_dispersion_bond_audit.py +136 -0
- scripts/export_top20_shards.py +207 -0
- scripts/external_validation_metrics.py +152 -0
- scripts/fit_topology_prior.py +117 -0
- scripts/frozen_dispersion_audit.py +281 -0
- scripts/geomanimol_debug.py +50 -0
- scripts/geomanimol_smoke.py +37 -0
- scripts/infer_etflow_matched.py +524 -0
- scripts/inspect_checkpoint.py +12 -0
- scripts/inspect_conformer_capacity.py +71 -0
- scripts/inspect_pool.py +12 -0
- scripts/make_figure3_selection_loss.py +474 -0
- scripts/make_figure3_selection_summary.py +275 -0
- scripts/make_geom_debug_subset.py +62 -0
- scripts/make_low_reference_test_subset.py +70 -0
- scripts/merge_stage1_into_stage2.py +82 -0
- scripts/place_hif2a_candidates_for_evaluation.py +66 -0
- scripts/plot_hif2a_low_budget_efficiency.py +100 -0
- scripts/plot_prior_validation.py +48 -0
- scripts/precompute_stage2_assignments.py +90 -0
- scripts/prepare_bace_activity.py +98 -0
- scripts/prepare_bace_etkdg_benchmark.py +90 -0
- scripts/prepare_figure5_4x4_cases.py +470 -0
- scripts/prepare_geom_drugs_geomol_top20.py +472 -0
- scripts/prepare_pdbbind_core_raw.py +90 -0
- scripts/prepare_platinum_raw.py +74 -0
- scripts/prepare_pubchem_etkdg.py +54 -0
- scripts/rebuild_hif2a_final_sdf_and_metrics.py +55 -0
- scripts/rebuild_hif2a_fixed_pool_sweep.py +175 -0
- scripts/rebuild_hif2a_strict.py +220 -0
- scripts/recompute_hif2a_bootstrap.py +63 -0
- scripts/reference_free_geometry.py +112 -0
- scripts/render_binding_modes.py +413 -0
- scripts/render_figure5_4x4.py +330 -0
- scripts/render_figure6_pharmacophore_pymol.py +162 -0
- scripts/render_hif2a_contact_pharmacophore_pymol.py +414 -0
- scripts/render_hif2a_figure11.py +397 -0
- scripts/run_bace_2d_baseline.py +73 -0
- scripts/run_drugs_validation_matrix.py +225 -0
- scripts/run_external_reference_free.py +53 -0
- scripts/run_manimol_finalk_sensitivity.py +106 -0
- scripts/run_manimol_oversampling_sensitivity.py +109 -0
- scripts/run_pdisp_matched_intervention.py +116 -0
- scripts/run_stage1_stage2_cross20.py +83 -0
- scripts/score_hif2a_candidates_with_pgraph.py +221 -0
- scripts/summarize_dispersion_intervention.py +88 -0
- scripts/test_mean_dispersion_bridge.py +50 -0
- scripts/train_dispersion_head_diagnostic.py +320 -0
- scripts/train_dispersion_head_streaming.py +519 -0
- scripts/train_geomanimol.py +100 -0
- scripts/train_geomanimol_flow.py +26 -0
- scripts/train_geomanimol_residual.py +70 -0
- scripts/train_geomanimol_torsion.py +50 -0
- scripts/train_quantile_representation_diagnostic.py +204 -0
- scripts/validate_mean_dispersion_prior.py +173 -0
- scripts/validate_packed_shard.py +41 -0
- scripts/validate_stage1_prior.py +221 -0
- scripts/validate_top20_shards.py +36 -0
- scripts/validation/__init__.py +1 -0
- scripts/validation/hif2a_downstream_baselines.py +105 -0
- scripts/validation/hif2a_pairwise_ranker.py +218 -0
- scripts/verify_binding_mode_figure.py +47 -0
- torsion_manifold.py +281 -0
- train.py +78 -0
- train_graph_encoder.py +206 -0
- train_local_torsion_corrector.py +511 -0
- train_mean_dispersion_torsion_prior.py +329 -0
- train_probability_basin.py +235 -0
- train_torsion_generator.py +1631 -0
- train_torsion_manifold_prior.py +258 -0
- train_torsional_denoiser.py +415 -0
- trainer.py +1038 -0
- utils/__init__.py +7 -0
- utils/checkpoint.py +40 -0
- utils/device.py +17 -0
- utils/helpers.py +98 -0
- utils/kabsch.py +29 -0
- utils/lookup_table.py +164 -0
- utils/metrics.py +50 -0
- utils/optuna.py +111 -0
- utils/save_mol.py +366 -0
- utils/util.py +36 -0
utils/save_mol.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
# mol_utils.py
|
|
2
|
+
# 将args中的输入的smiles中对应的结构保存到rdkit的conformer(这个在求RMSE时也需要用到)中,保存为pdb格式用以可视化,如果有其他更好的方式也可以采用其他的方式
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import pickle
|
|
6
|
+
import copy
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
from rdkit import Chem
|
|
10
|
+
from rdkit.Geometry import Point3D
|
|
11
|
+
|
|
12
|
+
# 初始化日志器(确保能使用logger.exception)
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def save_molecule_views(output_dir, mol_pred, pos_gt_data=None, smiles_target=None, args_to_save=None, save_pdb=True):
|
|
18
|
+
"""
|
|
19
|
+
Save mol_pred and its ground-truth conformer (if pos_gt_data provided).
|
|
20
|
+
Creates:
|
|
21
|
+
- mol_view.pkl
|
|
22
|
+
- mol_view_gt.pkl (if pos_gt_data)
|
|
23
|
+
- mol_view.pdb and mol_view_gt.pdb (if save_pdb True)
|
|
24
|
+
- train_args.json (if args_to_save provided)
|
|
25
|
+
# MOD 3: 将重复保存分子/生成 mol_gt 的逻辑抽出来,避免重复造轮子。
|
|
26
|
+
"""
|
|
27
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
28
|
+
|
|
29
|
+
# Save predicted mol
|
|
30
|
+
try:
|
|
31
|
+
with open(os.path.join(output_dir, "mol_view.pkl"), "wb") as f:
|
|
32
|
+
pickle.dump(mol_pred, f)
|
|
33
|
+
except Exception:
|
|
34
|
+
logger.exception("Failed to pickle mol_pred")
|
|
35
|
+
|
|
36
|
+
# If ground-truth positions provided, construct and save a GT conformer mol
|
|
37
|
+
if pos_gt_data is not None:
|
|
38
|
+
try:
|
|
39
|
+
mol_gt = copy.deepcopy(mol_pred)
|
|
40
|
+
mol_gt.RemoveAllConformers()
|
|
41
|
+
conf_gt = Chem.Conformer(mol_gt.GetNumAtoms())
|
|
42
|
+
for atom_idx, (x, y, z) in enumerate(pos_gt_data.tolist()):
|
|
43
|
+
conf_gt.SetAtomPosition(atom_idx, Point3D(x, y, z))
|
|
44
|
+
mol_gt.AddConformer(conf_gt, assignId=True)
|
|
45
|
+
with open(os.path.join(output_dir, "mol_view_gt.pkl"), "wb") as f:
|
|
46
|
+
pickle.dump(mol_gt, f)
|
|
47
|
+
except Exception:
|
|
48
|
+
logger.exception("Failed to create/save mol_gt")
|
|
49
|
+
|
|
50
|
+
# Save pdb files (if possible)
|
|
51
|
+
try:
|
|
52
|
+
if save_pdb:
|
|
53
|
+
Chem.MolToPDBFile(mol_pred, os.path.join(output_dir, "mol_view.pdb"))
|
|
54
|
+
if pos_gt_data is not None:
|
|
55
|
+
Chem.MolToPDBFile(mol_gt, os.path.join(output_dir, "mol_view_gt.pdb"))
|
|
56
|
+
except Exception:
|
|
57
|
+
logger.exception("Failed to write pdb files")
|
|
58
|
+
|
|
59
|
+
# Save args if provided (this keeps reproducibility)
|
|
60
|
+
if args_to_save is not None:
|
|
61
|
+
try:
|
|
62
|
+
with open(os.path.join(output_dir, "train_args.json"), "w") as f:
|
|
63
|
+
json.dump(vars(args_to_save), f, indent=4)
|
|
64
|
+
except Exception:
|
|
65
|
+
logger.exception("Failed to save args to json")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class MolSaver:
|
|
70
|
+
"""
|
|
71
|
+
保存分子 conformer 的小工具类:
|
|
72
|
+
- build_mol_with_pred: 根据预测坐标生成带 conformer 的分子副本(不会修改原对象)
|
|
73
|
+
- save_final: 保存训练结束(或 early-stop)时的 mol_pred + gt conformer + train args
|
|
74
|
+
- save_epoch: 保存中间 epoch 的 mol(只保存 mol_pred 的 epoch 视图)
|
|
75
|
+
"""
|
|
76
|
+
def __init__(self, base_dir='rdmol'):
|
|
77
|
+
self.base_dir = base_dir
|
|
78
|
+
# 记录最后一次保存的 epoch,防止重复保存
|
|
79
|
+
self.last_conformer_save_epoch = -1
|
|
80
|
+
os.makedirs(self.base_dir, exist_ok=True)
|
|
81
|
+
|
|
82
|
+
def _now_str(self):
|
|
83
|
+
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f")[:-3]
|
|
84
|
+
|
|
85
|
+
def _make_output_dir(self, prefix, smiles):
|
|
86
|
+
now_str = self._now_str()
|
|
87
|
+
dirn = os.path.join(prefix, f"{now_str}_{smiles}")
|
|
88
|
+
os.makedirs(dirn, exist_ok=True)
|
|
89
|
+
return dirn
|
|
90
|
+
|
|
91
|
+
def build_mol_with_pred(self, mol, pred_pos, node_mask):
|
|
92
|
+
"""
|
|
93
|
+
返回一个 deepcopy(mol) 并把 pred_pos[node_mask] 作为一个新的 conformer 添加进去。
|
|
94
|
+
pred_pos: Tensor/ndarray shape [N_atoms_total, 3]
|
|
95
|
+
node_mask: boolean mask (或 LongTensor 索引) 标识属于该分子的原子行
|
|
96
|
+
"""
|
|
97
|
+
mol_new = copy.deepcopy(mol)
|
|
98
|
+
try:
|
|
99
|
+
conf = Chem.Conformer(mol_new.GetNumAtoms())
|
|
100
|
+
coords = pred_pos[node_mask].tolist()
|
|
101
|
+
for atom_idx, (x, y, z) in enumerate(coords):
|
|
102
|
+
conf.SetAtomPosition(atom_idx, Point3D(x, y, z))
|
|
103
|
+
# remove existing conformers (defensive)
|
|
104
|
+
try:
|
|
105
|
+
mol_new.RemoveAllConformers()
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
mol_new.AddConformer(conf, assignId=True)
|
|
109
|
+
except Exception:
|
|
110
|
+
# 如果任何步骤失败,返回 deepcopy(mol)(不包含预测坐标)
|
|
111
|
+
mol_new = copy.deepcopy(mol)
|
|
112
|
+
return mol_new
|
|
113
|
+
|
|
114
|
+
def _write_pickle(self, path, obj):
|
|
115
|
+
with open(path, "wb") as f:
|
|
116
|
+
pickle.dump(obj, f)
|
|
117
|
+
|
|
118
|
+
def _write_json_args(self, dirn, args):
|
|
119
|
+
if args is None:
|
|
120
|
+
return
|
|
121
|
+
try:
|
|
122
|
+
with open(os.path.join(dirn, "train_args.json"), "w") as f:
|
|
123
|
+
json.dump(vars(args), f, indent=4)
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
def save_final(self, mol_pred, pos_gt=None, smiles="unknown", args=None, save_pdb=True, save_pickle=True):
|
|
128
|
+
"""
|
|
129
|
+
保存最终视图:mol_pred (+ mol_gt 如果 pos_gt 给出) 以及 train args。
|
|
130
|
+
返回 output_dir 路径(或 None if failed)
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
# 构建 mol_gt(如果有)
|
|
134
|
+
mol_gt = None
|
|
135
|
+
if pos_gt is not None:
|
|
136
|
+
try:
|
|
137
|
+
mol_gt = copy.deepcopy(mol_pred)
|
|
138
|
+
mol_gt.RemoveAllConformers()
|
|
139
|
+
conf_gt = Chem.Conformer(mol_gt.GetNumAtoms())
|
|
140
|
+
for atom_idx, (x, y, z) in enumerate(pos_gt.tolist()):
|
|
141
|
+
conf_gt.SetAtomPosition(atom_idx, Point3D(x, y, z))
|
|
142
|
+
mol_gt.AddConformer(conf_gt, assignId=True)
|
|
143
|
+
except Exception:
|
|
144
|
+
mol_gt = None
|
|
145
|
+
|
|
146
|
+
out_dir = self._make_output_dir(self.base_dir, smiles)
|
|
147
|
+
|
|
148
|
+
if save_pickle:
|
|
149
|
+
try:
|
|
150
|
+
self._write_pickle(os.path.join(out_dir, "mol_view.pkl"), mol_pred)
|
|
151
|
+
if mol_gt is not None:
|
|
152
|
+
self._write_pickle(os.path.join(out_dir, "mol_view_gt.pkl"), mol_gt)
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
if save_pdb:
|
|
157
|
+
try:
|
|
158
|
+
Chem.MolToPDBFile(mol_pred, os.path.join(out_dir, "mol_view.pdb"))
|
|
159
|
+
if mol_gt is not None:
|
|
160
|
+
Chem.MolToPDBFile(mol_gt, os.path.join(out_dir, "mol_view_gt.pdb"))
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
# 保存 args(如果提供)
|
|
165
|
+
self._write_json_args(out_dir, args)
|
|
166
|
+
|
|
167
|
+
return out_dir
|
|
168
|
+
except Exception:
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def save_epoch(self, mol_pred, epoch, smiles="unknown", save_pdb=True, save_pickle=True):
|
|
172
|
+
"""
|
|
173
|
+
保存中间 epoch 的 mol_pred(例如 'rdmol/epoch{epoch}_{time}_{smiles}/...')
|
|
174
|
+
只在 epoch > last_conformer_save_epoch 时保存并更新 last_conformer_save_epoch。
|
|
175
|
+
返回 output_dir 或 None。
|
|
176
|
+
"""
|
|
177
|
+
try:
|
|
178
|
+
if epoch <= self.last_conformer_save_epoch:
|
|
179
|
+
return None
|
|
180
|
+
prefix = os.path.join(self.base_dir, f"epoch{epoch}")
|
|
181
|
+
out_dir = self._make_output_dir(prefix, smiles)
|
|
182
|
+
|
|
183
|
+
if save_pickle:
|
|
184
|
+
try:
|
|
185
|
+
self._write_pickle(os.path.join(out_dir, "mol_view_epoch.pkl"), mol_pred)
|
|
186
|
+
except Exception:
|
|
187
|
+
pass
|
|
188
|
+
if save_pdb:
|
|
189
|
+
try:
|
|
190
|
+
Chem.MolToPDBFile(mol_pred, os.path.join(out_dir, "mol_view_epoch.pdb"))
|
|
191
|
+
except Exception:
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
self.last_conformer_save_epoch = epoch
|
|
195
|
+
return out_dir
|
|
196
|
+
except Exception:
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
from typing import List, Optional, Union, Sequence
|
|
201
|
+
import torch
|
|
202
|
+
from rdkit import Chem
|
|
203
|
+
from rdkit.Geometry import Point3D
|
|
204
|
+
|
|
205
|
+
def write_pred_pos_to_conformers(
|
|
206
|
+
pred_pos: torch.Tensor,
|
|
207
|
+
data,
|
|
208
|
+
rdmol_attr: str = "rdmol",
|
|
209
|
+
batch_attr: str = "batch",
|
|
210
|
+
allow_placeholder: bool = False,
|
|
211
|
+
placeholder_atom: str = "C"
|
|
212
|
+
) -> List[Chem.Mol]:
|
|
213
|
+
"""
|
|
214
|
+
将预测坐标写入 RDKit Mol 的 conformer 并返回分子列表,用于最终RMSD检测。
|
|
215
|
+
|
|
216
|
+
---- 输入 ----
|
|
217
|
+
- pred_pos: torch.Tensor, shape [N_total_atoms, 3], dtype float32/float64. 可以在任意 device,
|
|
218
|
+
函数内部会用 .detach().cpu() 读取数值用于写入 RDKit。
|
|
219
|
+
- data: 一个对象,期望包含以下之一:
|
|
220
|
+
1) data.batch: torch.LongTensor/torch.Tensor (长度 = N_total_atoms),表示每个原子所属分子索引;
|
|
221
|
+
同时 data.rdmol: 序列 (list/tuple) 包含每个分子的 rdkit.Chem.Mol。
|
|
222
|
+
2) 或者仅 data.rdmol: 序列 (list/tuple),此时函数按 rdmol 中每个分子的 atom-count
|
|
223
|
+
依次把 pred_pos 切成块(前提:总原子数与 pred_pos 行数一致)。
|
|
224
|
+
- rdmol_attr: data 中 rdkit mol 列表的属性名,默认 "rdmol"
|
|
225
|
+
- batch_attr: data 中 batch 的属性名,默认 "batch"
|
|
226
|
+
- allow_placeholder: 若 True,当 data.rdmol 缺失或某元素为 None 时,自动创建占位分子(仅用于可视化/调试)
|
|
227
|
+
- placeholder_atom: 占位分子使用的原子符号(如 "C")
|
|
228
|
+
|
|
229
|
+
---- 输出 ----
|
|
230
|
+
- mol_list: List[rdkit.Chem.Mol]
|
|
231
|
+
返回已复制并附加新 conformer 的分子列表。仅包含那些成功写入构象的分子。
|
|
232
|
+
注意:原始 data.rdmol 不会被原地修改(我们对每个 orig_mol 取了 Chem.Mol(orig_mol) 的副本)。
|
|
233
|
+
|
|
234
|
+
---- 行为 ----
|
|
235
|
+
- 完全使用 torch 来处理索引/切片(没有 numpy 依赖)。
|
|
236
|
+
- 当 batch 存在时,以 batch 决定每个分子的 atom indices;否则按 data.rdmol 的 atom counts 顺序分块。
|
|
237
|
+
- 若某分子的 atom_idx 为空会被跳过。
|
|
238
|
+
- 若 rdmol 缺失且 allow_placeholder=False,会抛出 ValueError(包含说明)。
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
if not isinstance(pred_pos, torch.Tensor):
|
|
242
|
+
raise TypeError("pred_pos 必须是 torch.Tensor,当前类型: {}".format(type(pred_pos)))
|
|
243
|
+
|
|
244
|
+
if pred_pos.ndim != 2 or pred_pos.size(1) != 3:
|
|
245
|
+
raise ValueError("pred_pos 必须形状为 [N,3],当前形状: {}".format(tuple(pred_pos.shape)))
|
|
246
|
+
|
|
247
|
+
# 将 pred_pos 保持为 tensor,但为读取数值时准备 cpu 副本(不转换为 numpy 全数组)
|
|
248
|
+
pred_pos_cpu = pred_pos.detach().cpu()
|
|
249
|
+
|
|
250
|
+
# 读取 batch 与 rdmol_list(均不做 numpy 转换)
|
|
251
|
+
batch = getattr(data, batch_attr, None)
|
|
252
|
+
rdmol_list: Optional[Sequence] = getattr(data, rdmol_attr, None)
|
|
253
|
+
|
|
254
|
+
if batch is not None:
|
|
255
|
+
if not isinstance(batch, torch.Tensor):
|
|
256
|
+
# 若 batch 是其他可迭代(例如 list/np array),尝试转为 torch tensor
|
|
257
|
+
batch = torch.tensor(batch, dtype=torch.long)
|
|
258
|
+
else:
|
|
259
|
+
batch = batch.detach().cpu().long()
|
|
260
|
+
# 计算分子数
|
|
261
|
+
if batch.numel() == 0:
|
|
262
|
+
n_mols = 0
|
|
263
|
+
else:
|
|
264
|
+
n_mols = int(batch.max().item()) + 1
|
|
265
|
+
batch_arr = batch
|
|
266
|
+
else:
|
|
267
|
+
# 没有 batch:需要 rdmol_list 来推断分子数和每个分子的原子数
|
|
268
|
+
if rdmol_list is None:
|
|
269
|
+
raise ValueError(f"data 中既没有属性 '{batch_attr}' 也没有属性 '{rdmol_attr}'。无法推断分子分块。")
|
|
270
|
+
try:
|
|
271
|
+
n_mols = len(rdmol_list)
|
|
272
|
+
except Exception:
|
|
273
|
+
raise ValueError(f"data.{rdmol_attr} 必须是可索引序列 (list/tuple)。 当前类型: {type(rdmol_list)}")
|
|
274
|
+
batch_arr = None
|
|
275
|
+
|
|
276
|
+
mol_list: List[Chem.Mol] = []
|
|
277
|
+
|
|
278
|
+
# 当没有 batch 时,预先计算每个分子的 atom counts(纯 Python 调用 RDKit 接口)
|
|
279
|
+
if batch_arr is None:
|
|
280
|
+
sizes = []
|
|
281
|
+
for i in range(n_mols):
|
|
282
|
+
mol_i = rdmol_list[i] if i < len(rdmol_list) else None
|
|
283
|
+
if mol_i is None:
|
|
284
|
+
sizes.append(0)
|
|
285
|
+
else:
|
|
286
|
+
sizes.append(mol_i.GetNumAtoms())
|
|
287
|
+
# 验证总数是否与 pred_pos 行数匹配(可选,不严格要求)
|
|
288
|
+
total = sum(sizes)
|
|
289
|
+
if total != pred_pos_cpu.size(0):
|
|
290
|
+
# 不必强制报错,但提醒用户(用异常会中断流程,遵循原逻辑可选择抛出)
|
|
291
|
+
raise ValueError(f"按 data.rdmol 推断的总原子数 {total} 与 pred_pos 行数 {pred_pos_cpu.size(0)} 不一致。")
|
|
292
|
+
|
|
293
|
+
# 计算每个分子的起止索引(torch-friendly)
|
|
294
|
+
starts = [0]
|
|
295
|
+
for s in sizes[:-1]:
|
|
296
|
+
starts.append(starts[-1] + s)
|
|
297
|
+
|
|
298
|
+
# 遍历每个分子,取对应 atom indices 并写入 conformer
|
|
299
|
+
for mi in range(n_mols):
|
|
300
|
+
if batch_arr is not None:
|
|
301
|
+
# 找到属于该分子的 atom 索引(torch.where -> 1D long tensor)
|
|
302
|
+
atom_idx = torch.where(batch_arr == mi)[0]
|
|
303
|
+
else:
|
|
304
|
+
s = sizes[mi]
|
|
305
|
+
if s == 0:
|
|
306
|
+
atom_idx = torch.empty((0,), dtype=torch.long)
|
|
307
|
+
else:
|
|
308
|
+
start = starts[mi]
|
|
309
|
+
atom_idx = torch.arange(start, start + s, dtype=torch.long)
|
|
310
|
+
|
|
311
|
+
if atom_idx.numel() == 0:
|
|
312
|
+
# 没有原子,跳过
|
|
313
|
+
continue
|
|
314
|
+
|
|
315
|
+
coords = pred_pos_cpu[atom_idx] # 仍是 torch.Tensor on cpu, shape [n_atoms_i, 3]
|
|
316
|
+
|
|
317
|
+
# 获取原始分子或创建占位(如果允许)
|
|
318
|
+
orig_mol = None
|
|
319
|
+
if rdmol_list is not None:
|
|
320
|
+
try:
|
|
321
|
+
orig_mol = rdmol_list[mi]
|
|
322
|
+
except Exception:
|
|
323
|
+
orig_mol = None
|
|
324
|
+
|
|
325
|
+
if orig_mol is None:
|
|
326
|
+
if not allow_placeholder:
|
|
327
|
+
raise ValueError(
|
|
328
|
+
f"data.{rdmol_attr}[{mi}] 缺失或为 None。无法为分子索引 {mi} 写入构象。"
|
|
329
|
+
" 如需自动创建占位分子,请将 allow_placeholder=True。"
|
|
330
|
+
)
|
|
331
|
+
# 创建占位分子:只包含相应数量的原子(无键)
|
|
332
|
+
mol_rw = Chem.RWMol()
|
|
333
|
+
n_atoms_i = int(coords.size(0))
|
|
334
|
+
for _ in range(n_atoms_i):
|
|
335
|
+
mol_rw.AddAtom(Chem.Atom(placeholder_atom))
|
|
336
|
+
orig_mol = mol_rw.GetMol()
|
|
337
|
+
|
|
338
|
+
# 复制 mol,避免修改原始对象
|
|
339
|
+
mol = Chem.Mol(orig_mol)
|
|
340
|
+
|
|
341
|
+
# 新建 conformer 并写入坐标(写入到 min(n_atoms_in_mol, coords.shape[0]))
|
|
342
|
+
n_write = min(mol.GetNumAtoms(), int(coords.size(0)))
|
|
343
|
+
conf = Chem.Conformer(mol.GetNumAtoms())
|
|
344
|
+
# coords 是 torch.Tensor; 逐个取 float,RDKit 需要 Python float
|
|
345
|
+
for ai in range(n_write):
|
|
346
|
+
# coords[ai] 是 tensor([x,y,z])
|
|
347
|
+
x = float(coords[ai, 0].item())
|
|
348
|
+
y = float(coords[ai, 1].item())
|
|
349
|
+
z = float(coords[ai, 2].item())
|
|
350
|
+
conf.SetAtomPosition(int(ai), Point3D(x, y, z))
|
|
351
|
+
|
|
352
|
+
# 移除旧 conformer 并添加新 conformer
|
|
353
|
+
try:
|
|
354
|
+
mol.RemoveAllConformers()
|
|
355
|
+
except Exception:
|
|
356
|
+
pass
|
|
357
|
+
mol.AddConformer(conf, assignId=True)
|
|
358
|
+
|
|
359
|
+
mol_list.append(mol)
|
|
360
|
+
|
|
361
|
+
return mol_list
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
|
utils/util.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
def get_arg(args, name, default=None):
|
|
5
|
+
"""
|
|
6
|
+
Safely get an attribute from args (replace multiple hasattr checks).
|
|
7
|
+
Usage: get_arg(args, 'get_image', False)
|
|
8
|
+
# MOD 1: 替换散落的 hasattr(args, 'xxx') 检查。
|
|
9
|
+
"""
|
|
10
|
+
return getattr(args, name, default)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def safe_float(x, default=float('inf')):
|
|
14
|
+
"""
|
|
15
|
+
Convert to float if possible; otherwise return default.
|
|
16
|
+
# MOD 2: 替换重复的 try/except float(...) 代码。
|
|
17
|
+
"""
|
|
18
|
+
try:
|
|
19
|
+
return float(x)
|
|
20
|
+
except Exception:
|
|
21
|
+
try:
|
|
22
|
+
return float(x.item())
|
|
23
|
+
except Exception:
|
|
24
|
+
return default
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _atomic_write_json(path, obj):
|
|
28
|
+
tmp = path + ".tmp"
|
|
29
|
+
with open(tmp, "w") as f:
|
|
30
|
+
json.dump(obj, f, indent=4)
|
|
31
|
+
f.flush()
|
|
32
|
+
try:
|
|
33
|
+
os.fsync(f.fileno())
|
|
34
|
+
except Exception:
|
|
35
|
+
pass
|
|
36
|
+
os.replace(tmp, path)
|