molforge-studio 7.4.3__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.
- main.py +71 -0
- molforge/__init__.py +19 -0
- molforge/ai/__init__.py +15 -0
- molforge/ai/deepseek_harness.py +185 -0
- molforge/ai/mcp/desktop_client.py +38 -0
- molforge/ai/mcp/desktop_service.py +121 -0
- molforge/ai/mcp/mcp_server.py +780 -0
- molforge/ai/mcp_bridge.py +945 -0
- molforge/ai/observation.py +152 -0
- molforge/ai/tools.py +455 -0
- molforge/application/__init__.py +22 -0
- molforge/application/ai/__init__.py +1 -0
- molforge/application/ai/deepseek_client.py +293 -0
- molforge/application/ai/observation.py +161 -0
- molforge/application/ai/tools.py +200 -0
- molforge/application/ai_proposals.py +166 -0
- molforge/application/bio_selection.py +143 -0
- molforge/application/builtin_commands.py +1445 -0
- molforge/application/calculators/__init__.py +10 -0
- molforge/application/calculators/base.py +143 -0
- molforge/application/calculators/calchem_engine.py +67 -0
- molforge/application/calculators/calchem_subprocess_worker.py +109 -0
- molforge/application/calculators/gaussian_engine.py +59 -0
- molforge/application/calculators/gaussian_job_spec.py +240 -0
- molforge/application/calculators/orca_engine.py +92 -0
- molforge/application/calculators/qc_input_generator.py +300 -0
- molforge/application/calculators/registry.py +29 -0
- molforge/application/calculators/rest_engine.py +262 -0
- molforge/application/command_bus.py +139 -0
- molforge/application/commands.py +55 -0
- molforge/application/conformers.py +143 -0
- molforge/application/document_session.py +156 -0
- molforge/application/events.py +74 -0
- molforge/application/fragment_catalog.py +422 -0
- molforge/application/fragment_commands.py +268 -0
- molforge/application/geometry_commands.py +84 -0
- molforge/application/history.py +105 -0
- molforge/application/internal_coordinates.py +293 -0
- molforge/application/invalidation.py +1174 -0
- molforge/application/jobs.py +185 -0
- molforge/application/measurement.py +167 -0
- molforge/application/measurement_targets.py +264 -0
- molforge/application/modeling_commands.py +61 -0
- molforge/application/plugins.py +197 -0
- molforge/application/ports/editor2d.py +85 -0
- molforge/application/reaction.py +75 -0
- molforge/application/selection.py +164 -0
- molforge/application/selection_commands.py +31 -0
- molforge/application/trajectory.py +120 -0
- molforge/application/trajectory_analysis.py +231 -0
- molforge/application/workspace_registry.py +226 -0
- molforge/core/__init__.py +12 -0
- molforge/core/conformer.py +45 -0
- molforge/core/molecule.py +150 -0
- molforge/core/orbital.py +33 -0
- molforge/core/properties.py +43 -0
- molforge/domain/__init__.py +12 -0
- molforge/domain/biomolecule.py +99 -0
- molforge/domain/chemical_summary.py +129 -0
- molforge/domain/chemistry.py +13 -0
- molforge/domain/coordinate_store.py +164 -0
- molforge/domain/coordination.py +133 -0
- molforge/domain/custom_fragments.py +255 -0
- molforge/domain/document.py +469 -0
- molforge/domain/element_reference.json +598 -0
- molforge/domain/elements.py +188 -0
- molforge/domain/ids.py +58 -0
- molforge/domain/massive_system.py +246 -0
- molforge/domain/periodic.py +116 -0
- molforge/domain/provenance.py +115 -0
- molforge/domain/topology.py +364 -0
- molforge/infrastructure/__init__.py +23 -0
- molforge/infrastructure/hpc/cluster_config.py +122 -0
- molforge/infrastructure/hpc/remote_executor.py +212 -0
- molforge/infrastructure/hpc/slurm_generator.py +93 -0
- molforge/io/__init__.py +35 -0
- molforge/io/calchem_bridge.py +407 -0
- molforge/io/calculators.py +893 -0
- molforge/io/cclib_adapter.py +422 -0
- molforge/io/conformers.py +183 -0
- molforge/io/cube_reader.py +215 -0
- molforge/io/custom_fragments.py +79 -0
- molforge/io/format_matrix.py +157 -0
- molforge/io/gemmi_adapter.py +150 -0
- molforge/io/history_skill.py +46 -0
- molforge/io/mdanalysis_adapter.py +155 -0
- molforge/io/mforge_storage.py +261 -0
- molforge/io/multiwfn_driver.py +614 -0
- molforge/io/openbabel_adapter.py +265 -0
- molforge/io/openbabel_handler.py +33 -0
- molforge/io/rdkit_adapter.py +1865 -0
- molforge/io/readers/__init__.py +10 -0
- molforge/io/readers/cube_reader.py +71 -0
- molforge/io/readers/gjf_reader.py +110 -0
- molforge/io/readers/glog_reader.py +45 -0
- molforge/io/readers/mol2_reader.py +36 -0
- molforge/io/readers/mol_reader.py +56 -0
- molforge/io/readers/pdb_reader.py +39 -0
- molforge/io/readers/smi_reader.py +40 -0
- molforge/io/readers/xyz_reader.py +47 -0
- molforge/io/registry.py +128 -0
- molforge/io/writers/__init__.py +7 -0
- molforge/io/writers/gjf_writer.py +68 -0
- molforge/io/writers/pdb_writer.py +37 -0
- molforge/io/writers/png_writer.py +31 -0
- molforge/io/writers/svg_writer.py +111 -0
- molforge/io/writers/xyz_writer.py +39 -0
- molforge/rendering/__init__.py +21 -0
- molforge/rendering/benchmark.py +121 -0
- molforge/rendering/bridge.py +60 -0
- molforge/rendering/contracts.py +119 -0
- molforge/rendering/glyph_scene.py +279 -0
- molforge/rendering/ketcher_bridge.py +131 -0
- molforge/rendering/ketcher_id_mapping.py +110 -0
- molforge/rendering/materials.py +127 -0
- molforge/rendering/molstar_backend.py +245 -0
- molforge/rendering/native_labels.py +134 -0
- molforge/rendering/orbitals.py +139 -0
- molforge/rendering/vtk_backend.py +2294 -0
- molforge/runtime.py +29 -0
- molforge/server/__init__.py +1 -0
- molforge/server/api_bridge.py +947 -0
- molforge/ui/__init__.py +1 -0
- molforge/ui/assets/caffeine_2d.svg +150 -0
- molforge/ui/assets/caffeine_3d_preview.svg +209 -0
- molforge/ui/assets/caffeine_preview.json +302 -0
- molforge/ui/assets/icons/atom.svg +1 -0
- molforge/ui/assets/icons/bond.svg +1 -0
- molforge/ui/assets/icons/cleanup.svg +1 -0
- molforge/ui/assets/icons/export.svg +1 -0
- molforge/ui/assets/icons/fragments.svg +1 -0
- molforge/ui/assets/icons/history.svg +1 -0
- molforge/ui/assets/icons/jobs.svg +1 -0
- molforge/ui/assets/icons/measure.svg +1 -0
- molforge/ui/assets/icons/molecules.svg +1 -0
- molforge/ui/assets/icons/overview.svg +1 -0
- molforge/ui/assets/icons/ring.svg +1 -0
- molforge/ui/assets/icons/search.svg +1 -0
- molforge/ui/assets/icons/select.svg +1 -0
- molforge/ui/assets/icons/settings.svg +1 -0
- molforge/ui/assets/icons/templates.svg +1 -0
- molforge/ui/assets/molforge_logo.ico +0 -0
- molforge/ui/assets/molforge_logo.png +0 -0
- molforge/ui/atom_labels.py +92 -0
- molforge/ui/bio_structure_dialog.py +57 -0
- molforge/ui/conformer_dialog.py +151 -0
- molforge/ui/dialogs/__init__.py +2 -0
- molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
- molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
- molforge/ui/dialogs/element_fragments.py +130 -0
- molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
- molforge/ui/dialogs/hpc_job_dialog.py +427 -0
- molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
- molforge/ui/editor2d_widget.py +1803 -0
- molforge/ui/element_picker.py +218 -0
- molforge/ui/gmv_window_manager.py +65 -0
- molforge/ui/gromacs_job_dialog.py +47 -0
- molforge/ui/hotkeys.py +107 -0
- molforge/ui/i18n.py +237 -0
- molforge/ui/live_llm_dialog.py +135 -0
- molforge/ui/llm_config_dialog.py +103 -0
- molforge/ui/modeling_actions.py +176 -0
- molforge/ui/molstar_widget.py +98 -0
- molforge/ui/molstar_window.py +85 -0
- molforge/ui/panels.py +2966 -0
- molforge/ui/qc_result_dialog.py +1924 -0
- molforge/ui/render3d_widget.py +1579 -0
- molforge/ui/scrolling.py +52 -0
- molforge/ui/settings_panel.py +330 -0
- molforge/ui/shells/__init__.py +4 -0
- molforge/ui/shells/base_shell.py +72 -0
- molforge/ui/shells/document_tabs.py +715 -0
- molforge/ui/shells/studio_2d.py +339 -0
- molforge/ui/shells/studio_3d.py +401 -0
- molforge/ui/shells/studio_split.py +370 -0
- molforge/ui/shells/workflow_inputs.py +698 -0
- molforge/ui/theme.py +719 -0
- molforge/ui/trajectory_window.py +333 -0
- molforge/ui/views.py +892 -0
- molforge/ui/vtk_multiview_widget.py +141 -0
- molforge/ui/welcome_window.py +223 -0
- molforge/ui/window.py +3320 -0
- molforge/workflows/__init__.py +25 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
- molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
- molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
- molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
- molforge/workflows/dipole_analysis.py +32 -0
- molforge/workflows/esp_surface.py +36 -0
- molforge/workflows/gromacs_submit.py +167 -0
- molforge/workflows/homo_lumo_plot.py +59 -0
- molforge/workflows/igmh_interaction.py +111 -0
- molforge/workflows/md_rdf_analysis.py +134 -0
- molforge/workflows/md_studio.py +255 -0
- molforge/workflows/osc_energy_diagram.py +24 -0
- molforge/workflows/planarity_analysis.py +66 -0
- molforge/workflows/reorganization_energy.py +166 -0
- molforge/workflows/scientific_workflows.py +650 -0
- molforge_studio-7.4.3.dist-info/METADATA +215 -0
- molforge_studio-7.4.3.dist-info/RECORD +219 -0
- molforge_studio-7.4.3.dist-info/WHEEL +5 -0
- molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
- molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
- molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
"""
|
|
2
|
+
domain/document.py - 分子文档(唯一化学事实源 + 严格不变量校验 + 双引擎 3D 弛豫)
|
|
3
|
+
=================================================================================
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import math
|
|
10
|
+
import uuid
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from .ids import AtomId, BondId
|
|
18
|
+
from .topology import Topology
|
|
19
|
+
from .coordinate_store import CoordinateStore
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DocumentStatus(Enum):
|
|
23
|
+
DRAFT = "draft"
|
|
24
|
+
VALIDATED = "validated"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class DocumentRevision:
|
|
29
|
+
document_id: str
|
|
30
|
+
revision: int
|
|
31
|
+
n_atoms: int
|
|
32
|
+
n_bonds: int
|
|
33
|
+
n_frames: int
|
|
34
|
+
topology_hash: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MoleculeDocument:
|
|
38
|
+
"""
|
|
39
|
+
分子文档:唯一化学事实源。
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, name: str = "untitled") -> None:
|
|
43
|
+
self.document_id: str = uuid.uuid4().hex[:12]
|
|
44
|
+
self.revision: int = 0
|
|
45
|
+
self.name: str = name
|
|
46
|
+
self.status: DocumentStatus = DocumentStatus.DRAFT
|
|
47
|
+
self.topology = Topology()
|
|
48
|
+
self._coordinates: CoordinateStore | None = None
|
|
49
|
+
# 2D 世界坐标(单位 Å,以 (0,0) 为中心,与窗口像素大小完全解耦!)
|
|
50
|
+
self.coords_2d: dict[AtomId, tuple[float, float]] = {}
|
|
51
|
+
self.properties: dict[str, Any] = {}
|
|
52
|
+
self.source_format: str = "unknown"
|
|
53
|
+
self.source_path: str | None = None
|
|
54
|
+
|
|
55
|
+
self.units = {
|
|
56
|
+
"coordinates": "angstrom",
|
|
57
|
+
"energy": "ev",
|
|
58
|
+
"bond_length": "angstrom",
|
|
59
|
+
"angle": "degree",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
# ---------- 双向映射与不变量检查(Phase 1) ----------
|
|
63
|
+
|
|
64
|
+
def atom_index_map(self) -> tuple[list[AtomId], dict[AtomId, int]]:
|
|
65
|
+
"""返回当前拓扑的 (idx_to_atom_id, atom_id_to_idx) 双向映射。"""
|
|
66
|
+
return self.topology.atom_index_map()
|
|
67
|
+
|
|
68
|
+
def get_atom_3d_pos(self, aid: AtomId) -> np.ndarray | None:
|
|
69
|
+
"""通过 AtomId 安全获取其 3D 坐标 (3,)。"""
|
|
70
|
+
if not self.has_3d or self.coordinates.current is None:
|
|
71
|
+
return None
|
|
72
|
+
_, id_to_idx = self.topology.atom_index_map()
|
|
73
|
+
idx = id_to_idx.get(aid)
|
|
74
|
+
if idx is None or idx >= len(self.coordinates.current.coords):
|
|
75
|
+
return None
|
|
76
|
+
return self.coordinates.current.coords[idx].copy()
|
|
77
|
+
|
|
78
|
+
def find_nearest_atom_3d(self, world_pos: np.ndarray, exclude: AtomId | None = None) -> tuple[AtomId | None, float]:
|
|
79
|
+
"""寻找距离 3D 点 world_pos 最近的已有原子 ID 及其距离(Å)。"""
|
|
80
|
+
if not self.has_3d or self.coordinates.current is None or self.topology.num_atoms == 0:
|
|
81
|
+
return None, float("inf")
|
|
82
|
+
idx_to_id, _ = self.topology.atom_index_map()
|
|
83
|
+
coords = self.coordinates.current.coords
|
|
84
|
+
p = np.asarray(world_pos, dtype=np.float32)
|
|
85
|
+
best_aid = None
|
|
86
|
+
best_dist = float("inf")
|
|
87
|
+
# 优先连接重原子(非氢),若只有氢则连接氢
|
|
88
|
+
for prefer_heavy in (True, False):
|
|
89
|
+
for i, aid in enumerate(idx_to_id):
|
|
90
|
+
if aid == exclude or i >= len(coords):
|
|
91
|
+
continue
|
|
92
|
+
atom = self.topology.get_atom(aid)
|
|
93
|
+
if prefer_heavy and atom.atomic_num == 1:
|
|
94
|
+
continue
|
|
95
|
+
d = float(np.linalg.norm(coords[i] - p))
|
|
96
|
+
if d < best_dist:
|
|
97
|
+
best_dist = d
|
|
98
|
+
best_aid = aid
|
|
99
|
+
if best_aid is not None:
|
|
100
|
+
break
|
|
101
|
+
return best_aid, best_dist
|
|
102
|
+
|
|
103
|
+
def validate(self) -> list[str]:
|
|
104
|
+
"""
|
|
105
|
+
验证文档的化学与拓扑正确性(注意:允许 0 个原子的空文档,以便删光原子后不阻断)。
|
|
106
|
+
"""
|
|
107
|
+
errors = []
|
|
108
|
+
for bid in self.topology.bond_ids:
|
|
109
|
+
bond = self.topology.get_bond(bid)
|
|
110
|
+
if bond.begin not in self.topology._atoms:
|
|
111
|
+
errors.append(f"键 {bid.value} 的起始原子 {bond.begin.value} 不存在")
|
|
112
|
+
if bond.end not in self.topology._atoms:
|
|
113
|
+
errors.append(f"键 {bid.value} 的结束原子 {bond.end.value} 不存在")
|
|
114
|
+
if bond.begin == bond.end:
|
|
115
|
+
errors.append(f"键 {bid.value} 是自环键(原子连接自己)")
|
|
116
|
+
|
|
117
|
+
if not errors:
|
|
118
|
+
self.status = DocumentStatus.VALIDATED
|
|
119
|
+
return errors
|
|
120
|
+
|
|
121
|
+
def check_invariants(self) -> list[str]:
|
|
122
|
+
"""检查数据层强不变量:拓扑原子数 == 坐标帧行数,键两端原子存在,无 NaN。"""
|
|
123
|
+
errs = self.validate()
|
|
124
|
+
n = self.topology.num_atoms
|
|
125
|
+
if self.has_3d and self.coordinates.current is not None:
|
|
126
|
+
c_shape = self.coordinates.current.coords.shape
|
|
127
|
+
if c_shape != (n, 3):
|
|
128
|
+
errs.append(f"坐标帧形状 {c_shape} 与拓扑原子数 ({n}, 3) 不一致")
|
|
129
|
+
if np.isnan(self.coordinates.current.coords).any():
|
|
130
|
+
errs.append("3D 坐标包含 NaN")
|
|
131
|
+
return errs
|
|
132
|
+
|
|
133
|
+
def topology_hash(self) -> str:
|
|
134
|
+
atom_list = []
|
|
135
|
+
for aid in self.topology.atom_ids:
|
|
136
|
+
atom = self.topology.get_atom(aid)
|
|
137
|
+
atom_list.append(f"{atom.atomic_num}:{atom.formal_charge}")
|
|
138
|
+
bond_list = []
|
|
139
|
+
for bid in self.topology.bond_ids:
|
|
140
|
+
bond = self.topology.get_bond(bid)
|
|
141
|
+
a = min(bond.begin.value, bond.end.value)
|
|
142
|
+
b = max(bond.begin.value, bond.end.value)
|
|
143
|
+
bond_list.append(f"{a}-{b}:{bond.order}:{int(bond.aromatic)}")
|
|
144
|
+
atom_list.sort()
|
|
145
|
+
bond_list.sort()
|
|
146
|
+
topo_str = f"atoms={','.join(atom_list)};bonds={','.join(bond_list)}"
|
|
147
|
+
return hashlib.sha256(topo_str.encode()).hexdigest()[:16]
|
|
148
|
+
|
|
149
|
+
# ---------- 坐标管理 ----------
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def coordinates(self) -> CoordinateStore:
|
|
153
|
+
if self._coordinates is None:
|
|
154
|
+
self._coordinates = CoordinateStore(self.topology.num_atoms)
|
|
155
|
+
return self._coordinates
|
|
156
|
+
|
|
157
|
+
def ensure_coordinates(self) -> CoordinateStore:
|
|
158
|
+
"""确保坐标存储与当前拓扑原子数严格同步(行数 == num_atoms)。"""
|
|
159
|
+
n = self.topology.num_atoms
|
|
160
|
+
if self._coordinates is None:
|
|
161
|
+
self._coordinates = CoordinateStore(n)
|
|
162
|
+
return self._coordinates
|
|
163
|
+
|
|
164
|
+
if n == 0:
|
|
165
|
+
self._coordinates = CoordinateStore(0)
|
|
166
|
+
return self._coordinates
|
|
167
|
+
|
|
168
|
+
if self._coordinates.n_atoms == n and (
|
|
169
|
+
self._coordinates.num_frames == 0 or self._coordinates.current.coords.shape == (n, 3)
|
|
170
|
+
):
|
|
171
|
+
return self._coordinates
|
|
172
|
+
|
|
173
|
+
old = self._coordinates
|
|
174
|
+
if old.num_frames == 0:
|
|
175
|
+
self._coordinates = CoordinateStore(n)
|
|
176
|
+
return self._coordinates
|
|
177
|
+
|
|
178
|
+
if old.n_atoms < n:
|
|
179
|
+
k = n - old.n_atoms
|
|
180
|
+
cur = old.current.coords if old.current is not None else np.zeros((old.n_atoms, 3), dtype=np.float32)
|
|
181
|
+
extra = np.zeros((k, 3), dtype=np.float32)
|
|
182
|
+
atom_ids = list(self.topology.atom_ids)
|
|
183
|
+
for idx_offset in range(k):
|
|
184
|
+
global_idx = old.n_atoms + idx_offset
|
|
185
|
+
aid = atom_ids[global_idx]
|
|
186
|
+
nbrs = self.topology.neighbors_of(aid)
|
|
187
|
+
placed = False
|
|
188
|
+
for nbr_id in nbrs:
|
|
189
|
+
nbr_idx = atom_ids.index(nbr_id)
|
|
190
|
+
if nbr_idx < old.n_atoms:
|
|
191
|
+
from .chemistry import estimate_bond_length
|
|
192
|
+
length = estimate_bond_length(self.topology.get_atom(nbr_id).atomic_num, self.topology.get_atom(aid).atomic_num)
|
|
193
|
+
extra[idx_offset] = self.suggest_bonded_3d_position(nbr_id, bond_length=length)
|
|
194
|
+
placed = True
|
|
195
|
+
break
|
|
196
|
+
if not placed:
|
|
197
|
+
xmax = float(cur[:, 0].max()) if len(cur) > 0 else 0.0
|
|
198
|
+
extra[idx_offset] = [xmax + 1.8 * (idx_offset + 1), 0.0, 0.0]
|
|
199
|
+
old.append_atoms(extra)
|
|
200
|
+
return old
|
|
201
|
+
else:
|
|
202
|
+
new_store = CoordinateStore(n)
|
|
203
|
+
for fr in old:
|
|
204
|
+
new_store.add_frame(fr.coords[:n], energy=fr.energy, source=fr.source)
|
|
205
|
+
self._coordinates = new_store
|
|
206
|
+
return self._coordinates
|
|
207
|
+
|
|
208
|
+
def suggest_bonded_3d_position(self, anchor_id: AtomId, bond_length: float = 1.45) -> np.ndarray:
|
|
209
|
+
"""根据锚点原子已有邻居计算四面体/平面三角新键生长方向(Å)。"""
|
|
210
|
+
if not self.has_3d or self.coordinates.current is None:
|
|
211
|
+
return np.array([bond_length, 0.0, 0.0], dtype=np.float32)
|
|
212
|
+
|
|
213
|
+
atom_ids, id_to_idx = self.topology.atom_index_map()
|
|
214
|
+
coords = self.coordinates.current.coords
|
|
215
|
+
if anchor_id not in id_to_idx:
|
|
216
|
+
return np.array([bond_length, 0.0, 0.0], dtype=np.float32)
|
|
217
|
+
|
|
218
|
+
idx = id_to_idx[anchor_id]
|
|
219
|
+
if idx >= len(coords):
|
|
220
|
+
return np.array([bond_length, 0.0, 0.0], dtype=np.float32)
|
|
221
|
+
|
|
222
|
+
p0 = coords[idx].astype(np.float64)
|
|
223
|
+
nbrs = [n for n in self.topology.neighbors_of(anchor_id) if n in id_to_idx and id_to_idx[n] < len(coords)]
|
|
224
|
+
|
|
225
|
+
if not nbrs:
|
|
226
|
+
return (p0 + np.array([bond_length, 0.0, 0.0])).astype(np.float32)
|
|
227
|
+
|
|
228
|
+
vecs = []
|
|
229
|
+
for n in nbrs:
|
|
230
|
+
v = coords[id_to_idx[n]].astype(np.float64) - p0
|
|
231
|
+
norm = np.linalg.norm(v)
|
|
232
|
+
if norm > 1e-4:
|
|
233
|
+
vecs.append(v / norm)
|
|
234
|
+
|
|
235
|
+
from .coordination import inferred_geometry, fit_directions
|
|
236
|
+
geometry = inferred_geometry(self, anchor_id)
|
|
237
|
+
if geometry is not None and len(vecs) < geometry.coordination:
|
|
238
|
+
oriented, occupied = fit_directions(geometry, vecs)
|
|
239
|
+
free = [i for i in range(geometry.coordination) if i not in occupied]
|
|
240
|
+
return (p0 + oriented[free[0]] * bond_length).astype(np.float32)
|
|
241
|
+
|
|
242
|
+
if not vecs:
|
|
243
|
+
return (p0 + np.array([bond_length, 0.0, 0.0])).astype(np.float32)
|
|
244
|
+
|
|
245
|
+
if len(vecs) == 1:
|
|
246
|
+
v1 = vecs[0]
|
|
247
|
+
ref = np.array([0.0, 0.0, 1.0]) if abs(v1[2]) < 0.85 else np.array([0.0, 1.0, 0.0])
|
|
248
|
+
perp = np.cross(v1, ref)
|
|
249
|
+
perp /= (np.linalg.norm(perp) + 1e-9)
|
|
250
|
+
direction = -0.45 * v1 + 0.893 * perp
|
|
251
|
+
direction /= (np.linalg.norm(direction) + 1e-9)
|
|
252
|
+
return (p0 + direction * bond_length).astype(np.float32)
|
|
253
|
+
|
|
254
|
+
sum_v = np.sum(vecs, axis=0)
|
|
255
|
+
norm_s = np.linalg.norm(sum_v)
|
|
256
|
+
if norm_s > 0.15:
|
|
257
|
+
direction = -sum_v / norm_s
|
|
258
|
+
if len(vecs) == 2:
|
|
259
|
+
normal = np.cross(vecs[0], vecs[1])
|
|
260
|
+
n_norm = np.linalg.norm(normal)
|
|
261
|
+
if n_norm > 1e-3:
|
|
262
|
+
normal /= n_norm
|
|
263
|
+
direction = 0.88 * direction + 0.47 * normal
|
|
264
|
+
direction /= np.linalg.norm(direction)
|
|
265
|
+
return (p0 + direction * bond_length).astype(np.float32)
|
|
266
|
+
else:
|
|
267
|
+
ref = np.array([0.0, 0.0, 1.0]) if abs(vecs[0][2]) < 0.85 else np.array([1.0, 0.0, 0.0])
|
|
268
|
+
direction = np.cross(vecs[0], ref)
|
|
269
|
+
direction /= (np.linalg.norm(direction) + 1e-9)
|
|
270
|
+
return (p0 + direction * bond_length).astype(np.float32)
|
|
271
|
+
|
|
272
|
+
def relax_3d_geometry(self, max_iters: int = 120) -> bool:
|
|
273
|
+
"""
|
|
274
|
+
双引擎 3D 结构几何优化:
|
|
275
|
+
1. 优先尝试 RDKit MMFF94 / UFF 力场优化
|
|
276
|
+
2. 若 RDKit 因非标价态或环境原因跳过,则执行内置 NumPy 化学谐振弹簧+斥力弛豫算法,
|
|
277
|
+
确保「3D 力场优化」按钮在任何分子结构下都 100% 生效!
|
|
278
|
+
"""
|
|
279
|
+
n = self.topology.num_atoms
|
|
280
|
+
if n == 0:
|
|
281
|
+
return False
|
|
282
|
+
self.ensure_coordinates()
|
|
283
|
+
if self.coordinates.current is None:
|
|
284
|
+
self.coordinates.add_frame(np.zeros((n, 3), dtype=np.float32), source="init")
|
|
285
|
+
|
|
286
|
+
# 引擎 1:尝试 RDKit MMFF94 / UFF
|
|
287
|
+
try:
|
|
288
|
+
from rdkit.Chem import AllChem
|
|
289
|
+
from ..io.rdkit_adapter import doc_to_rdkit
|
|
290
|
+
|
|
291
|
+
rdmol, atom_map, _ = doc_to_rdkit(self, sanitize=True, strict=True)
|
|
292
|
+
if rdmol.GetNumAtoms() == n:
|
|
293
|
+
if rdmol.GetNumConformers() == 0:
|
|
294
|
+
params = AllChem.ETKDGv3()
|
|
295
|
+
params.randomSeed = 42
|
|
296
|
+
AllChem.EmbedMolecule(rdmol, params)
|
|
297
|
+
if rdmol.GetNumConformers() > 0:
|
|
298
|
+
fixed = [aid for aid in self.topology.atom_ids if self.topology.get_atom(aid).properties.get("frozen")]
|
|
299
|
+
if AllChem.MMFFHasAllMoleculeParams(rdmol):
|
|
300
|
+
props = AllChem.MMFFGetMoleculeProperties(rdmol)
|
|
301
|
+
force_field = AllChem.MMFFGetMoleculeForceField(rdmol, props)
|
|
302
|
+
method = "MMFF94"
|
|
303
|
+
else:
|
|
304
|
+
force_field = AllChem.UFFGetMoleculeForceField(rdmol)
|
|
305
|
+
method = "UFF"
|
|
306
|
+
if force_field is None:
|
|
307
|
+
raise ValueError("Force field unavailable")
|
|
308
|
+
for aid in fixed:
|
|
309
|
+
force_field.AddFixedPoint(atom_map[aid])
|
|
310
|
+
force_field.Initialize()
|
|
311
|
+
convergence = force_field.Minimize(maxIts=max_iters)
|
|
312
|
+
self.properties["last_optimization"] = {"method":method,"converged":convergence==0,"frozen_atoms":len(fixed)}
|
|
313
|
+
conf = rdmol.GetConformer()
|
|
314
|
+
new_coords = np.zeros((n, 3), dtype=np.float32)
|
|
315
|
+
for i, aid in enumerate(self.topology.atom_ids):
|
|
316
|
+
rd_idx = atom_map.get(aid, i)
|
|
317
|
+
pos = conf.GetAtomPosition(rd_idx)
|
|
318
|
+
new_coords[i] = [pos.x, pos.y, pos.z]
|
|
319
|
+
if not fixed:
|
|
320
|
+
new_coords -= new_coords.mean(axis=0)
|
|
321
|
+
self.coordinates.update_current_coords(new_coords)
|
|
322
|
+
return True
|
|
323
|
+
except Exception:
|
|
324
|
+
pass
|
|
325
|
+
|
|
326
|
+
# 引擎 2:内置 NumPy 键长弹簧 + VSEPR 键角斥力弛豫器(100% 兜底成功)
|
|
327
|
+
return self._numpy_spring_relax_3d(steps=max(40, min(150, max_iters)))
|
|
328
|
+
|
|
329
|
+
def _numpy_spring_relax_3d(self, steps: int = 80) -> bool:
|
|
330
|
+
"""纯 NumPy 3D 分子几何弛豫器:修正畸变键长至标准共价键长并消除原子重叠。"""
|
|
331
|
+
n = self.topology.num_atoms
|
|
332
|
+
if n <= 1 or self.coordinates.current is None:
|
|
333
|
+
return True
|
|
334
|
+
coords = self.coordinates.current.coords.astype(np.float64).copy()
|
|
335
|
+
idx_to_id, id_to_idx = self.topology.atom_index_map()
|
|
336
|
+
z_arr = np.array([self.topology.get_atom(aid).atomic_num for aid in idx_to_id])
|
|
337
|
+
fixed_indices = [i for i, aid in enumerate(idx_to_id) if self.topology.get_atom(aid).properties.get("frozen")]
|
|
338
|
+
fixed_coords = coords[fixed_indices].copy()
|
|
339
|
+
|
|
340
|
+
# 若有完全重合点,加微小非零扰动解开奇点
|
|
341
|
+
for i in range(n):
|
|
342
|
+
for j in range(i + 1, n):
|
|
343
|
+
if np.linalg.norm(coords[i] - coords[j]) < 0.05:
|
|
344
|
+
coords[j] += np.array([0.35 * ((j % 3) - 1), 0.35 * ((j % 2) - 0.5), 0.15])
|
|
345
|
+
|
|
346
|
+
bonds_idx = []
|
|
347
|
+
for bid in self.topology.bond_ids:
|
|
348
|
+
b = self.topology.get_bond(bid)
|
|
349
|
+
if b.begin in id_to_idx and b.end in id_to_idx:
|
|
350
|
+
i, j = id_to_idx[b.begin], id_to_idx[b.end]
|
|
351
|
+
zi, zj = z_arr[i], z_arr[j]
|
|
352
|
+
from .chemistry import estimate_bond_length
|
|
353
|
+
r0 = estimate_bond_length(zi, zj, b.order, b.aromatic)
|
|
354
|
+
bonds_idx.append((i, j, r0))
|
|
355
|
+
|
|
356
|
+
for _ in range(steps):
|
|
357
|
+
forces = np.zeros_like(coords)
|
|
358
|
+
# 1. 成键谐振弹簧力
|
|
359
|
+
for i, j, r0 in bonds_idx:
|
|
360
|
+
diff = coords[j] - coords[i]
|
|
361
|
+
dist = float(np.linalg.norm(diff)) + 1e-8
|
|
362
|
+
f_mag = 0.35 * (dist - r0)
|
|
363
|
+
f_vec = (diff / dist) * f_mag
|
|
364
|
+
forces[i] += f_vec
|
|
365
|
+
forces[j] -= f_vec
|
|
366
|
+
|
|
367
|
+
# 2. 非键范德华短程排斥(防止未成键原子挤在一起)
|
|
368
|
+
for i in range(n):
|
|
369
|
+
diff = coords[i] - coords
|
|
370
|
+
dist = np.linalg.norm(diff, axis=1) + 1e-6
|
|
371
|
+
mask = (dist < 2.2) & (dist > 1e-5)
|
|
372
|
+
for j in np.where(mask)[0]:
|
|
373
|
+
if any((i == bi and j == bj) or (i == bj and j == bi) for bi, bj, _ in bonds_idx):
|
|
374
|
+
continue
|
|
375
|
+
rep = 0.08 * (2.2 - dist[j]) / dist[j]
|
|
376
|
+
forces[i] += diff[j] * rep
|
|
377
|
+
|
|
378
|
+
coords += np.clip(forces, -0.25, 0.25)
|
|
379
|
+
coords[fixed_indices] = fixed_coords
|
|
380
|
+
|
|
381
|
+
if not fixed_indices:
|
|
382
|
+
coords -= coords.mean(axis=0)
|
|
383
|
+
self.properties["last_optimization"] = {"method":"heuristic spring relaxation","converged":False,"frozen_atoms":len(fixed_indices)}
|
|
384
|
+
self.coordinates.update_current_coords(coords.astype(np.float32))
|
|
385
|
+
return True
|
|
386
|
+
|
|
387
|
+
def sync_2d_coords_from_3d(self) -> None:
|
|
388
|
+
"""当存在新原子尚无 2D 世界坐标时,按化学键或 3D 投影补齐其 2D 坐标(单位 Å)。"""
|
|
389
|
+
# 对 > 1500 原子的宏观体系或动力学盒子,严格禁止计算 2D 坐标,防止系统内存耗尽与 CPU 卡死
|
|
390
|
+
if self.topology.num_atoms > 1500 or self.properties.get("is_massive_system"):
|
|
391
|
+
self.coords_2d = {}
|
|
392
|
+
return
|
|
393
|
+
|
|
394
|
+
idx_to_id, id_to_idx = self.topology.atom_index_map()
|
|
395
|
+
# 清理已删除原子的残留 2D 坐标
|
|
396
|
+
for k in list(self.coords_2d.keys()):
|
|
397
|
+
if k not in id_to_idx:
|
|
398
|
+
self.coords_2d.pop(k, None)
|
|
399
|
+
|
|
400
|
+
# 如果原本缓存的是旧版屏幕像素坐标(绝对值 > 40),自动归一化到 Å 世界坐标
|
|
401
|
+
if self.coords_2d:
|
|
402
|
+
vals = np.array(list(self.coords_2d.values()), dtype=np.float64)
|
|
403
|
+
span = max(float(np.ptp(vals[:, 0])) if len(vals) > 1 else 0.0,
|
|
404
|
+
float(np.ptp(vals[:, 1])) if len(vals) > 1 else 0.0)
|
|
405
|
+
if len(vals) < 120 and (span > 120.0 or np.abs(vals).max() > 150.0):
|
|
406
|
+
center = vals.mean(axis=0)
|
|
407
|
+
for aid, (px, py) in list(self.coords_2d.items()):
|
|
408
|
+
self.coords_2d[aid] = ((px - center[0]) / 36.0, -(py - center[1]) / 36.0)
|
|
409
|
+
|
|
410
|
+
for i, aid in enumerate(idx_to_id):
|
|
411
|
+
if aid in self.coords_2d:
|
|
412
|
+
continue
|
|
413
|
+
nbrs = [n for n in self.topology.neighbors_of(aid) if n in self.coords_2d]
|
|
414
|
+
if nbrs:
|
|
415
|
+
anchor = nbrs[0]
|
|
416
|
+
ax, ay = self.coords_2d[anchor]
|
|
417
|
+
other_nbrs = [n for n in self.topology.neighbors_of(anchor) if n in self.coords_2d and n != aid]
|
|
418
|
+
if not other_nbrs:
|
|
419
|
+
ang = math.pi / 6
|
|
420
|
+
elif len(other_nbrs) == 1:
|
|
421
|
+
ox, oy = self.coords_2d[other_nbrs[0]]
|
|
422
|
+
base_ang = math.atan2(ay - oy, ax - ox)
|
|
423
|
+
ang = base_ang + (math.pi / 3 if (aid.value % 2 == 0) else -math.pi / 3)
|
|
424
|
+
else:
|
|
425
|
+
vx = sum(self.coords_2d[n][0] - ax for n in other_nbrs)
|
|
426
|
+
vy = sum(self.coords_2d[n][1] - ay for n in other_nbrs)
|
|
427
|
+
ang = math.atan2(-vy, -vx) if math.hypot(vx, vy) > 1e-4 else 0.0
|
|
428
|
+
self.coords_2d[aid] = (ax + 1.50 * math.cos(ang), ay + 1.50 * math.sin(ang))
|
|
429
|
+
elif self.has_3d and self.coordinates.current is not None and i < len(self.coordinates.current.coords):
|
|
430
|
+
p3 = self.coordinates.current.coords[i]
|
|
431
|
+
self.coords_2d[aid] = (float(p3[0]), float(p3[1]))
|
|
432
|
+
else:
|
|
433
|
+
self.coords_2d[aid] = (float(i) * 1.50, 0.0)
|
|
434
|
+
|
|
435
|
+
# ---------- 版本与查询 ----------
|
|
436
|
+
|
|
437
|
+
def bump_revision(self) -> None:
|
|
438
|
+
self.revision += 1
|
|
439
|
+
|
|
440
|
+
@property
|
|
441
|
+
def revision_snapshot(self) -> DocumentRevision:
|
|
442
|
+
return DocumentRevision(
|
|
443
|
+
document_id=self.document_id,
|
|
444
|
+
revision=self.revision,
|
|
445
|
+
n_atoms=self.topology.num_atoms,
|
|
446
|
+
n_bonds=self.topology.num_bonds,
|
|
447
|
+
n_frames=self.coordinates.num_frames if self._coordinates else 0,
|
|
448
|
+
topology_hash=self.topology_hash(),
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def num_atoms(self) -> int:
|
|
453
|
+
return self.topology.num_atoms
|
|
454
|
+
|
|
455
|
+
@property
|
|
456
|
+
def num_bonds(self) -> int:
|
|
457
|
+
return self.topology.num_bonds
|
|
458
|
+
|
|
459
|
+
@property
|
|
460
|
+
def has_3d(self) -> bool:
|
|
461
|
+
return self._coordinates is not None and self._coordinates.num_frames > 0
|
|
462
|
+
|
|
463
|
+
def summary(self) -> str:
|
|
464
|
+
parts = [self.name] if self.name else []
|
|
465
|
+
parts.append(f"{self.num_atoms} atoms")
|
|
466
|
+
parts.append(f"{self.num_bonds} bonds")
|
|
467
|
+
if self.has_3d:
|
|
468
|
+
parts.append(f"{self.coordinates.num_frames} frames")
|
|
469
|
+
return " | ".join(parts)
|