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.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. 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
  188. 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
  189. 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
  190. 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
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1445 @@
1
+ """
2
+ application/builtin_commands.py - 严格保持 AtomId/BondId 与坐标帧一致性的内置命令集
3
+ ===================================================================================
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import math
10
+ import numpy as np
11
+
12
+ from ..domain.document import MoleculeDocument
13
+ from ..domain.chemistry import estimate_bond_length
14
+ from ..domain.ids import AtomId, BondId
15
+ from .commands import Command, CommandResult
16
+
17
+
18
+ class AddAtomCommand(Command):
19
+ """
20
+ 添加一个原子:
21
+ - 支持显式传入 3D 坐标 (x, y, z)
22
+ - 支持传入 bond_to 自动与指定原子成键并按四面体/三角方向计算合理键长 (元素相关估算键长)
23
+ - 支持 auto_bond_nearest=True(3D 点击空白处时,自动与最近原子按 元素相关估算键长 成键)
24
+ - redo 时严格复用首次分配的 _added_atom_id 与 _added_bond_id,保证 ID 绝不漂移!
25
+ """
26
+
27
+ description = "添加原子"
28
+
29
+ def __init__(
30
+ self,
31
+ atomic_num: int,
32
+ x: float | None = None,
33
+ y: float | None = None,
34
+ z: float | None = None,
35
+ bond_to: AtomId | None = None,
36
+ bond_order: int = 1,
37
+ pos_2d: tuple[float, float] | None = None,
38
+ auto_bond_nearest: bool = False,
39
+ ):
40
+ self.atomic_num = int(atomic_num)
41
+ self.explicit_pos = (
42
+ (float(x), float(y), float(z))
43
+ if (x is not None and y is not None and z is not None)
44
+ else None
45
+ )
46
+ self.bond_to = bond_to
47
+ self.bond_order = int(bond_order)
48
+ self.pos_2d = pos_2d
49
+ self.auto_bond_nearest = bool(auto_bond_nearest)
50
+ self._added_atom_id: AtomId | None = None
51
+ self._added_bond_id: BondId | None = None
52
+ self._resolved_bond_to: AtomId | None = None
53
+
54
+ def do(self, doc: MoleculeDocument) -> CommandResult:
55
+ target_bond_aid = self.bond_to
56
+
57
+ # 若开启了 3D 自动连接最近原子,且当前分子非空
58
+ if target_bond_aid is None and self.auto_bond_nearest and doc.topology.num_atoms > 0:
59
+ ref_pt = np.array(self.explicit_pos or (0.0, 0.0, 0.0), dtype=np.float32)
60
+ nearest_aid, dist = doc.find_nearest_atom_3d(ref_pt)
61
+ if nearest_aid is not None:
62
+ target_bond_aid = nearest_aid
63
+ length = estimate_bond_length(doc.topology.get_atom(nearest_aid).atomic_num, self.atomic_num, self.bond_order)
64
+ # 将新原子坐标校准到从 nearest_aid 朝向点击位置的 元素相关估算键长 合理键长处
65
+ anchor_pos = doc.get_atom_3d_pos(nearest_aid)
66
+ if anchor_pos is not None:
67
+ vec = ref_pt - anchor_pos
68
+ norm = float(np.linalg.norm(vec))
69
+ if norm > 0.15:
70
+ new_coord = (anchor_pos + (vec / norm) * length).astype(np.float32)
71
+ else:
72
+ new_coord = doc.suggest_bonded_3d_position(nearest_aid, bond_length=length)
73
+ else:
74
+ new_coord = ref_pt
75
+ else:
76
+ new_coord = ref_pt
77
+ elif self.explicit_pos is not None:
78
+ new_coord = np.array(self.explicit_pos, dtype=np.float32)
79
+ elif target_bond_aid is not None and doc.has_3d:
80
+ new_coord = doc.suggest_bonded_3d_position(target_bond_aid, bond_length=estimate_bond_length(doc.topology.get_atom(target_bond_aid).atomic_num, self.atomic_num, self.bond_order))
81
+ elif self.pos_2d is not None:
82
+ # 从 2D 世界坐标 (wx, wy) 直接映射为 3D (wx, wy, 0.0)
83
+ z_mean = 0.0
84
+ if doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) > 0:
85
+ z_mean = float(doc.coordinates.current.coords[:, 2].mean())
86
+ new_coord = np.array([float(self.pos_2d[0]), float(self.pos_2d[1]), z_mean], dtype=np.float32)
87
+ elif doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) > 0:
88
+ coords = doc.coordinates.current.coords
89
+ xmax = float(coords[:, 0].max())
90
+ ymid = float(coords[:, 1].mean())
91
+ zmid = float(coords[:, 2].mean())
92
+ new_coord = np.array([xmax + 1.5, ymid, zmid], dtype=np.float32)
93
+ else:
94
+ new_coord = np.zeros(3, dtype=np.float32)
95
+
96
+ if target_bond_aid is not None and (self.explicit_pos is None or self.auto_bond_nearest):
97
+ from ..domain.coordination import automatic_bond_error
98
+ error = automatic_bond_error(doc, target_bond_aid, self.atomic_num, self.bond_order)
99
+ if error:
100
+ return CommandResult(False, message=error)
101
+ self._resolved_bond_to = target_bond_aid
102
+
103
+ # 复用已有 _added_atom_id(支持 redo 不改变 ID)
104
+ aid = doc.topology.add_atom(self.atomic_num, atom_id=self._added_atom_id)
105
+ self._added_atom_id = aid
106
+
107
+ if target_bond_aid is not None and target_bond_aid in doc.topology._atoms:
108
+ self._added_bond_id = doc.topology.add_bond(
109
+ target_bond_aid, aid, order=self.bond_order, bond_id=self._added_bond_id
110
+ )
111
+
112
+ doc.coordinates.append_atoms(new_coord.reshape(1, 3))
113
+
114
+ if self.pos_2d is not None:
115
+ doc.coords_2d[aid] = (float(self.pos_2d[0]), float(self.pos_2d[1]))
116
+ else:
117
+ doc.coords_2d[aid] = (float(new_coord[0]), float(new_coord[1]))
118
+
119
+ return CommandResult(
120
+ success=True,
121
+ changed=True,
122
+ message=f"添加原子 #{aid.value}",
123
+ data={
124
+ "atom_id": aid.value,
125
+ "bond_id": self._added_bond_id.value if self._added_bond_id else None,
126
+ },
127
+ )
128
+
129
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
130
+ if self._added_atom_id is None:
131
+ return CommandResult(success=False, message="没有可撤销的原子")
132
+ if self._added_bond_id is not None:
133
+ doc.topology.remove_bond(self._added_bond_id)
134
+ if doc.has_3d:
135
+ doc.coordinates.remove_trailing_atoms(1)
136
+ doc.coords_2d.pop(self._added_atom_id, None)
137
+ doc.topology.remove_atom(self._added_atom_id)
138
+ return CommandResult(
139
+ success=True,
140
+ changed=True,
141
+ message=f"撤销添加原子 #{self._added_atom_id.value}",
142
+ )
143
+
144
+
145
+ class DeleteAtomCommand(Command):
146
+ """删除指定原子(连带删除相连的氢原子,完整备份支持完美撤销)。"""
147
+
148
+ description = "删除原子"
149
+ requires_confirmation = True
150
+
151
+ def __init__(self, atom_id: AtomId):
152
+ self.atom_id = atom_id
153
+ self._backup_atom = None
154
+ self._backup_index: int = -1
155
+ self._backup_bonds: list = []
156
+ self._backup_coord_3d: np.ndarray | None = None
157
+ self._backup_coord_2d: tuple[float, float] | None = None
158
+ # 连带删除的氢原子
159
+ self._deleted_hydrogens: list = [] # list of (atom, bonds, coord_2d, coord_3d, index)
160
+
161
+ def do(self, doc: MoleculeDocument) -> CommandResult:
162
+ if self.atom_id not in doc.topology._atoms:
163
+ return CommandResult(success=False, message=f"原子 {self.atom_id} 不存在")
164
+
165
+ self._deleted_hydrogens = []
166
+ # 先找到所有仅与当前原子相连的末端氢原子(若当前删除的就是 H 自身则不递归)
167
+ target_atom = doc.topology.get_atom(self.atom_id)
168
+ hydrogen_ids: list[AtomId] = []
169
+ if target_atom.atomic_num != 1:
170
+ for bid in list(doc.topology._adjacency.get(self.atom_id, [])):
171
+ bond = doc.topology.get_bond(bid)
172
+ other = bond.end if bond.begin == self.atom_id else bond.begin
173
+ if other in doc.topology._atoms and doc.topology.get_atom(other).atomic_num == 1:
174
+ if len(doc.topology._adjacency.get(other, [])) <= 1:
175
+ hydrogen_ids.append(other)
176
+
177
+ # 按当前拓扑索引从大到小排序并删除氢原子(避免移除坐标帧行时索引偏移)
178
+ hydrogen_ids.sort(key=lambda a: doc.topology.index_of_atom(a), reverse=True)
179
+ for hid in hydrogen_ids:
180
+ h_index = doc.topology.index_of_atom(hid)
181
+ h_atom = copy.deepcopy(doc.topology.get_atom(hid))
182
+ h_bonds = [copy.deepcopy(doc.topology.get_bond(b)) for b in doc.topology._adjacency.get(hid, [])]
183
+ h_coord2d = doc.coords_2d.get(hid)
184
+ h_coord3d = doc.coordinates.remove_atom_at(h_index) if doc.has_3d else None
185
+ doc.coords_2d.pop(hid, None)
186
+ doc.topology.remove_atom(hid)
187
+ self._deleted_hydrogens.append({
188
+ 'atom': h_atom,
189
+ 'bonds': h_bonds,
190
+ 'coord_2d': h_coord2d,
191
+ 'coord_3d': h_coord3d,
192
+ 'index': h_index,
193
+ })
194
+
195
+ # 备份并删除主原子
196
+ self._backup_index = doc.topology.index_of_atom(self.atom_id)
197
+ self._backup_atom = copy.deepcopy(doc.topology.get_atom(self.atom_id))
198
+ self._backup_coord_2d = doc.coords_2d.get(self.atom_id)
199
+
200
+ incident_bids = list(doc.topology._adjacency.get(self.atom_id, []))
201
+ self._backup_bonds = [copy.deepcopy(doc.topology.get_bond(bid)) for bid in incident_bids]
202
+
203
+ if doc.has_3d:
204
+ self._backup_coord_3d = doc.coordinates.remove_atom_at(self._backup_index)
205
+
206
+ doc.coords_2d.pop(self.atom_id, None)
207
+ doc.topology.remove_atom(self.atom_id)
208
+ return CommandResult(
209
+ success=True,
210
+ changed=True,
211
+ message=f"删除原子 #{self.atom_id.value}(连带 {len(hydrogen_ids)} 个氢)",
212
+ )
213
+
214
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
215
+ if self._backup_atom is None:
216
+ return CommandResult(success=False, message="没有可恢复的原子数据")
217
+
218
+ # 先恢复主原子
219
+ doc.topology.restore_atom(copy.deepcopy(self._backup_atom), index=self._backup_index)
220
+ if self._backup_coord_3d is not None:
221
+ doc.coordinates.insert_atom_at(self._backup_index, self._backup_coord_3d)
222
+ if self._backup_coord_2d is not None:
223
+ doc.coords_2d[self.atom_id] = self._backup_coord_2d
224
+ for bond in self._backup_bonds:
225
+ try:
226
+ doc.topology.restore_bond(copy.deepcopy(bond))
227
+ except Exception:
228
+ pass
229
+
230
+ # 再恢复被连带删除的氢原子(从后往前恢复)
231
+ for h in reversed(self._deleted_hydrogens):
232
+ doc.topology.restore_atom(copy.deepcopy(h['atom']), index=h['index'])
233
+ if h['coord_3d'] is not None:
234
+ doc.coordinates.insert_atom_at(h['index'], h['coord_3d'])
235
+ if h['coord_2d'] is not None:
236
+ hid = h['atom'].id
237
+ doc.coords_2d[hid] = h['coord_2d']
238
+ for bond in h['bonds']:
239
+ try:
240
+ doc.topology.restore_bond(copy.deepcopy(bond))
241
+ except Exception:
242
+ pass
243
+
244
+ return CommandResult(
245
+ success=True,
246
+ changed=True,
247
+ message=f"恢复原子 #{self.atom_id.value}(连带 {len(self._deleted_hydrogens)} 个氢)",
248
+ data={"atom_id": self.atom_id.value},
249
+ )
250
+
251
+
252
+ class AddBondCommand(Command):
253
+ """在两个原子之间添加键(若已存在则更新键级,redo 保持 BondId 不变)。"""
254
+
255
+ description = "添加键"
256
+
257
+ def __init__(self, atom_a: AtomId | int, atom_b: AtomId | int, order: int = 1):
258
+ self.atom_a = AtomId(atom_a) if isinstance(atom_a, int) else atom_a
259
+ self.atom_b = AtomId(atom_b) if isinstance(atom_b, int) else atom_b
260
+ self.order = int(order)
261
+ self._added_bond_id: BondId | None = None
262
+ self._was_existing: bool = False
263
+ self._old_order: int = 1
264
+ self._old_aromatic: bool = False
265
+
266
+ def do(self, doc: MoleculeDocument) -> CommandResult:
267
+ existing = doc.topology.bond_between(self.atom_a, self.atom_b)
268
+ if existing is not None:
269
+ self._was_existing = True
270
+ self._added_bond_id = existing
271
+ bond = doc.topology.get_bond(existing)
272
+ self._old_order = bond.order
273
+ self._old_aromatic = bond.aromatic
274
+ bond.order = self.order
275
+ bond.aromatic = (self.order == 4)
276
+ return CommandResult(
277
+ success=True,
278
+ changed=True,
279
+ message=f"更新键 #{existing.value} 键级为 {self.order}",
280
+ data={"bond_id": existing.value},
281
+ )
282
+
283
+ self._was_existing = False
284
+ bond_id = doc.topology.add_bond(
285
+ self.atom_a,
286
+ self.atom_b,
287
+ order=self.order,
288
+ aromatic=(self.order == 4),
289
+ bond_id=self._added_bond_id,
290
+ )
291
+ self._added_bond_id = bond_id
292
+ return CommandResult(
293
+ success=True,
294
+ changed=True,
295
+ message=f"添加键 #{bond_id.value}",
296
+ data={"bond_id": bond_id.value},
297
+ )
298
+
299
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
300
+ if self._added_bond_id is None:
301
+ return CommandResult(success=False, message="没有可撤销的键")
302
+ if self._was_existing:
303
+ bond = doc.topology.get_bond(self._added_bond_id)
304
+ bond.order = self._old_order
305
+ bond.aromatic = self._old_aromatic
306
+ return CommandResult(success=True, changed=True, message=f"恢复键 #{self._added_bond_id.value}")
307
+ doc.topology.remove_bond(self._added_bond_id)
308
+ return CommandResult(
309
+ success=True,
310
+ changed=True,
311
+ message=f"撤销添加键 #{self._added_bond_id.value}",
312
+ )
313
+
314
+
315
+ class DeleteBondCommand(Command):
316
+ """删除指定的化学键。"""
317
+
318
+ description = "删除键"
319
+
320
+ def __init__(self, bond_id: BondId):
321
+ self.bond_id = bond_id
322
+ self._backup_bond = None
323
+
324
+ def do(self, doc: MoleculeDocument) -> CommandResult:
325
+ if self.bond_id not in doc.topology._bonds:
326
+ return CommandResult(success=False, message=f"键 {self.bond_id} 不存在")
327
+ self._backup_bond = copy.deepcopy(doc.topology.get_bond(self.bond_id))
328
+ doc.topology.remove_bond(self.bond_id)
329
+ return CommandResult(
330
+ success=True,
331
+ changed=True,
332
+ message=f"删除键 #{self.bond_id.value}",
333
+ )
334
+
335
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
336
+ if self._backup_bond is None:
337
+ return CommandResult(success=False, message="没有可恢复的键")
338
+ doc.topology.restore_bond(copy.deepcopy(self._backup_bond))
339
+ return CommandResult(
340
+ success=True,
341
+ changed=True,
342
+ message=f"恢复键 #{self.bond_id.value}",
343
+ )
344
+
345
+
346
+ class ChangeElementCommand(Command):
347
+ """修改原子的元素类型。"""
348
+
349
+ description = "修改元素"
350
+
351
+ def __init__(self, atom_id: AtomId, new_atomic_num: int):
352
+ self.atom_id = atom_id
353
+ self.new_atomic_num = int(new_atomic_num)
354
+ self._old_atomic_num: int | None = None
355
+
356
+ def do(self, doc: MoleculeDocument) -> CommandResult:
357
+ atom = doc.topology.get_atom(self.atom_id)
358
+ self._old_atomic_num = atom.atomic_num
359
+ atom.atomic_num = self.new_atomic_num
360
+ return CommandResult(
361
+ success=True,
362
+ changed=True,
363
+ message=f"修改原子 #{self.atom_id.value} 为元素 Z={self.new_atomic_num}",
364
+ )
365
+
366
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
367
+ if self._old_atomic_num is None:
368
+ return CommandResult(success=False, message="没有可恢复的数据")
369
+ atom = doc.topology.get_atom(self.atom_id)
370
+ atom.atomic_num = self._old_atomic_num
371
+ return CommandResult(
372
+ success=True,
373
+ changed=True,
374
+ message=f"恢复原子 #{self.atom_id.value} 为元素 Z={self._old_atomic_num}",
375
+ )
376
+
377
+
378
+ class ChangeBondOrderCommand(Command):
379
+ """修改键级。"""
380
+
381
+ description = "修改键级"
382
+
383
+ def __init__(self, bond_id: BondId, new_order: int):
384
+ self.bond_id = bond_id
385
+ self.new_order = int(new_order)
386
+ self._old_order: int | None = None
387
+ self._old_aromatic: bool = False
388
+
389
+ def do(self, doc: MoleculeDocument) -> CommandResult:
390
+ bond = doc.topology.get_bond(self.bond_id)
391
+ self._old_order = bond.order
392
+ self._old_aromatic = bond.aromatic
393
+ bond.order = self.new_order
394
+ bond.aromatic = (self.new_order == 4)
395
+ return CommandResult(
396
+ success=True,
397
+ changed=True,
398
+ message=f"修改键 #{self.bond_id.value} 为 {self.new_order} 级键",
399
+ )
400
+
401
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
402
+ if self._old_order is None:
403
+ return CommandResult(success=False, message="没有可恢复的数据")
404
+ bond = doc.topology.get_bond(self.bond_id)
405
+ bond.order = self._old_order
406
+ bond.aromatic = self._old_aromatic
407
+ return CommandResult(
408
+ success=True,
409
+ changed=True,
410
+ message=f"恢复键 #{self.bond_id.value} 为 {self._old_order} 级键",
411
+ )
412
+
413
+
414
+ class MoveAtom3DCommand(Command):
415
+ """移动原子 3D 坐标(同时可选更新 2D 世界坐标)。"""
416
+
417
+ description = "移动原子坐标"
418
+
419
+ def __init__(
420
+ self,
421
+ atom_id: AtomId,
422
+ new_pos: np.ndarray | tuple[float, float, float],
423
+ old_pos: np.ndarray | tuple[float, float, float] | None = None,
424
+ new_pos_2d: tuple[float, float] | None = None,
425
+ old_pos_2d: tuple[float, float] | None = None,
426
+ ):
427
+ self.atom_id = atom_id
428
+ self.new_pos = np.asarray(new_pos, dtype=np.float32).copy()
429
+ self._old_pos = np.asarray(old_pos, dtype=np.float32).copy() if old_pos is not None else None
430
+ self.new_pos_2d = new_pos_2d
431
+ self._old_pos_2d: tuple[float, float] | None = old_pos_2d
432
+
433
+ def do(self, doc: MoleculeDocument) -> CommandResult:
434
+ if not doc.has_3d or doc.coordinates.current is None:
435
+ return CommandResult(success=False, message="当前文档无 3D 坐标")
436
+ idx = doc.topology.index_of_atom(self.atom_id)
437
+ if self._old_pos is None:
438
+ self._old_pos = doc.coordinates.current.coords[idx].copy()
439
+ if self._old_pos_2d is None and self.atom_id in doc.coords_2d:
440
+ self._old_pos_2d = doc.coords_2d[self.atom_id]
441
+ doc.coordinates.set_atom_coord(idx, self.new_pos)
442
+ if self.new_pos_2d is not None:
443
+ doc.coords_2d[self.atom_id] = self.new_pos_2d
444
+ else:
445
+ doc.coords_2d[self.atom_id] = (float(self.new_pos[0]), float(self.new_pos[1]))
446
+ return CommandResult(
447
+ success=True,
448
+ changed=True,
449
+ message=f"移动原子 #{self.atom_id.value} -> ({self.new_pos[0]:.2f}, {self.new_pos[1]:.2f}, {self.new_pos[2]:.2f}) Å",
450
+ )
451
+
452
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
453
+ if self._old_pos is None or not doc.has_3d:
454
+ return CommandResult(success=False, message="无可恢复的 3D 坐标")
455
+ idx = doc.topology.index_of_atom(self.atom_id)
456
+ doc.coordinates.set_atom_coord(idx, self._old_pos)
457
+ if self._old_pos_2d is not None:
458
+ doc.coords_2d[self.atom_id] = self._old_pos_2d
459
+ return CommandResult(
460
+ success=True,
461
+ changed=True,
462
+ message=f"恢复原子 #{self.atom_id.value} 坐标",
463
+ )
464
+
465
+
466
+ class CleanGeometry3DCommand(Command):
467
+ """对当前分子执行 3D 结构力场弛豫优化(支持一键撤销回优化前构型)。"""
468
+
469
+ description = "3D 结构优化清理"
470
+
471
+ def __init__(self, max_iters: int = 120):
472
+ self.max_iters = max_iters
473
+ self._old_coords: np.ndarray | None = None
474
+
475
+ def do(self, doc: MoleculeDocument) -> CommandResult:
476
+ if doc.has_3d and doc.coordinates.current is not None:
477
+ self._old_coords = doc.coordinates.current.coords.copy()
478
+ ok = doc.relax_3d_geometry(max_iters=self.max_iters)
479
+ if not ok:
480
+ return CommandResult(success=False, message="当前分子为空")
481
+ return CommandResult(
482
+ success=True,
483
+ changed=True,
484
+ message="几何优化:" + str(doc.properties.get("last_optimization", {})),
485
+ )
486
+
487
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
488
+ if self._old_coords is None or not doc.has_3d:
489
+ return CommandResult(success=False, message="无可恢复的旧坐标")
490
+ doc.coordinates.update_current_coords(self._old_coords)
491
+ return CommandResult(
492
+ success=True,
493
+ changed=True,
494
+ message="已恢复优化前的 3D 坐标",
495
+ )
496
+
497
+
498
+ class GenerateConformation3DCommand(Command):
499
+ """
500
+ 基于 RDKit ETKDGv3 结合 MMFF94/UFF 力场从 2D 拓扑结构生成高质量 3D 空间立体构象
501
+ (支持纯 NumPy VSEPR 弹簧力场兜底与单次 Ctrl+Z 原位撤销)。
502
+ """
503
+
504
+ description = "2D ➜ 3D 构象生成 (ETKDG)"
505
+ affects_geometry = False
506
+
507
+ def __init__(self, optimize_iters: int = 150, random_seed: int = 42):
508
+ self.optimize_iters = optimize_iters
509
+ self.random_seed = random_seed
510
+ self._old_coords = None
511
+
512
+ def do(self, doc: MoleculeDocument) -> CommandResult:
513
+ n = doc.topology.num_atoms
514
+ if n == 0:
515
+ return CommandResult(success=False, message="当前分子为空")
516
+
517
+ if doc.has_3d and doc.coordinates.current is not None:
518
+ self._old_coords = doc.coordinates.current.coords.copy()
519
+
520
+ embedded = False
521
+ opt_method = "NumPy VSEPR 弹簧力场"
522
+ try:
523
+ from rdkit import Chem
524
+ from rdkit.Chem import AllChem
525
+ from ..io.rdkit_adapter import doc_to_rdkit
526
+
527
+ rdmol, atom_map, _ = doc_to_rdkit(doc, sanitize=True, strict=False)
528
+ if rdmol.GetNumAtoms() == n:
529
+ params = AllChem.ETKDGv3() if hasattr(AllChem, "ETKDGv3") else AllChem.ETKDG()
530
+ params.randomSeed = self.random_seed
531
+ params.useRandomCoords = True
532
+ if hasattr(params, 'maxIterations'): params.maxIterations = 50
533
+ res = AllChem.EmbedMolecule(rdmol, params)
534
+ if res != 0 or rdmol.GetNumConformers() == 0:
535
+ params.enforceChirality = False
536
+ res = AllChem.EmbedMolecule(rdmol, params)
537
+
538
+ if rdmol.GetNumConformers() > 0:
539
+ if AllChem.MMFFHasAllMoleculeParams(rdmol):
540
+ AllChem.MMFFOptimizeMolecule(rdmol, maxIters=self.optimize_iters)
541
+ opt_method = "ETKDGv3 + MMFF94"
542
+ else:
543
+ AllChem.UFFOptimizeMolecule(rdmol, maxIters=self.optimize_iters)
544
+ opt_method = "ETKDGv3 + UFF"
545
+
546
+ conf = rdmol.GetConformer()
547
+ new_coords = np.zeros((n, 3), dtype=np.float32)
548
+ for i, aid in enumerate(doc.topology.atom_ids):
549
+ rd_i = atom_map.get(aid, i)
550
+ pos = conf.GetAtomPosition(rd_i)
551
+ new_coords[i] = [pos.x, pos.y, pos.z]
552
+ new_coords -= new_coords.mean(axis=0)
553
+ doc.ensure_coordinates()
554
+ doc.coordinates.update_current_coords(new_coords)
555
+ doc.properties["last_optimization"] = {"method": opt_method, "converged": True}
556
+ embedded = True
557
+ except Exception:
558
+ pass
559
+
560
+ if not embedded:
561
+ doc.relax_3d_geometry(max_iters=self.optimize_iters)
562
+ opt_method = "NumPy 弹簧力场"
563
+
564
+ return CommandResult(
565
+ success=True,
566
+ changed=True,
567
+ message=f"3D 构象生成完成 ({opt_method})",
568
+ )
569
+
570
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
571
+ if self._old_coords is None or not doc.has_3d:
572
+ return CommandResult(success=False, message="无可恢复的旧 3D 坐标")
573
+ doc.coordinates.update_current_coords(self._old_coords)
574
+ return CommandResult(
575
+ success=True,
576
+ changed=True,
577
+ message="已恢复生成前的 3D 构象",
578
+ )
579
+
580
+
581
+ class Project3DTo2DCommand(Command):
582
+ """
583
+ 将当前 3D 构象正交投影至当前视平面或生成 ChemDraw 出版级规范二维布局(支持一键撤销)。
584
+ """
585
+
586
+ description = "3D ➜ 2D 视角规整投影"
587
+ affects_geometry = False
588
+
589
+ def __init__(
590
+ self,
591
+ camera_right = None,
592
+ camera_up = None,
593
+ use_coordgen: bool = False,
594
+ ):
595
+ self.camera_right = np.asarray(camera_right, dtype=np.float64) if camera_right is not None else None
596
+ self.camera_up = np.asarray(camera_up, dtype=np.float64) if camera_up is not None else None
597
+ self.use_coordgen = use_coordgen
598
+ self._old_coords_2d = None
599
+
600
+ def do(self, doc: MoleculeDocument) -> CommandResult:
601
+ n = doc.topology.num_atoms
602
+ if n == 0:
603
+ return CommandResult(success=False, message="当前分子为空")
604
+
605
+ self._old_coords_2d = dict(doc.coords_2d)
606
+
607
+ # 模式 1:ChemDraw 规范化学出版重排 (RDKit CoordGen / Compute2DCoords)
608
+ if self.use_coordgen:
609
+ try:
610
+ from rdkit.Chem import AllChem
611
+ from ..io.rdkit_adapter import doc_to_rdkit
612
+
613
+ rdmol, atom_map, _ = doc_to_rdkit(doc, sanitize=True, strict=False)
614
+ AllChem.Compute2DCoords(rdmol)
615
+ if rdmol.GetNumConformers() > 0:
616
+ conf = rdmol.GetConformer()
617
+ raw = np.array([
618
+ [conf.GetAtomPosition(i).x, conf.GetAtomPosition(i).y]
619
+ for i in range(rdmol.GetNumAtoms())
620
+ ])
621
+ center = raw.mean(axis=0) if len(raw) > 0 else np.zeros(2)
622
+ new_2d = {}
623
+ for aid in doc.topology.atom_ids:
624
+ rd_i = atom_map.get(aid)
625
+ if rd_i is not None:
626
+ new_2d[aid] = (
627
+ float(raw[rd_i, 0] - center[0]),
628
+ float(raw[rd_i, 1] - center[1]),
629
+ )
630
+ doc.coords_2d = new_2d
631
+ return CommandResult(
632
+ success=True,
633
+ changed=True,
634
+ message="已生成 ChemDraw 规范出版级 2D 布局",
635
+ )
636
+ except Exception:
637
+ pass
638
+
639
+ # 模式 2:根据当前 3D 观察相机基向量投影或 SVD 主平面正交投影
640
+ if not doc.has_3d or doc.coordinates.current is None:
641
+ return CommandResult(success=False, message="当前分子无 3D 坐标")
642
+
643
+ atom_ids, id_to_idx = doc.topology.atom_index_map()
644
+ pts = doc.coordinates.current.coords.astype(np.float64)
645
+ center = pts.mean(axis=0)
646
+ centered = pts - center
647
+
648
+ if self.camera_right is not None and self.camera_up is not None:
649
+ rx = self.camera_right.copy()
650
+ uy = self.camera_up.copy()
651
+ r_norm = np.linalg.norm(rx)
652
+ u_norm = np.linalg.norm(uy)
653
+ if r_norm > 1e-6 and u_norm > 1e-6:
654
+ rx /= r_norm
655
+ uy /= u_norm
656
+ px = centered @ rx
657
+ py = centered @ uy
658
+ xy = np.column_stack([px, py])
659
+ else:
660
+ xy = centered[:, :2].copy()
661
+ else:
662
+ # SVD 主平面正交投影
663
+ _, _, vh = np.linalg.svd(centered, full_matrices=False)
664
+ ax_x = vh[0]
665
+ ax_y = vh[1] if len(vh) > 1 else np.array([0.0, 1.0, 0.0])
666
+ px = centered @ ax_x
667
+ py = centered @ ax_y
668
+ xy = np.column_stack([px, py])
669
+
670
+ # 键长归一化:将平均/中位数键长缩放到 ~1.50 Å (ChemDraw 标准键长)
671
+ b_lengths = []
672
+ for bid in doc.topology.bond_ids:
673
+ b = doc.topology.get_bond(bid)
674
+ if b.begin in id_to_idx and b.end in id_to_idx:
675
+ i, j = id_to_idx[b.begin], id_to_idx[b.end]
676
+ d = float(np.linalg.norm(xy[i] - xy[j]))
677
+ if d > 0.15:
678
+ b_lengths.append(d)
679
+
680
+ if b_lengths:
681
+ median_d = float(np.median(b_lengths))
682
+ if median_d > 0.05:
683
+ xy *= (1.50 / median_d)
684
+
685
+ xy -= xy.mean(axis=0)
686
+ new_2d = {atom_ids[i]: (float(xy[i, 0]), float(xy[i, 1])) for i in range(n)}
687
+ doc.coords_2d = new_2d
688
+ return CommandResult(
689
+ success=True,
690
+ changed=True,
691
+ message="已将当前 3D 构象投影至 2D 画布",
692
+ )
693
+
694
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
695
+ if self._old_coords_2d is None:
696
+ return CommandResult(success=False, message="无可撤销的旧 2D 坐标")
697
+ doc.coords_2d = dict(self._old_coords_2d)
698
+ return CommandResult(
699
+ success=True,
700
+ changed=True,
701
+ message="已恢复之前的 2D 布局",
702
+ )
703
+
704
+
705
+ class AddRingCommand(Command):
706
+ """
707
+ 添加一个共轭环或饱和环(支持自动与当前选中原子或最近外围原子通过单键相连!)。
708
+ """
709
+
710
+ description = "添加环"
711
+
712
+ def __init__(
713
+ self,
714
+ size: int = 6,
715
+ aromatic: bool = False,
716
+ hetero_atoms: dict[int, int] | None = None,
717
+ center_2d: tuple[float, float] | None = None,
718
+ center_3d: tuple[float, float, float] | None = None,
719
+ attach_to: AtomId | None = None,
720
+ ):
721
+ self.size = int(size)
722
+ self.aromatic = bool(aromatic)
723
+ self.hetero_atoms = hetero_atoms or {}
724
+ self.center_2d = center_2d
725
+ self.center_3d = center_3d
726
+ self.attach_to = attach_to
727
+ self._atom_ids: list[AtomId] = []
728
+ self._bond_ids: list[BondId] = []
729
+ self._bridge_bond_id: BondId | None = None
730
+
731
+ def do(self, doc: MoleculeDocument) -> CommandResult:
732
+ r = 1.42 / (2.0 * math.sin(math.pi / self.size))
733
+
734
+ # 计算环中心与连接方向,使新加的环自然接在选中原子(或分子外侧)上
735
+ anchor_id = self.attach_to
736
+ bridge_dir_3d = np.array([1.0, 0.0, 0.0], dtype=np.float32)
737
+ if anchor_id is not None and anchor_id in doc.topology._atoms and doc.has_3d:
738
+ anchor_pos = doc.get_atom_3d_pos(anchor_id)
739
+ bridge_length = estimate_bond_length(doc.topology.get_atom(anchor_id).atomic_num, self.hetero_atoms.get(0, 6))
740
+ sprout_pos = doc.suggest_bonded_3d_position(anchor_id, bond_length=bridge_length)
741
+ if anchor_pos is not None:
742
+ v = sprout_pos - anchor_pos
743
+ vn = float(np.linalg.norm(v))
744
+ if vn > 1e-4:
745
+ bridge_dir_3d = (v / vn).astype(np.float32)
746
+ c3d = anchor_pos + bridge_dir_3d * (bridge_length + r)
747
+ else:
748
+ c3d = np.zeros(3, dtype=np.float32)
749
+ elif self.center_3d is not None:
750
+ c3d = np.asarray(self.center_3d, dtype=np.float32)
751
+ elif doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) > 0:
752
+ coords = doc.coordinates.current.coords
753
+ xmax = float(coords[:, 0].max())
754
+ ymid = float(coords[:, 1].mean())
755
+ zmid = float(coords[:, 2].mean())
756
+ c3d = np.array([xmax + 2.4 + r, ymid, zmid], dtype=np.float32)
757
+ else:
758
+ c3d = np.zeros(3, dtype=np.float32)
759
+
760
+ # 生成正多边形顶点(让第 0 个或第 1 个碳正对 anchor_id 以便成键)
761
+ base_angle = math.atan2(float(-bridge_dir_3d[1]), float(-bridge_dir_3d[0]))
762
+ # 若第 0 号位是杂原子(如噻吩 S、呋喃 O),让第 1 号位(C2 alpha 位)与母核相连!
763
+ connect_ring_idx = 1 if (0 in self.hetero_atoms and self.size >= 5) else 0
764
+ angle_offset = base_angle - (2.0 * math.pi * connect_ring_idx / self.size)
765
+
766
+ ring_coords_3d = np.zeros((self.size, 3), dtype=np.float32)
767
+ for i in range(self.size):
768
+ ang = angle_offset + 2.0 * math.pi * i / self.size
769
+ ring_coords_3d[i] = [
770
+ c3d[0] + r * math.cos(ang),
771
+ c3d[1] + r * math.sin(ang),
772
+ c3d[2],
773
+ ]
774
+
775
+ reusing_atoms = len(self._atom_ids) == self.size
776
+ new_aids: list[AtomId] = []
777
+ for i in range(self.size):
778
+ z = self.hetero_atoms.get(i, 6)
779
+ preset_aid = self._atom_ids[i] if reusing_atoms else None
780
+ aid = doc.topology.add_atom(z, aromatic=self.aromatic, atom_id=preset_aid)
781
+ new_aids.append(aid)
782
+ self._atom_ids = new_aids
783
+
784
+ reusing_bonds = len(self._bond_ids) == self.size
785
+ new_bids: list[BondId] = []
786
+ for i in range(self.size):
787
+ a = self._atom_ids[i]
788
+ b = self._atom_ids[(i + 1) % self.size]
789
+ order = (2 if (i % 2 == 1) else 1) if self.aromatic else 1
790
+ preset_bid = self._bond_ids[i] if reusing_bonds else None
791
+ bid = doc.topology.add_bond(a, b, order=order, aromatic=self.aromatic, bond_id=preset_bid)
792
+ new_bids.append(bid)
793
+ self._bond_ids = new_bids
794
+
795
+ # 若指定了连接锚点原子,自动加上环与母核之间的单键
796
+ if anchor_id is not None and anchor_id in doc.topology._atoms:
797
+ target_ring_aid = self._atom_ids[connect_ring_idx]
798
+ self._bridge_bond_id = doc.topology.add_bond(
799
+ anchor_id, target_ring_aid, order=1, bond_id=self._bridge_bond_id
800
+ )
801
+
802
+ doc.coordinates.append_atoms(ring_coords_3d)
803
+
804
+ # 写入 2D 世界坐标(单位 Å)
805
+ if self.center_2d is not None:
806
+ cx2, cy2 = self.center_2d
807
+ elif anchor_id is not None and anchor_id in doc.coords_2d:
808
+ ax, ay = doc.coords_2d[anchor_id]
809
+ cx2 = ax + float(bridge_dir_3d[0]) * (1.50 + r)
810
+ cy2 = ay + float(bridge_dir_3d[1]) * (1.50 + r)
811
+ else:
812
+ cx2, cy2 = float(c3d[0]), float(c3d[1])
813
+
814
+ for i, aid in enumerate(self._atom_ids):
815
+ ang = angle_offset + 2.0 * math.pi * i / self.size
816
+ doc.coords_2d[aid] = (cx2 + r * math.cos(ang), cy2 + r * math.sin(ang))
817
+
818
+ return CommandResult(
819
+ success=True,
820
+ changed=True,
821
+ message=f"添加 {self.size} 元环",
822
+ data={"size": self.size, "atom_ids": [a.value for a in self._atom_ids]},
823
+ )
824
+
825
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
826
+ if self._bridge_bond_id is not None:
827
+ doc.topology.remove_bond(self._bridge_bond_id)
828
+ for bid in self._bond_ids:
829
+ doc.topology.remove_bond(bid)
830
+ if doc.has_3d:
831
+ doc.coordinates.remove_trailing_atoms(self.size)
832
+ for aid in self._atom_ids:
833
+ doc.coords_2d.pop(aid, None)
834
+ doc.topology.remove_atom(aid)
835
+ return CommandResult(
836
+ success=True,
837
+ changed=True,
838
+ message=f"撤销 {self.size} 元环",
839
+ )
840
+
841
+
842
+
843
+ class ChangeAtomStyleCommand(Command):
844
+ affects_geometry = False
845
+ """
846
+ 修改单个或多个原子的独立显示半径缩放 (atom.scale)、独立颜色 (atom.color) 或形式电荷 (atom.formal_charge)。
847
+ 完整记录修改前状态,100% 支持 Ctrl+Z / Ctrl+Y 撤销重做!
848
+ """
849
+
850
+ description = "修改选中原子外观属性"
851
+
852
+ def __init__(
853
+ self,
854
+ atom_ids: list[AtomId] | set[AtomId] | AtomId,
855
+ scale: float | None = None,
856
+ color: tuple[float, float, float] | None = None,
857
+ clear_color: bool = False,
858
+ formal_charge: int | None = None,
859
+ ):
860
+ if isinstance(atom_ids, AtomId):
861
+ self.atom_ids = [atom_ids]
862
+ else:
863
+ self.atom_ids = list(atom_ids)
864
+ self.scale = float(scale) if scale is not None else None
865
+ self.color = tuple(float(c) for c in color) if color is not None else None
866
+ self.clear_color = bool(clear_color)
867
+ self.formal_charge = int(formal_charge) if formal_charge is not None else None
868
+ self._old_states: dict[AtomId, tuple[float, tuple | None, int]] = {}
869
+
870
+ def do(self, doc: MoleculeDocument) -> CommandResult:
871
+ changed_count = 0
872
+ for aid in self.atom_ids:
873
+ if aid not in doc.topology._atoms:
874
+ continue
875
+ atom = doc.topology.get_atom(aid)
876
+ if aid not in self._old_states:
877
+ self._old_states[aid] = (
878
+ float(getattr(atom, "scale", 1.0)),
879
+ getattr(atom, "color", None),
880
+ int(getattr(atom, "formal_charge", 0)),
881
+ )
882
+ if self.scale is not None:
883
+ atom.scale = max(0.20, min(3.50, self.scale))
884
+ if self.clear_color:
885
+ atom.color = None
886
+ elif self.color is not None:
887
+ atom.color = self.color
888
+ if self.formal_charge is not None:
889
+ atom.formal_charge = self.formal_charge
890
+ changed_count += 1
891
+
892
+ if changed_count == 0:
893
+ return CommandResult(success=False, message="未找到目标原子")
894
+ return CommandResult(
895
+ success=True,
896
+ changed=True,
897
+ message=f"已更新 {changed_count} 个原子的独立外观属性",
898
+ )
899
+
900
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
901
+ for aid, (old_scale, old_color, old_charge) in self._old_states.items():
902
+ if aid in doc.topology._atoms:
903
+ atom = doc.topology.get_atom(aid)
904
+ atom.scale = old_scale
905
+ atom.color = old_color
906
+ atom.formal_charge = old_charge
907
+ return CommandResult(
908
+ success=True,
909
+ changed=True,
910
+ message="已撤销原子外观修改",
911
+ )
912
+
913
+
914
+ class ChangeBondStyleCommand(Command):
915
+ affects_geometry = False
916
+ """
917
+ 修改单条或多条化学键的独立粗细缩放 (bond.width_scale) 或独立颜色 (bond.color)。
918
+ 完整支持 Ctrl+Z / Ctrl+Y 撤销重做!
919
+ """
920
+
921
+ description = "修改选中化学键外观属性"
922
+
923
+ def __init__(
924
+ self,
925
+ bond_ids: list[BondId] | set[BondId] | BondId,
926
+ width_scale: float | None = None,
927
+ color: tuple[float, float, float] | None = None,
928
+ clear_color: bool = False,
929
+ ):
930
+ if isinstance(bond_ids, BondId):
931
+ self.bond_ids = [bond_ids]
932
+ else:
933
+ self.bond_ids = list(bond_ids)
934
+ self.width_scale = float(width_scale) if width_scale is not None else None
935
+ self.color = tuple(float(c) for c in color) if color is not None else None
936
+ self.clear_color = bool(clear_color)
937
+ self._old_states: dict[BondId, tuple[float, tuple | None]] = {}
938
+
939
+ def do(self, doc: MoleculeDocument) -> CommandResult:
940
+ changed_count = 0
941
+ for bid in self.bond_ids:
942
+ if bid not in doc.topology._bonds:
943
+ continue
944
+ bond = doc.topology.get_bond(bid)
945
+ if bid not in self._old_states:
946
+ self._old_states[bid] = (
947
+ float(getattr(bond, "width_scale", 1.0)),
948
+ getattr(bond, "color", None),
949
+ )
950
+ if self.width_scale is not None:
951
+ bond.width_scale = max(0.20, min(3.50, self.width_scale))
952
+ if self.clear_color:
953
+ bond.color = None
954
+ elif self.color is not None:
955
+ bond.color = self.color
956
+ changed_count += 1
957
+
958
+ if changed_count == 0:
959
+ return CommandResult(success=False, message="未找到目标化学键")
960
+ return CommandResult(
961
+ success=True,
962
+ changed=True,
963
+ message=f"已更新 {changed_count} 条化学键的独立粗细/颜色",
964
+ )
965
+
966
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
967
+ for bid, (old_w, old_c) in self._old_states.items():
968
+ if bid in doc.topology._bonds:
969
+ bond = doc.topology.get_bond(bid)
970
+ bond.width_scale = old_w
971
+ bond.color = old_c
972
+ return CommandResult(
973
+ success=True,
974
+ changed=True,
975
+ message="已撤销化学键外观修改",
976
+ )
977
+
978
+
979
+ class TransformCoordinates3DCommand(Command):
980
+ """
981
+ 批量变换 3D 坐标(用于镜像反转 Mirror Invert、主轴对齐 Reorient、键角/二面角精确修改等),
982
+ 100% 支持 Ctrl+Z / Ctrl+Y 撤销重做!
983
+ """
984
+
985
+ def __init__(self, new_coords: np.ndarray, description: str = "三维几何变换"):
986
+ self.new_coords = np.asarray(new_coords, dtype=np.float32).copy()
987
+ self.description = description
988
+ self._old_coords: np.ndarray | None = None
989
+ self._old_coords_2d: dict[AtomId, tuple[float, float]] | None = None
990
+
991
+ def do(self, doc: MoleculeDocument) -> CommandResult:
992
+ if not doc.has_3d or doc.coordinates.current is None:
993
+ return CommandResult(success=False, message="当前分子无 3D 坐标")
994
+ if self._old_coords is None:
995
+ self._old_coords = doc.coordinates.current.coords.copy()
996
+ self._old_coords_2d = dict(doc.coords_2d)
997
+ if self.new_coords.shape != doc.coordinates.current.coords.shape:
998
+ return CommandResult(success=False, message="坐标维度不匹配")
999
+ doc.coordinates.update_current_coords(self.new_coords.copy())
1000
+ doc.sync_2d_coords_from_3d()
1001
+ return CommandResult(success=True, changed=True, message=f"已执行:{self.description}")
1002
+
1003
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
1004
+ if self._old_coords is None or not doc.has_3d:
1005
+ return CommandResult(success=False, message="无可恢复的 3D 坐标")
1006
+ doc.coordinates.update_current_coords(self._old_coords.copy())
1007
+ if self._old_coords_2d is not None:
1008
+ doc.coords_2d = dict(self._old_coords_2d)
1009
+ return CommandResult(success=True, changed=True, message=f"已撤销:{self.description}")
1010
+
1011
+
1012
+ # ===========================================================================
1013
+ # v6 新增核心命令:
1014
+ # 1. MoveAtomsBatch3DCommand(框选/套索多原子同步平移,单次 Ctrl+Z 全部恢复)
1015
+ # 2. AppendMoleculeCommand(Ctrl+V 智能追加粘贴分子到当前文档,带自动防重叠偏移与 Ctrl+Z 撤销)
1016
+ # 3. ModifyBondLength3DCommand(精确修改键长 Å,带动端基基团位移,支持 Ctrl+Z 撤销)
1017
+ # 4. SetAtomStyleCommand / SetBondStyleCommand / SetAtomChargeCommand(兼容 Win10 严格校验单测)
1018
+ # ===========================================================================
1019
+ import math as _math
1020
+
1021
+
1022
+ def _validate_scale_value(val: float | None) -> float | None:
1023
+ if val is None:
1024
+ return None
1025
+ f = float(val)
1026
+ if not _math.isfinite(f) or f < 0.15 or f > 6.0:
1027
+ raise ValueError(f"Invalid scale {val}: must be finite in [0.15, 6.0]")
1028
+ return f
1029
+
1030
+
1031
+ def _validate_rgb_tuple(color: tuple | list | None) -> tuple[float, float, float] | None:
1032
+ if color is None:
1033
+ return None
1034
+ if not isinstance(color, (tuple, list)) or len(color) != 3:
1035
+ raise ValueError("RGB color must be a 3-tuple of floats in [0.0, 1.0]")
1036
+ rgb = tuple(float(c) for c in color)
1037
+ if not all(_math.isfinite(c) and 0.0 <= c <= 1.0 for c in rgb):
1038
+ raise ValueError(f"RGB channels out of range [0.0, 1.0]: {rgb}")
1039
+ return rgb
1040
+
1041
+
1042
+ class SetAtomStyleCommand(ChangeAtomStyleCommand):
1043
+ """严格参数校验版单原子/多原子外观修改命令(100% 兼容 test_v4_true_style_and_storage)。"""
1044
+
1045
+ affects_geometry = False
1046
+
1047
+ def __init__(
1048
+ self,
1049
+ atom_ids: list[AtomId] | set[AtomId] | AtomId,
1050
+ scale: float | None = None,
1051
+ color: tuple[float, float, float] | None = None,
1052
+ formal_charge: int | None = None,
1053
+ clear_color: bool = False,
1054
+ ):
1055
+ v_scale = _validate_scale_value(scale)
1056
+ v_color = _validate_rgb_tuple(color)
1057
+ super().__init__(
1058
+ atom_ids=atom_ids,
1059
+ scale=v_scale,
1060
+ color=v_color,
1061
+ formal_charge=formal_charge,
1062
+ clear_color=clear_color,
1063
+ )
1064
+
1065
+
1066
+ class SetBondStyleCommand(ChangeBondStyleCommand):
1067
+ """严格参数校验版单键/多键外观修改命令(100% 兼容 test_v4_true_style_and_storage)。"""
1068
+
1069
+ affects_geometry = False
1070
+
1071
+ def __init__(
1072
+ self,
1073
+ bond_ids: list[BondId] | set[BondId] | BondId,
1074
+ width_scale: float | None = None,
1075
+ color: tuple[float, float, float] | None = None,
1076
+ clear_color: bool = False,
1077
+ ):
1078
+ v_scale = _validate_scale_value(width_scale)
1079
+ v_color = _validate_rgb_tuple(color)
1080
+ super().__init__(
1081
+ bond_ids=bond_ids,
1082
+ width_scale=v_scale,
1083
+ color=v_color,
1084
+ clear_color=clear_color,
1085
+ )
1086
+
1087
+
1088
+ class SetAtomChargeCommand(Command):
1089
+ """修改原子形式电荷命令(走 CommandBus 支持 Undo/Redo,不破坏 2D 坐标)。"""
1090
+
1091
+ affects_geometry = False
1092
+ description = "修改原子形式电荷"
1093
+
1094
+ def __init__(self, atom_id: AtomId, formal_charge: int):
1095
+ if not isinstance(formal_charge, (int, np.integer)) or abs(int(formal_charge)) > 8:
1096
+ raise ValueError(f"Invalid formal charge: {formal_charge}")
1097
+ self.atom_id = atom_id
1098
+ self.formal_charge = int(formal_charge)
1099
+ self._old_charge: int | None = None
1100
+
1101
+ def do(self, doc: MoleculeDocument) -> CommandResult:
1102
+ if self.atom_id not in doc.topology._atoms:
1103
+ return CommandResult(success=False, message="未找到目标原子")
1104
+ atom = doc.topology.get_atom(self.atom_id)
1105
+ if self._old_charge is None:
1106
+ self._old_charge = int(getattr(atom, "formal_charge", 0))
1107
+ atom.formal_charge = self.formal_charge
1108
+ return CommandResult(
1109
+ success=True,
1110
+ changed=True,
1111
+ message=f"已将原子 #{self.atom_id.value} 形式电荷设为 {self.formal_charge:+d}",
1112
+ )
1113
+
1114
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
1115
+ if self.atom_id in doc.topology._atoms and self._old_charge is not None:
1116
+ doc.topology.get_atom(self.atom_id).formal_charge = self._old_charge
1117
+ return CommandResult(
1118
+ success=True,
1119
+ changed=True,
1120
+ message=f"已撤销原子 #{self.atom_id.value} 形式电荷修改",
1121
+ )
1122
+
1123
+
1124
+ class MoveAtomsBatch3DCommand(Command):
1125
+ """
1126
+ 批量移动多个选中原子的 3D 坐标(框选/套索后一起拖拽平移)。
1127
+ 一次 Ctrl+Z 即可把所有被拖动的原子同时恢复到拖动前的位置!
1128
+ """
1129
+
1130
+ description = "批量平移选中原子"
1131
+
1132
+ def __init__(
1133
+ self,
1134
+ atom_moves: dict[AtomId, tuple[np.ndarray, np.ndarray]],
1135
+ description: str = "批量平移选中原子",
1136
+ old_coords_2d: dict[AtomId, tuple[float, float]] | None = None,
1137
+ new_coords_2d: dict[AtomId, tuple[float, float]] | None = None,
1138
+ ):
1139
+ # atom_moves: {atom_id: (old_pos_3d, new_pos_3d)}
1140
+ self.atom_moves = {
1141
+ aid: (
1142
+ np.asarray(old_p, dtype=np.float32).copy(),
1143
+ np.asarray(new_p, dtype=np.float32).copy(),
1144
+ )
1145
+ for aid, (old_p, new_p) in atom_moves.items()
1146
+ }
1147
+ self.description = description
1148
+ self._old_coords_2d: dict[AtomId, tuple[float, float]] | None = dict(old_coords_2d) if old_coords_2d is not None else None
1149
+ self._new_coords_2d: dict[AtomId, tuple[float, float]] | None = dict(new_coords_2d) if new_coords_2d is not None else None
1150
+
1151
+ def do(self, doc: MoleculeDocument) -> CommandResult:
1152
+ if not doc.has_3d or doc.coordinates.current is None or not self.atom_moves:
1153
+ return CommandResult(success=False, message="无有效 3D 坐标可平移")
1154
+ if self._old_coords_2d is None:
1155
+ self._old_coords_2d = dict(doc.coords_2d)
1156
+ _, id_to_idx = doc.topology.atom_index_map()
1157
+ coords = doc.coordinates.current.coords.copy()
1158
+ moved = 0
1159
+ for aid, (_, new_p) in self.atom_moves.items():
1160
+ if aid in id_to_idx and id_to_idx[aid] < len(coords):
1161
+ coords[id_to_idx[aid]] = new_p
1162
+ moved += 1
1163
+ if moved == 0:
1164
+ return CommandResult(success=False, message="未命中可移动原子")
1165
+ doc.coordinates.update_current_coords(coords)
1166
+ if self._new_coords_2d is not None:
1167
+ doc.coords_2d.update(self._new_coords_2d)
1168
+ else:
1169
+ for aid, (_, new_p) in self.atom_moves.items():
1170
+ doc.coords_2d[aid] = (float(new_p[0]), float(new_p[1]))
1171
+ return CommandResult(
1172
+ success=True,
1173
+ changed=True,
1174
+ message=f"已同步平移 {moved} 个选中原子",
1175
+ )
1176
+
1177
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
1178
+ if not doc.has_3d or doc.coordinates.current is None or not self.atom_moves:
1179
+ return CommandResult(success=False, message="无有效 3D 坐标可恢复")
1180
+ _, id_to_idx = doc.topology.atom_index_map()
1181
+ coords = doc.coordinates.current.coords.copy()
1182
+ for aid, (old_p, _) in self.atom_moves.items():
1183
+ if aid in id_to_idx and id_to_idx[aid] < len(coords):
1184
+ coords[id_to_idx[aid]] = old_p
1185
+ doc.coordinates.update_current_coords(coords)
1186
+ if self._old_coords_2d is not None:
1187
+ doc.coords_2d = dict(self._old_coords_2d)
1188
+ return CommandResult(
1189
+ success=True,
1190
+ changed=True,
1191
+ message=f"已撤销 {len(self.atom_moves)} 个原子的批量平移",
1192
+ )
1193
+
1194
+
1195
+ class MoveMultiAtoms3DCommand(MoveAtomsBatch3DCommand):
1196
+ """兼容 (old_positions, new_positions) 接口的多原子 3D 批量平移命令。"""
1197
+
1198
+ def __init__(
1199
+ self,
1200
+ old_positions: dict[AtomId, np.ndarray | tuple[float, float, float] | None],
1201
+ new_positions: dict[AtomId, np.ndarray | tuple[float, float, float]],
1202
+ description: str = "批量平移选中原子",
1203
+ old_coords_2d: dict[AtomId, tuple[float, float]] | None = None,
1204
+ new_coords_2d: dict[AtomId, tuple[float, float]] | None = None,
1205
+ ):
1206
+ atom_moves: dict[AtomId, tuple[np.ndarray, np.ndarray]] = {}
1207
+ for aid, new_p in new_positions.items():
1208
+ if new_p is None:
1209
+ continue
1210
+ old_p = old_positions.get(aid)
1211
+ if old_p is None:
1212
+ old_p = new_p
1213
+ atom_moves[aid] = (
1214
+ np.asarray(old_p, dtype=np.float32),
1215
+ np.asarray(new_p, dtype=np.float32),
1216
+ )
1217
+ super().__init__(
1218
+ atom_moves=atom_moves,
1219
+ description=description,
1220
+ old_coords_2d=old_coords_2d,
1221
+ new_coords_2d=new_coords_2d,
1222
+ )
1223
+
1224
+
1225
+ class AppendMoleculeCommand(Command):
1226
+ """
1227
+ 将另一个 MoleculeDocument(来自 Ctrl+V 粘贴的 SMILES / XYZ / 片段)追加合并到当前文档中,
1228
+ 自动计算非重叠空间偏移,且支持 Ctrl+Z 一键撤销整个粘贴操作!
1229
+ """
1230
+
1231
+ description = "粘贴追加分子结构"
1232
+
1233
+ def __init__(self, source_doc: MoleculeDocument, offset_3d: np.ndarray | None = None):
1234
+ self.source_doc = source_doc
1235
+ self.offset_3d = np.asarray(offset_3d, dtype=np.float32) if offset_3d is not None else None
1236
+ self._added_atom_ids: list[AtomId] = []
1237
+ self._added_bond_ids: list[BondId] = []
1238
+ self._old_coords_3d: np.ndarray | None = None
1239
+ self._old_coords_2d: dict[AtomId, tuple[float, float]] | None = None
1240
+
1241
+ def do(self, doc: MoleculeDocument) -> CommandResult:
1242
+ if self.source_doc is None or self.source_doc.num_atoms == 0:
1243
+ return CommandResult(success=False, message="待粘贴分子为空")
1244
+
1245
+ self._old_coords_2d = dict(doc.coords_2d)
1246
+ old_n = doc.num_atoms
1247
+ if doc.has_3d and doc.coordinates.current is not None and old_n > 0:
1248
+ self._old_coords_3d = doc.coordinates.current.coords.copy()
1249
+ else:
1250
+ self._old_coords_3d = np.zeros((0, 3), dtype=np.float32)
1251
+
1252
+ # 计算 3D 自动防重叠偏移量(置于现有分子右侧 +3.8 Å)
1253
+ src_n = self.source_doc.num_atoms
1254
+ if self.source_doc.has_3d and self.source_doc.coordinates.current is not None:
1255
+ src_coords = self.source_doc.coordinates.current.coords.copy()
1256
+ else:
1257
+ self.source_doc.relax_3d_geometry(max_iters=60)
1258
+ src_coords = (
1259
+ self.source_doc.coordinates.current.coords.copy()
1260
+ if self.source_doc.coordinates.current is not None
1261
+ else np.zeros((src_n, 3), dtype=np.float32)
1262
+ )
1263
+ src_coords = src_coords - src_coords.mean(axis=0)
1264
+
1265
+ if self.offset_3d is not None:
1266
+ shift_3d = self.offset_3d
1267
+ elif len(self._old_coords_3d) > 0:
1268
+ max_x = float(self._old_coords_3d[:, 0].max())
1269
+ min_src_x = float(src_coords[:, 0].min()) if len(src_coords) > 0 else 0.0
1270
+ shift_3d = np.array([max_x - min_src_x + 3.5, 0.0, 0.0], dtype=np.float32)
1271
+ else:
1272
+ shift_3d = np.zeros(3, dtype=np.float32)
1273
+
1274
+ src_coords_shifted = src_coords + shift_3d
1275
+
1276
+ # 添加原子(若 Redo 则复用上次分配的 AtomId)
1277
+ src_atom_ids = list(self.source_doc.topology.atom_ids)
1278
+ src_to_new_aid: dict[AtomId, AtomId] = {}
1279
+ reusing_ids = len(self._added_atom_ids) == len(src_atom_ids)
1280
+ new_aids: list[AtomId] = []
1281
+
1282
+ for idx, s_aid in enumerate(src_atom_ids):
1283
+ s_atom = self.source_doc.topology.get_atom(s_aid)
1284
+ forced_id = self._added_atom_ids[idx] if reusing_ids else None
1285
+ new_aid = doc.topology.add_atom(
1286
+ atomic_num=s_atom.atomic_num,
1287
+ formal_charge=s_atom.formal_charge,
1288
+ aromatic=s_atom.aromatic,
1289
+ atom_id=forced_id,
1290
+ )
1291
+ dst_atom = doc.topology.get_atom(new_aid)
1292
+ dst_atom.scale = float(getattr(s_atom, "scale", 1.0))
1293
+ dst_atom.color = getattr(s_atom, "color", None)
1294
+ src_to_new_aid[s_aid] = new_aid
1295
+ new_aids.append(new_aid)
1296
+ self._added_atom_ids = new_aids
1297
+
1298
+ # 添加化学键
1299
+ src_bond_ids = list(self.source_doc.topology.bond_ids)
1300
+ reusing_bids = len(self._added_bond_ids) == len(src_bond_ids)
1301
+ new_bids: list[BondId] = []
1302
+ for idx, s_bid in enumerate(src_bond_ids):
1303
+ s_bond = self.source_doc.topology.get_bond(s_bid)
1304
+ if s_bond.begin in src_to_new_aid and s_bond.end in src_to_new_aid:
1305
+ forced_bid = self._added_bond_ids[idx] if reusing_bids else None
1306
+ new_bid = doc.topology.add_bond(
1307
+ src_to_new_aid[s_bond.begin],
1308
+ src_to_new_aid[s_bond.end],
1309
+ order=s_bond.order,
1310
+ aromatic=s_bond.aromatic,
1311
+ bond_id=forced_bid,
1312
+ )
1313
+ dst_bond = doc.topology.get_bond(new_bid)
1314
+ dst_bond.width_scale = float(getattr(s_bond, "width_scale", 1.0))
1315
+ dst_bond.color = getattr(s_bond, "color", None)
1316
+ new_bids.append(new_bid)
1317
+ self._added_bond_ids = new_bids
1318
+
1319
+ # 合并 3D 坐标
1320
+ combined_3d = (
1321
+ np.vstack([self._old_coords_3d, src_coords_shifted]).astype(np.float32)
1322
+ if len(self._old_coords_3d) > 0
1323
+ else src_coords_shifted.astype(np.float32)
1324
+ )
1325
+ store = doc.ensure_coordinates()
1326
+ if store.num_frames == 0:
1327
+ store.add_frame(combined_3d, source="paste_append")
1328
+ else:
1329
+ store.update_current_coords(combined_3d)
1330
+
1331
+ doc.sync_2d_coords_from_3d()
1332
+ return CommandResult(
1333
+ success=True,
1334
+ changed=True,
1335
+ message=f"已追加粘贴 {len(new_aids)} 个原子、{len(new_bids)} 条化学键",
1336
+ data={"added_atom_ids": list(new_aids)},
1337
+ )
1338
+
1339
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
1340
+ for bid in reversed(self._added_bond_ids):
1341
+ if bid in doc.topology._bonds:
1342
+ doc.topology.remove_bond(bid)
1343
+ for aid in reversed(self._added_atom_ids):
1344
+ if aid in doc.topology._atoms:
1345
+ doc.topology.remove_atom(aid)
1346
+ if self._old_coords_3d is not None:
1347
+ if len(self._old_coords_3d) == 0:
1348
+ doc._coordinates = None
1349
+ elif doc.has_3d and doc.coordinates.current is not None:
1350
+ doc.coordinates.update_current_coords(self._old_coords_3d.copy())
1351
+ if self._old_coords_2d is not None:
1352
+ doc.coords_2d = dict(self._old_coords_2d)
1353
+ return CommandResult(
1354
+ success=True,
1355
+ changed=True,
1356
+ message=f"已撤销粘贴追加的 {len(self._added_atom_ids)} 个原子",
1357
+ )
1358
+
1359
+
1360
+ class ModifyBondLength3DCommand(Command):
1361
+ """
1362
+ 精确修改选中化学键的 3D 键长 (Å),自动带动远端连接子树平移(若成环则仅移动端点),
1363
+ 100% 支持 Ctrl+Z / Ctrl+Y 撤销重做!
1364
+ """
1365
+
1366
+ description = "精确修改化学键长"
1367
+
1368
+ def __init__(self, bond_id: BondId, target_length: float):
1369
+ self.bond_id = bond_id
1370
+ self.target_length = max(0.40, min(5.00, float(target_length)))
1371
+ self._old_coords: np.ndarray | None = None
1372
+ self._old_coords_2d: dict[AtomId, tuple[float, float]] | None = None
1373
+
1374
+ def do(self, doc: MoleculeDocument) -> CommandResult:
1375
+ if self.bond_id not in doc.topology._bonds or not doc.has_3d or doc.coordinates.current is None:
1376
+ return CommandResult(success=False, message="无法修改键长:未找到化学键或缺少 3D 坐标")
1377
+ if self._old_coords is None:
1378
+ self._old_coords = doc.coordinates.current.coords.copy()
1379
+ self._old_coords_2d = dict(doc.coords_2d)
1380
+
1381
+ bond = doc.topology.get_bond(self.bond_id)
1382
+ _, id2idx = doc.topology.atom_index_map()
1383
+ a1, a2 = bond.begin, bond.end
1384
+ if a1 not in id2idx or a2 not in id2idx:
1385
+ return CommandResult(success=False, message="化学键端点索引无效")
1386
+
1387
+ coords = doc.coordinates.current.coords.copy()
1388
+ p1 = coords[id2idx[a1]].astype(np.float64)
1389
+ p2 = coords[id2idx[a2]].astype(np.float64)
1390
+ vec = p2 - p1
1391
+ cur_len = float(np.linalg.norm(vec))
1392
+ if cur_len < 1e-6:
1393
+ unit_v = np.array([1.0, 0.0, 0.0], dtype=np.float64)
1394
+ else:
1395
+ unit_v = vec / cur_len
1396
+
1397
+ delta = unit_v * (self.target_length - cur_len)
1398
+
1399
+ # BFS 查找 a2 侧子树(不经过 self.bond_id);若包含 a1(说明在环内)则只移动 a2
1400
+ visited = {a2}
1401
+ queue = [a2]
1402
+ in_ring = False
1403
+ while queue:
1404
+ curr = queue.pop(0)
1405
+ for bid in doc.topology._adjacency.get(curr, []):
1406
+ if bid == self.bond_id or bid not in doc.topology._bonds:
1407
+ continue
1408
+ b_obj = doc.topology.get_bond(bid)
1409
+ nbr = b_obj.end if b_obj.begin == curr else b_obj.begin
1410
+ if nbr == a1:
1411
+ in_ring = True
1412
+ break
1413
+ if nbr not in visited:
1414
+ visited.add(nbr)
1415
+ queue.append(nbr)
1416
+ if in_ring:
1417
+ break
1418
+
1419
+ move_atoms = {a2} if in_ring else visited
1420
+ for aid in move_atoms:
1421
+ if aid in id2idx:
1422
+ coords[id2idx[aid]] = (coords[id2idx[aid]] + delta).astype(np.float32)
1423
+
1424
+ doc.coordinates.update_current_coords(coords)
1425
+ doc.sync_2d_coords_from_3d()
1426
+ return CommandResult(
1427
+ success=True,
1428
+ changed=True,
1429
+ message=f"已将键 #{self.bond_id.value} 键长从 {cur_len:.3f} Å 调整为 {self.target_length:.3f} Å",
1430
+ )
1431
+
1432
+ def undo(self, doc: MoleculeDocument) -> CommandResult:
1433
+ if self._old_coords is None or not doc.has_3d or doc.coordinates.current is None:
1434
+ return CommandResult(success=False, message="无历史坐标可恢复")
1435
+ doc.coordinates.update_current_coords(self._old_coords.copy())
1436
+ if self._old_coords_2d is not None:
1437
+ doc.coords_2d = dict(self._old_coords_2d)
1438
+ return CommandResult(
1439
+ success=True,
1440
+ changed=True,
1441
+ message=f"已撤销键 #{self.bond_id.value} 的键长修改",
1442
+ )
1443
+
1444
+
1445
+ from .internal_coordinates import ModifyAngle3DCommand, ModifyDihedral3DCommand